Turn Your FastAPI /openapi.json into an MCP Server
Every FastAPI application already exposes a rich OpenAPI 3.1 schema at /openapi.json. Compile it directly into a standalone, decoupled FastMCP or TypeScript MCP server.
MCP Tool Selection
10 / 10 Free12 endpoints parsed • 1 safety-guarded
12 endpoints detected — Free tier compiles up to 10
Unlock unlimited endpoints, hosted Remote MCP URL, OAuth2 proxy & GitHub CI auto-sync with Pro Cloud.
List workspace tasks with status & assignee filters
Create a new engineering or CRM task
Get task details and subtasks
Update task status, priority, or assignee
Permanently delete a task
List active workspace projects
Create a new project milestone
Search CRM contacts by email or company
Add a new CRM contact
List pipeline deals and ARR values
Attach a call summary or note to a deal
GDPR purge a CRM contact record
1"""2Generated by Spec2MCP (https://spec2mcp.com)3Server: workspace-crm-tasks-api v2.1.04Tools exposed: 105"""6from __future__ import annotations78import json9import os10from typing import Any, Optional11from urllib.parse import quote1213import httpx14from mcp.server.fastmcp import FastMCP1516BASE_URL = os.environ.get("WORKSPACE_CRM_TASKS_API_BASE_URL", "https://api.workspace-crm.example.com/v2").rstrip("/")17API_KEY = os.environ.get("WORKSPACE_CRM_TASKS_API_API_KEY", "")18def build_auth_headers() -> dict[str, str]:19return {"X-Workspace-Key": API_KEY} if API_KEY else {}2021mcp = FastMCP("workspace-crm-tasks-api")222324async def call_upstream(25method: str,26path: str,27params: Optional[dict[str, Any]] = None,28json_body: Optional[dict[str, Any]] = None,29) -> str:30url = f"{BASE_URL}{path}"31headers = {32"Accept": "application/json",33"User-Agent": "spec2mcp/workspace-crm-tasks-api",34**build_auth_headers(),35}36try:37async with httpx.AsyncClient(timeout=20.0) as client:38response = await client.request(39method=method,40url=url,41headers=headers,42params=params,43json=json_body,44)45try:46body_text = json.dumps(response.json(), indent=2)47except Exception:48body_text = response.text4950if response.is_error:51return f"HTTP {response.status_code} from {method} {path}\n{body_text}"52return body_text or f"HTTP {response.status_code} (empty body)"53except httpx.HTTPError as exc:54return f"Network error calling {method} {url}: {exc}"555657@mcp.tool(name="list_tasks")58async def list_tasks(status: Optional[str] = None, assignee_id: Optional[str] = None, limit: Optional[int] = None) -> str:59"""List workspace tasks with status & assignee filters [GET /tasks]"""60query_params: dict[str, Any] = {}61if status is not None:62query_params["status"] = status63if assignee_id is not None:64query_params["assignee_id"] = assignee_id65if limit is not None:66query_params["limit"] = limit67return await call_upstream(method="GET", path="/tasks", params=query_params)686970@mcp.tool(name="create_task")71async def create_task(title: str, project_id: str, priority: Optional[int] = None, due_date: Optional[str] = None) -> str:72"""Create a new engineering or CRM task [POST /tasks]"""73json_body: dict[str, Any] = {}74if title is not None:75json_body["title"] = title76if project_id is not None:77json_body["project_id"] = project_id78if priority is not None:79json_body["priority"] = priority80if due_date is not None:81json_body["due_date"] = due_date82return await call_upstream(method="POST", path="/tasks", json_body=json_body)838485@mcp.tool(name="get_task")86async def get_task(task_id: str) -> str:87"""Get task details and subtasks [GET /tasks/{task_id}]"""88return await call_upstream(method="GET", path=f"/tasks/{quote(str(task_id), safe="")}")899091@mcp.tool(name="update_task")92async def update_task(task_id: str, status: Optional[str] = None, priority: Optional[int] = None, assignee_id: Optional[str] = None) -> str:93"""Update task status, priority, or assignee [PATCH /tasks/{task_id}]"""94json_body: dict[str, Any] = {}95if status is not None:96json_body["status"] = status97if priority is not None:98json_body["priority"] = priority99if assignee_id is not None:100json_body["assignee_id"] = assignee_id101return await call_upstream(method="PATCH", path=f"/tasks/{quote(str(task_id), safe="")}", json_body=json_body)102103104@mcp.tool(name="delete_task")105async def delete_task(task_id: str, confirm_destructive_action: bool = False) -> str:106"""Permanently delete a task [DELETE /tasks/{task_id}]"""107if not confirm_destructive_action:108return "Blocked by safety guard: set confirm_destructive_action=True after user confirmation."109return await call_upstream(method="DELETE", path=f"/tasks/{quote(str(task_id), safe="")}")110111112@mcp.tool(name="list_projects")113async def list_projects(archived: Optional[bool] = None) -> str:114"""List active workspace projects [GET /projects]"""115query_params: dict[str, Any] = {}116if archived is not None:117query_params["archived"] = archived118return await call_upstream(method="GET", path="/projects", params=query_params)119120121@mcp.tool(name="create_project")122async def create_project(name: str, lead_id: Optional[str] = None) -> str:123"""Create a new project milestone [POST /projects]"""124json_body: dict[str, Any] = {}125if name is not None:126json_body["name"] = name127if lead_id is not None:128json_body["lead_id"] = lead_id129return await call_upstream(method="POST", path="/projects", json_body=json_body)130131132@mcp.tool(name="search_crm_contacts")133async def search_crm_contacts(q: Optional[str] = None, stage: Optional[str] = None) -> str:134"""Search CRM contacts by email or company [GET /contacts]"""135query_params: dict[str, Any] = {}136if q is not None:137query_params["q"] = q138if stage is not None:139query_params["stage"] = stage140return await call_upstream(method="GET", path="/contacts", params=query_params)141142143@mcp.tool(name="create_crm_contact")144async def create_crm_contact(email: str, full_name: str, company: Optional[str] = None) -> str:145"""Add a new CRM contact [POST /contacts]"""146json_body: dict[str, Any] = {}147if email is not None:148json_body["email"] = email149if full_name is not None:150json_body["full_name"] = full_name151if company is not None:152json_body["company"] = company153return await call_upstream(method="POST", path="/contacts", json_body=json_body)154155156@mcp.tool(name="list_deals")157async def list_deals(stage: Optional[str] = None) -> str:158"""List pipeline deals and ARR values [GET /deals]"""159query_params: dict[str, Any] = {}160if stage is not None:161query_params["stage"] = stage162return await call_upstream(method="GET", path="/deals", params=query_params)163164165if __name__ == "__main__":166mcp.run(transport="stdio")167
How to export & compile your FastAPI OpenAPI spec
Run curl http://localhost:8000/openapi.json > openapi.json while FastAPI is running, then upload it in the studio above.
High-Signal FastAPI MCP Tools to Expose First
| Method | Endpoint Path | MCP Tool Name | Purpose |
|---|---|---|---|
| GET | /api/v1/items | list_items | Auto-exported from @app.get('/api/v1/items') |
| POST | /api/v1/items | create_item | Pydantic BaseModel unpacked into FastMCP args |
| DELETE | /api/v1/items/{item_id} | delete_item | Guarded delete route with confirmation flag |
Best Practices for FastAPI
- Give every FastAPI route an explicit operation_id and summary= so generated MCP tool names stay clean instead of auto-suffixed.
- FastAPI Pydantic models serialize into #/components/schemas/... references—Spec2MCP resolves all local $refs automatically.
- Keep your MCP server decoupled from FastAPI internals so you can iterate on prompts, safety guards, and auth without redeploying your core API.
Common FastAPI MCP Gotchas
- FastAPI defaults to OpenAPI 3.1 with anyOf: [{type: 'string'}, {type: 'null'}] for Optional fields; Spec2MCP normalizes nullable types cleanly.
- If your FastAPI app runs locally on port 8000, set BASE_URL to http://127.0.0.1:8000 in mcp.json so Claude Desktop can reach it.
- Exclude healthcheck routes (/health, /metrics) in the endpoint checklist so they don't waste tool tokens.
FastAPI to MCP Server — Frequently Asked Questions
Why generate a standalone MCP server instead of mounting MCP inside FastAPI?
A standalone stdio MCP server works instantly with Claude Desktop and Cursor against localhost or staging without adding MCP runtime dependencies to your production FastAPI container.
Does Spec2MCP handle FastAPI's OpenAPI 3.1 output?
Yes. Spec2MCP resolves OpenAPI 3.0 and 3.1 schemas, including component schema $ref links and array type declarations.
Should I output Python FastMCP or TypeScript for a FastAPI backend?
Both work identically over HTTP, though Python teams typically pick server.py (FastMCP + httpx) to keep a single language across the repo.
Related OpenAPI-to-MCP Converters
View all 20Environment-variable Bearer, API Key, or Basic Auth headers
DRF Token / JWT Bearer / API Key Header
NestJS JwtAuthGuard (Bearer) or ApiKeyGuard header
JWT Bearer Token or X-API-Key middleware header
Free locally forever. Upgrade when your team goes remote.
Compile focused local TypeScript & Python MCP servers in your browser for $0. Move to Pro Cloud or Team when you need unlimited endpoints, hosted Remote MCP URLs, OAuth2 proxying, and CI sync.
Everything solo engineers need to turn REST APIs into local stdio MCP servers with zero login.
- Local TypeScript SDK + Zod codegen
- Local Python FastMCP + httpx codegen
- Up to 10 endpoints per MCP server
- Live context-window token estimator
- Destructive action confirmation guards
- Claude Desktop, Cursor, Windsurf & Antigravity mcp.json
- 100% client-side — specs stay in browser
Compile unlimited endpoints and publish a hosted Remote MCP URL with encrypted credential vaulting.
- Unlimited OpenAPI endpoints & tool grouping
- 1-click hosted Remote MCP endpoint (Streamable HTTP)
- Encrypted OAuth2 & API-Key secret vault
- Custom tool presets & OpenAPI overlay persistence
- Response payload truncation to stop context blowups
- Priority email & Discord support
Built for engineering orgs keeping internal MCP servers automatically synced with OpenAPI repos.
- Everything in Pro Cloud
- GitHub / GitLab CI auto-sync on OpenAPI PR merges
- Per-tool invocation audit logs & latency metrics
- Per-user rate limits & destructive-tool approval policies
- Role-based access across engineering & ops teams
- Dedicated onboarding & custom auth helpers