Skip to main content

Expose djangorestframework-services services and selectors as an MCP (Model Context Protocol) server.

Project description

djangorestframework-mcp-server

CI PyPI Python versions Django versions Docs Coverage Ruff License

Expose djangorestframework-services services and selectors as a Model Context Protocol (MCP) server, conforming to MCP 2025-11-25 (Streamable HTTP).

Idea

Register ServiceSpec instances directly — no DRF router or viewset involvement. The unit of registration is the ServiceSpec, not a view.

from django.urls import path
from rest_framework_services.types.selector_kind import SelectorKind
from rest_framework_services.types.selector_spec import SelectorSpec
from rest_framework_services.types.service_spec import ServiceSpec

from rest_framework_mcp import MCPServer

server = MCPServer(name="my-app")

server.register_service_tool(
    name="invoices.create",
    spec=ServiceSpec(
        service=create_invoice,
        input_serializer=InvoiceInputSerializer,
        output_selector_spec=SelectorSpec(
            kind=SelectorKind.RETRIEVE,
            output_serializer=InvoiceOutputSerializer,
        ),
    ),
)

server.register_resource(
    name="invoice",
    uri_template="invoices://{pk}",
    selector=SelectorSpec(
        kind=SelectorKind.RETRIEVE,
        selector=get_invoice,
        output_serializer=InvoiceOutputSerializer,
    ),
)

urlpatterns = [path("mcp/", server.urls)]

A decorator form is also supported (@server.service_tool(...) / @server.resource(...)). See the quickstart for the full end-to-end recipe.

  • Services (mutations) → MCP tools.
  • Selectors (reads) → MCP resources.
  • A single /mcp endpoint speaks Streamable HTTP. The /.well-known/oauth-protected-resource endpoint comes mounted alongside.

What ships

  • Toolstools/list, tools/call for register_service_tool (mutations) and register_selector_tool (reads, with optional FilterSet + ordering + pagination).
  • Resourcesresources/list, resources/templates/list, resources/read against SelectorSpec-backed callables; RFC 6570 templated URIs.
  • Promptsprompts/list, prompts/get against render callables returning strings, PromptMessages, or async coroutines.
  • In-process transport surface — call tools without an HTTP round-trip: MCPServer.call_tool / acall_tool and list_tools / alist_tools drive the same dispatch and permission checks as the wire path, for embedding in agent bridges, toolsets, or management commands.
  • Tool annotations — pass annotations= at registration (or rely on the read/mutation default) to advertise MCP hints like readOnlyHint / destructiveHint on tools/list.
  • Generic _meta — pass meta= at registration to populate the base protocol's free-form _meta object on a tool, resource, or prompt's listing entry (and on the contents of resources/read). Passed through verbatim, so protocol extensions have somewhere to live.
  • Interactive views (MCP Apps)register_ui_resource(...) declares an HTML view with typed CSP / permission metadata; ui=UIToolMeta(...) on a tool links its result to that view, and a host renders it inline in the chat. The render payload is the structuredContent you already emit, and a view's own tools/calls inherit your auth, permissions and rate limits. An extension over base MCP, so no protocol bump. We declare; the host sandboxes and renders.
  • Pluggable authDjangoOAuthToolkitBackend (default) and AllowAnyBackend (dev only). Per-binding MCPPermission classes (ScopeRequired, DjangoPermRequired) plus your own.
  • RFC 8707 audience binding when RESOURCE_URL is configured; RFC 9728 PRM served from the configured backend.
  • Per-binding rate limitsMCPRateLimit Protocol with FixedWindowRateLimit, SlidingWindowRateLimit, and TokenBucketRateLimit implementations shipped.
  • Output formats — JSON (default) and TOON (token-oriented; optional extra with safe JSON fallback).
  • Async POST/DELETE + GET-side SSE push — sync urls for WSGI, async_urls for ASGI; MCPServer.notify(session_id, payload) pushes JSON-RPC frames on the session's SSE stream. Per-worker InMemorySSEBroker or cross-worker RedisSSEBroker (behind [redis]); Last-Event-ID resume via InMemorySSEReplayBuffer / RedisSSEReplayBuffer.
  • OpenTelemetry instrumentationmcp.tools.call, mcp.resources.read, mcp.prompts.get spans (no-op without the [otel] extra installed).
  • Origin allowlist + protocol-version validation + session lifecycle per the 2025-11-25 transport rules.

Install

pip install djangorestframework-mcp-server                              # JSON only
pip install "djangorestframework-mcp-server[toon]"                      # +TOON encoder
pip install "djangorestframework-mcp-server[oauth]"                     # +django-oauth-toolkit backend
pip install "djangorestframework-mcp-server[redis]"                     # +Redis SSE broker for multi-worker ASGI
pip install "djangorestframework-mcp-server[otel]"                      # +OpenTelemetry instrumentation
pip install "djangorestframework-mcp-server[filter]"                    # +django-filter for selector-tool FilterSets
pip install "djangorestframework-mcp-server[spectacular]"               # +drf-spectacular schema overrides
pip install "djangorestframework-mcp-server[jwt]"                       # +SimpleJWTCookieAdapter (djangorestframework-simplejwt)
pip install "djangorestframework-mcp-server[toon,oauth,redis,otel,filter,spectacular,jwt]"  # everything

…or with uv:

uv add djangorestframework-mcp-server                                   # JSON only
uv add "djangorestframework-mcp-server[toon]"                           # +TOON encoder
uv add "djangorestframework-mcp-server[oauth]"                          # +django-oauth-toolkit backend
uv add "djangorestframework-mcp-server[redis]"                          # +Redis SSE broker for multi-worker ASGI
uv add "djangorestframework-mcp-server[otel]"                           # +OpenTelemetry instrumentation
uv add "djangorestframework-mcp-server[filter]"                         # +django-filter for selector-tool FilterSets
uv add "djangorestframework-mcp-server[spectacular]"                    # +drf-spectacular schema overrides
uv add "djangorestframework-mcp-server[jwt]"                            # +SimpleJWTCookieAdapter (djangorestframework-simplejwt)
uv add "djangorestframework-mcp-server[toon,oauth,redis,otel,filter,spectacular,jwt]"  # everything

Optional extras degrade gracefully: TOON falls back to JSON with a runtime warning if python-toon is not installed, and the OAuth backend module imports cleanly without oauth2_provider — the ImportError only fires when you actually configure it.

Try it

Install mcp-inspector and point it at your dev server:

npx @modelcontextprotocol/inspector --url http://localhost:8000/mcp/

Inspector lists tools, fills in arguments from the generated JSON Schema, and walks the OAuth auth flow against your configured Authorization Server.

Documentation

  • Quickstart — copy-pasteable end-to-end.
  • Concepts — tools vs resources, sessions, output formats.
  • Authentication — backends, permissions, audience binding, bring-your-own AS recipe.
  • Recipes — focused cookbook entries.
  • Reference — autodocs for every public symbol.

License

MIT.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

djangorestframework_mcp_server-0.19.0.tar.gz (477.7 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

djangorestframework_mcp_server-0.19.0-py3-none-any.whl (236.5 kB view details)

Uploaded Python 3

File details

Details for the file djangorestframework_mcp_server-0.19.0.tar.gz.

File metadata

File hashes

Hashes for djangorestframework_mcp_server-0.19.0.tar.gz
Algorithm Hash digest
SHA256 8a40adf9e5f7fae19d24b7a959371fdd741dfd6668b6eb3449c1b16a805a61e9
MD5 0e5267cc70f45b538374a692032f2949
BLAKE2b-256 7f9761b4457b302ed0a4158b6d2b518080e7689a46e30f40f9933d33d3b06519

See more details on using hashes here.

Provenance

The following attestation bundles were made for djangorestframework_mcp_server-0.19.0.tar.gz:

Publisher: release.yml on Artui/djangorestframework-mcp-server

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file djangorestframework_mcp_server-0.19.0-py3-none-any.whl.

File metadata

File hashes

Hashes for djangorestframework_mcp_server-0.19.0-py3-none-any.whl
Algorithm Hash digest
SHA256 1f1b9e0c9f4fda99b771eb5af7f40c253db0158cd9426ce7b034d899cfdb1463
MD5 6166b09f844de65e6d819a9fd8a370c7
BLAKE2b-256 2f0e76817a4d342fafa3aacfff3678cfa502cbfe22c0aad0bcec4041ca55f007

See more details on using hashes here.

Provenance

The following attestation bundles were made for djangorestframework_mcp_server-0.19.0-py3-none-any.whl:

Publisher: release.yml on Artui/djangorestframework-mcp-server

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page