DEV Community

Cover image for Build Your First MCP Server in Python (and Give Claude Your Database)
Muiduzzaman Lipu for Refactorly

Posted on

Build Your First MCP Server in Python (and Give Claude Your Database)

What if you could ask Claude "who are my top customers?" and it queried your database to answer?

That's what the Model Context Protocol (MCP) is for. In this post we build an MCP server in Python in under 30 lines, connect it to Claude Code, and make sure it can't delete anything. Everything below was run with mcp 2.3.0, Python 3.12 and Claude Code 2.1, against a small local SQLite database.

Video version:

What MCP is, in one paragraph

MCP is an open standard for connecting AI applications to tools and data. Think of it as USB-C for AI. Your server exposes tools (functions). An MCP client (Claude Code, Claude Desktop, IDEs…) reads each tool's name, description and input schema, decides when to call it, and uses the result. Write a server once and it works in any MCP client.

Heads up: SDK 2.x renamed FastMCP

$ pip install mcp
Successfully installed mcp-2.3.0
Enter fullscreen mode Exit fullscreen mode

Most MCP tutorials use from mcp.server.fastmcp import FastMCP. On a fresh install today, that fails:

ModuleNotFoundError: No module named 'mcp.server.fastmcp'. This is mcp 2.x, where FastMCP
was renamed to MCPServer (from mcp.server.mcpserver import MCPServer) and other APIs changed
Enter fullscreen mode Exit fullscreen mode

The new import is:

from mcp.server.mcpserver import MCPServer
Enter fullscreen mode Exit fullscreen mode

The @mcp.tool() decorator works the same way. See the official migration guide for the other changes, such as snake_case result fields like result.is_error.

The server

My demo database shop.db has two tables, customers and orders (with total_cents). Here's the complete server:

import sqlite3
from mcp.server.mcpserver import MCPServer

mcp = MCPServer("shop-db")
DB = "file:shop.db?mode=ro"          # read-only connection


@mcp.tool()
def list_tables() -> str:
    """List the tables in the shop database and their columns."""
    with sqlite3.connect(DB, uri=True) as db:
        rows = db.execute("SELECT name, sql FROM sqlite_master WHERE type='table'")
        return "\n".join(sql for _, sql in rows)


@mcp.tool()
def query(sql: str) -> list[list]:
    """Run a read-only SQL query on the shop database."""
    with sqlite3.connect(DB, uri=True) as db:
        return [list(r) for r in db.execute(sql).fetchmany(50)]


if __name__ == "__main__":
    mcp.run(transport="stdio")
Enter fullscreen mode Exit fullscreen mode
  • MCPServer("shop-db") creates the server.
  • Every function decorated with @mcp.tool() becomes a tool.
  • mode=ro in the SQLite URI opens the database read-only.
  • mcp.run(transport="stdio") serves over standard input/output, which is how local clients launch it.

What the AI actually sees

I listed the tools with the SDK's own client (ClientSession + stdio_client):

list_tables - List the tables in the shop database and their columns.
query       - Run a read-only SQL query on the shop database.
              input: {'sql': {'title': 'Sql', 'type': 'string'}}
Enter fullscreen mode Exit fullscreen mode

The docstring becomes the description and the type hints become the input schema. That's everything the model knows about your tool, so write docstrings like you'd write a prompt.

Connect it to Claude Code

$ claude mcp add shop-db -- python server.py
Enter fullscreen mode Exit fullscreen mode

Everything after -- is the command that starts your server. Use the Python that has mcp installed. Then just ask:

$ claude -p "Who are my top 3 customers by total spend? Answer in dollars."
Enter fullscreen mode Exit fullscreen mode

Claude called list_tables, saw the schema, wrote the join and aggregation itself, and answered:

Rank Customer Total spend Orders
1 Ana $1,344.25 12
2 Eli $1,110.72 9
3 Chen $686.96 7

It even noted that "the database stores amounts in cents, so I divided by 100". I checked the totals with a direct SQL query, and they match.

Can it delete my data?

What if the model, or a prompt injection hidden in some data, sends a DELETE?

await session.call_tool("query", {"sql": "DELETE FROM orders"})
# is_error=True  'Error executing tool query'
Enter fullscreen mode Exit fullscreen mode

The server log shows why:

sqlite3.OperationalError: attempt to write a readonly database
Enter fullscreen mode Exit fullscreen mode
$ sqlite3 shop.db "SELECT count(*) FROM orders"
40
Enter fullscreen mode Exit fullscreen mode

All 40 orders are still there. Don't rely on the AI to behave. Make the dangerous thing impossible.

5 rules before you give an AI your data

  1. Read-only by default. mode=ro here; in production, connect with a read-only database user.
  2. Small, specific tools beat one "run anything" tool. get_top_customers(limit) is easier to reason about than raw SQL.
  3. Limit output. fetchmany(50) stops a single call from dumping a whole table into the model's context.
  4. Never return secrets: tokens, API keys, password hashes, personal data you don't need.
  5. Review tool calls before you auto-approve them, especially anything that writes.

Recap

  • pip install mcp. In 2.x, the class is MCPServer, not FastMCP.
  • @mcp.tool() + a docstring + type hints = a tool.
  • mcp.run(transport="stdio")
  • claude mcp add shop-db -- python server.py
  • Start read-only, then add power carefully.

What would you connect to Claude first? πŸ‘‡


I post one tested coding tip every day on YouTube at Refactorly. The 30-second version of this one is here.

Top comments (0)