MCP Server Development
Python (FastMCP)
Quick Start
uv init mcp-server && cd mcp-server
uv add "mcp[cli]" httpx
Complete Server
from mcp.server.fastmcp import FastMCP
mcp = FastMCP("my-server")
@mcp.tool()
async def search_docs(query: str, limit: int = 10) -> str:
"""Search documentation for relevant content.
Args:
query: Search query string
limit: Maximum results to return
"""
# Implementation
return f"Found {limit} results for: {query}"
@mcp.resource("config://settings")
def get_settings() -> str:
"""Get application settings."""
return '{"theme": "dark", "language": "en"}'
@mcp.resource("file://documents/{name}")
def read_document(name: str) -> str:
"""Read a document by name."""
return f"Content of {name}"
@mcp.prompt()
def review_code(code: str, language: str = "python") -> str:
"""Generate a code review prompt."""
return f"Review this {language} code for bugs and improvements:\n```{language}\n{code}\n```"
if __name__ == "__main__":
mcp.run(transport="stdio")
Progress Reporting
from mcp.server.fastmcp import Context
from mcp.server.session import ServerSession
@mcp.tool()
async def long_task(name: str, ctx: Context[ServerSession, None]) -> str:
"""Task with progress updates."""
for i in range(5):
await ctx.report_progress(progress=(i+1)/5, total=1.0)
await ctx.info(f"Step {i+1}/5")
return f"Task '{name}' completed"
Lifespan Management
from contextlib import asynccontextmanager
from dataclasses import dataclass
@dataclass
class AppContext:
db: Database
@asynccontextmanager
async def app_lifespan(server: FastMCP):
db = await Database.connect()
try:
yield AppContext(db=db)
finally:
await db.disconnect()
mcp = FastMCP("My App", lifespan=app_lifespan)
@mcp.tool()
def query(ctx: Context[ServerSession, AppContext]) -> str:
db = ctx.request_context.lifespan_context.db
return db.query("SELECT 1")
TypeScript
Quick Start
npm install @modelcontextprotocol/sdk zod
Complete Server
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import { z } from "zod";
const server = new McpServer({ name: "my-server", version: "1.0.0" });
server.registerTool(
"search_docs",
{
description: "Search documentation",
inputSchema: {
query: z.string().describe("Search query"),
limit: z.number().min(1).max(100).default(10).describe("Max results"),
},
},
async ({ query, limit }) => ({
content: [{ type: "text", text: `Found ${limit} results for: ${query}` }],
}),
);
const transport = new StdioServerTransport();
await server.connect(transport);
Transport Options
mcp.run(transport="stdio") # Standard I/O (default)
mcp.run(transport="streamable-http") # HTTP with streaming
mcp.run(transport="sse") # Server-Sent Events
Error Handling
Two categories:
- Protocol errors — JSON-RPC error (tool not found, server issues)
- Tool execution errors —
isError: truein result (LLM can self-correct)
@mcp.tool()
async def safe_tool(path: str) -> str:
try:
return read_file(path)
except FileNotFoundError:
# Return as tool error, not protocol error
return f"Error: File '{path}' not found. Available files: {list_files()}"
Testing
npx -y @modelcontextprotocol/inspector # MCP Inspector
Claude Code Integration
claude mcp add my-server -- python server.py
claude mcp add -e API_KEY=xxx my-server -- npx my-mcp-server
claude mcp add --transport http remote https://example.com/mcp
claude mcp list
Design Principles (Anthropic)
- ACI > HCI: Invest as much in agent-computer interfaces as human-computer interfaces
- Poka-yoke: Structurally prevent errors (e.g., require absolute paths)
- Descriptions are prompts: Write tool descriptions for a junior developer
- Natural formats: Avoid formats requiring accurate counting
- Iterate on errors: Spend more time optimizing tools than prompts