Skip to Content
FeaturesModulesMCP (AI Agents)MCP Tools

MCP Tools

Tool registry

tools/base.py defines MCPTool (abstract base class) and MCPToolRegistry. A single global tool_registry instance is shared across the whole Django process.

Tools are registered in handlers/tools.py at import time. That module is imported by auto_loader.py, which is called from AppConfig.ready(). By the time Django finishes startup, all tools are registered and available to both the MCP protocol server and the application agent.

Built-in tools

Introspection (tools/introspection.py)

Controlled by DjangoMCPModuleConfig.introspection. When introspection.enabled = False, these tools exist in the registry but return permission-denied responses.

ToolDescription
list_appsLists all installed Django apps and their models.
get_model_schemaReturns field definitions for a specific model.
list_urlsReturns URL patterns (requires introspection.expose_urls = True).

list_urls is paginated — a real project can have thousands of URL patterns, and an unbounded response has been measured at ~9,700 patterns / ~360 KB / ~90k tokens in a single tool result, enough to consume an agent’s entire context window on one call. It accepts:

ArgumentDefaultDescription
contains—Substring filter, matched against the pattern or the URL name.
limit200Max patterns returned, capped at 2000.
offset0Skip this many matches — for paging through a filtered set.

The response includes total_urls, matched, returned, offset, and truncated: bool so an agent can tell “these are all the matches” from “there are more — increase offset or narrow contains”.

Model queries (tools/model_tools.py)

Both tools check config.is_model_exposed(app_label, model_name) before executing. Fields listed in ModelMCPConfig.hidden_fields are stripped from results. max_results caps the queryset size.

ToolDescription
query_modelFilter and list records from any exposed model.
get_objectRetrieve a single record by primary key.

Management commands (tools/command_tool.py)

ToolDescription
execute_commandRun a Django management command.

Only commands in CommandMCPConfig.allowed_commands are permitted. Execution is capped at timeout_seconds. Output is captured and returned as a string.

User info (tools/user_info.py)

ToolDescription
get_user_infoReturns information about the current agent session.

Advanced analytics (agent/orm_tools.py)

These tools bypass the per-model exposure check — they are always available when MCP is enabled. They are intended for analytical queries.

ToolDescription
aggregate_modelCOUNT, SUM, AVG, MIN, MAX on any model field.
time_seriesGroup records by time period (day, week, month).
top_valuesTop N values for a field with occurrence counts.
distributionValue distribution / histogram for a numeric field.

Raw SQL (agent/tools.py — RawSQLTool)

Not registered by default. raw_sql_tool is importable from django_cfg.modules.django_mcp.agent.tools and can be registered like any custom tool; nothing exposes it unless you do.

It runs a read-only SELECT through a four-stage pipeline: pglast AST validation, EXPLAIN cost estimation (rejecting above 50,000 cost units or 10,000 estimated rows), execution inside a read-only transaction with a 5s statement timeout, and a row cap (default 50, max 100).

AST validation requires pglast, shipped as the mcp-sql extra (pip install 'django-cfg[mcp-sql]'). Without it the tool refuses rather than degrading: the only remaining check would be startswith("SELECT"), which a data-modifying CTE (WITH x AS (DELETE ... RETURNING *) SELECT ...) passes. A tool that advertises AST validation must not silently downgrade to a string prefix.

SQLValidator uses PostgreSQL’s own parser, so a keyword hidden in a comment, a dollar-quoted string or a Unicode homoglyph is classified the way the server would classify it rather than the way a regex would. SelectStmt is the only permitted statement type — anything absent from that allowlist is refused, so a future PostgreSQL statement type is refused by default rather than admitted by omission.

Four things beyond the statement check:

  • The whole parse tree is walked, not just the root. A data-modifying CTE (WITH x AS (DELETE ... RETURNING *) SELECT ...) has a SelectStmt root and would otherwise pass the statement check alone.
  • Blocked schemas and tables. pg_catalog, information_schema and the toast/temp schemas are refused, as are credential-bearing tables (auth_user, django_session, authtoken_token, otp_totp_totpdevice, pg_authid, …). Pass allowed_tables / blocked_tables to SQLValidator to change the sets.
  • Dangerous functions — pg_sleep, lo_import/lo_export, dblink, pg_read_file, set_config, pg_terminate_backend and similar — are checked on both the bare and the schema-qualified spelling, since pg_catalog.pg_sleep(10) parses to a two-part name a blocklist keyed on the joined name would miss.
  • CTE names are bound by the query, not by tables. They are collected in a first pass (the walk is breadth-first and reaches FROM active_users before the WITH that declares it) and skipped by the table allowlist — but only when unqualified, so WITH auth_user AS (...) cannot shadow the real table.

Parameters are passed separately as params. psycopg’s %s and %(name)s markers are rewritten to PostgreSQL’s $n outside string literals before parsing, so the parameterised form — the safe one — is not refused as a syntax error, which would push callers toward interpolating values into the string instead.

How tools work

Every tool is a class inheriting MCPTool:

class MCPTool(ABC): name: str = "" # unique identifier used in tool calls description: str = "" # shown to the LLM — affects when the tool is chosen input_schema: Dict # JSON Schema for the arguments object def execute(self, context: MCPContext, arguments: Dict) -> str | ToolResult: ... # a string, or a ToolResult with image/link blocks
  • name is what the LLM uses in a tool call. Must be unique across the registry.
  • description is the most important field — it determines when the LLM decides to use the tool. Write it precisely.
  • input_schema is sent verbatim to the LLM as the function parameter schema in OpenAI tool format.
  • execute() returns a str (one text block) or a ToolResult (text plus image or link blocks, see below). For structured data return a JSON-encoded string. For errors return a plain error message string — do not raise exceptions (the runner catches them and returns the message).
  • is_available(context) may be called with context=None — the /info/ listing checks availability without a request context. If you override is_available, it must tolerate a missing context rather than assume one is always present.
  • public (bool, default False) declares whether the public profile may serve this tool. The default is the design: the tool, declared beside its own code, is the only place that knows whether it is safe to expose. Set it True only for a tool that reads data that is already public, returns no personal data, and cannot mutate anything.
  • schema_for(profile) returns the input schema a given profile should be shown. See Profile-aware schemas below.

Return a ToolResult to attach an image. The text block always comes first, the extra blocks follow in order (MCP 2025-06-18 types: text, image, audio, resource_link, resource).

from django_cfg.modules.django_mcp import ToolResult, image_block, resource_link_block def execute(self, context, arguments): png = render_drawing(arguments["id"]) # bytes return ToolResult( "Drawing 42, 800x600.", [image_block(png, "image/png"), resource_link_block("https://example.com/d/42", "Open in editor")], )

image_block and audio_block take raw bytes and base64-encode them; resource_link_block carries no payload. ToolResult(text, blocks=[], is_error=False); is_error=True marks a tool error. A block with an unknown type raises ValueError when the result is built.

The total base64 payload of the blocks is capped per profile by MCPProfile.max_block_bytes (default 1,000,000). Above it the call returns a tool error that names the limit, so the model can retry with a smaller image or a link. The access log’s bytes= counts the text only.

Profile-aware schemas

A tool whose limit differs per profile must advertise the ceiling that actually applies. input_schema is a class attribute evaluated once at import, so without an override the public listing would keep advertising the operator ceiling while execute quietly returned fewer rows — and an agent reads the schema as the contract, so it reports the clamp as a broken server.

Override schema_for to say so:

import copy class CatalogSearchTool(MCPTool): name = "catalog_search" public = True input_schema = { "type": "object", "properties": { "query": {"type": "string"}, "limit": {"type": "integer", "maximum": 200}, }, "required": ["query"], } def schema_for(self, profile): if profile is not None and profile.name == "public": # A NEW dict — see the warning below. schema = copy.deepcopy(self.input_schema) schema["properties"]["limit"]["maximum"] = 20 return schema return self.input_schema

schema_for must return a new dict. Tools are registered as singleton instances shared by every profile and every request, so mutating self.input_schema per request is a cross-request race, not merely an inaccuracy.

to_definition(profile=None) calls schema_for when a profile is given, and returns the class attribute unchanged when it is not. Both parameters are optional, so a tool that does not override either is unaffected. tools/list passes the request’s profile; GET <path>info/ passes the profile the listing belongs to.

Access logging

Every tools/call writes one line to the django_cfg.modules.django_mcp.handlers.tools logger. A shared or per-user key does not name the individual caller, so this log is the record of what a caller did.

mcp.call profile=public tool=catalog_search ip=198.51.100.7 args=limit,query ms=42 bytes=1731 outcome=ok
FieldMeaning
profileName of the profile that answered, or -
toolRequested tool name
ipClient IP from get_client_ip() (edge trust), else -
argsArgument names, sorted and comma-joined, or -
msWall-clock execution time
bytesLength of the returned string (outcome=ok only)
outcomeok, error, or refused

Argument names are logged; argument values never are. On a public profile the values are attacker-supplied, and a search phrase is the caller’s own words — logging them would make the access log the thing worth stealing. The names still say which shape of call was made.

Three outcomes:

  • outcome=ok at INFO, with bytes.
  • outcome=error at WARNING, carrying error=<ExceptionClassName> — the class name only, not the message, which may quote the arguments.
  • outcome=refused at INFO, when the profile does not serve the requested tool. These are the lines worth reading: an operator_* name posted at the public endpoint is the signal. A refusal is logged before execution, so it carries no args, ms, or bytes.

The address is the one the edge trust rules accept: behind Cloudflare the visitor, never your proxy or a value the caller put in X-Forwarded-For. It is a log field, never an auth input.

This is independent of enable_audit_log / MCPAuditLog, which records MCP operations to the database.

Adding a custom tool

Step 1: Create the tool class

# my_extension/mcp_tools.py from django_cfg.modules.django_mcp.tools.base import MCPTool from django_cfg.modules.django_mcp.services.context import MCPContext class MyCustomTool(MCPTool): name = "my_custom_tool" description = "Does something specific. Use when the user asks about X." input_schema = { "type": "object", "properties": { "param": { "type": "string", "description": "The input parameter", }, }, "required": ["param"], } def execute(self, context: MCPContext, arguments: dict) -> str: param = arguments.get("param", "") # Access config through context if not context.config.enabled: return "MCP is not enabled" # Do your work return f"Result: {param}" my_custom_tool = MyCustomTool()

Step 2: Register the tool

From a Django extension’s AppConfig.ready():

# my_extension/apps.py from django.apps import AppConfig class MyExtensionConfig(AppConfig): name = "my_extension" def ready(self): from django_cfg.modules.django_mcp.tools.base import tool_registry from .mcp_tools import my_custom_tool tool_registry.register(my_custom_tool)

From the core module (when modifying django_mcp itself), add to handlers/tools.py:

# a new module under django_mcp/tools/ (here: tools/my_module.py, which you create) from django_cfg.modules.django_mcp.tools.my_module import my_custom_tool # noqa: placeholder name tool_registry.register(my_custom_tool)

From your project’s mcp/tools/ directory — the simplest path, and the one most projects use. Every *.py file there whose name does not start with _ is imported during AppConfig.ready(), so registering at module level is enough:

# <project_root>/mcp/tools/my_tools.py from django_cfg.modules.django_mcp.tools.base import MCPTool, tool_registry class MyCustomTool(MCPTool): name = "my_custom_tool" description = "Does something specific. Use when the user asks about X." input_schema = {"type": "object", "properties": {}} def execute(self, context, arguments) -> str: return "Result" tool_registry.register(MyCustomTool())

Discovery requires mcp/__init__.py to exist (see Configuration). Prefix a filename with _ to keep it out of discovery — useful for shared helpers.

When a tool module fails to import

A tool file with an import-time error registers nothing, so its tools are simply absent from tools/list. An agent cannot tell that absence apart from “this data does not exist” — it reads as an empty result and the investigation stops, silently, for as long as nobody calls the tool.

Discovery therefore fails loudly in development:

  • debug=True — startup raises ImproperlyConfigured listing every broken module and its exception. All failures are reported together, so you do not fix one per restart.
  • debug=False — the failure is logged at ERROR with the traceback and the module is skipped, so one bad file cannot take production down.
django.core.exceptions.ImproperlyConfigured: 1 MCP tool module(s) in /app/mcp/tools failed to import: - my_tools.py: ModuleNotFoundError: No module named 'requests'

If a file in mcp/tools/ is not meant to be a tool module, rename it with a leading underscore rather than leaving it broken.

Context differences between subsystems

Tools are called with slightly different context depending on which subsystem calls them:

# MCP protocol server — full MCPContext with request info result = tool.execute(context, arguments) # ^^^^^^^ MCPContext: has access_key, tenant, user info # Application agent — config only result = tool.execute(context.config, arguments) # ^^^^^^^^^^^^^^ DjangoMCPModuleConfig only

This is a known inconsistency. Tools that need request-level information (tenant, IP address, user identity) cannot be used safely from the application agent until it passes a full MCPContext. Built-in tools work correctly because they only use context.config or ignore context entirely.

PII redaction

MCPTool exposes execute_with_redaction() which applies the configured redactor after execution:

mode = RedactionMode(context.config.redaction.mode.lower()) return redactor.redact_string(result, mode)

Redaction is opt-in per tool — ToolsHandler calls execute() directly, not execute_with_redaction(). This is intentional: not all tools produce output that needs redaction, and the check adds overhead.

Built-in patterns cover: email addresses, phone numbers, credit card numbers, SSNs. Add custom patterns via redaction.custom_patterns in the configuration.

Positive scalar model reads

A model with read_policy uses the same bounded projected reader in the base and extended query_model implementations. It selects only approved columns and applies fixed row scope before pagination. get_object uses the same policy and approved primary-key mapping. Unsupported enhanced/analytics readers refuse projected models rather than silently taking a broader path. A restricted profile also checks the reviewed implementation at execution, so a custom tool with the same name or a read_only hint gains no access.

The wire arguments remain app label, model name, filters, ordering, limit and offset. Projection comes from server configuration; callers cannot add arbitrary fields, relations, aggregation or raw SQL. Successful query output remains count, model and results; count is the returned page length. Policy refusals use the MCP tool error flag with a bounded explanation and no partial data.

See Restricted model-read profiles for the configuration, limits, dedicated credentials and deployment prerequisites.

Last updated on