Configuration
The module is configured via DjangoMCPModuleConfig in your project’s config.py. Assign it to DjangoConfig.mcp.
Minimal setup
from django_cfg import DjangoConfig
from django_cfg.modules.django_mcp.__cfg__ import DjangoMCPModuleConfig
class MyConfig(DjangoConfig):
mcp = DjangoMCPModuleConfig(
enabled=True,
access_key="your-secret-key",
)When enabled=False (the default), the MCP endpoint exists but returns errors on every call. The admin Overview does not embed an MCP connection tab or chat.
Top-level fields
| Field | Type | Default | Description |
|---|---|---|---|
enabled | bool | False | Master switch. Must be True for any MCP functionality. |
endpoint_path | str | "/cfg/mcp/" | URL path for the JSON-RPC endpoint. |
llm_model | str | "openai/gpt-4.1-nano" | Default model for the application agent (OpenRouter format). |
access_key | str | None | None | Static key for X-MCP-Access-Key header auth. The implicit default profile requires a key or additional keys; explicit profiles may use a validator. Every tool and full discovery request requires an accepted credential. |
service_username | str | None | None | Bind access_key to a real Django account. See Service accounts below. |
rate_limit | str | "100/minute" | Format: "N/period". Period is second, minute, hour, or day. |
protocol_version | str | "2025-03-26" | MCP protocol version reported in the initialize handshake. |
server_name | str | None | project slug | Server name reported in initialize. |
server_version | str | "1.0.0" | Server version reported in initialize. |
enable_streaming | bool | False | Reserved for future protocol-level streaming. Does not affect application SSE agent responses. |
enable_audit_log | bool | True | Write every MCP operation to MCPAuditLog. |
install_targets | Dict[str, MCPTargetConfig] | {} | Deployments manage.py mcp_install --<name> can register. See mcp_install. |
profiles | Dict[str, MCPProfile] | {} | MCP surfaces this process serves, keyed by profile name. Empty means the flat fields above describe one implicit surface. See Profiles below. |
Service accounts
By default, a valid access_key authenticates the caller as AnonymousUser. That’s deliberate — tools gated on user.is_staff refuse an anonymous caller, so a leaked key doesn’t automatically unlock staff-only tools. Set service_username to bind the key to a real, auditable Django account instead:
mcp = DjangoMCPModuleConfig(
enabled=True,
access_key="your-secret-key",
service_username="mcp-service",
)Two things change once service_username is set:
- A missing account is a rejection, not a fallback. If no user matches
service_username, the request gets a 401 — it never silently falls back toAnonymousUser. The same is true for an inactive account (is_active=False). - The key becomes that account’s password. Every holder of the key gets that account’s permissions, and every action it takes is attributable to that username rather than to “somebody with the key”. Treat the key with the same care as a real credential — never commit it.
The ergonomic entry point is MCPConfigBuilder.set_access_key(key, service_username=...) — see Declarative config via MCPConfigBuilder below.
Authorisation is mandatory
There is no anonymous mode. A missing key, access="anonymous" and the old public_info flag all raise a ValueError with migration advice. GET <endpoint>/info/ returns the tool listing (names, descriptions, full input schemas) — a capability map — so it requires the same X-MCP-Access-Key as JSON-RPC on that profile. Tool calls, tool discovery and the full tool listing require an accepted credential. Bootstrap installer/skill files and OAuth discovery may be public; they do not expose an anonymous tool surface.
An unauthorized request gets 401 with WWW-Authenticate: MCPAccessKey realm="mcp", header="X-MCP-Access-Key" — not Bearer, deliberately, so MCP clients don’t mistake it for OAuth and go looking for discovery that isn’t there. A profile that enables OAuth sign-in answers Bearer resource_metadata=... instead, and every profile reads the credential from X-MCP-Access-Key or Authorization: Bearer.
Profiles
A profile is one MCP surface, and it binds three things that must never be set independently: credentials, a tool set, and a mount path. One Django process can serve several — typically an operator endpoint plus a public-tools one. Every profile is key-protected: “public” means only public = True tools, for a wider set of key holders, never “no key”.
The implicit default profile
A deployment that declares no profiles still has exactly one surface. DjangoMCPModuleConfig synthesises a profile named default from the flat fields — endpoint_path, access_key, service_username, rate_limit — serving all tools. Nothing changes for existing projects; the request path just always has a profile to read.
The synthesised profile is key-protected like any other; if access_key and extra_keys are both empty the config refuses to build.
MCPProfile fields
| Field | Type | Default | Description |
|---|---|---|---|
name | str | — | Profile identifier, matching ^[a-z][a-z0-9_-]*$. |
path | str | — | URL path this profile is mounted at. Must start with /. |
access | str | "key" | Always "key"; "anonymous" raises with migration advice. |
access_key | str | None | None | Primary key. At least one of access_key, extra_keys, key_validator is required. |
extra_keys | List[MCPExtraKey] | [] | Further keys, one per holder. |
key_validator | str | None | None | Dotted path to callable(key: str) -> user | True | None for per-user API keys kept in your database. Checked after the static keys. |
service_username | str | None | None | Account the static key acts as. |
tools | List[str] | [] | Tool names this profile serves, ["*"] for all, or ["public"] for every tool declaring public = True. Defaults to empty, never to all. |
exposures | Dict[str, ModelMCPConfig] | {} | Model exposures scoped to this profile, keyed by "app.Model". |
introspection | IntrospectionConfig | None | None | Introspection for this profile. |
rate_limit | str | "100/minute" | Rate limit for this profile’s endpoints. |
ALL_TOOLS ("*") and PUBLIC_TOOLS ("public") are importable from django_cfg.modules.django_mcp. PUBLIC_TOOLS resolves by reading each tool class’s own public flag rather than restating a list in your config, so adding a tool cannot silently change what is public in either direction.
The one-call form
The common case — an operator surface plus a public-tools one — is a single builder call:
from django_cfg.modules.django_mcp import MCPConfigBuilder
mcp = MCPConfigBuilder()
mcp.set_access_key("your-secret-key", service_username="mcp-service")
mcp.enable_public_profile(
path="/mcp/",
rate_limit="20/minute",
) # defaults to django-cfg personal UserAPIKey validation
mcp_config = mcp.build()Everything configured before that call becomes the operator profile, mounted at the default endpoint_path and serving all tools. public is added beside it at path, serving only tools that declare public = True, and it is key-protected too. The operator keys do not open the public profile. With neither key_validator nor public_keys, the builder uses auth.validate_user_api_key and resolves each valid personal key to its active django-cfg user. Supply a custom validator and/or separately assigned static keys only when the project needs them. A custom validator returns the account (or True for a machine caller) on success, and None to refuse. Inactive users and rotated personal keys are rejected. The built-in frontend Settings integration can reveal or renew a user’s own key through the existing accounts API; it does not use Admin Overview.
rate_limit defaults tighter than the operator’s ("20/minute"). enable_public_profile() requires that set_access_key() was called first.
Writing profiles by hand
mcp.profile(name, path) returns a ProfileBuilder used as a context manager, so it is visible which surface each setting belongs to:
mcp = MCPConfigBuilder()
with mcp.profile("operator", path="/cfg/mcp/") as op:
op.set_access_key("your-secret-key", "mcp-service")
op.tools("*")
op.enable_introspection(expose_urls=True)
with mcp.profile("public", path="/mcp/") as pub:
pub.set_key_validator("api.mcp_keys.validate")
pub.tools("catalog_search", "catalog_get")
pub.set_rate_limit("20/minute")
pub.expose("catalog.Product", max_results=20)
mcp_config = mcp.build()Declaring a profile by hand means profiles describe every surface. build() rejects a config that mixes hand-written profiles with the flat set_access_key() / enable_introspection() calls — a flat setting alongside profiles governs no endpoint while looking like it protects one. enable_public_profile() is exempt, because there the flat settings are the operator profile’s source.
What fails at build
- a profile with no credential (
access_key,extra_keysorkey_validator); access="anonymous"andpublic_info— removed, with migration advice in the message;enable_public_profile()without the preceding operator access key (omitting a custom validator and public keys is valid: personal keys are the default);- a repeated key or key label.
Two further checks run at the config level: two profiles mounted at the same path is rejected (one would silently shadow the other), and an install_targets entry naming a profile that does not exist is rejected where the typo is.
Routing
Profiles are mounted by URL, never selected by a header — a header would let the caller choose their own surface, making the public tool set advisory rather than enforced. Each declared profile gets its own tool and discovery routes, registered by django_cfg’s URL configuration (plus bootstrap and OAuth routes where applicable):
| Route | View |
|---|---|
POST <profile.path> | JSON-RPC endpoint for that profile |
GET <profile.path>info/ | Tool listing for that profile |
The profile whose path equals endpoint_path is skipped, because urls.py already serves it wherever the project mounted the module. The agent endpoints (agent/, agent/stream/, agent/history/) are deliberately not mounted per profile: they spend an LLM budget on the deployment’s account, so a public profile must not expose them.
Enforcement
tools/call re-checks the profile, not just tools/list. Filtering the listing alone is cosmetic — a caller who learned an operator tool’s name from documentation, another deployment, or a leaked listing could still invoke it. A refused call is reported as not found rather than forbidden: from that profile’s perspective the tool genuinely does not exist, and a permission error would confirm it is real, which is what the filtered listing set out to withhold.
introspection — IntrospectionConfig
Controls whether agents can discover the app’s structure through introspection tools.
| Field | Default | Description |
|---|---|---|
enabled | False | Allow list_apps and get_model_schema tools. |
expose_urls | False | Allow the list_urls tool — returns URL patterns. |
expose_code | False | Expose view source snippets. Development use only. |
max_depth | 3 | Max relationship traversal depth (1–10). |
from django_cfg.modules.django_mcp.__cfg__ import DjangoMCPModuleConfig, IntrospectionConfig
mcp = DjangoMCPModuleConfig(
enabled=True,
introspection=IntrospectionConfig(
enabled=True,
expose_urls=True,
),
)When introspection.enabled = False, the introspection tools exist in the registry but return permission-denied responses.
exposed_apps — Dict[str, AppMCPConfig]
Controls which Django app models are accessible via query_model and get_object. Apps not listed here are not accessible to any MCP tool.
from django_cfg.modules.django_mcp.__cfg__ import (
DjangoMCPModuleConfig,
AppMCPConfig,
ModelMCPConfig,
)
mcp = DjangoMCPModuleConfig(
enabled=True,
exposed_apps={
"auth": AppMCPConfig(
enabled=True,
models={
"user": ModelMCPConfig(
enabled=True,
read_only=True,
hidden_fields=["password", "last_login"],
max_results=50,
allowed_operations=["list", "retrieve"],
),
},
),
},
)AppMCPConfig fields
| Field | Default | Description |
|---|---|---|
enabled | False | App-level switch. All models are inaccessible when False. |
models | {} | Per-model config, keyed by lowercase model name. |
max_results | 100 | Default max_results applied to all models in this app. |
ModelMCPConfig fields
| Field | Default | Description |
|---|---|---|
enabled | False | Model-level switch. |
read_only | True | If True, only list and retrieve operations are permitted. |
hidden_fields | [] | Fields stripped from all responses for this model. |
max_results | 100 | Max rows returned per query (1–1000). |
allowed_operations | ["list", "retrieve"] | Permitted operations. Subset of: list, retrieve, create, update, delete. |
commands — CommandMCPConfig
Controls the execute_command tool that runs Django management commands.
| Field | Default | Description |
|---|---|---|
enabled | False | Allow management command execution. |
allowed_commands | [] | Whitelist of command names. Commands not listed are rejected outright. |
timeout_seconds | 30 | Max execution time per command (1–300 seconds). |
from django_cfg.modules.django_mcp.__cfg__ import CommandMCPConfig
mcp = DjangoMCPModuleConfig(
enabled=True,
commands=CommandMCPConfig(
enabled=True,
allowed_commands=["check", "migrate_all", "shell"],
timeout_seconds=60,
),
)Be conservative with allowed_commands. Management commands like flush, migrate, or shell can have destructive effects. Only whitelist commands you are comfortable with an AI agent running autonomously.
redaction — RedactionConfig
Automatic PII redaction applied to tool results before they are returned to the agent.
| Field | Default | Description |
|---|---|---|
enabled | True | Enable redaction processing. |
mode | "REDACT" | NONE / REDACT / BLOCK — see below. |
custom_patterns | {} | Extra regex patterns as {"label": "pattern"}. |
Modes:
NONE— results pass through unchanged.REDACT— text matching any pattern is replaced with[REDACTED].BLOCK— if any match is found, the entire result is rejected with an error.
Built-in patterns detect: email addresses, phone numbers, credit card numbers, and US Social Security Numbers.
from django_cfg.modules.django_mcp.__cfg__ import RedactionConfig
mcp = DjangoMCPModuleConfig(
enabled=True,
redaction=RedactionConfig(
mode="REDACT",
custom_patterns={
"api_key": r"sk-[a-zA-Z0-9]{32,}",
"internal_id": r"INT-[0-9]{8}",
},
),
)Declarative config via MCPConfigBuilder
MCPConfigBuilder is a fluent, method-chaining alternative to constructing DjangoMCPModuleConfig (and its nested models) by hand. It’s the pattern most projects use — put it in <project_root>/mcp/__init__.py:
from django_cfg.modules.django_mcp import MCPConfigBuilder
mcp = MCPConfigBuilder()
# Expose models
mcp.expose("profiles.UserProfile")
mcp.expose("accounts.User", hidden_fields=["password", "secret_key"])
mcp.expose("orders.Order", operations=["list", "retrieve", "create"])
# Allow management commands
mcp.allow_command("clearsessions")
# Custom tools
@mcp.tool(name="get_user_stats", description="Get user statistics")
def get_user_stats(ctx, user_id: str) -> str:
return f"Stats for user {user_id}"
# Enable introspection
mcp.enable_introspection(expose_urls=True)
# Auth + install targets
mcp.set_access_key("your-secret-key", service_username="mcp-service")
mcp.add_target("local")
mcp.add_target("prod", "../../deploy/.env")
mcp_config = mcp.build()| Method | Equivalent to |
|---|---|
.expose(model_path, ...) | An entry in exposed_apps |
.allow_command(name, staff_only=False) | An entry in commands.allowed_commands |
.enable_introspection(expose_urls=..., expose_code=...) | introspection config |
.tool(name, description, input_schema=None) | Decorator that registers a custom MCPTool |
.set_access_key(key, service_username=None) | access_key + service_username |
.add_target(kind, *env_files, url=None, access_key=None, server_name=None, profile=None) | An entry in install_targets, keyed by kind |
.profile(name, path) | A hand-written entry in profiles — used as a context manager |
.enable_public_profile(path="/mcp/", rate_limit="20/minute", expose=None, key_validator=None, public_keys=None) | An operator + key-protected public profile pair |
.set_llm_model(model) | llm_model |
.set_rate_limit(limit) | rate_limit |
.disable() | enabled=False |
.build() | Returns the assembled DjangoMCPModuleConfig |
.add_target() declares a deployment manage.py mcp_install --<kind> can register — see mcp_install for the full resolution and probing behavior. kind="local" needs no env_files: the running process is that deployment, so its own access_key/URL answer directly. A remote target ("prod", "staging", …) should point at the dotenv file(s) that configure that deployment — resolving a remote target’s key from the current process would register the local development key against production.
Helper methods
DjangoMCPModuleConfig exposes convenience methods used internally by tools:
config.is_model_exposed("auth", "user") # → bool
config.get_model_config("auth", "user") # → ModelMCPConfig | None
config.is_command_allowed("migrate_all") # → boolThese are available in your custom tool implementations via the MCPContext object passed to execute().
Restricted model-read profiles
Use a dedicated profile for an assistant that may read selected scalar records. Its exposures are authoritative: an explicitly declared profile never falls back to global model exposure. An empty exposure map denies generic model reads. The implicit flat default profile and the operator profile synthesized by enable_public_profile() retain the global model grants they intentionally copy.
import os
from django_cfg.modules.django_mcp import MCPConfigBuilder, ScalarReadPolicy
mcp = MCPConfigBuilder()
with mcp.profile("reader", path="/cfg/mcp/reader/") as reader:
reader.set_access_key(os.environ["MCP_READER_KEY"])
reader.restrict_model_reads()
reader.tools("query_model")
reader.expose(
"billing.Customer",
max_results=25,
read_policy=ScalarReadPolicy(
fields=["id", "email", "plan", "tenant_id"],
filter_fields=["id", "email"],
order_fields=["id"],
scope={"tenant_id": 7},
),
)
mcp_config = mcp.build()The models and tenant in this example are invented. Supply a dedicated credential through your own deployment secret mechanism. Restricted readers accept static keys only; they cannot reuse a key assigned to another profile or fall through another profile’s key validator or OAuth authentication. They have no chat-agent capability.
ScalarReadPolicy is also accepted by ModelMCPConfig.read_policy and the builder’s flat expose method. It is an explicit opt-in; existing grants without it retain their legacy serialization. Restricted profiles require it for every enabled model. A projection cannot grant writes, include hidden/credential fields or omit the actual primary key. Filter, order and fixed-scope fields must be in the projection. Foreign-key identities use concrete scalar columns such as tenant_id, without loading related objects. JSON, files, binary values, relation traversal and unknown columns refuse.
Restricted profiles admit only reviewed built-in implementations of query_model, get_object, list_apps and get_model_schema, and only names explicitly listed in tools. Wildcards, public-tool macros, custom lookalikes, analytics, SQL, commands and authentication-user readers are not admitted. Registered resources/prompts and remote providers are not loaded; model-schema resources still require introspection and expose the selected fields only. Custom Python tools are not automatically rewritten to enforce model policy: keep them outside this restricted surface.
Caller filters use approved fields and bounded scalar lookups (exact, iexact, contains, icontains, gt, gte, lt, lte, isnull, in). At most 12 filters and 25 in values apply. The pk alias resolves to the real projected primary key and requires that field in filter_fields. A caller predicate cannot replace or broaden scope; incompatible predicates refuse. Ordering is approved fields plus a stable primary-key tie-breaker.
Projected reads return at most 25 rows, with the lower model max_results taking precedence; offsets are 0–1000. Strings are bounded to 4096 characters, and request/response JSON to 128 KiB. An oversized page or invalid value refuses the whole result. Errors carry static policy advice, not raw record values or ORM exceptions. Neither the MCP readOnlyHint nor this profile replaces a read-only database role where the deployment requires one.
For existing explicit profiles that relied on global expose calls, move each intended grant onto that profile. A framework release does not update running product images: verify the deployed version and profile/model/field/tenant restrictions before enabling a consuming gateway.