Building an MCP Server in Python: A Step-by-Step Tutorial
The Model Context Protocol (MCP) is transforming how AI assistants interact with external tools and data sources. Instead of building custom integrations for every AI platform, you build one MCP server that works with Claude, VS Code Copilot, and any other MCP-compatible client. It's the USB standard for AI tool integration.
This tutorial walks through building a production-ready MCP server in Python from scratch. By the end, you'll have a working server with custom tools, resources, error handling, and authentication — ready to deploy as a pip package. The complete code is available, and every pattern is production-tested.
Need help with MCP server development? I provide MCP server development for businesses ready to grow. Learn about my MCP server development service or get in touch for a free consultation.
- What MCP Actually Does
- Tool Definition with JSON Schema
- Authentication and Security
- Real-World MCP Server Examples
What MCP Actually Does
MCP defines a JSON-RPC protocol between AI clients (like Claude Code) and servers that expose tools and resources. Tools are functions the AI can call — think "search database," "create file," or "query API." Resources are data the AI can read — think "project configuration," "database schema," or "recent logs."
The key insight is that MCP servers don't need to know anything about the AI model calling them. They expose capabilities through a standard interface. The AI client discovers what's available and calls it when relevant. This decoupling means your server works with every MCP-compatible client, present and future.
Setting Up the Project
Start with a clean Python project structure. MCP servers need Python 3.10+ for the async features they rely on. Create a new project with the following layout:
my-mcp-server/
├── src/
│ └── my_mcp_server/
│ ├── __init__.py
│ ├── server.py
│ └── tools/
│ ├── __init__.py
│ └── database.py
├── tests/
│ └── test_server.py
├── pyproject.toml
└── README.md
Install the MCP SDK: pip install mcp. This provides the server framework, protocol types, and transport handlers. For this tutorial, we'll also use httpx for making API calls from our tools and pydantic for input validation (which you likely already have as an MCP dependency).
Returns up to 50 results sorted by relevance" tells the AI exactly when this tool is appropriate.
Building the Minimal Server
Every MCP server starts with a Server instance and at least one tool or resource. Here's the minimal working example:
from mcp.server import Server
from mcp.types import Tool, TextContent
import mcp.server.stdio
app = Server("my-server")
@app.list_tools()
async def list_tools():
return [
Tool(
name="hello",
description="Says hello to a name",
inputSchema={
"type": "object",
"properties": {
"name": {"type": "string", "description": "Name to greet"}
},
"required": ["name"]
}
)
]
@app.call_tool()
async def call_tool(name: str, arguments: dict):
if name == "hello":
return [TextContent(type="text", text=f"Hello, {arguments['name']}!")]
raise ValueError(f"Unknown tool: {name}")
async def main():
async with mcp.server.stdio.stdio_server() as (read, write):
await app.run(read, write, app.create_initialization_options())
if __name__ == "__main__":
import asyncio
asyncio.run(main())
This server exposes a single "hello" tool. The AI client discovers it through list_tools, and when it decides to use the tool, calls call_tool with the tool name and arguments. The input schema uses JSON Schema — the same standard used by OpenAPI and many validation libraries.
The AI client discovers it through list_tools, and when it decides to use the tool, calls call_tool with the tool name and arguments.
Tool Definition with JSON Schema
The input schema is critical for AI tool use. A well-defined schema tells the AI exactly what parameters are available, their types, constraints, and descriptions. Poor schemas lead to incorrect tool calls and frustrated users.
Best practices for tool schemas:
Write descriptive descriptions. The AI reads these to decide when and how to use the tool. "Search the database" is vague. "Search the PostgreSQL database for records matching a query string, with optional filters by date range and status. Returns up to 50 results sorted by relevance" tells the AI exactly when this tool is appropriate.
Use enums for constrained values. If a parameter accepts only specific values, define them as an enum. This prevents the AI from hallucinating invalid options. For example, a status filter should enumerate its values: "enum": ["active", "pending", "archived"].
Mark required fields. Every parameter that the tool needs to function should be in the required array. Optional parameters should have sensible defaults documented in their descriptions.
Validate inputs. Even though the AI client should send valid data according to the schema, always validate inputs server-side. Use Pydantic models for clean validation with helpful error messages.
Building a Real Tool: Database Query
Let's build a practical tool that queries a PostgreSQL database. This demonstrates parameter handling, error management, and result formatting — all patterns you'll reuse.
from pydantic import BaseModel, Field
from typing import Optional
import asyncpg
class SearchParams(BaseModel):
query: str = Field(description="Search term")
table: str = Field(description="Table to search")
limit: int = Field(default=20, ge=1, le=100)
status: Optional[str] = Field(default=None)
SEARCH_TOOL = Tool(
name="search_records",
description="Search database records by keyword with optional status filter. "
"Searches across all text columns using PostgreSQL full-text search.",
inputSchema=SearchParams.model_json_schema()
)
async def execute_search(arguments: dict) -> list[TextContent]:
params = SearchParams(**arguments)
pool = await get_db_pool()
async with pool.acquire() as conn:
rows = await conn.fetch(
f"SELECT * FROM {params.table} "
f"WHERE search_vector @@ plainto_tsquery($1) "
f"{'AND status = $2' if params.status else ''} "
f"LIMIT ${'3' if params.status else '2'}",
params.query,
*([params.status] if params.status else []),
params.limit
)
if not rows:
return [TextContent(type="text", text="No records found.")]
formatted = "
".join(
f"- {dict(row)}" for row in rows
)
return [TextContent(
type="text",
text=f"Found {len(rows)} records:
{formatted}"
)]
Note how we use Pydantic's model_json_schema() to automatically generate the JSON Schema from the Python model. This ensures the schema stays in sync with the validation logic — a single source of truth.
Implementing Resources
Resources are read-only data that the AI can access for context. Unlike tools (which perform actions), resources provide information: configuration files, database schemas, documentation, logs, or any reference data.
from mcp.types import Resource
@app.list_resources()
async def list_resources():
return [
Resource(
uri="config://database",
name="Database Schema",
description="Current database table definitions and relationships",
mimeType="application/json"
),
Resource(
uri="logs://recent",
name="Recent Logs",
description="Application logs from the last hour",
mimeType="text/plain"
)
]
@app.read_resource()
async def read_resource(uri: str):
if uri == "config://database":
schema = await fetch_database_schema()
return json.dumps(schema, indent=2)
elif uri == "logs://recent":
logs = await fetch_recent_logs(hours=1)
return "
".join(logs)
raise ValueError(f"Unknown resource: {uri}")
Resources use URI schemes for identification. Use meaningful schemes: config:// for configuration, db:// for database information, logs:// for log data. The AI client can list available resources and read them when it needs context for a task.
Want expert help with this? Let's make it happen.
Get a Free ConsultationError Handling Patterns
MCP tools will fail — databases go down, APIs rate-limit, permissions get denied. Proper error handling is the difference between a useful tool and a frustrating one.
Return errors as TextContent with clear, actionable messages rather than raising exceptions that crash the server. The AI reads error responses and can retry or adjust its approach:
async def execute_tool_safely(name: str, arguments: dict):
try:
if name == "search_records":
return await execute_search(arguments)
except asyncpg.ConnectionError:
return [TextContent(
type="text",
text="Database connection failed. The database may be "
"temporarily unavailable. Try again in a few seconds."
)]
except asyncpg.InsufficientPrivilegeError:
return [TextContent(
type="text",
text="Permission denied for this query. The server's "
"database user lacks access to the requested table."
)]
except Exception as e:
return [TextContent(
type="text",
text=f"Unexpected error: {type(e).__name__}: {str(e)}"
)]
Authentication and Security
MCP servers often access sensitive systems — databases, APIs, internal services. Implement authentication at two levels: verifying the client connecting to your server, and authenticating your server with the services it accesses.
For client authentication, MCP supports transport-level security. When running over stdio (the most common local transport), the client is the process that launched your server — authentication is implicit. For HTTP/SSE transports, use bearer tokens validated against your auth system.
For service authentication, store credentials in environment variables, never in code. Load them at server startup and validate that all required credentials are present before accepting connections. Use the principle of least privilege: your database user should have read-only access unless write operations are explicitly needed.
Testing Your MCP Server
Test MCP servers with Claude Code directly. Add your server to the Claude Code configuration:
{
"mcpServers": {
"my-server": {
"command": "python",
"args": ["-m", "my_mcp_server.server"],
"env": {
"DATABASE_URL": "postgresql://localhost/mydb"
}
}
}
}
Then ask Claude to use your tools. Watch for: correct tool discovery, proper parameter passing, helpful error messages, and appropriate tool selection. The AI should choose your tools when they're the best fit and avoid them when they're not — a sign that your descriptions are well-written.
For automated testing, use the MCP test client to send requests directly to your server without an AI in the loop. This lets you verify individual tools in a CI/CD pipeline.
Deployment as a Pip Package
Package your server for easy distribution. The pyproject.toml should define a console script entry point so users can install and run your server with a single command:
[project.scripts]
my-mcp-server = "my_mcp_server.server:main"
After pip install my-mcp-server, users add it to their Claude Code config with just "command": "my-mcp-server". No cloning repos, no manual setup. Publish to PyPI for public servers or your organization's internal package registry for private ones.
Real-World MCP Server Examples
The MCP ecosystem is growing rapidly. Here are patterns from production servers that demonstrate advanced capabilities:
GitHub server — exposes repository data as resources (file contents, PR diffs, issue lists) and actions as tools (create PR, merge branch, comment). The key design pattern: resources for read-heavy data the AI references frequently, tools for write operations the AI triggers intentionally.
Database server — exposes schema as a resource and query/mutation tools. Uses a query allowlist to prevent destructive operations while still enabling powerful data exploration.
Monitoring server — exposes dashboards and alert configurations as resources, with tools for acknowledging alerts and creating incidents. The AI uses resource context to understand the monitoring landscape before taking action.
MCP servers are the foundation of the AI tool integration revolution. By building your business logic as MCP servers, you make it accessible to every AI assistant your team uses — now and in the future. Explore our MCP Explorer demo to see servers in action, and check our MCP development service for custom server implementations.
Related reading: MCP Protocol Explained: Building AI Tool Integrations · Building AI Chatbots for Customer Support: Architecture and ROI · Building Real-Time Dashboards with Django Channels and HTMX
Frequently asked questions
What is MCP and why should developers care about it?
Model Context Protocol (MCP) is an open standard that lets AI models connect to external tools, APIs, and data sources through a unified interface. Developers should care because it standardizes how AI integrations work — build one MCP server, and any MCP-compatible AI client can use it, reducing integration effort significantly.
How does MCP differ from regular API integrations?
Regular APIs require custom integration code for each AI model. MCP provides a standard protocol — your tools, resources, and prompts work with any MCP client (Claude, IDEs, custom apps) without rewriting integration code. It is to AI tool integration what REST was to web APIs.
Can I build an MCP server in Python?
Yes. The official MCP Python SDK makes it straightforward. Define your tools as Python functions with type hints, register them with the MCP server, and expose them over stdio or SSE transport. A basic MCP server with 3-5 tools takes about 100 lines of Python.
Full-stack developer specializing in Django, AI automation, and Google Ads management. Building production SaaS platforms and custom web applications for businesses across the US.