Build an MCP Server for a REST API
A common production pattern is to keep your existing business API and add an MCP layer specifically designed for agents.
import os
import httpx
from mcp.server import MCPServer
mcp = MCPServer("Orders")
BASE_URL = os.environ["ORDERS_API_URL"]
TOKEN = os.environ["ORDERS_API_TOKEN"]
@mcp.tool()
async def get_order(order_id: str) -> dict:
"""Fetch one order by its public order ID."""
async with httpx.AsyncClient(timeout=10) as client:
r = await client.get(
f"{BASE_URL}/orders/{order_id}",
headers={"Authorization": f"Bearer {TOKEN}"},
)
r.raise_for_status()
return r.json()Do not mirror every endpoint
Create agent-oriented operations rather than one MCP tool per REST route. A tool can orchestrate several backend calls when that creates a coherent task boundary.
Normalize errors
Translate downstream 404s, validation failures, and service outages into concise tool errors. Avoid returning raw stack traces or internal headers.
Use explicit timeouts
Every external HTTP call should have a timeout. For idempotent reads you may add bounded retries; for mutations, use downstream idempotency keys before retrying automatically.
SSRF warning: do not accept arbitrary URLs from the model and fetch them with privileged server credentials.