Convert Django REST Framework (drf-spectacular) to MCP
Turn Django REST Framework ViewSets and Serializers (exported via drf-spectacular) into an async Python FastMCP server without touching your Django WSGI/ASGI stack.
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 Django DRF OpenAPI spec
Run python manage.py spectacular --format openapi-json --file schema.json and upload schema.json above.
High-Signal Django DRF MCP Tools to Expose First
| Method | Endpoint Path | MCP Tool Name | Purpose |
|---|---|---|---|
| GET | /api/projects/ | list_projects | DRF ModelViewSet list action |
| POST | /api/projects/ | create_project | DRF Serializer create action |
| PATCH | /api/projects/{id}/ | partial_update_project | Partial serializer update |
Best Practices for Django DRF
- Use drf-spectacular's --format openapi-json flag to export clean JSON ready for Spec2MCP.
- If your Django API uses DRF's classic TokenAuthentication (Authorization: Token <key>), replace 'Bearer ' with 'Token ' in build_auth_headers() (one-line tweak).
- Keep Django trailing slashes consistent in your OpenAPI paths (e.g., /api/tasks/) to avoid POST 301 redirect drops.
Common Django DRF MCP Gotchas
- Django APPEND_SLASH redirects POST requests missing a trailing slash—keep the exact paths exported by drf-spectacular.
- DRF ModelViewSet generates 6 endpoints per model (list, create, retrieve, update, partial_update, destroy); uncheck PUT if you already expose PATCH to save 15% of tool tokens.
- Use Django's SimpleJWT Bearer tokens or scoped API keys instead of superuser credentials.
Django REST Framework to MCP Server — Frequently Asked Questions
How do I get OpenAPI JSON from Django REST Framework?
Install drf-spectacular and run python manage.py spectacular --format openapi-json --file schema.json.
Why disable PUT when PATCH is already enabled on DRF ViewSets?
LLMs perform better with PATCH (partial updates) than full-object PUT replacements, and disabling redundant PUT endpoints cuts your MCP tool token footprint significantly.
Can I run the generated FastMCP server inside the same Python repo as Django?
Yes—save server.py in an mcp/ subdirectory and run it via uv or your existing virtualenv.
Related OpenAPI-to-MCP Converters
View all 20FastAPI HTTPBearer / OAuth2PasswordBearer / APIKeyHeader
Environment-variable Bearer, API Key, or Basic Auth headers
Rails Bearer API Token or X-Api-Key header
Laravel Sanctum / Passport Bearer Token
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