Architecture
django_mcp contains two independent subsystems that share configuration and a global tool registry but otherwise operate completely separately.
Two subsystems
1. MCP Protocol Server
Exposes Django data to external AI clients via the Model Context Protocol JSON-RPC 2.0 wire format.
External AI client (Claude Desktop, Cursor, custom agent)
│ POST /cfg/mcp/ (JSON-RPC 2.0, X-MCP-Access-Key header)
▼
MCPView (views.py)
│
├── method: initialize → handlers/initialize.py
├── method: tools/list → handlers/tools.py → tool_registry.get_all_tools()
├── method: tools/call → handlers/tools.py → tool.execute(context, args)
└── method: resources/list → handlers/resources.pyEvery tool call receives an MCPContext (from services/context.py) carrying user (AnonymousUser by default, or the resolved service account when service_username is set), session_key (used for logging only — never an authorization input), the Django request, and the resolved DjangoMCPModuleConfig. There is no raw access_key field on the context; the key is only ever compared during authentication.
2. Application Agent API
Optional LLM-powered endpoints for application-specific clients. The admin Overview has no embedded chat UI. It bypasses the MCP protocol entirely — it talks directly to the LLM via django_llm and uses MCP tools as plain Python callables.
Authorized application client
│ POST /cfg/mcp/agent/stream/
│ body: {message, session_id, model}
│ auth: Django session cookie + CSRF token
▼
MCPAgentStreamView (agents/api/views.py)
│ validates auth, parses body
│ builds AgentContext with all registered tools
│ calls agent_runner.stream(message, context)
▼
MCPAgentRunner (agents/runner/runner.py)
│
│ ┌─────────────────────────────────────┐
│ │ pydantic_ai.Agent over the MCP tools │
│ │ (django_llm harness owns the loop) │
│ │ │
│ │ each MCPTool → pydantic_ai.Tool via │
│ │ Tool.from_schema(input_schema) │
│ │ execute() runs in a thread │
│ └─────────────────────────────────────┘
│ ↓
│ final text answer
▼
StreamingHttpResponse (text/event-stream)
▼
Browser JS reads ReadableStream, renders tool calls + final answerRequest lifecycle
MCPView.post() (the JSON-RPC endpoint) runs four steps for every request:
- Parse the JSON-RPC 2.0 envelope. A malformed body returns a JSON-RPC parse error, not an HTTP-level 400.
- Authenticate and enforce.
_authenticate()resolves the caller (AnonymousUseror the configured service account) fromX-MCP-Access-Key. Its return value is enforced immediately: if authentication fails and a key is required, the request is rejected with401before any handler runs. - Derive a session key for logging only.
_get_session_key()computes a key from the request, but nothing is gated on it — see below. - Route to the JSON-RPC method handler (
initialize,tools/list,tools/call,resources/list, …) with a freshly builtMCPContext.
The transport is intentionally stateless, per the MCP Streamable HTTP spec. The server never issues an Mcp-Session-Id header, and nothing is gated on _is_initialized or any other session state — every tools/call is authenticated and authorized independently of whether initialize was ever called on that connection. Gating on session state without issuing a session ID previously broke every spec-compliant client: state was keyed on a hash of IP + User-Agent, so initialize and the following tools/call looked like different sessions whenever a client’s requests didn’t share one identical User-Agent — which is exactly what happens with real MCP clients spread across worker processes.
A 401 response carries WWW-Authenticate: MCPAccessKey realm="mcp", header="X-MCP-Access-Key" — a custom scheme, not Bearer. Bearer reads as OAuth 2.0 to MCP clients, which then go looking for /.well-known/oauth-protected-resource and fail in a way that’s harder to diagnose than a plain 401. The one exception is a profile with OAuth sign-in enabled: it does serve that discovery, so it answers Bearer resource_metadata=....
Profile routing
A profile is resolved from the URL the request arrived on, never from a header, and it is what step 2 and step 4 above read. MCPView.as_view(profile="public") binds a view to one; the plain MCPView falls back to the synthesised default profile, which is what every URL registered before profiles existed resolves to.
Profile routes are registered by django_cfg.apps.urls, not by the project — a profile that exists in the config but on no URL is invisible in the worst way: the config reads correct, the tool filter works, and the endpoint 404s. urls.profile_urlpatterns() builds them lazily, behind a URLResolver whose URLconf is resolved on first use. The module is imported while settings are still being built, when the MCP config does not yet exist; reading it at import time yields None and silently registers nothing, and an empty list is a perfectly valid URLconf, so the routes simply would not be there.
Both MCPView and MCPInfoView read the profile the same way, and take the access key from the same object — the profile when one resolves, the flat config otherwise. Taking the gate from one and the key from the other would let a profile be gated by one key and unlocked by another.
Shared tool registry
Both subsystems use the same global MCPToolRegistry instance from tools/base.py. Tools are registered once in handlers/tools.py at import time, which is triggered by auto_loader.py inside AppConfig.ready(). After Django startup, both MCPView and MCPAgentRunner pull from the same registry — adding a tool makes it available in both contexts simultaneously.
Module layout
django_mcp/
├── __cfg__.py DjangoMCPModuleConfig — Pydantic config
├── views.py JSON-RPC MCP protocol endpoint
├── urls.py URL routing for all MCP endpoints
├── apps.py Django AppConfig
├── auto_loader.py Loads tools and handlers at AppConfig.ready()
│
├── agents/ Application agent layer
│ ├── api/
│ │ ├── views.py MCPAgentChatView (sync), MCPAgentStreamView (SSE),
│ │ │ MCPAgentHistoryView
│ │ └── serializers.py DRF serializers for agent request/response
│ ├── runner/
│ │ ├── runner.py MCPAgentRunner — the pydantic-ai harness run
│ │ └── _harness_tools.py Wraps each MCPTool as a pydantic_ai.Tool
│ └── services/
│ └── agent_service.py High-level wrapper for the sync view
│
├── handlers/ MCP protocol method handlers
│ ├── tools.py tools/list + tools/call + registry population
│ ├── initialize.py initialize handshake handler
│ └── resources.py resources/list handler
│
├── tools/ Built-in MCP tool implementations
│ ├── base.py MCPTool ABC + MCPToolRegistry
│ ├── model_tools.py query_model, get_object
│ ├── introspection.py list_apps, get_model_schema, list_urls
│ ├── command_tool.py execute_command (management commands)
│ └── user_info.py get_user_info
│
├── agent/ Advanced analytics tools (ORM-level)
│ └── orm_tools.py aggregate_model, time_series, top_values, distribution
│
├── protocols/ JSON-RPC 2.0 types and parser
├── services/ MCPContext dataclass + PII redactor
├── sql/ pglast AST validator + EXPLAIN cost estimator (`mcp-sql` extra)
├── models/ MCPAuditLog Django model
├── cache.py QueryCache — Redis query result cache
├── budget.py QueryBudget — per-session resource limits
└── chat/ RedisMCPChatStore — application agent conversation historyLLM integration
The application agent builds a pydantic_ai.Agent and delegates the agentic loop to django_llm’s harness, which resolves the provider (OpenRouter first). MCPAgentRunner keeps its public surface — run(...) -> str and stream(...) -> Generator[dict] — so callers are unaffected by that.
Each registered MCPTool is wrapped as a pydantic_ai.Tool: input_schema becomes the parameter schema via Tool.from_schema, and execute() runs in a thread (sync_to_async), because it is synchronous and may touch the ORM — a tool coroutine that blocked on the database would stall the event loop the streaming path drives. A tool that raises returns its error as the tool result rather than raising into the loop, so the model can read the failure and recover.
The model is resolved in this priority order:
modelfield in the request body (explicit per-request override)mcp_config.llm_modelfromDjangoMCPModuleConfig(default:"openai/gpt-4.1-nano")- Hard fallback:
"openai/gpt-4o-mini"
Security boundaries
| Path | Auth mechanism | Who can access |
|---|---|---|
POST /cfg/mcp/ | X-MCP-Access-Key header | External MCP clients with static key |
POST /cfg/mcp/agent/ | X-MCP-Access-Key header | Programmatic agents with static key |
POST /cfg/mcp/agent/stream/ | Django session + CSRF token | Authenticated users |
GET /cfg/mcp/info/ | X-MCP-Access-Key header | The same holders as POST /cfg/mcp/; there is no public listing |
POST <profile.path> | That profile’s keys (access_key, extra_keys, key_validator) | Callers of that profile — see Profiles |
GET <profile.path>info/ | That profile’s keys (access_key, extra_keys, key_validator) | Holders of that profile’s keys only |
The streaming endpoint (agent/stream/) checks request.user.is_authenticated and requires a valid CSRF token. There is no built-in admin UI; consuming applications must enforce their intended access policy.
Authorisation is mandatory. /info/ returns tool names, descriptions and full input schemas — a capability map — so it needs the key like every other MCP route. access="anonymous" and public_info were removed; a config without a credential does not build.
Effective model policy
MCPContext resolves the URL-selected profile into a request-local copy of model exposure and introspection settings. Explicit profiles have no global fallback, and a multi-profile programmatic context must select a profile rather than guess a wider one. The legacy flat surface carries its global grants into its synthesized default profile so round-tripping configuration preserves the intended behavior. Request-local changes do not mutate another profile or the shared configuration.
An optional positive scalar policy is validated before the ORM evaluates a query. It owns output columns, filter/order fields, fixed row scope and bounded pagination/serialization. The basic and extended query implementations share this path; unsupported readers refuse it. Schema discovery uses the same projected names and does not expand foreign-key identities into related records.
restricted_reads further narrows capability discovery and execution to explicitly named, reviewed built-ins. Remote providers and registered resources/prompts are skipped before callbacks are evaluated. All authoritative HTTP credential checks reserve dedicated reader keys before broader validator/OAuth fallback; a reader key cannot become an operator or agent-chat credential. Existing general-purpose profiles retain their explicit capabilities, while the new restricted surface grants no write, SQL, command or arbitrary custom-tool path.
Restricted model-read configuration describes the public API. This is an application permission boundary, not a claim of database transaction enforcement or proof that a consuming deployment has updated its code and credential scope.