[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M77SQVDV0MHDFH1TYEWPAG2T":3,"skill-same:01M77SQVDV0MHDFH1TYEWPAG2T":61},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":9,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":15,"categories":16,"keywords":17,"publishedAt":18,"linkOnly":19,"markdownContent":20,"markdownBody":21,"frontMatter":22,"refName":29,"commitSha":30,"skillDirectory":31,"forksCount":13,"repositoryHtmlUrl":32,"repositoryHomepageUrl":6,"ownerHtmlUrl":33,"ownerBlogUrl":6,"ownerDescription":6,"updatedAt":34,"install":35,"resources":48},"01M77SQVDV0MHDFH1TYEWPAG2T","fastmcp-django",null,"Use when adding, changing, deploying, testing, or debugging FastMCP MCP servers in existing Django apps, including ASGI mounting, stdio or sidecar servers, Django ORM access from MCP tools, auth and permissions, Streamable HTTP deployment, and MCP client tests.","ConcertoNotes\u002Fcodex-plugins","ConcertoNotes","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F249301288?v=4","01M77NJ0BK2KN5YW0D8RHD99TB","01M77NJ0CCEDPATAY3JTXEWNK5",0,"MIT","https:\u002F\u002Fgithub.com\u002FConcertoNotes\u002Fcodex-plugins\u002Fblob\u002Fmain\u002Fplugins\u002Fcommunity\u002Flvtd-skills\u002Fskills\u002Ffastmcp-django\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"---\nname: fastmcp-django\ndescription: Use when adding, changing, deploying, testing, or debugging FastMCP MCP servers in existing Django apps, including ASGI mounting, stdio or sidecar servers, Django ORM access from MCP tools, auth and permissions, Streamable HTTP deployment, and MCP client tests.\nlicense: MIT\ncompatibility: Codex, Claude Code, and other Agent Skills-compatible clients.\nmetadata:\n  version: \"0.1.0\"\n  displayName: FastMCP Django\n  category: Django\n  tags: fastmcp,django,mcp,asgi\n---\n\n# FastMCP with Django\n\nUse this when exposing Django application capabilities to agents through MCP.\nKeep Django as the source of truth for auth, permissions, validation, models,\ntransactions, and business rules. Use FastMCP as the protocol layer around\nsmall, typed capabilities.\n\n## Tool Choice\n\n- Prefer the standalone `fastmcp` package (`from fastmcp import FastMCP`) for\n  new Python MCP work in Django. It is the actively maintained FastMCP project\n  and includes HTTP transport, clients, auth helpers, CLI tooling, testing\n  utilities, server composition, and OpenAPI\u002FFastAPI conversion features.\n- Use the official MCP Python SDK (`from mcp.server.fastmcp import FastMCP`)\n  when the project has already standardized on it, when you need lower-level\n  protocol control, or when a host explicitly requires SDK behavior.\n- Consider `django-mcp-server` only when the project needs a Django-native\n  package that works inside WSGI or declaratively exposes models\u002FDRF APIs. Audit\n  its security model and generated tool contracts before exposing private data.\n- If the app already has a deliberate public OpenAPI surface, generating or\n  proxying tools from that API can be useful for a first pass. For production\n  agents, prefer hand-curated tools with purpose-built names, input schemas,\n  permission checks, and bounded outputs.\n\nFastMCP docs track the project's `main` branch, so re-check the current docs\nwhen relying on recently added features or version badges.\n\n## Implementation Workflow\n\n1. Read the existing Django entrypoints first: `manage.py`, `settings.py`,\n   `asgi.py`, `wsgi.py`, URL routing, auth middleware, DRF\u002FNinja APIs, Celery or\n   Django Q tasks, and deployment files.\n2. Choose the transport boundary:\n   - Use stdio for a local desktop\u002Feditor MCP server that runs beside the app.\n   - Use a separate FastMCP HTTP sidecar when the Django deployment is WSGI-only\n     or when MCP should scale independently.\n   - Mount FastMCP into the Django ASGI process when the app already runs under\n     ASGI and sharing the same domain\u002Fprocess is intentional.\n3. Put MCP server registration in a small module such as `apps\u002Fcore\u002Fmcp.py` or\n   `project\u002Fmcp.py`. Keep tool bodies thin and call existing services,\n   selectors, forms, serializers, policies, or domain functions.\n4. Make every exposed capability explicit. Avoid generic SQL, generic model\n   browsing, arbitrary imports, file path access, or \"admin\" tools unless the\n   project has a clear allowlist and authorization plan.\n5. Add tests through `fastmcp.Client` before wiring the transport. Most behavior\n   should be tested in-memory without a running web server.\n\n## Stdio Server Pattern\n\nFor local agent clients, create a standalone script that initializes Django\nbefore importing models or tool modules.\n\n```python\n# mcp_server.py\nimport os\n\nos.environ.setdefault(\"DJANGO_SETTINGS_MODULE\", \"project.settings\")\n\nimport django\n\ndjango.setup()\n\nfrom apps.core.mcp import mcp\n\nif __name__ == \"__main__\":\n    mcp.run()\n```\n\nThis shape also works well with the FastMCP CLI because the file fully prepares\nDjango when loaded by `fastmcp list`, `fastmcp call`, or an MCP inspector.\n\n## HTTP Sidecar Pattern\n\nUse a sidecar when Django is still deployed through WSGI, when MCP needs\nseparate scaling, or when you want a clear operational boundary. The sidecar is\na separate process that initializes Django, imports the same MCP server object,\nand serves Streamable HTTP.\n\n```python\n# mcp_http_server.py\nimport os\n\nos.environ.setdefault(\"DJANGO_SETTINGS_MODULE\", \"project.settings\")\n\nimport django\n\ndjango.setup()\n\nfrom apps.core.mcp import mcp\n\nif __name__ == \"__main__\":\n    mcp.run(\n        transport=\"http\",\n        host=\"127.0.0.1\",\n        port=8765,\n        path=\"\u002Fmcp\",\n    )\n```\n\nRun the Django web process and MCP process independently:\n\n```text\nweb: gunicorn project.wsgi:application\nmcp: python mcp_http_server.py\n```\n\nPoint the reverse proxy or internal client at the sidecar's `\u002Fmcp` endpoint.\nKeep the sidecar on a private interface unless it has production-grade TLS,\nauth, rate limits, logging, and monitoring. Give it the same settings module,\ndatabase URL, cache\u002Fbroker settings, secrets, and migrations as the web process.\nDo not try to mount FastMCP inside WSGI middleware; use ASGI mounting only when\nthe combined process is actually served by an ASGI server.\n\n## ASGI Mount Pattern\n\nFor a Django app already served by ASGI, make FastMCP a sibling ASGI app and\nroute `\u002Fmcp` before the Django catch-all. Pass the FastMCP lifespan to the outer\nStarlette app; otherwise Streamable HTTP session management may not initialize.\n\n```python\n# project\u002Fasgi.py\nimport os\n\nfrom django.core.asgi import get_asgi_application\nfrom starlette.applications import Starlette\nfrom starlette.routing import Mount\n\nos.environ.setdefault(\"DJANGO_SETTINGS_MODULE\", \"project.settings\")\n\ndjango_app = get_asgi_application()\n\nfrom apps.core.mcp import mcp\n\nmcp_app = mcp.http_app(path=\"\u002F\")\n\napplication = Starlette(\n    routes=[\n        Mount(\"\u002Fmcp\", app=mcp_app),\n        Mount(\"\u002F\", app=django_app),\n    ],\n    lifespan=mcp_app.lifespan,\n)\n```\n\nIf the project uses Channels, keep websocket routing in `ProtocolTypeRouter` and\nput the Starlette HTTP router in the `\"http\"` branch. If the project already has\nan app lifespan, compose it with the FastMCP lifespan instead of replacing it.\n\nDo not set both the mount prefix and `http_app(path=...)` to `\u002Fmcp` unless the\nintended endpoint is `\u002Fmcp\u002Fmcp`. When mounting at `\u002Fmcp`, use\n`mcp.http_app(path=\"\u002F\")`; when running FastMCP as the whole HTTP app, use a path\nsuch as `mcp.http_app(path=\"\u002Fmcp\")` or `mcp.run(transport=\"http\", path=\"\u002Fmcp\")`.\n\n## Tool Design\n\nCreate tools as narrow application actions, not generic database access.\n\n```python\n# apps\u002Fcore\u002Fmcp.py\nfrom collections.abc import Callable\nfrom typing import Annotated\n\nfrom django.core.exceptions import PermissionDenied\nfrom django.db import close_old_connections, transaction\nfrom fastmcp import FastMCP\nfrom fastmcp.dependencies import Depends\nfrom pydantic import Field\n\n\nclass ResourceNotFound(Exception):\n    \"\"\"Safe not-found error for MCP clients.\"\"\"\n\n\ndef get_current_actor_id() -> int:\n    \"\"\"Return the authenticated Django user ID from trusted MCP auth context.\"\"\"\n    raise PermissionDenied(\"Authentication is required\")\n\n\ndef _order_summary(order_id: int, actor_id: int) -> dict:\n    from apps.orders.models import Order\n\n    try:\n        order = Order.objects.select_related(\"customer\").get(pk=order_id)\n    except Order.DoesNotExist as exc:\n        raise ResourceNotFound(\"Order not found\") from exc\n\n    if not order.can_be_viewed_by_id(actor_id):\n        raise PermissionDenied(\"Not allowed to view this order\")\n\n    return {\n        \"id\": order.pk,\n        \"status\": order.status,\n        \"customer\": order.customer.name,\n        \"total_cents\": order.total_cents,\n    }\n\n\ndef create_mcp(\n    actor_id_dependency: Callable[[], int] = get_current_actor_id,\n) -> FastMCP:\n    mcp = FastMCP(\"Project MCP\", on_duplicate_tools=\"error\")\n\n    @mcp.tool(timeout=10)\n    def get_order_summary(\n        order_id: Annotated[int, Field(gt=0, description=\"Internal order ID\")],\n        actor_id: int = Depends(actor_id_dependency),\n    ) -> dict:\n        \"\"\"Return a concise order summary the actor is allowed to view.\"\"\"\n        close_old_connections()\n        try:\n            return _order_summary(order_id=order_id, actor_id=actor_id)\n        except ResourceNotFound:\n            return {\"error\": \"not_found\", \"message\": \"Order not found\"}\n        except PermissionDenied:\n            return {\n                \"error\": \"forbidden\",\n                \"message\": \"Not allowed to view this order\",\n            }\n        finally:\n            close_old_connections()\n\n    @mcp.tool(timeout=20)\n    def cancel_order(\n        order_id: Annotated[int, Field(gt=0)],\n        reason: Annotated[str, Field(min_length=3, max_length=500)],\n        actor_id: int = Depends(actor_id_dependency),\n    ) -> dict:\n        \"\"\"Cancel an order if the actor is allowed to do so.\"\"\"\n        close_old_connections()\n        try:\n            with transaction.atomic():\n                from apps.orders.services import cancel_order_for_actor\n\n                order = cancel_order_for_actor(\n                    order_id=order_id,\n                    actor_id=actor_id,\n                    reason=reason,\n                )\n                transaction.on_commit(lambda: order.enqueue_cancellation_email())\n                return {\"id\": order.pk, \"status\": order.status}\n        except PermissionDenied:\n            return {\n                \"error\": \"forbidden\",\n                \"message\": \"Not allowed to cancel this order\",\n            }\n        except ValueError:\n            return {\n                \"error\": \"invalid_state\",\n                \"message\": \"Order cannot be cancelled\",\n            }\n        finally:\n            close_old_connections()\n\n    return mcp\n\n\nmcp = create_mcp()\n```\n\nRules for tool contracts:\n\n- Use typed parameters, Pydantic `Field` constraints, docstrings, return type\n  annotations, and small JSON-serializable return values.\n- Use existing Django services and policy methods. Do not duplicate permission\n  logic inside MCP modules when a project already has one source of truth.\n- Keep writes idempotent where possible. Include explicit confirmation fields or\n  idempotency keys for costly\u002Fdestructive tools.\n- Pass durable identifiers, not Django model instances, request objects, lazy\n  querysets, open files, or huge payloads.\n- Paginate and cap every list\u002Fsearch tool. Return stable IDs and summaries, not\n  entire model dumps.\n- Add `timeout=...` on slow or externally dependent tools and make long-running\n  work enqueue a background job instead of holding the MCP request open.\n- Never let the model provide privileged identity fields in production. Inject\n  the current user\u002Faccount from validated auth context or a trusted dependency.\n\n## Django Async Rules\n\n- A synchronous `def` FastMCP tool is usually simplest for Django ORM work.\n  FastMCP dispatches sync tools without blocking the event loop, and the tool\n  can use normal ORM, transactions, forms, and serializers.\n- In an `async def` tool, do not call sync ORM or other async-unsafe Django code\n  directly. Use Django async ORM methods (`aget`, `acreate`, `asave`,\n  `async for`) when they cover the operation.\n- Transactions do not work in Django async mode. Put transactional work in one\n  synchronous helper and call it with `sync_to_async(..., thread_sensitive=True)`\n  from the async tool.\n- Do not set `DJANGO_ALLOW_ASYNC_UNSAFE` to make MCP tools work. Fix the calling\n  boundary instead.\n- Because MCP calls are not Django requests, there is no normal request\n  lifecycle to clean database connections. For long-lived MCP processes, call\n  `close_old_connections()` around ORM work or centralize connection cleanup in\n  a thin helper that preserves function signatures.\n\n## Auth And Permissions\n\n- Treat MCP auth separately from Django browser auth. Django session middleware,\n  login decorators, and CSRF middleware do not automatically protect a mounted\n  Starlette\u002FFastMCP sub-application.\n- Prefer bearer\u002FJWT\u002FOAuth-style auth for remote HTTP MCP servers. FastMCP auth\n  only applies to HTTP-based transports; stdio inherits the local process\n  security model.\n- Map validated token claims to Django users, organizations, and scopes before\n  calling domain services. Enforce object-level permissions inside each tool.\n- Do not expose `user_id`, `organization_id`, `is_staff`, scope lists, or\n  permission flags as LLM-controlled parameters. Use FastMCP dependency\n  injection or request\u002Fauth context to hide trusted values from the tool schema.\n- Do not rely on CORS or CSRF as an auth mechanism. Add CORS only when a browser\n  MCP client or inspector needs it, and keep allowed origins and headers narrow.\n- Mask sensitive error details in production. Return explicit, safe errors for\n  denied permissions and validation failures; log full exceptions server-side.\n\n## Resources And Prompts\n\n- Use tools for permissioned data, mutations, searches, and any result that\n  depends on the current user.\n- Use resources for bounded, read-only, low-risk content such as public docs,\n  product metadata, or static schemas. Do not publish private model tables as\n  global resources unless every client may read them.\n- Use prompts for reusable agent workflows such as \"triage this customer\", but\n  keep prompts free of secrets and make them call tools rather than embedding\n  stale database facts.\n\n## Deployment\n\n- Streamable HTTP is the preferred remote transport. SSE is legacy; stdio is for\n  local tools.\n- If Django is still WSGI-only, either run FastMCP as a separate HTTP sidecar or\n  migrate the deployment to ASGI before mounting it into the same process.\n- Run remote MCP behind TLS and real authentication. Avoid exposing unauthenticated\n  internal tools on a public domain.\n- For nginx or another reverse proxy, disable response buffering for MCP\u002FSSE\n  streams and raise read\u002Fsend timeouts for long operations.\n- If OAuth discovery is used under a mount prefix, verify well-known discovery\n  URLs and avoid double-prefixing `base_url` and MCP paths.\n- Keep environment parity: the MCP process needs the same `DJANGO_SETTINGS_MODULE`,\n  database URL, cache\u002Fbroker settings, secret management, logging, and migrations\n  as the Django process.\n\n## Testing\n\nUse in-memory FastMCP clients for most tests. Async tests require\n`pytest-asyncio` or an equivalent async pytest plugin. Either set\n`asyncio_mode = \"auto\"` in pytest configuration or mark async tests explicitly\nwith `@pytest.mark.asyncio`.\n\n```toml\n[tool.pytest.ini_options]\nasyncio_mode = \"auto\"\n```\n\n```python\nimport pytest\nfrom fastmcp import Client\n\nfrom apps.core.mcp import create_mcp\n\n\n@pytest.mark.asyncio\n@pytest.mark.django_db\nasync def test_get_order_summary(order, user):\n    mcp = create_mcp(actor_id_dependency=lambda: user.pk)\n\n    async with Client(mcp) as mcp_client:\n        result = await mcp_client.call_tool(\n            \"get_order_summary\",\n            {\"order_id\": order.pk},\n        )\n\n    assert result.data[\"id\"] == order.pk\n    assert result.data[\"status\"] == order.status\n```\n\nTesting checklist:\n\n- Assert `list_tools()` output for names, descriptions, and schemas when tool\n  contracts matter.\n- Test allowed and denied users for every permissioned tool.\n- Test invalid inputs, missing objects, pagination caps, and destructive action\n  confirmation paths.\n- Test write tools against database state and `transaction.on_commit` side\n  effects.\n- When tools use auth-injected dependencies, test through the same auth path or\n  build the server through a factory that accepts a test auth resolver. Do not\n  expose `actor_id` as an LLM parameter just to make tests easier.\n- Add one HTTP transport smoke test only when ASGI mounting, auth headers, proxy\n  behavior, or URL paths changed.\n- Use `pytest.mark.django_db(transaction=True)` when a separate server process\n  or background worker must observe committed rows.\n\nUseful local checks:\n\n```bash\nDJANGO_SETTINGS_MODULE=project.settings fastmcp list mcp_server.py\nDJANGO_SETTINGS_MODULE=project.settings fastmcp inspect mcp_server.py --format json\nfastmcp call http:\u002F\u002Flocalhost:8000\u002Fmcp get_order_summary order_id=1 --auth \"Bearer $TOKEN\"\n```\n\n## Debugging Checklist\n\n- `AppRegistryNotReady`: initialize Django before importing models, or move model\n  imports inside tools\u002Fhelpers.\n- `SynchronousOnlyOperation`: sync Django code is running in an async tool. Use a\n  sync tool, async ORM methods, or `sync_to_async(..., thread_sensitive=True)`.\n- HTTP 404 or `\u002Fmcp\u002Fmcp`: check the ASGI mount prefix versus `http_app(path=...)`.\n- Session manager or stream errors: make sure the outer ASGI app uses\n  `mcp_app.lifespan`.\n- Client connects but receives no streamed results: check proxy buffering and\n  timeout settings.\n- Tool list is huge or unsafe: replace generic model\u002FAPI exposure with a small\n  allowlist of agent-focused capabilities.\n- Tool schema is wrong: remove `*args`\u002F`**kwargs`, add type annotations, avoid\n  wrappers that hide the original function signature, and inspect with\n  `fastmcp inspect`.\n- Auth appears bypassed: remember that Django middleware may not run for mounted\n  FastMCP routes. Validate tokens and enforce permissions inside the MCP layer\n  and domain services.\n\n## References\n\n- FastMCP docs: https:\u002F\u002Fgofastmcp.com\u002Fgetting-started\u002Fwelcome\n- FastMCP GitHub: https:\u002F\u002Fgithub.com\u002FPrefectHQ\u002Ffastmcp\n- FastMCP HTTP deployment: https:\u002F\u002Fgofastmcp.com\u002Fdeployment\u002Fhttp\n- FastMCP tests: https:\u002F\u002Fgofastmcp.com\u002Fdevelopment\u002Ftests\n- FastMCP tools: https:\u002F\u002Fgofastmcp.com\u002Fservers\u002Ftools\n- FastMCP authentication: https:\u002F\u002Fgofastmcp.com\u002Fservers\u002Fauth\u002Fauthentication\n- FastMCP dependency injection: https:\u002F\u002Fgofastmcp.com\u002Fservers\u002Fdependency-injection\n- Django async support: https:\u002F\u002Fdocs.djangoproject.com\u002Fen\u002F5.2\u002Ftopics\u002Fasync\u002F\n- Django ASGI deployment: https:\u002F\u002Fdocs.djangoproject.com\u002Fen\u002F5.2\u002Fhowto\u002Fdeployment\u002Fasgi\u002F\n","# FastMCP with Django\n\nUse this when exposing Django application capabilities to agents through MCP.\nKeep Django as the source of truth for auth, permissions, validation, models,\ntransactions, and business rules. Use FastMCP as the protocol layer around\nsmall, typed capabilities.\n\n## Tool Choice\n\n- Prefer the standalone `fastmcp` package (`from fastmcp import FastMCP`) for\n  new Python MCP work in Django. It is the actively maintained FastMCP project\n  and includes HTTP transport, clients, auth helpers, CLI tooling, testing\n  utilities, server composition, and OpenAPI\u002FFastAPI conversion features.\n- Use the official MCP Python SDK (`from mcp.server.fastmcp import FastMCP`)\n  when the project has already standardized on it, when you need lower-level\n  protocol control, or when a host explicitly requires SDK behavior.\n- Consider `django-mcp-server` only when the project needs a Django-native\n  package that works inside WSGI or declaratively exposes models\u002FDRF APIs. Audit\n  its security model and generated tool contracts before exposing private data.\n- If the app already has a deliberate public OpenAPI surface, generating or\n  proxying tools from that API can be useful for a first pass. For production\n  agents, prefer hand-curated tools with purpose-built names, input schemas,\n  permission checks, and bounded outputs.\n\nFastMCP docs track the project's `main` branch, so re-check the current docs\nwhen relying on recently added features or version badges.\n\n## Implementation Workflow\n\n1. Read the existing Django entrypoints first: `manage.py`, `settings.py`,\n   `asgi.py`, `wsgi.py`, URL routing, auth middleware, DRF\u002FNinja APIs, Celery or\n   Django Q tasks, and deployment files.\n2. Choose the transport boundary:\n   - Use stdio for a local desktop\u002Feditor MCP server that runs beside the app.\n   - Use a separate FastMCP HTTP sidecar when the Django deployment is WSGI-only\n     or when MCP should scale independently.\n   - Mount FastMCP into the Django ASGI process when the app already runs under\n     ASGI and sharing the same domain\u002Fprocess is intentional.\n3. Put MCP server registration in a small module such as `apps\u002Fcore\u002Fmcp.py` or\n   `project\u002Fmcp.py`. Keep tool bodies thin and call existing services,\n   selectors, forms, serializers, policies, or domain functions.\n4. Make every exposed capability explicit. Avoid generic SQL, generic model\n   browsing, arbitrary imports, file path access, or \"admin\" tools unless the\n   project has a clear allowlist and authorization plan.\n5. Add tests through `fastmcp.Client` before wiring the transport. Most behavior\n   should be tested in-memory without a running web server.\n\n## Stdio Server Pattern\n\nFor local agent clients, create a standalone script that initializes Django\nbefore importing models or tool modules.\n\n```python\n# mcp_server.py\nimport os\n\nos.environ.setdefault(\"DJANGO_SETTINGS_MODULE\", \"project.settings\")\n\nimport django\n\ndjango.setup()\n\nfrom apps.core.mcp import mcp\n\nif __name__ == \"__main__\":\n    mcp.run()\n```\n\nThis shape also works well with the FastMCP CLI because the file fully prepares\nDjango when loaded by `fastmcp list`, `fastmcp call`, or an MCP inspector.\n\n## HTTP Sidecar Pattern\n\nUse a sidecar when Django is still deployed through WSGI, when MCP needs\nseparate scaling, or when you want a clear operational boundary. The sidecar is\na separate process that initializes Django, imports the same MCP server object,\nand serves Streamable HTTP.\n\n```python\n# mcp_http_server.py\nimport os\n\nos.environ.setdefault(\"DJANGO_SETTINGS_MODULE\", \"project.settings\")\n\nimport django\n\ndjango.setup()\n\nfrom apps.core.mcp import mcp\n\nif __name__ == \"__main__\":\n    mcp.run(\n        transport=\"http\",\n        host=\"127.0.0.1\",\n        port=8765,\n        path=\"\u002Fmcp\",\n    )\n```\n\nRun the Django web process and MCP process independently:\n\n```text\nweb: gunicorn project.wsgi:application\nmcp: python mcp_http_server.py\n```\n\nPoint the reverse proxy or internal client at the sidecar's `\u002Fmcp` endpoint.\nKeep the sidecar on a private interface unless it has production-grade TLS,\nauth, rate limits, logging, and monitoring. Give it the same settings module,\ndatabase URL, cache\u002Fbroker settings, secrets, and migrations as the web process.\nDo not try to mount FastMCP inside WSGI middleware; use ASGI mounting only when\nthe combined process is actually served by an ASGI server.\n\n## ASGI Mount Pattern\n\nFor a Django app already served by ASGI, make FastMCP a sibling ASGI app and\nroute `\u002Fmcp` before the Django catch-all. Pass the FastMCP lifespan to the outer\nStarlette app; otherwise Streamable HTTP session management may not initialize.\n\n```python\n# project\u002Fasgi.py\nimport os\n\nfrom django.core.asgi import get_asgi_application\nfrom starlette.applications import Starlette\nfrom starlette.routing import Mount\n\nos.environ.setdefault(\"DJANGO_SETTINGS_MODULE\", \"project.settings\")\n\ndjango_app = get_asgi_application()\n\nfrom apps.core.mcp import mcp\n\nmcp_app = mcp.http_app(path=\"\u002F\")\n\napplication = Starlette(\n    routes=[\n        Mount(\"\u002Fmcp\", app=mcp_app),\n        Mount(\"\u002F\", app=django_app),\n    ],\n    lifespan=mcp_app.lifespan,\n)\n```\n\nIf the project uses Channels, keep websocket routing in `ProtocolTypeRouter` and\nput the Starlette HTTP router in the `\"http\"` branch. If the project already has\nan app lifespan, compose it with the FastMCP lifespan instead of replacing it.\n\nDo not set both the mount prefix and `http_app(path=...)` to `\u002Fmcp` unless the\nintended endpoint is `\u002Fmcp\u002Fmcp`. When mounting at `\u002Fmcp`, use\n`mcp.http_app(path=\"\u002F\")`; when running FastMCP as the whole HTTP app, use a path\nsuch as `mcp.http_app(path=\"\u002Fmcp\")` or `mcp.run(transport=\"http\", path=\"\u002Fmcp\")`.\n\n## Tool Design\n\nCreate tools as narrow application actions, not generic database access.\n\n```python\n# apps\u002Fcore\u002Fmcp.py\nfrom collections.abc import Callable\nfrom typing import Annotated\n\nfrom django.core.exceptions import PermissionDenied\nfrom django.db import close_old_connections, transaction\nfrom fastmcp import FastMCP\nfrom fastmcp.dependencies import Depends\nfrom pydantic import Field\n\n\nclass ResourceNotFound(Exception):\n    \"\"\"Safe not-found error for MCP clients.\"\"\"\n\n\ndef get_current_actor_id() -> int:\n    \"\"\"Return the authenticated Django user ID from trusted MCP auth context.\"\"\"\n    raise PermissionDenied(\"Authentication is required\")\n\n\ndef _order_summary(order_id: int, actor_id: int) -> dict:\n    from apps.orders.models import Order\n\n    try:\n        order = Order.objects.select_related(\"customer\").get(pk=order_id)\n    except Order.DoesNotExist as exc:\n        raise ResourceNotFound(\"Order not found\") from exc\n\n    if not order.can_be_viewed_by_id(actor_id):\n        raise PermissionDenied(\"Not allowed to view this order\")\n\n    return {\n        \"id\": order.pk,\n        \"status\": order.status,\n        \"customer\": order.customer.name,\n        \"total_cents\": order.total_cents,\n    }\n\n\ndef create_mcp(\n    actor_id_dependency: Callable[[], int] = get_current_actor_id,\n) -> FastMCP:\n    mcp = FastMCP(\"Project MCP\", on_duplicate_tools=\"error\")\n\n    @mcp.tool(timeout=10)\n    def get_order_summary(\n        order_id: Annotated[int, Field(gt=0, description=\"Internal order ID\")],\n        actor_id: int = Depends(actor_id_dependency),\n    ) -> dict:\n        \"\"\"Return a concise order summary the actor is allowed to view.\"\"\"\n        close_old_connections()\n        try:\n            return _order_summary(order_id=order_id, actor_id=actor_id)\n        except ResourceNotFound:\n            return {\"error\": \"not_found\", \"message\": \"Order not found\"}\n        except PermissionDenied:\n            return {\n                \"error\": \"forbidden\",\n                \"message\": \"Not allowed to view this order\",\n            }\n        finally:\n            close_old_connections()\n\n    @mcp.tool(timeout=20)\n    def cancel_order(\n        order_id: Annotated[int, Field(gt=0)],\n        reason: Annotated[str, Field(min_length=3, max_length=500)],\n        actor_id: int = Depends(actor_id_dependency),\n    ) -> dict:\n        \"\"\"Cancel an order if the actor is allowed to do so.\"\"\"\n        close_old_connections()\n        try:\n            with transaction.atomic():\n                from apps.orders.services import cancel_order_for_actor\n\n                order = cancel_order_for_actor(\n                    order_id=order_id,\n                    actor_id=actor_id,\n                    reason=reason,\n                )\n                transaction.on_commit(lambda: order.enqueue_cancellation_email())\n                return {\"id\": order.pk, \"status\": order.status}\n        except PermissionDenied:\n            return {\n                \"error\": \"forbidden\",\n                \"message\": \"Not allowed to cancel this order\",\n            }\n        except ValueError:\n            return {\n                \"error\": \"invalid_state\",\n                \"message\": \"Order cannot be cancelled\",\n            }\n        finally:\n            close_old_connections()\n\n    return mcp\n\n\nmcp = create_mcp()\n```\n\nRules for tool contracts:\n\n- Use typed parameters, Pydantic `Field` constraints, docstrings, return type\n  annotations, and small JSON-serializable return values.\n- Use existing Django services and policy methods. Do not duplicate permission\n  logic inside MCP modules when a project already has one source of truth.\n- Keep writes idempotent where possible. Include explicit confirmation fields or\n  idempotency keys for costly\u002Fdestructive tools.\n- Pass durable identifiers, not Django model instances, request objects, lazy\n  querysets, open files, or huge payloads.\n- Paginate and cap every list\u002Fsearch tool. Return stable IDs and summaries, not\n  entire model dumps.\n- Add `timeout=...` on slow or externally dependent tools and make long-running\n  work enqueue a background job instead of holding the MCP request open.\n- Never let the model provide privileged identity fields in production. Inject\n  the current user\u002Faccount from validated auth context or a trusted dependency.\n\n## Django Async Rules\n\n- A synchronous `def` FastMCP tool is usually simplest for Django ORM work.\n  FastMCP dispatches sync tools without blocking the event loop, and the tool\n  can use normal ORM, transactions, forms, and serializers.\n- In an `async def` tool, do not call sync ORM or other async-unsafe Django code\n  directly. Use Django async ORM methods (`aget`, `acreate`, `asave`,\n  `async for`) when they cover the operation.\n- Transactions do not work in Django async mode. Put transactional work in one\n  synchronous helper and call it with `sync_to_async(..., thread_sensitive=True)`\n  from the async tool.\n- Do not set `DJANGO_ALLOW_ASYNC_UNSAFE` to make MCP tools work. Fix the calling\n  boundary instead.\n- Because MCP calls are not Django requests, there is no normal request\n  lifecycle to clean database connections. For long-lived MCP processes, call\n  `close_old_connections()` around ORM work or centralize connection cleanup in\n  a thin helper that preserves function signatures.\n\n## Auth And Permissions\n\n- Treat MCP auth separately from Django browser auth. Django session middleware,\n  login decorators, and CSRF middleware do not automatically protect a mounted\n  Starlette\u002FFastMCP sub-application.\n- Prefer bearer\u002FJWT\u002FOAuth-style auth for remote HTTP MCP servers. FastMCP auth\n  only applies to HTTP-based transports; stdio inherits the local process\n  security model.\n- Map validated token claims to Django users, organizations, and scopes before\n  calling domain services. Enforce object-level permissions inside each tool.\n- Do not expose `user_id`, `organization_id`, `is_staff`, scope lists, or\n  permission flags as LLM-controlled parameters. Use FastMCP dependency\n  injection or request\u002Fauth context to hide trusted values from the tool schema.\n- Do not rely on CORS or CSRF as an auth mechanism. Add CORS only when a browser\n  MCP client or inspector needs it, and keep allowed origins and headers narrow.\n- Mask sensitive error details in production. Return explicit, safe errors for\n  denied permissions and validation failures; log full exceptions server-side.\n\n## Resources And Prompts\n\n- Use tools for permissioned data, mutations, searches, and any result that\n  depends on the current user.\n- Use resources for bounded, read-only, low-risk content such as public docs,\n  product metadata, or static schemas. Do not publish private model tables as\n  global resources unless every client may read them.\n- Use prompts for reusable agent workflows such as \"triage this customer\", but\n  keep prompts free of secrets and make them call tools rather than embedding\n  stale database facts.\n\n## Deployment\n\n- Streamable HTTP is the preferred remote transport. SSE is legacy; stdio is for\n  local tools.\n- If Django is still WSGI-only, either run FastMCP as a separate HTTP sidecar or\n  migrate the deployment to ASGI before mounting it into the same process.\n- Run remote MCP behind TLS and real authentication. Avoid exposing unauthenticated\n  internal tools on a public domain.\n- For nginx or another reverse proxy, disable response buffering for MCP\u002FSSE\n  streams and raise read\u002Fsend timeouts for long operations.\n- If OAuth discovery is used under a mount prefix, verify well-known discovery\n  URLs and avoid double-prefixing `base_url` and MCP paths.\n- Keep environment parity: the MCP process needs the same `DJANGO_SETTINGS_MODULE`,\n  database URL, cache\u002Fbroker settings, secret management, logging, and migrations\n  as the Django process.\n\n## Testing\n\nUse in-memory FastMCP clients for most tests. Async tests require\n`pytest-asyncio` or an equivalent async pytest plugin. Either set\n`asyncio_mode = \"auto\"` in pytest configuration or mark async tests explicitly\nwith `@pytest.mark.asyncio`.\n\n```toml\n[tool.pytest.ini_options]\nasyncio_mode = \"auto\"\n```\n\n```python\nimport pytest\nfrom fastmcp import Client\n\nfrom apps.core.mcp import create_mcp\n\n\n@pytest.mark.asyncio\n@pytest.mark.django_db\nasync def test_get_order_summary(order, user):\n    mcp = create_mcp(actor_id_dependency=lambda: user.pk)\n\n    async with Client(mcp) as mcp_client:\n        result = await mcp_client.call_tool(\n            \"get_order_summary\",\n            {\"order_id\": order.pk},\n        )\n\n    assert result.data[\"id\"] == order.pk\n    assert result.data[\"status\"] == order.status\n```\n\nTesting checklist:\n\n- Assert `list_tools()` output for names, descriptions, and schemas when tool\n  contracts matter.\n- Test allowed and denied users for every permissioned tool.\n- Test invalid inputs, missing objects, pagination caps, and destructive action\n  confirmation paths.\n- Test write tools against database state and `transaction.on_commit` side\n  effects.\n- When tools use auth-injected dependencies, test through the same auth path or\n  build the server through a factory that accepts a test auth resolver. Do not\n  expose `actor_id` as an LLM parameter just to make tests easier.\n- Add one HTTP transport smoke test only when ASGI mounting, auth headers, proxy\n  behavior, or URL paths changed.\n- Use `pytest.mark.django_db(transaction=True)` when a separate server process\n  or background worker must observe committed rows.\n\nUseful local checks:\n\n```bash\nDJANGO_SETTINGS_MODULE=project.settings fastmcp list mcp_server.py\nDJANGO_SETTINGS_MODULE=project.settings fastmcp inspect mcp_server.py --format json\nfastmcp call http:\u002F\u002Flocalhost:8000\u002Fmcp get_order_summary order_id=1 --auth \"Bearer $TOKEN\"\n```\n\n## Debugging Checklist\n\n- `AppRegistryNotReady`: initialize Django before importing models, or move model\n  imports inside tools\u002Fhelpers.\n- `SynchronousOnlyOperation`: sync Django code is running in an async tool. Use a\n  sync tool, async ORM methods, or `sync_to_async(..., thread_sensitive=True)`.\n- HTTP 404 or `\u002Fmcp\u002Fmcp`: check the ASGI mount prefix versus `http_app(path=...)`.\n- Session manager or stream errors: make sure the outer ASGI app uses\n  `mcp_app.lifespan`.\n- Client connects but receives no streamed results: check proxy buffering and\n  timeout settings.\n- Tool list is huge or unsafe: replace generic model\u002FAPI exposure with a small\n  allowlist of agent-focused capabilities.\n- Tool schema is wrong: remove `*args`\u002F`**kwargs`, add type annotations, avoid\n  wrappers that hide the original function signature, and inspect with\n  `fastmcp inspect`.\n- Auth appears bypassed: remember that Django middleware may not run for mounted\n  FastMCP routes. Validate tokens and enforce permissions inside the MCP layer\n  and domain services.\n\n## References\n\n- FastMCP docs: https:\u002F\u002Fgofastmcp.com\u002Fgetting-started\u002Fwelcome\n- FastMCP GitHub: https:\u002F\u002Fgithub.com\u002FPrefectHQ\u002Ffastmcp\n- FastMCP HTTP deployment: https:\u002F\u002Fgofastmcp.com\u002Fdeployment\u002Fhttp\n- FastMCP tests: https:\u002F\u002Fgofastmcp.com\u002Fdevelopment\u002Ftests\n- FastMCP tools: https:\u002F\u002Fgofastmcp.com\u002Fservers\u002Ftools\n- FastMCP authentication: https:\u002F\u002Fgofastmcp.com\u002Fservers\u002Fauth\u002Fauthentication\n- FastMCP dependency injection: https:\u002F\u002Fgofastmcp.com\u002Fservers\u002Fdependency-injection\n- Django async support: https:\u002F\u002Fdocs.djangoproject.com\u002Fen\u002F5.2\u002Ftopics\u002Fasync\u002F\n- Django ASGI deployment: https:\u002F\u002Fdocs.djangoproject.com\u002Fen\u002F5.2\u002Fhowto\u002Fdeployment\u002Fasgi\u002F\n",{"name":5,"license":14,"metadata":23,"description":7,"compatibility":28},{"tags":24,"version":25,"category":26,"displayName":27},"fastmcp,django,mcp,asgi","0.1.0","Django","FastMCP Django","Codex, Claude Code, and other Agent Skills-compatible clients.","main","9ba3c9fadff1092395837bf1502e1b8a7f98b1e1","plugins\u002Fcommunity\u002Flvtd-skills\u002Fskills\u002Ffastmcp-django","https:\u002F\u002Fgithub.com\u002FConcertoNotes\u002Fcodex-plugins","https:\u002F\u002Fgithub.com\u002FConcertoNotes","2026-06-26 10:13:54",{"source":8,"skillName":5,"commands":36,"prompt":46,"zipAvailable":47},[37,40,43],{"tool":38,"command":39},"npx","npx skills add ConcertoNotes\u002Fcodex-plugins --skill fastmcp-django",{"tool":41,"command":42},"bunx","bunx skills add ConcertoNotes\u002Fcodex-plugins --skill fastmcp-django",{"tool":44,"command":45},"pnpm","pnpm dlx skills add ConcertoNotes\u002Fcodex-plugins --skill fastmcp-django","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FConcertoNotes\u002Fcodex-plugins\u002Fblob\u002Fmain\u002Fplugins\u002Fcommunity\u002Flvtd-skills\u002Fskills\u002Ffastmcp-django\u002FSKILL.md",true,[49,55],{"path":50,"resourceType":51,"resourceTypeDesc":52,"sizeBytes":53,"sourceHtmlUrl":54},"agents\u002Fopenai.yaml","REFERENCE","参考文档",194,"https:\u002F\u002Fgithub.com\u002FConcertoNotes\u002Fcodex-plugins\u002Fblob\u002Fmain\u002Fplugins\u002Fcommunity\u002Flvtd-skills\u002Fskills\u002Ffastmcp-django\u002Fagents\u002Fopenai.yaml",{"path":56,"resourceType":57,"resourceTypeDesc":58,"sizeBytes":59,"sourceHtmlUrl":60},"assets\u002Fapp-icon.png","ASSET","资产文件",63590,"https:\u002F\u002Fgithub.com\u002FConcertoNotes\u002Fcodex-plugins\u002Fblob\u002Fmain\u002Fplugins\u002Fcommunity\u002Flvtd-skills\u002Fskills\u002Ffastmcp-django\u002Fassets\u002Fapp-icon.png",[62,71,78,86,93,100],{"skillNo":63,"name":64,"nameZh":6,"description":65,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":9,"repositoryNo":12,"starsCount":13,"licenseSpdxId":66,"licenseFileUrl":67,"sourceHtmlUrl":68,"categories":69,"keywords":70,"publishedAt":18},"01M77YB7WW36DS9AERTWP673E0","android-emulator-qa","Use when validating Android feature flows in an emulator with adb-driven launch, input, UI-tree inspection, screenshots, and logcat capture.","Apache-2.0","https:\u002F\u002Fgithub.com\u002FConcertoNotes\u002Fcodex-plugins\u002Fblob\u002Fmain\u002Fplugins\u002Fofficial\u002Ftest-android-apps\u002Fskills\u002Fandroid-emulator-qa\u002FLICENSE.txt","https:\u002F\u002Fgithub.com\u002FConcertoNotes\u002Fcodex-plugins\u002Fblob\u002Fmain\u002Fplugins\u002Fofficial\u002Ftest-android-apps\u002Fskills\u002Fandroid-emulator-qa\u002FSKILL.md",[],[],{"skillNo":72,"name":73,"nameZh":6,"description":74,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":9,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":75,"categories":76,"keywords":77,"publishedAt":18},"01M77Y7AA8N45G6NM0WJSS2W9C","supabase-postgres-best-practices","Postgres performance optimization and best practices from Supabase. Use this skill when writing, reviewing, or optimizing Postgres queries, schema designs, or database configurations.","https:\u002F\u002Fgithub.com\u002FConcertoNotes\u002Fcodex-plugins\u002Fblob\u002Fmain\u002Fplugins\u002Fofficial\u002Fsupabase\u002Fskills\u002Fsupabase-postgres-best-practices\u002FSKILL.md",[],[],{"skillNo":79,"name":80,"nameZh":6,"description":81,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":9,"repositoryNo":12,"starsCount":13,"licenseSpdxId":66,"licenseFileUrl":82,"sourceHtmlUrl":83,"categories":84,"keywords":85,"publishedAt":18},"01M77Y2W5H5YGSW7MYWEJ8HYXD","sentry","Use when the user asks to inspect Sentry issues or events, summarize recent production errors, or pull basic Sentry health data via the Sentry API; perform read-only queries with the bundled script and require `SENTRY_AUTH_TOKEN`.","https:\u002F\u002Fgithub.com\u002FConcertoNotes\u002Fcodex-plugins\u002Fblob\u002Fmain\u002Fplugins\u002Fofficial\u002Fsentry\u002Fskills\u002Fsentry\u002FLICENSE.txt","https:\u002F\u002Fgithub.com\u002FConcertoNotes\u002Fcodex-plugins\u002Fblob\u002Fmain\u002Fplugins\u002Fofficial\u002Fsentry\u002Fskills\u002Fsentry\u002FSKILL.md",[],[],{"skillNo":87,"name":88,"nameZh":6,"description":89,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":9,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":90,"categories":91,"keywords":92,"publishedAt":18},"01M77Y06GV1DAME7PN9KBFHWRX","render-workflows","Sets up, develops, tests, and deploys Render Workflows. Covers first-time scaffolding (via CLI or manual), SDK installation (Python or TypeScript), task patterns (retries, subtasks, fan-out), local development, Dashboard deployment, and troubleshooting. Use when a user wants to set up Render Workflows for the first time, scaffold a workflow service, add or modify workflow tasks, test workflows locally, or deploy workflows to Render.","https:\u002F\u002Fgithub.com\u002FConcertoNotes\u002Fcodex-plugins\u002Fblob\u002Fmain\u002Fplugins\u002Fofficial\u002Frender\u002Fskills\u002Frender-workflows\u002FSKILL.md",[],[],{"skillNo":94,"name":95,"nameZh":6,"description":96,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":9,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":97,"categories":98,"keywords":99,"publishedAt":18},"01M77Y01A6RJA8VYT7CZ2TVETF","render-web-services","Configures Render web services—port binding, TLS, health checks, custom domains, auto-deploy, PR previews, persistent disks, and deploy lifecycle. Use when the user needs to set up a web service, fix health check failures, add a custom domain, configure zero-downtime deploys, or troubleshoot port binding issues.","https:\u002F\u002Fgithub.com\u002FConcertoNotes\u002Fcodex-plugins\u002Fblob\u002Fmain\u002Fplugins\u002Fofficial\u002Frender\u002Fskills\u002Frender-web-services\u002FSKILL.md",[],[],{"skillNo":101,"name":102,"nameZh":6,"description":103,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":9,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":104,"categories":105,"keywords":106,"publishedAt":18},"01M77XZW1AZ6B6NZTWWFVY72T3","render-static-sites","Deploys and configures static sites on Render's global CDN—build commands, publish paths, SPA routing, redirects, custom headers, and PR previews. Use when the user needs to deploy a static site, set up a React\u002FVue\u002FHugo\u002FGatsby frontend, configure SPA fallback routing, add redirect rules, customize response headers, or choose between a static site and a web service for their frontend. Trigger terms: static site, CDN, SPA, single-page app, React deploy, Vue deploy, Hugo, Gatsby, Docusaurus, Jekyll, staticPublishPath.","https:\u002F\u002Fgithub.com\u002FConcertoNotes\u002Fcodex-plugins\u002Fblob\u002Fmain\u002Fplugins\u002Fofficial\u002Frender\u002Fskills\u002Frender-static-sites\u002FSKILL.md",[],[]]