How to Build an MCP Server in Python

Jun 12, 2026 07:00 AM - 19 hours ago 462

Introduction

An MCP server successful Python exposes tools, resources, and prompts to AI hosts through the Model Context Protocol (MCP). You constitute a mini Python program. Cursor, Claude Desktop, aliases different MCP host starts the programme and calls your functions erstwhile the exemplary needs unrecorded data.

This tutorial builds a section SQLite query server pinch the official MCP Python SDK and FastMCP. You registry 1 tool, link the server to Cursor and Claude Desktop, and corroborate the exemplary sounds your database astatine chat time.

For protocol background, commencement pinch DigitalOcean’s MCP 101: An Introduction to Model Context Protocol and Understanding Model Context Protocol (MCP).

claude_mcp_server_sqlite_demoI inquire for the apical chatters and Claude shows the results consecutive from my MCP server.
cursor_mcp_server_sqlite_demoI petition the apical chatters and Cursor pulls the information unrecorded from my MCP server.

Key takeaways

  • An MCP server successful Python uses the mcp package. Pin mcp>=1.27,<2 until the unchangeable 2.x merchandise ships.
  • FastMCP (from mcp.server.fastmcp import FastMCP) registers devices with @mcp.tool() and runs complete stdio by default for section hosts.
  • MCP has 3 primitives: tools (model actions), resources (read-only data), and prompts (reusable templates). This tutorial focuses connected tools.
  • Local hosts commencement your server arsenic a subprocess. Cursor reads ~/.cursor/mcp.json. Claude Desktop reads claude_desktop_config.json nether some mcpServers keys.
  • Use absolute paths to your virtualenv Python binary and server book in every config file.
  • On stdio transports, log to stderr. Never print() to stdout aliases you break JSON-RPC messages.
  • After setup, the big shows a greenish position dot (Cursor) aliases a devices icon (Claude Desktop). Approve each instrumentality telephone earlier the server runs.

What you’ll learn

  • Why MCP matters for LLM apps
  • How to build a Python MCP server pinch FastMCP and SQLite
  • How to registry the server successful Cursor and Claude Desktop
  • How to trial instrumentality calls extremity to end
  • Where to spell adjacent for distant MCP and accumulation deployment

Prerequisites

Before you start, corroborate you have:

  • Python 3.10 aliases newer (the official MCP Python quickstart requires 3.10+)
  • pip and venv (bundled pinch existent Python installers)
  • Cursor pinch MCP enabled, or Claude Desktop for the 2nd integration test
  • A terminal connected macOS aliases Linux, aliases PowerShell connected Windows
  • Network entree to download the sample community.db file

What is MCP and why do you request it?

MCP is an unfastened protocol for connecting LLM hosts to outer information and actions. Anthropic introduced MCP successful November 2024. Hosts speak JSON-RPC over stdio aliases HTTP transports. Servers expose system capabilities alternatively of custom one-off integrations per model.

Large connection models predict text. They do not query your database aliases telephone your APIs unless a host routes a instrumentality telephone to a server you control. MCP standardizes that bridge.

Role What it does Example successful this tutorial
Host UI wherever you chat Cursor aliases Claude Desktop
Client MCP protocol furniture wrong the host Built into the big app
Server Your Python codification pinch tools sqlite-server.py
Tool Function the exemplary requests get_top_chatters

How the pieces fresh together

When you chat successful Cursor aliases Claude Desktop, the big is the app window. The MCP client wrong the big lists disposable tools, sends your connection to the model, and forwards approved instrumentality calls to your server.

  1. You inquire a question, for illustration “List the apical chatters.”
  2. The exemplary selects the get_top_chatters instrumentality if the explanation matches.
  3. The big asks you to o.k. the instrumentality call.
  4. The MCP customer sends the telephone to your Python server complete stdio.
  5. The server queries SQLite and returns JSON rows.
  6. The exemplary formats the reply successful the chat.

mcp-flow-diagram

Everything successful the sketch runs connected your instrumentality for this walkthrough. The host spawns your server locally. The server opens community.db connected disk.

Note: Host and customer often stock 1 process. To constitute a standalone MCP client, travel the Build an MCP client guide.

MCP server primitives astatine a glance

Primitive Who controls it Purpose
Tool Model (with personification approval) Run code: query a DB, telephone an API
Resource Application Expose read-only files aliases records
Prompt User Ship reusable punctual templates

This task implements 1 tool. Resources and prompts travel the same FastMCP decorators (@mcp.resource(), @mcp.prompt()). See the MCP Python SDK server docs for afloat examples.

Building your first MCP server successful Python

You will create a virtual environment, instal the SDK, download sample data, and write sqlite-server.py.

Step 1: Set up your environment

Create and activate a virtual environment:

python3 -m venv mcp-env source mcp-env/bin/activate

On Windows PowerShell:

python -m venv mcp-env mcp-env\Scripts\Activate.ps1

Install the MCP Python SDK. Pin beneath 2.x while v2 is successful alpha:

pip install "mcp>=1.27,<2"

Step 2: Download the sample database

Download community.db into the aforesaid files arsenic your server script. The record contains a chatters table with sanction and messages columns.

For SQLite fundamentals successful a web app context, see How To Use an SQLite Database successful a Flask Application.

Step 3: Write the MCP server

Create sqlite-server.py:

# sqlite-server.py from pathlib import Path import sqlite3 from mcp.server.fastmcp import FastMCP DB_PATH = Path(__file__).resolve().parent / "community.db" mcp = FastMCP("Community Chatters") @mcp.tool() def get_top_chatters(limit: int = 10) -> list[dict]: """Return chatters classed by connection count.""" conn = sqlite3.connect(DB_PATH) cursor = conn.cursor() cursor.execute( "SELECT name, messages FROM chatters ORDER BY messages DESC LIMIT ?", (limit,), ) rows = cursor.fetchall() conn.close() return [{"name": name, "messages": messages} for name, messages in rows] if __name__ == "__main__": mcp.run()

FastMCP sounds the usability name, type hints, and docstring to build the tool schema. mcp.run() starts the stdio transport, which section hosts expect.

Stdio logging: Do not usage print() connected stdout successful stdio servers. Use logging aliases print(..., file=sys.stderr) truthful JSON-RPC frames enactment intact. See the official server logging notes.

Test the query without the host:

python3 -c "import sqlite3; c=sqlite3.connect('community.db'); print(c.execute('SELECT COUNT(*) FROM chatters').fetchone())"

You should spot a statement count printed to the terminal.

Adding your MCP server to Cursor

Open Cursor → Settings → MCP and click Add a New Global MCP Server. Cursor opens ~/.cursor/mcp.json.

cursor_mcp_server_sqlite_add

Replace the placeholder paths pinch your absolute paths. Run which python inside your activated virtualenv to get the expert path.

{ "mcpServers": { "sqlite-server": { "command": "/absolute/path/to/mcp-env/bin/python", "args": [ "/absolute/path/to/sqlite-server.py" ], "description": "Query apical chatters from the organization SQLite database" } } }

cursor_mcp_server_sqlite_json

Save the record and return to MCP Settings. A green dot adjacent to the server name means the process started cleanly.

cursor_mcp_server_sqlite_verify

Testing your MCP server successful Cursor

  1. Open a chat and ask: “How galore chatters are successful the database?”
  2. Cursor proposes the get_top_chatters tool. Approve the prompt.
  3. The server returns rows. The exemplary summarizes them successful the reply.

cursor_mcp_server_sqlite_ask

cursor_mcp_server_sqlite_results

If the instrumentality ne'er appears, spot Troubleshooting below.

Adding your MCP server to Claude Desktop

Claude Desktop uses the aforesaid mcpServers entity style arsenic Cursor.

  1. Open Claude Desktop → Settings → Developer → Edit Config.
  2. Edit claude_desktop_config.json (macOS: ~/Library/Application Support/Claude/claude_desktop_config.json).
  3. Add your server artifact pinch the aforesaid bid and args paths arsenic Cursor.
  4. Save, discontinue Claude Desktop completely, and reopen the app.
{ "mcpServers": { "sqlite-server": { "command": "/absolute/path/to/mcp-env/bin/python", "args": [ "/absolute/path/to/sqlite-server.py" ] } } }

claude_mcp_server_sqlite_tool_icon

Ask Claude: “Show maine the apical 5 chatters.” Approve the instrumentality telephone erstwhile prompted.

claude_mcp_server_sqlite_ask

claude_mcp_server_sqlite_results

The aforesaid Python server now useful from 2 hosts. The exemplary marque changes. The MCP statement stays the same.

Troubleshooting

Symptom Fix
Red aliases missing position successful Cursor Check absolute paths, corroborate pip show mcp wrong the venv, tally the server manually pinch the aforesaid bid and args
Tool ne'er offered Improve the instrumentality docstring, restart the host, verify the greenish dot aliases devices icon
ModuleNotFoundError: mcp Activate the venv whose Python way you put successful mcp.json
Empty aliases correction results Confirm community.db sits beside sqlite-server.py
Claude Desktop shows nary tools Use mcpServers, not a top-level servers array. Restart the app aft edits

Claude Desktop writes MCP logs to ~/Library/Logs/Claude/mcp*.log connected macOS. See Connect to section MCP servers for log locations connected different platforms.

FAQs

1. What is MCP successful Python?

MCP successful Python intends you instrumentality a Model Context Protocol server pinch the mcp package (FastMCP connected top). The server exposes devices the big forwards to the model. Python is 1 supported language. The TypeScript SDK serves the aforesaid domiciled for Node hosts.

2. What is the champion Python MCP room for building a server?

You tin usage the charismatic mcp package with FastMCP from mcp.server.fastmcp. Install with pip instal "mcp>=1.27,<2". The standalone fastmcp task targets the same ergonomic API for HTTP-first deployments. Start pinch the charismatic SDK truthful your code matches modelcontextprotocol.io docs.

3. How do you create an MCP server successful Python?

  1. Create a virtualenv and pip instal "mcp>=1.27,<2".
  2. Instantiate FastMCP("ServerName").
  3. Register functions pinch @mcp.tool().
  4. Call mcp.run() nether if __name__ == "__main__":.
  5. Point Cursor aliases Claude Desktop astatine the venv Python and your book way in mcpServers.

The create-python-server scaffold generates a starter repo if you for illustration a template.

4. What is the quality betwixt an MCP SDK and MCP?

MCP is the protocol specification (messages, transports, capacity types). An MCP SDK is simply a connection room that implements the spec. The Python SDK handles JSON-RPC framing, schema generation, and stdio aliases HTTP transports truthful you focus connected instrumentality logic.

5. Is MCP conscionable a REST API?

No. MCP uses JSON-RPC messages and a defined capacity exemplary (tools, resources, prompts). Hosts spawn stdio servers aliases link complete Streamable HTTP. REST endpoints are optional. You wrap existing REST APIs wrong instrumentality functions, but the ligament format is not plain HTTP CRUD.

Conclusion

You built an MCP server successful Python pinch FastMCP, wired SQLite information into Cursor and Claude Desktop, and validated instrumentality calls extremity to end. The aforesaid shape extends to email gateways, unreality APIs, and deployment workflows.

What’s next

Grow from this section stdio server into production-oriented patterns:

  • From Prompt to App successful Minutes pinch the DigitalOcean MCP Server for App Platform actions from Claude aliases Cursor
  • How to Use MCP pinch OpenAI Agents for supplier frameworks beyond desktop hosts
  • Claude Code MCP Server for terminal-based supplier workflows
  • MongoDB and DigitalOcean MCP Server Tutorial for database-backed MCP astatine scale
  • MCP Python SDK connected GitHub for resources, prompts, and Streamable HTTP examples

Run experiments connected a DigitalOcean Droplet or vessel apps pinch App Platform. For managed models and knowledge bases, research the DigitalOcean AI Platform.

Still looking for an answer?

Creative CommonsThis activity is licensed nether a Creative Commons Attribution-NonCommercial- ShareAlike 4.0 International License.

More