Registering Existing REST APIs as MCP Servers
The most common real-world scenario: you have existing REST APIs and want to expose them via MCP so AI agents can use them.
Pattern: REST API Wrapper
# Wrap any REST API as an MCP server
from mcp.server import Server
from mcp.server.sse import SseServerTransport
from mcp.types import Tool, TextContent
from starlette.applications import Starlette
from starlette.routing import Route, Mount
from starlette.requests import Request
from starlette.responses import JSONResponse
import httpx
import uvicorn
server = Server("api-gateway-mcp")
sse = SseServerTransport("/messages/")
# Configuration: your existing REST APIs
API_BASE = "https://api.yourcompany.com/v1"
API_KEY = "your-api-key"
@server.list_tools()
async def list_tools():
return [
Tool(
name="get_customers",
description="Fetch customers. Optional filters: status, plan, limit",
inputSchema={
"type": "object",
"properties": {
"status": {"type": "string", "enum": ["active", "inactive", "all"]},
"plan": {"type": "string", "enum": ["free", "pro", "enterprise"]},
"limit": {"type": "integer", "default": 10}
}
}
),
Tool(
name="get_customer_by_id",
description="Fetch a single customer by their ID",
inputSchema={
"type": "object",
"properties": {
"customer_id": {"type": "string"}
},
"required": ["customer_id"]
}
),
Tool(
name="create_customer",
description="Create a new customer record",
inputSchema={
"type": "object",
"properties": {
"name": {"type": "string"},
"email": {"type": "string", "format": "email"},
"plan": {"type": "string", "enum": ["free", "pro", "enterprise"]}
},
"required": ["name", "email", "plan"]
}
),
Tool(
name="update_customer",
description="Update an existing customer's information",
inputSchema={
"type": "object",
"properties": {
"customer_id": {"type": "string"},
"name": {"type": "string"},
"email": {"type": "string"},
"plan": {"type": "string"}
},
"required": ["customer_id"]
}
),
Tool(
name="get_invoices",
description="Get invoices for a customer",
inputSchema={
"type": "object",
"properties": {
"customer_id": {"type": "string"},
"status": {"type": "string", "enum": ["paid", "pending", "overdue"]}
},
"required": ["customer_id"]
}
)
]
@server.call_tool()
async def call_tool(name: str, arguments: dict):
headers = {"Authorization": f"Bearer {API_KEY}", "Content-Type": "application/json"}
async with httpx.AsyncClient() as client:
if name == "get_customers":
params = {k: v for k, v in arguments.items() if v is not None}
resp = await client.get(f"{API_BASE}/customers", headers=headers, params=params)
elif name == "get_customer_by_id":
resp = await client.get(
f"{API_BASE}/customers/{arguments['customer_id']}", headers=headers
)
elif name == "create_customer":
resp = await client.post(f"{API_BASE}/customers", headers=headers, json=arguments)
elif name == "update_customer":
cid = arguments.pop("customer_id")
resp = await client.patch(
f"{API_BASE}/customers/{cid}", headers=headers, json=arguments
)
elif name == "get_invoices":
cid = arguments["customer_id"]
params = {"status": arguments.get("status")}
resp = await client.get(
f"{API_BASE}/customers/{cid}/invoices", headers=headers, params=params
)
else:
return [TextContent(type="text", text=f"Unknown tool: {name}")]
if resp.status_code >= 400:
return [TextContent(type="text", text=f"API Error {resp.status_code}: {resp.text}")]
return [TextContent(type="text", text=resp.text)]
async def handle_sse(request: Request):
async with sse.connect_sse(request.scope, request.receive, request._send) as streams:
await server.run(streams[0], streams[1])
async def health(request: Request):
return JSONResponse({"status": "ok"})
app = Starlette(routes=[
Route("/health", health),
Route("/sse", handle_sse),
Mount("/messages/", app=sse.handle_post_message),
])
if __name__ == "__main__":
uvicorn.run(app, host="0.0.0.0", port=8000)
Auto-Generating MCP Server from OpenAPI Spec
If your REST API has an OpenAPI/Swagger spec, you can auto-generate the MCP server:
# openapi_to_mcp.py
import yaml
import httpx
from mcp.server import Server
from mcp.server.sse import SseServerTransport
from mcp.types import Tool, TextContent
from starlette.applications import Starlette
from starlette.routing import Route, Mount
from starlette.requests import Request
from starlette.responses import JSONResponse
import uvicorn
# Load OpenAPI spec
with open("openapi.yaml") as f:
spec = yaml.safe_load(f)
server = Server("openapi-mcp-server")
sse = SseServerTransport("/messages/")
BASE_URL = spec["servers"][0]["url"]
def build_tools_from_spec(spec):
"""Convert OpenAPI paths to MCP tools."""
tools = []
tool_map = {} # name -> (method, path, params)
for path, methods in spec.get("paths", {}).items():
for method, details in methods.items():
if method not in ["get", "post", "put", "patch", "delete"]:
continue
operation_id = details.get("operationId", f"{method}_{path.replace('/', '_')}")
description = details.get("summary", details.get("description", ""))
# Build input schema from parameters and request body
properties = {}
required = []
for param in details.get("parameters", []):
properties[param["name"]] = {
"type": param["schema"].get("type", "string"),
"description": param.get("description", "")
}
if param.get("required"):
required.append(param["name"])
if "requestBody" in details:
body_schema = details["requestBody"]["content"]["application/json"]["schema"]
if "properties" in body_schema:
properties.update(body_schema["properties"])
required.extend(body_schema.get("required", []))
tools.append(Tool(
name=operation_id,
description=description,
inputSchema={"type": "object", "properties": properties, "required": required}
))
tool_map[operation_id] = (method, path, details.get("parameters", []))
return tools, tool_map
TOOLS, TOOL_MAP = build_tools_from_spec(spec)
@server.list_tools()
async def list_tools():
return TOOLS
@server.call_tool()
async def call_tool(name: str, arguments: dict):
if name not in TOOL_MAP:
return [TextContent(type="text", text=f"Unknown tool: {name}")]
method, path, params = TOOL_MAP[name]
# Replace path parameters
url = BASE_URL + path
query_params = {}
body = {}
for param in params:
value = arguments.get(param["name"])
if value is None:
continue
if param["in"] == "path":
url = url.replace(f"{{{param['name']}}}", str(value))
elif param["in"] == "query":
query_params[param["name"]] = value
# Remaining arguments go to request body
for key in arguments:
if key not in [p["name"] for p in params]:
body[key] = arguments[key]
async with httpx.AsyncClient() as client:
resp = await getattr(client, method)(url, params=query_params, json=body or None)
return [TextContent(type="text", text=resp.text)]
async def handle_sse(request: Request):
async with sse.connect_sse(request.scope, request.receive, request._send) as streams:
await server.run(streams[0], streams[1])
app = Starlette(routes=[
Route("/health", lambda r: JSONResponse({"status": "ok"})),
Route("/sse", handle_sse),
Mount("/messages/", app=sse.handle_post_message),
])
if __name__ == "__main__":
uvicorn.run(app, host="0.0.0.0", port=8000)
Client Configuration for Remote MCP Servers
Claude Desktop (remote SSE server):
{
"mcpServers": {
"my-api": {
"url": "http://your-server.com:8000/sse"
}
}
}
Cursor IDE:
{
"mcpServers": {
"my-api": {
"url": "http://your-server.com:8000/sse"
}
}
}