Get a quote

How to build an MCP server in Python (2026 guide)

Published 2026-10-14. 7 min read.

Python is the quickest way to put a database or internal script behind MCP. The official SDK turns ordinary typed functions into tools an AI assistant can call.

Code follows the official Python SDK as documented in October 2026, where the server class is MCPServer. Older tutorials use the name FastMCP for the same idea.

1. Install

pip install "mcp[cli]"
# or, with uv
uv add "mcp[cli]"

2. Write the server

Create server.py:

from mcp.server import MCPServer

mcp = MCPServer("Demo")

@mcp.tool()
def add(a: int, b: int) -> int:
    """Add two numbers."""
    return a + b

The function name becomes the tool name, the type hints become the input schema, and the docstring becomes the description the model reads. Write docstrings for the model, not for yourself: say what the tool returns and when to use it.

3. Run it as a remote server

uv run mcp run server.py --transport streamable-http

A client can then connect to http://localhost:8000/mcp. Put it behind HTTPS and authentication before anyone outside your machine uses it.

4. A more realistic tool

Here is the shape we use for read-only database tools: a fixed, parameterized query, a row limit and a timeout, so the model can never run arbitrary SQL.

@mcp.tool()
def orders_for_customer(email: str, limit: int = 20) -> list[dict]:
    """Return the most recent orders for one customer, newest first.
    Use when someone asks about a customer's orders or order status."""
    limit = max(1, min(limit, 50))
    rows = db.fetch(
        "SELECT id, status, total, created_at FROM orders "
        "WHERE customer_email = %s ORDER BY created_at DESC LIMIT %s",
        (email, limit),
        timeout_ms=3000,
    )
    return rows

Here db.fetch stands for your own database helper that uses a read-only connection.

5. Production checklist

  • Use a read-only database role and point it at a replica if you can.
  • Prefer approved queries over free SQL. If you must allow free SQL, expose views, not tables.
  • Log every call with user, tool and arguments.
  • Run our MCP security checklist before rollout.

Need it done for PostgreSQL or MySQL? See our PostgreSQL and MySQL connectors.

Related guides

Tell us which system your team wants AI to work with.

Fill in a 5-minute brief. Within 48 hours you get a tool list, a fixed price and an honest answer on whether you need us at all. No meetings needed.

Get a fixed quote