Mcp builder
Build MCP servers in Python with FastMCP. Define tools / resources / prompts, build the server, test locally, deploy to FastMCP Cloud or Docker. Use whenever the user mentions building an MCP server, exposing tools to LLMs, FastMCP, building a Claude integration, or troubleshooting FastMCP module-level server, storage, lifespan, middleware, OAuth, or deployment errors.
By- name:
- mcp-builder
- description:
- Build MCP servers in Python with FastMCP. Define tools / resources / prompts, build the server, test locally, deploy to FastMCP Cloud or Docker. Use whenever the user mentions building an MCP server, exposing tools to LLMs, FastMCP, building a Claude integration, or troubleshooting FastMCP module-level server, storage, lifespan, middleware, OAuth, or deployment errors.
MCP Builder
Build a working MCP server from a description of the tools you need. Produces a deployable Python server using FastMCP.
Workflow
Step 1: Define What to Expose
Ask what the server needs to provide:
- Tools -- Functions Claude can call (API wrappers, calculations, file operations)
- Resources -- Data Claude can read (database records, config, documents)
- Prompts -- Reusable prompt templates with parameters
A brief like "MCP server for querying our customer database" is enough.
Step 2: Scaffold the Server
pip install fastmcp
Create the server file. The server instance MUST be at module level:
from fastmcp import FastMCP
# MUST be at module level for FastMCP Cloud
mcp = FastMCP("My Server")
@mcp.tool()
async def search_customers(query: str) -> str:
"""Search customers by name or email."""
# Implementation here
return f"Found customers matching: {query}"
@mcp.resource("customers://{customer_id}")
async def get_customer(customer_id: str) -> str:
"""Get customer details by ID."""
return f"Customer {customer_id} details"
if __name__ == "__main__":
mcp.run()
Step 3: Add Companion CLI Scripts (Optional)
For Claude Code terminal use, add scripts alongside the MCP server:
my-mcp-server/
├── src/index.ts # MCP server (for Claude.ai)
├── scripts/
│ ├── search.ts # CLI version of search tool
│ └── _shared.ts # Shared auth/config
├── SCRIPTS.md # Documents available scripts
└── package.json
CLI scripts provide file I/O, batch processing, and richer output that MCP can't.
See assets/SCRIPTS-TEMPLATE.md and assets/script-template.ts for TypeScript templates.
Step 4: Test Locally
Quick test -- run directly:
python server.py
Dev mode with inspector UI (recommended):
fastmcp dev server.py
# Opens inspector at http://localhost:5173
# Hot reload, detailed logging, tool/resource inspection
HTTP mode for remote clients:
python server.py --transport http --port 8000
Automated test script using FastMCP Client:
import asyncio
from fastmcp import Client
async def test_server(server_path):
async with Client(server_path) as client:
# List everything
tools = await client.list_tools()
resources = await client.list_resources()
prompts = await client.list_prompts()
print(f"Tools: {[t.name for t in tools]}")
print(f"Resources: {[r.uri for r in resources]}")
print(f"Prompts: {[p.name for p in prompts]}")
# Call first tool
if tools:
result = await client.call_tool(tools[0].name, {})
print(f"Tool result: {result}")
# Read first resource
if resources:
data = await client.read_resource(resources[0].uri)
print(f"Resource data: {data}")
asyncio.run(test_server("server.py"))
Step 5: Pre-Deploy Checklist
Run these checks before deploying. All required checks must pass.
Required (will cause deploy failure):
- Server file exists
- Python syntax valid:
python3 -m py_compile server.py - Module-level server object (not inside a function):
grep -q "^mcp = FastMCP\|^server = FastMCP\|^app = FastMCP" server.py requirements.txtexists with PyPI packages only (nogit+,-e,.whl,.tar.gz)- No hardcoded secrets (check for
api_key = "..."patterns excludingos.getenv/os.environ)
Advisory (warnings):
fastmcplisted in requirements.txt.gitignoreincludes.env- No circular imports
- Git repository initialised with remote
- Server can load:
timeout 5 fastmcp inspect server.py
Step 6: Deploy
FastMCP Cloud (simplest):
git add . && git commit -m "Ready for deployment"
git push -u origin main
# Visit https://fastmcp.cloud, connect repo, add env vars, deploy
# URL: https://your-project.fastmcp.app/mcp
Cloud requirements:
- Module-level server object named
mcp,server, orapp - PyPI dependencies only in
requirements.txt - Public GitHub repository
- Environment variables for secrets (no hardcoded values)
- Auto-deploys on push to main, PR preview deployments
Docker (self-hosted):
FROM python:3.12-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install -r requirements.txt
COPY . .
EXPOSE 8000
CMD ["python", "server.py", "--transport", "http", "--port", "8000"]
Cloudflare Workers (edge):
Build it in TypeScript with Cloudflare's agents SDK (McpAgent); Cloudflare's remote MCP server docs carry the current template.
Critical Patterns
Module-Level Server Instance
FastMCP Cloud requires the server instance at module level:
# CORRECT
mcp = FastMCP("My Server")
@mcp.tool()
def my_tool(): ...
# WRONG -- Cloud can't find the server
def create_server():
mcp = FastMCP("My Server")
return mcp
# FIX for factory pattern -- export at module level
def create_server() -> FastMCP:
mcp = FastMCP("server")
return mcp
mcp = create_server()
Type Annotations Required
FastMCP uses type annotations to generate tool schemas:
@mcp.tool()
async def search(
query: str, # Required parameter
limit: int = 10, # Optional with default
tags: list[str] = [] # Complex types supported
) -> str:
"""Docstring becomes the tool description."""
...
Error Handling
Return errors as strings, don't raise exceptions:
@mcp.tool()
async def get_data(id: str) -> str:
try:
result = await fetch_data(id)
return json.dumps(result)
except NotFoundError:
return f"Error: No data found for ID {id}"
Cloud-Ready Server Pattern
import os
from fastmcp import FastMCP
mcp = FastMCP("production-server")
API_KEY = os.getenv("API_KEY")
@mcp.tool()
async def production_tool(data: str) -> dict:
if not API_KEY:
return {"error": "API_KEY not configured"}
return {"status": "success", "data": data}
if __name__ == "__main__":
mcp.run()
Common Errors and Fixes
These are the errors you will hit. Fix them before deploying.
| Error | Cause | Fix |
|---|---|---|
RuntimeError: No server object found at module level |
Server inside a function | Export mcp = FastMCP(...) at module level |
RuntimeError: no running event loop |
Missing async/await | Use async def for async operations |
TypeError: missing required argument 'context' |
Context not type-hinted | Add context: Context with type hint |
ValueError: Invalid resource URI |
Missing URI scheme | Use data://, file://, info://, api:// |
| Resource template parameter mismatch | Name mismatch | user://{user_id} needs def get_user(user_id: str) |
| Pydantic validation error | Wrong type hints | Ensure hints match actual data types |
| Transport mismatch | Client/server protocol differ | Match both to stdio or both to http |
| Import errors with editable package | Package not installed | pip install -e . or add to PYTHONPATH |
DeprecationWarning: mcp.settings |
Old API | Use os.getenv() instead |
| Port already in use | Stale process | lsof -ti:8000 | xargs kill -9 |
| Schema generation failure | Non-JSON types | Use JSON-compatible types (no NumPy arrays) |
| JSON serialization error | datetime/bytes in response | Convert to .isoformat() or string |
| Circular import | Factory in __init__.py |
Use direct imports, avoid factory pattern |
| Python 3.12+ datetime warning | datetime.utcnow() deprecated |
Use datetime.now(timezone.utc) |
| Import-time execution | Async resource at module level | Use lazy init pattern |
Production Patterns
Self-Contained Server
Keep all utilities in one file to avoid circular imports:
from fastmcp import FastMCP
import os
mcp = FastMCP("my-server")
# Config
class Config:
API_KEY = os.getenv("API_KEY", "")
BASE_URL = os.getenv("BASE_URL", "https://api.example.com")
# Helpers
def format_success(data): return {"status": "success", "data": data}
def format_error(msg): return {"status": "error", "message": msg}
@mcp.tool()
async def my_tool(query: str) -> dict:
if not Config.API_KEY:
return format_error("API_KEY not configured")
return format_success({"query": query})
Lazy Initialisation
Don't create async resources at module level. Initialise on first use:
_db = None
async def get_db():
global _db
if _db is None:
_db = await create_connection(Config.DB_URL)
return _db
Health Check Resource
@mcp.resource("health://status")
async def health_check() -> dict:
return {
"status": "healthy",
"version": "1.0.0",
"checks": {
"api": "connected",
"database": "connected"
}
}
Connection Pooling
import httpx
_client = None
def get_client() -> httpx.AsyncClient:
global _client
if _client is None:
_client = httpx.AsyncClient(
base_url=Config.BASE_URL,
headers={"Authorization": f"Bearer {Config.API_KEY}"},
limits=httpx.Limits(max_connections=20, max_keepalive_connections=5),
timeout=30.0
)
return _client
Retry with Backoff
async def retry_with_backoff(func, max_retries=3, initial_delay=1.0):
for attempt in range(max_retries):
try:
return await func()
except Exception as e:
if attempt == max_retries - 1:
raise
delay = initial_delay * (2 ** attempt)
await asyncio.sleep(delay)
Context Features (Advanced)
Context Injection
from fastmcp import Context
@mcp.tool()
async def tool_with_context(param: str, context: Context) -> dict:
# Context parameter MUST have type hint
pass
Progress Tracking
@mcp.tool()
async def long_task(items: list[str], context: Context) -> str:
for i, item in enumerate(items):
await context.report_progress(i + 1, len(items), f"Processing {item}")
await process(item)
return "Done"
Sampling (LLM from within tools)
@mcp.tool()
async def summarise(text: str, context: Context) -> str:
result = await context.request_sampling(
messages=[{"role": "user", "content": f"Summarise: {text}"}],
max_tokens=200
)
return result
CLI Quick Reference
fastmcp dev server.py # Dev mode with inspector UI
fastmcp run server.py # Run (stdio)
fastmcp run server.py --transport http --port 8000 # Run (HTTP)
fastmcp inspect server.py # Inspect without running
fastmcp install server.py # Install to Claude Desktop
fastmcp deploy server.py --name my-server # Deploy to Cloud
Environment variables: FASTMCP_LOG_LEVEL (DEBUG/INFO/WARNING/ERROR), FASTMCP_ENV (development/staging/production).
Integration Patterns (Optional)
For specific integration approaches, see references/integration-patterns.md:
- Manual API --
httpx.AsyncClientwith reusable client - OpenAPI auto-generation --
FastMCP.from_openapi(spec, client, route_maps=[...]) - FastAPI conversion --
FastMCP.from_fastapi(app)
Asset Files
assets/basic-server.py-- Minimal FastMCP server templateassets/self-contained-server.py-- Server with storage and middlewareassets/tools-examples.py-- Tool patterns and type annotationsassets/resources-examples.py-- Resource URI patternsassets/prompts-examples.py-- Prompt template patternsassets/client-example.py-- MCP client usageassets/SCRIPTS-TEMPLATE.md-- CLI companion docs templateassets/script-template.ts-- TypeScript CLI script template
Open this reference as its own page
FastMCP Integration Patterns Reference
Quick reference for API integration patterns with FastMCP.
Pattern 1: Manual API Integration
Best for simple APIs or when you need fine control.
import httpx
from fastmcp import FastMCP
mcp = FastMCP("API Integration")
# Reusable client
client = httpx.AsyncClient(
base_url="https://api.example.com",
headers={"Authorization": f"Bearer {API_KEY}"},
timeout=30.0
)
@mcp.tool()
async def fetch_data(endpoint: str) -> dict:
"""Fetch from API."""
response = await client.get(endpoint)
response.raise_for_status()
return response.json()
Pros:
- Full control over requests
- Easy to customize
- Simple to understand
Cons:
- Manual tool creation for each endpoint
- More boilerplate code
Pattern 2: OpenAPI/Swagger Auto-Generation
Best for well-documented APIs with OpenAPI specs.
from fastmcp import FastMCP
from fastmcp.server.openapi import RouteMap, MCPType
import httpx
# Load spec
spec = httpx.get("https://api.example.com/openapi.json").json()
# Create client
client = httpx.AsyncClient(
base_url="https://api.example.com",
headers={"Authorization": f"Bearer {API_KEY}"}
)
# Auto-generate server
mcp = FastMCP.from_openapi(
openapi_spec=spec,
client=client,
name="API Server",
route_maps=[
# GET + params → Resource Templates
RouteMap(
methods=["GET"],
pattern=r".*\{.*\}.*",
mcp_type=MCPType.RESOURCE_TEMPLATE
),
# GET no params → Resources
RouteMap(
methods=["GET"],
mcp_type=MCPType.RESOURCE
),
# POST/PUT/DELETE → Tools
RouteMap(
methods=["POST", "PUT", "PATCH", "DELETE"],
mcp_type=MCPType.TOOL
),
]
)
Pros:
- Instant integration (minutes not hours)
- Auto-updates with spec changes
- No manual endpoint mapping
Cons:
- Requires OpenAPI/Swagger spec
- Less control over individual endpoints
- May include unwanted endpoints
Pattern 3: FastAPI Conversion
Best for converting existing FastAPI applications.
from fastapi import FastAPI
from fastmcp import FastMCP
# Existing FastAPI app
app = FastAPI()
@app.get("/users/{user_id}")
def get_user(user_id: int):
return {"id": user_id, "name": "User"}
# Convert to MCP
mcp = FastMCP.from_fastapi(
app=app,
httpx_client_kwargs={
"headers": {"Authorization": "Bearer token"}
}
)
Pros:
- Reuse existing FastAPI code
- Minimal changes needed
- Familiar FastAPI patterns
Cons:
- FastAPI must be running separately
- Extra HTTP hop (slower)
Route Mapping Strategies
Strategy 1: By HTTP Method
route_maps = [
RouteMap(methods=["GET"], mcp_type=MCPType.RESOURCE),
RouteMap(methods=["POST"], mcp_type=MCPType.TOOL),
RouteMap(methods=["PUT", "PATCH"], mcp_type=MCPType.TOOL),
RouteMap(methods=["DELETE"], mcp_type=MCPType.TOOL),
]
Strategy 2: By Path Pattern
route_maps = [
# Admin endpoints → Exclude
RouteMap(
pattern=r"/admin/.*",
mcp_type=MCPType.EXCLUDE
),
# Internal → Exclude
RouteMap(
pattern=r"/internal/.*",
mcp_type=MCPType.EXCLUDE
),
# Health → Exclude
RouteMap(
pattern=r"/(health|healthz)",
mcp_type=MCPType.EXCLUDE
),
# Everything else
RouteMap(mcp_type=MCPType.TOOL),
]
Strategy 3: By Parameters
route_maps = [
# Has path parameters → Resource Template
RouteMap(
pattern=r".*\{[^}]+\}.*",
mcp_type=MCPType.RESOURCE_TEMPLATE
),
# No parameters → Static Resource or Tool
RouteMap(
methods=["GET"],
mcp_type=MCPType.RESOURCE
),
RouteMap(
methods=["POST", "PUT", "DELETE"],
mcp_type=MCPType.TOOL
),
]
Authentication Patterns
API Key Authentication
client = httpx.AsyncClient(
base_url="https://api.example.com",
headers={"X-API-Key": os.getenv("API_KEY")}
)
Bearer Token
client = httpx.AsyncClient(
base_url="https://api.example.com",
headers={"Authorization": f"Bearer {os.getenv('API_TOKEN')}"}
)
OAuth2 with Token Refresh
class OAuth2Client:
def __init__(self):
self.access_token = None
self.expires_at = None
async def get_token(self) -> str:
if not self.expires_at or datetime.now() > self.expires_at:
await self.refresh_token()
return self.access_token
async def refresh_token(self):
async with httpx.AsyncClient() as client:
response = await client.post(
"https://auth.example.com/token",
data={
"grant_type": "client_credentials",
"client_id": CLIENT_ID,
"client_secret": CLIENT_SECRET
}
)
data = response.json()
self.access_token = data["access_token"]
self.expires_at = datetime.now() + timedelta(
seconds=data["expires_in"] - 60
)
oauth = OAuth2Client()
@mcp.tool()
async def authenticated_request(endpoint: str) -> dict:
token = await oauth.get_token()
async with httpx.AsyncClient() as client:
response = await client.get(
endpoint,
headers={"Authorization": f"Bearer {token}"}
)
return response.json()
Error Handling Patterns
Basic Error Handling
@mcp.tool()
async def safe_api_call(endpoint: str) -> dict:
try:
response = await client.get(endpoint)
response.raise_for_status()
return {"success": True, "data": response.json()}
except httpx.HTTPStatusError as e:
return {
"success": False,
"error": f"HTTP {e.response.status_code}",
"message": e.response.text
}
except httpx.TimeoutException:
return {"success": False, "error": "Request timeout"}
except Exception as e:
return {"success": False, "error": str(e)}
Retry with Exponential Backoff
async def retry_with_backoff(func, max_retries=3):
delay = 1.0
for attempt in range(max_retries):
try:
return await func()
except (httpx.TimeoutException, httpx.NetworkError) as e:
if attempt < max_retries - 1:
await asyncio.sleep(delay)
delay *= 2
else:
raise
Caching Patterns
Simple Time-Based Cache
import time
class SimpleCache:
def __init__(self, ttl=300):
self.cache = {}
self.timestamps = {}
self.ttl = ttl
def get(self, key: str):
if key in self.cache:
if time.time() - self.timestamps[key] < self.ttl:
return self.cache[key]
return None
def set(self, key: str, value):
self.cache[key] = value
self.timestamps[key] = time.time()
cache = SimpleCache()
@mcp.tool()
async def cached_fetch(endpoint: str) -> dict:
# Check cache
cached = cache.get(endpoint)
if cached:
return {"data": cached, "from_cache": True}
# Fetch from API
data = await fetch_from_api(endpoint)
cache.set(endpoint, data)
return {"data": data, "from_cache": False}
Rate Limiting Patterns
Simple Rate Limiter
from collections import deque
from datetime import datetime, timedelta
class RateLimiter:
def __init__(self, max_requests: int, time_window: int):
self.max_requests = max_requests
self.time_window = timedelta(seconds=time_window)
self.requests = deque()
async def acquire(self):
now = datetime.now()
# Remove old requests
while self.requests and now - self.requests[0] > self.time_window:
self.requests.popleft()
# Check limit
if len(self.requests) >= self.max_requests:
sleep_time = (self.requests[0] + self.time_window - now).total_seconds()
await asyncio.sleep(sleep_time)
return await self.acquire()
self.requests.append(now)
limiter = RateLimiter(100, 60) # 100 requests per minute
@mcp.tool()
async def rate_limited_call(endpoint: str) -> dict:
await limiter.acquire()
return await api_call(endpoint)
Connection Pooling
Singleton Client Pattern
class APIClient:
_instance = None
@classmethod
async def get_client(cls):
if cls._instance is None:
cls._instance = httpx.AsyncClient(
base_url=API_BASE_URL,
timeout=30.0,
limits=httpx.Limits(
max_keepalive_connections=5,
max_connections=10
)
)
return cls._instance
@classmethod
async def cleanup(cls):
if cls._instance:
await cls._instance.aclose()
cls._instance = None
# Use in tools
@mcp.tool()
async def api_request(endpoint: str) -> dict:
client = await APIClient.get_client()
response = await client.get(endpoint)
return response.json()
Batch Request Patterns
Parallel Batch Requests
@mcp.tool()
async def batch_fetch(endpoints: list[str]) -> dict:
"""Fetch multiple endpoints in parallel."""
async def fetch_one(endpoint: str):
try:
response = await client.get(endpoint)
return {"endpoint": endpoint, "success": True, "data": response.json()}
except Exception as e:
return {"endpoint": endpoint, "success": False, "error": str(e)}
results = await asyncio.gather(*[fetch_one(ep) for ep in endpoints])
return {
"total": len(endpoints),
"successful": len([r for r in results if r["success"]]),
"results": results
}
Webhook Patterns
Webhook Receiver
from fastapi import FastAPI, Request
app = FastAPI()
@app.post("/webhook")
async def handle_webhook(request: Request):
data = await request.json()
# Process webhook
return {"status": "received"}
# Add to MCP server
mcp = FastMCP.from_fastapi(app)
When to Use Each Pattern
| Pattern | Use When | Avoid When |
|---|---|---|
| Manual Integration | Simple API, custom logic needed | API has 50+ endpoints |
| OpenAPI Auto-gen | Well-documented API, many endpoints | No OpenAPI spec available |
| FastAPI Conversion | Existing FastAPI app | Starting from scratch |
| Custom Route Maps | Need precise control | Simple use case |
| Connection Pooling | High-frequency requests | Single request needed |
| Caching | Expensive API calls, data rarely changes | Real-time data required |
| Rate Limiting | API has rate limits | No limits or internal API |
Resources
- FastMCP OpenAPI: FastMCP.from_openapi documentation
- FastAPI Integration: FastMCP.from_fastapi documentation
- HTTPX Docs: https://www.python-httpx.org
- OpenAPI Spec: https://spec.openapis.org
More in this playbook
Cross crm opportunity sync
Coordinate opportunities and customer records across multiple CRMs while preserving attribution, visibility, commissions, and governance.
IntegrationsMIT Wade Foster + 1Co-founder & CEO @ ZapierInstall zapier
Install and connect Zapier, routing to the right surface (MCP, SDK, or CLI) for what the person needs. Use when someone says "install Zapier", "add Zapier", "connect Zapier", or "set up Zapier", or when they want an AI client (Claude, ChatGPT, Cursor) to use their apps, want to call Zapier from code, or want Zapier in the terminal.
IntegrationsMIT Wade Foster + 1Co-founder & CEO @ ZapierMcp sheet cache bridge
Keep Zapier Tables or another MCP-connected record store as the source of truth while Google Sheets-based tools read an event-driven cache tab.

