django-admin-api-mcp 0.1.0a2__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- admin_api/__init__.py +9 -0
- admin_api/actions.py +115 -0
- admin_api/admin.py +108 -0
- admin_api/apps.py +9 -0
- admin_api/auth.py +62 -0
- admin_api/changelist.py +194 -0
- admin_api/checks.py +35 -0
- admin_api/contrib/__init__.py +1 -0
- admin_api/contrib/subadmin.py +37 -0
- admin_api/custom_views.py +458 -0
- admin_api/decorators.py +26 -0
- admin_api/deletion.py +54 -0
- admin_api/detail.py +127 -0
- admin_api/encoders.py +59 -0
- admin_api/errors.py +44 -0
- admin_api/jsonschema.py +216 -0
- admin_api/management/__init__.py +0 -0
- admin_api/management/commands/__init__.py +0 -0
- admin_api/management/commands/create_api_token.py +40 -0
- admin_api/management/commands/mcp_serve.py +86 -0
- admin_api/mcp/__init__.py +7 -0
- admin_api/mcp/bridge.py +71 -0
- admin_api/mcp/confirm.py +54 -0
- admin_api/mcp/handlers.py +665 -0
- admin_api/mcp/server.py +75 -0
- admin_api/mcp/sites.py +198 -0
- admin_api/mcp/stdio.py +53 -0
- admin_api/mcp/tools.py +84 -0
- admin_api/mcp/views.py +69 -0
- admin_api/middleware.py +18 -0
- admin_api/migrations/0001_initial.py +40 -0
- admin_api/migrations/__init__.py +0 -0
- admin_api/mixins.py +144 -0
- admin_api/models.py +113 -0
- admin_api/nested.py +122 -0
- admin_api/resolver.py +95 -0
- admin_api/scopes.py +121 -0
- admin_api/services.py +423 -0
- admin_api/sites.py +225 -0
- admin_api/views/__init__.py +0 -0
- admin_api/views/changelist.py +50 -0
- admin_api/views/custom.py +31 -0
- admin_api/views/detail.py +39 -0
- admin_api/views/nested.py +70 -0
- admin_api/views/registry.py +15 -0
- admin_api/writes.py +479 -0
- django_admin_api_mcp-0.1.0a2.dist-info/METADATA +274 -0
- django_admin_api_mcp-0.1.0a2.dist-info/RECORD +49 -0
- django_admin_api_mcp-0.1.0a2.dist-info/WHEEL +4 -0
admin_api/mcp/server.py
ADDED
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
"""The MCP server built on the official ``mcp`` SDK (low-level ``Server``).
|
|
2
|
+
|
|
3
|
+
This module and :mod:`.bridge` are the only places that import the SDK. Tools run through
|
|
4
|
+
:meth:`AdminMcpSite.call_tool` in a sync thread (``sync_to_async(thread_sensitive=True)``), so
|
|
5
|
+
when the transport is a sync Django view they run on the view's own thread and DB connection.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import contextvars
|
|
11
|
+
import json
|
|
12
|
+
|
|
13
|
+
import mcp_types as types
|
|
14
|
+
from asgiref.sync import sync_to_async
|
|
15
|
+
from mcp.server import Server
|
|
16
|
+
|
|
17
|
+
# The Django request of the current MCP message (HTTP: the view's request; stdio: one per call).
|
|
18
|
+
current_request: contextvars.ContextVar = contextvars.ContextVar("admin_api_mcp_request")
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def _version() -> str:
|
|
22
|
+
from importlib.metadata import PackageNotFoundError, version
|
|
23
|
+
|
|
24
|
+
try:
|
|
25
|
+
return version("django-admin-api-mcp")
|
|
26
|
+
except PackageNotFoundError: # pragma: no cover
|
|
27
|
+
return "0"
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def _tool(spec) -> types.Tool:
|
|
31
|
+
data = {
|
|
32
|
+
"name": spec.name,
|
|
33
|
+
"title": spec.title,
|
|
34
|
+
"description": spec.description,
|
|
35
|
+
"inputSchema": spec.input_schema,
|
|
36
|
+
}
|
|
37
|
+
if spec.output_schema is not None:
|
|
38
|
+
data["outputSchema"] = spec.output_schema
|
|
39
|
+
if spec.annotations:
|
|
40
|
+
data["annotations"] = {"title": spec.title, **spec.annotations}
|
|
41
|
+
return types.Tool.model_validate(data)
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def build_server(mcp_site, request_factory=None) -> Server:
|
|
45
|
+
"""An SDK ``Server`` whose tools are ``mcp_site``'s.
|
|
46
|
+
|
|
47
|
+
``request_factory()`` returns the Django request for a message; by default the request
|
|
48
|
+
stored in :data:`current_request` by the HTTP view.
|
|
49
|
+
"""
|
|
50
|
+
get_request = request_factory or current_request.get
|
|
51
|
+
|
|
52
|
+
async def on_list_tools(ctx, params):
|
|
53
|
+
request = await sync_to_async(get_request, thread_sensitive=True)()
|
|
54
|
+
return types.ListToolsResult(tools=[_tool(spec) for spec in mcp_site.get_tools(request)])
|
|
55
|
+
|
|
56
|
+
def _call(name, arguments):
|
|
57
|
+
request = get_request()
|
|
58
|
+
return mcp_site.call_tool(request, name, arguments)
|
|
59
|
+
|
|
60
|
+
async def on_call_tool(ctx, params):
|
|
61
|
+
result = await sync_to_async(_call, thread_sensitive=True)(params.name, params.arguments)
|
|
62
|
+
text = json.dumps(result.data, ensure_ascii=False, separators=(",", ":"))
|
|
63
|
+
return types.CallToolResult(
|
|
64
|
+
content=[types.TextContent(text=text)],
|
|
65
|
+
structured_content=result.data,
|
|
66
|
+
is_error=result.is_error,
|
|
67
|
+
)
|
|
68
|
+
|
|
69
|
+
return Server(
|
|
70
|
+
mcp_site.server_name,
|
|
71
|
+
version=_version(),
|
|
72
|
+
instructions=mcp_site.instructions,
|
|
73
|
+
on_list_tools=on_list_tools,
|
|
74
|
+
on_call_tool=on_call_tool,
|
|
75
|
+
)
|
admin_api/mcp/sites.py
ADDED
|
@@ -0,0 +1,198 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import logging
|
|
4
|
+
from weakref import WeakSet
|
|
5
|
+
|
|
6
|
+
from django.conf import settings
|
|
7
|
+
from django.core.exceptions import ImproperlyConfigured
|
|
8
|
+
|
|
9
|
+
from ..auth import TokenAuthenticator
|
|
10
|
+
from ..errors import ApiError, NotAuthenticated, PermissionDeniedError
|
|
11
|
+
from ..mixins import ApiAdminMixin
|
|
12
|
+
from .tools import ToolResult, ToolSpec
|
|
13
|
+
|
|
14
|
+
logger = logging.getLogger("admin_api.mcp")
|
|
15
|
+
|
|
16
|
+
_all_sites: WeakSet = WeakSet()
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def mcp_enabled() -> bool:
|
|
20
|
+
return getattr(settings, "ADMIN_API_MCP_ENABLED", True)
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def all_mcp_sites():
|
|
24
|
+
return list(_all_sites)
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
DEFAULT_INSTRUCTIONS = """\
|
|
28
|
+
This server exposes a Django admin. You act as the authenticated user, with exactly their \
|
|
29
|
+
permissions; validation and business rules are the admin's own.
|
|
30
|
+
1. Call list_models to see what you can access.
|
|
31
|
+
2. Call describe_model before filtering or writing: it lists filter parameters, sortable \
|
|
32
|
+
columns, actions and the JSON Schema for create/update.
|
|
33
|
+
3. Prefer dry_run=true on create_object/update_object before the real write. Write results include the \
|
|
34
|
+
saved document's 'totals' when the admin declares them. When the server requires a dry run, a real \
|
|
35
|
+
write is refused unless you pass the confirm_token returned by a valid dry run of the same write.
|
|
36
|
+
4. delete_object only deletes with confirm=true; without it you get a preview.
|
|
37
|
+
5. Some models have custom views (reports, statements, computed pages, business operations), listed under 'views' by list_models and described (parameters) by describe_model. Run them with run_view; some are also published as their own tools.
|
|
38
|
+
Errors come back with the same envelope as the REST API (error, detail, fields, \
|
|
39
|
+
non_field_errors, inlines)."""
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
class AdminMcpSite:
|
|
43
|
+
"""Exposes an :class:`admin_api.AdminApiSite` as an MCP server.
|
|
44
|
+
|
|
45
|
+
Same admins, permissions, token scopes and write pipeline as the REST API. Hide an admin
|
|
46
|
+
from MCP only with ``mcp_enabled = False``; give the LLM context with ``mcp_description``.
|
|
47
|
+
|
|
48
|
+
The transports are ``urls`` (Streamable HTTP) and ``manage.py mcp_serve`` (stdio); both are
|
|
49
|
+
off when ``settings.ADMIN_API_MCP_ENABLED`` is False.
|
|
50
|
+
"""
|
|
51
|
+
|
|
52
|
+
default_per_page = 25
|
|
53
|
+
confirm_token_max_age = 900 # seconds a dry run's confirm_token stays valid
|
|
54
|
+
instructions = DEFAULT_INSTRUCTIONS
|
|
55
|
+
# Bearer tokens only: MCP clients are not browsers, and a session cookie must not be enough.
|
|
56
|
+
authenticators = [TokenAuthenticator]
|
|
57
|
+
|
|
58
|
+
def __init__(
|
|
59
|
+
self,
|
|
60
|
+
api_site,
|
|
61
|
+
*,
|
|
62
|
+
name: str = "admin_mcp",
|
|
63
|
+
read_only: bool = False,
|
|
64
|
+
server_name: str | None = None,
|
|
65
|
+
instructions: str | None = None,
|
|
66
|
+
require_dry_run: bool = False,
|
|
67
|
+
):
|
|
68
|
+
self.api_site = api_site
|
|
69
|
+
self.name = name
|
|
70
|
+
self.read_only = read_only
|
|
71
|
+
self.server_name = server_name or name
|
|
72
|
+
self.require_dry_run = require_dry_run
|
|
73
|
+
if instructions is not None:
|
|
74
|
+
self.instructions = instructions
|
|
75
|
+
_all_sites.add(self)
|
|
76
|
+
|
|
77
|
+
# --- policy hooks (override in a subclass) -------------------------------------------------
|
|
78
|
+
def is_exposed(self, model_admin) -> bool:
|
|
79
|
+
return self.api_site.is_exposed(model_admin) and getattr(model_admin, "mcp_enabled", True) is not False
|
|
80
|
+
|
|
81
|
+
def get_model_description(self, model_admin, request) -> str | None:
|
|
82
|
+
"""Calls the admin's ``get_mcp_description(request)`` hook; admins without the mixin
|
|
83
|
+
get its default."""
|
|
84
|
+
hook = getattr(model_admin, "get_mcp_description", None)
|
|
85
|
+
if hook is None:
|
|
86
|
+
return ApiAdminMixin.get_mcp_description(model_admin, request)
|
|
87
|
+
description = hook(request)
|
|
88
|
+
return str(description) if description else None
|
|
89
|
+
|
|
90
|
+
def is_view_exposed(self, model_admin, spec) -> bool:
|
|
91
|
+
"""Is the custom view ``spec`` (``@admin_api.view``) of ``model_admin`` exposed through MCP?
|
|
92
|
+
Called after the view's own ``api_enabled`` / ``mcp_enabled`` and the read-only rule."""
|
|
93
|
+
return True
|
|
94
|
+
|
|
95
|
+
def requires_dry_run(self, model_admin) -> bool:
|
|
96
|
+
"""Must writes to ``model_admin`` follow a valid dry run? The admin's ``mcp_require_dry_run``
|
|
97
|
+
(``True``/``False``) overrides the site's ``require_dry_run``."""
|
|
98
|
+
override = getattr(model_admin, "mcp_require_dry_run", None)
|
|
99
|
+
return self.require_dry_run if override is None else bool(override)
|
|
100
|
+
|
|
101
|
+
@property
|
|
102
|
+
def confirm_salt(self) -> str:
|
|
103
|
+
return f"admin_api.mcp.confirm.{self.name}"
|
|
104
|
+
|
|
105
|
+
def get_tools(self, request=None) -> list[ToolSpec]:
|
|
106
|
+
"""The generic tools plus the views published with ``mcp_tool=``. With a ``request``, a
|
|
107
|
+
view tool is only listed when the user may run the view (as checked without an object)."""
|
|
108
|
+
from .handlers import TOOLS
|
|
109
|
+
|
|
110
|
+
tools = [tool for tool in TOOLS if not (self.read_only and tool.writes)]
|
|
111
|
+
return tools + self.get_view_tools(request, reserved={t.name for t in tools})
|
|
112
|
+
|
|
113
|
+
def get_view_tools(self, request=None, *, reserved=()) -> list[ToolSpec]:
|
|
114
|
+
from .. import custom_views
|
|
115
|
+
from .handlers import view_tool
|
|
116
|
+
|
|
117
|
+
out, seen = [], {}
|
|
118
|
+
for model, model_admin in self.api_site.exposed_admins():
|
|
119
|
+
if not self.is_exposed(model_admin):
|
|
120
|
+
continue
|
|
121
|
+
label = f"{model._meta.app_label}.{model._meta.model_name}"
|
|
122
|
+
for spec in custom_views.declared_views(model_admin).values():
|
|
123
|
+
if not spec.mcp_tool:
|
|
124
|
+
continue
|
|
125
|
+
if spec.mcp_tool in reserved or spec.mcp_tool in seen:
|
|
126
|
+
other = seen.get(spec.mcp_tool, "a built-in tool")
|
|
127
|
+
raise ImproperlyConfigured(
|
|
128
|
+
f"MCP tool name {spec.mcp_tool!r} of view {label}:{spec.name} is already used by {other}."
|
|
129
|
+
)
|
|
130
|
+
seen[spec.mcp_tool] = f"{label}:{spec.name}"
|
|
131
|
+
if not spec.api_enabled or not spec.mcp_enabled or (self.read_only and spec.writes):
|
|
132
|
+
continue
|
|
133
|
+
if not self.is_view_exposed(model_admin, spec):
|
|
134
|
+
continue
|
|
135
|
+
if request is not None and not (
|
|
136
|
+
model_admin.has_view_or_change_permission(request)
|
|
137
|
+
and custom_views.has_view_permission(model_admin, request, spec)
|
|
138
|
+
):
|
|
139
|
+
continue
|
|
140
|
+
out.append(view_tool(self, model_admin, spec))
|
|
141
|
+
return out
|
|
142
|
+
|
|
143
|
+
def get_tool(self, name: str, request=None) -> ToolSpec | None:
|
|
144
|
+
return next((tool for tool in self.get_tools(request) if tool.name == name), None)
|
|
145
|
+
|
|
146
|
+
def authenticate(self, request):
|
|
147
|
+
"""Set ``request.user`` from the first authenticator that recognizes the request."""
|
|
148
|
+
for authenticator_class in self.authenticators:
|
|
149
|
+
user = authenticator_class().authenticate(request)
|
|
150
|
+
if user is not None:
|
|
151
|
+
request.user = user
|
|
152
|
+
return user
|
|
153
|
+
raise NotAuthenticated("Send 'Authorization: Bearer <api token>'.")
|
|
154
|
+
|
|
155
|
+
# --- calling tools -------------------------------------------------------------------------
|
|
156
|
+
@staticmethod
|
|
157
|
+
def prepare_request(request):
|
|
158
|
+
"""Mark ``request`` as an MCP request (also an API request, so api_ twins apply)."""
|
|
159
|
+
request.is_api = True
|
|
160
|
+
request.is_mcp = True
|
|
161
|
+
request.is_dry_run = False
|
|
162
|
+
return request
|
|
163
|
+
|
|
164
|
+
def call_tool(self, request, name: str, arguments: dict | None) -> ToolResult:
|
|
165
|
+
"""Run a tool for ``request.user``. Errors become ``is_error`` results with the REST envelope."""
|
|
166
|
+
self.prepare_request(request)
|
|
167
|
+
tool = self.get_tool(name, request)
|
|
168
|
+
if tool is None:
|
|
169
|
+
return ToolResult(_error(ApiError(f"Unknown tool {name!r}.", code="unknown_tool")), is_error=True)
|
|
170
|
+
if arguments is not None and not isinstance(arguments, dict):
|
|
171
|
+
return ToolResult(_error(ApiError("Arguments must be an object.", code="invalid_arguments")), True)
|
|
172
|
+
if not self.api_site.has_permission(request):
|
|
173
|
+
return ToolResult(_error(PermissionDeniedError()), is_error=True)
|
|
174
|
+
try:
|
|
175
|
+
return ToolResult(tool.handler(self, request, arguments or {}))
|
|
176
|
+
except ApiError as exc:
|
|
177
|
+
return ToolResult(_error(exc), is_error=True)
|
|
178
|
+
except Exception:
|
|
179
|
+
logger.exception("MCP tool %s failed", name)
|
|
180
|
+
return ToolResult({"error": "server_error", "detail": "The tool failed; see the server log."}, True)
|
|
181
|
+
|
|
182
|
+
# --- transports ------------------------------------------------------------------------------
|
|
183
|
+
def get_urls(self):
|
|
184
|
+
from .views import mcp_urlpatterns
|
|
185
|
+
|
|
186
|
+
return mcp_urlpatterns(self)
|
|
187
|
+
|
|
188
|
+
@property
|
|
189
|
+
def urls(self):
|
|
190
|
+
return self.get_urls(), "admin_mcp", self.name
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
def _error(exc: ApiError) -> dict:
|
|
194
|
+
payload = {"error": exc.code, "status": exc.status}
|
|
195
|
+
if exc.detail:
|
|
196
|
+
payload["detail"] = exc.detail
|
|
197
|
+
payload.update(exc.extra)
|
|
198
|
+
return payload
|
admin_api/mcp/stdio.py
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
"""stdio transport: ``manage.py mcp_serve``. Imports the SDK."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import anyio
|
|
6
|
+
from django.contrib.auth.models import AnonymousUser
|
|
7
|
+
from django.db import close_old_connections
|
|
8
|
+
from django.test import RequestFactory
|
|
9
|
+
from mcp.server.stdio import stdio_server
|
|
10
|
+
|
|
11
|
+
from ..auth import get_token_model
|
|
12
|
+
from ..writes import capture_messages
|
|
13
|
+
from .server import build_server
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class StdioRequestFactory:
|
|
17
|
+
"""Builds a fresh Django request per MCP message.
|
|
18
|
+
|
|
19
|
+
With ``raw_token`` the token is looked up on every call, so revoking or expiring it takes
|
|
20
|
+
effect immediately and its scopes apply. With ``user`` (development only) there is no token.
|
|
21
|
+
"""
|
|
22
|
+
|
|
23
|
+
def __init__(self, mcp_site, *, raw_token: str | None = None, user=None):
|
|
24
|
+
self.mcp_site = mcp_site
|
|
25
|
+
self.raw_token = raw_token
|
|
26
|
+
self.user = user
|
|
27
|
+
self._factory = RequestFactory()
|
|
28
|
+
|
|
29
|
+
def __call__(self):
|
|
30
|
+
close_old_connections() # long-running process: drop stale/broken DB connections
|
|
31
|
+
request = self._factory.post("/mcp/", content_type="application/json")
|
|
32
|
+
request.user = AnonymousUser()
|
|
33
|
+
if self.raw_token is not None:
|
|
34
|
+
token = get_token_model().objects.get_for_raw(self.raw_token)
|
|
35
|
+
if token is not None and token.user.is_active:
|
|
36
|
+
token.touch()
|
|
37
|
+
request.api_token = token
|
|
38
|
+
request.user = token.user
|
|
39
|
+
elif self.user is not None:
|
|
40
|
+
request.user = self.user
|
|
41
|
+
capture_messages(request) # admin code may call messages.* even on reads
|
|
42
|
+
return self.mcp_site.prepare_request(request)
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def serve(mcp_site, request_factory) -> None:
|
|
46
|
+
"""Serve ``mcp_site`` on stdin/stdout until the client disconnects."""
|
|
47
|
+
server = build_server(mcp_site, request_factory)
|
|
48
|
+
|
|
49
|
+
async def main():
|
|
50
|
+
async with stdio_server() as (read_stream, write_stream):
|
|
51
|
+
await server.run(read_stream, write_stream, server.create_initialization_options())
|
|
52
|
+
|
|
53
|
+
anyio.run(main)
|
admin_api/mcp/tools.py
ADDED
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
"""Tool definitions for the MCP layer. Plain data + sync callables: no MCP SDK import here."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections.abc import Callable
|
|
6
|
+
from dataclasses import dataclass, field
|
|
7
|
+
from typing import Any
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
@dataclass(frozen=True)
|
|
11
|
+
class ToolSpec:
|
|
12
|
+
"""One MCP tool.
|
|
13
|
+
|
|
14
|
+
``handler(mcp_site, request, arguments) -> dict`` runs synchronously in a Django request
|
|
15
|
+
context (``request.user``, ``request.is_api``, ``request.is_mcp``) and raises
|
|
16
|
+
:class:`admin_api.errors.ApiError` on failure.
|
|
17
|
+
"""
|
|
18
|
+
|
|
19
|
+
name: str
|
|
20
|
+
title: str
|
|
21
|
+
description: str
|
|
22
|
+
input_schema: dict
|
|
23
|
+
handler: Callable[..., dict]
|
|
24
|
+
output_schema: dict | None = None
|
|
25
|
+
writes: bool = False
|
|
26
|
+
annotations: dict = field(default_factory=dict)
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
@dataclass
|
|
30
|
+
class ToolResult:
|
|
31
|
+
"""What a tool call returns: ``data`` is the structured result (or the error envelope)."""
|
|
32
|
+
|
|
33
|
+
data: dict
|
|
34
|
+
is_error: bool = False
|
|
35
|
+
|
|
36
|
+
def as_dict(self) -> dict[str, Any]:
|
|
37
|
+
return {"data": self.data, "is_error": self.is_error}
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def obj(properties: dict, required=(), *, additional=False, description=None) -> dict:
|
|
41
|
+
schema: dict[str, Any] = {"type": "object", "properties": properties, "additionalProperties": additional}
|
|
42
|
+
if required:
|
|
43
|
+
schema["required"] = list(required)
|
|
44
|
+
if description:
|
|
45
|
+
schema["description"] = description
|
|
46
|
+
return schema
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
MODEL_ARG = {
|
|
50
|
+
"type": "string",
|
|
51
|
+
"description": "Model exactly as returned by list_models: 'app_label.model_name' (e.g. 'store.sales'), "
|
|
52
|
+
"or a nested path 'app_label.parent/child' for models listed with nested_under (e.g. 'store.client/sales').",
|
|
53
|
+
}
|
|
54
|
+
PARENTS_ARG = {
|
|
55
|
+
"type": "array",
|
|
56
|
+
"items": {"type": ["integer", "string"]},
|
|
57
|
+
"description": "Nested models only: the pk of each parent object, outermost first, one per 'nested_under' "
|
|
58
|
+
"entry (e.g. model 'store.client/sales/salesitem' with parents [client_pk, sales_pk]).",
|
|
59
|
+
}
|
|
60
|
+
PK_ARG = {"type": ["integer", "string"], "description": "Primary key of the object."}
|
|
61
|
+
DATA_ARG = {
|
|
62
|
+
"type": "object",
|
|
63
|
+
"description": "Field values, matching describe_model's input_schema. Inline rows go under 'inlines'.",
|
|
64
|
+
}
|
|
65
|
+
DRY_RUN_ARG = {
|
|
66
|
+
"type": "boolean",
|
|
67
|
+
"default": False,
|
|
68
|
+
"description": "Validate and run the full save pipeline, then roll everything back. "
|
|
69
|
+
"Use it to check a write before doing it.",
|
|
70
|
+
}
|
|
71
|
+
CONFIRM_TOKEN_ARG = {
|
|
72
|
+
"type": "string",
|
|
73
|
+
"description": "Only when the server requires a dry run first: the confirm_token returned by a valid "
|
|
74
|
+
"dry_run of this exact write (same model, pk and data).",
|
|
75
|
+
}
|
|
76
|
+
FILTERS_ARG = {
|
|
77
|
+
"type": "object",
|
|
78
|
+
"additionalProperties": {"type": ["string", "integer", "number", "boolean", "array"]},
|
|
79
|
+
"description": "Admin changelist filter parameters as listed in describe_model's filters[].choices[].params "
|
|
80
|
+
"(e.g. {'status__exact': 'posted', 'client__id__exact': 2}). Arrays repeat the parameter.",
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
# Output schemas are permissive on purpose: the shape depends on each admin's configuration.
|
|
84
|
+
ANY_OBJECT = {"type": "object", "additionalProperties": True}
|
admin_api/mcp/views.py
ADDED
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
"""``/mcp/``: the Streamable HTTP endpoint (stateless, JSON responses).
|
|
2
|
+
|
|
3
|
+
Authentication happens here, in Django, before the SDK sees the request: the site's
|
|
4
|
+
authenticators (API tokens by default; sessions are not accepted), then
|
|
5
|
+
``api_site.has_permission``. The MCP spec requires validating ``Origin`` against DNS
|
|
6
|
+
rebinding; a browser ``Origin`` must be the request's own host or in ``CSRF_TRUSTED_ORIGINS``.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
from urllib.parse import urlsplit
|
|
12
|
+
|
|
13
|
+
from asgiref.sync import async_to_sync
|
|
14
|
+
from django.conf import settings
|
|
15
|
+
from django.http import JsonResponse
|
|
16
|
+
from django.urls import path
|
|
17
|
+
from django.views.decorators.csrf import csrf_exempt
|
|
18
|
+
|
|
19
|
+
from ..errors import ApiError, PermissionDeniedError
|
|
20
|
+
from . import bridge
|
|
21
|
+
from .server import build_server
|
|
22
|
+
from .sites import mcp_enabled
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def _origin_allowed(request) -> bool:
|
|
26
|
+
origin = request.headers.get("Origin")
|
|
27
|
+
if not origin:
|
|
28
|
+
return True # non-browser clients
|
|
29
|
+
if origin in getattr(settings, "CSRF_TRUSTED_ORIGINS", ()):
|
|
30
|
+
return True
|
|
31
|
+
return urlsplit(origin).netloc.lower() == request.get_host().lower()
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def _error(exc: ApiError, **headers) -> JsonResponse:
|
|
35
|
+
response = exc.as_response()
|
|
36
|
+
for key, value in headers.items():
|
|
37
|
+
response[key] = value
|
|
38
|
+
return response
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def make_view(mcp_site):
|
|
42
|
+
server = build_server(mcp_site)
|
|
43
|
+
|
|
44
|
+
@csrf_exempt
|
|
45
|
+
def mcp_view(request):
|
|
46
|
+
request.is_api = True
|
|
47
|
+
if not mcp_enabled():
|
|
48
|
+
return _error(ApiError("MCP is disabled (ADMIN_API_MCP_ENABLED = False).", status=404, code="mcp_disabled"))
|
|
49
|
+
if request.method != "POST":
|
|
50
|
+
# Stateless server: no SSE stream to GET, no session to DELETE.
|
|
51
|
+
response = _error(ApiError("Use POST.", status=405, code="method_not_allowed"))
|
|
52
|
+
response["Allow"] = "POST"
|
|
53
|
+
return response
|
|
54
|
+
if not _origin_allowed(request):
|
|
55
|
+
return _error(PermissionDeniedError("Origin not allowed.", code="origin_not_allowed"))
|
|
56
|
+
try:
|
|
57
|
+
mcp_site.authenticate(request)
|
|
58
|
+
except ApiError as exc:
|
|
59
|
+
return _error(exc, **{"WWW-Authenticate": 'Bearer realm="mcp"'})
|
|
60
|
+
if not mcp_site.api_site.has_permission(request):
|
|
61
|
+
return _error(PermissionDeniedError())
|
|
62
|
+
mcp_site.prepare_request(request)
|
|
63
|
+
return async_to_sync(bridge.handle)(server, request)
|
|
64
|
+
|
|
65
|
+
return mcp_view
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def mcp_urlpatterns(mcp_site):
|
|
69
|
+
return [path("", make_view(mcp_site), name="endpoint")]
|
admin_api/middleware.py
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
class ApiRequestMiddleware:
|
|
2
|
+
"""Sets ``request.is_api``, ``request.is_mcp`` and ``request.is_dry_run`` to ``False`` on
|
|
3
|
+
every request.
|
|
4
|
+
|
|
5
|
+
API views flip ``is_api`` to ``True``; MCP requests set ``is_api`` and ``is_mcp``; MCP
|
|
6
|
+
``dry_run`` writes set ``is_dry_run`` (the write is rolled back afterwards, so hooks can
|
|
7
|
+
skip side effects such as e-mails). With this middleware installed, admin code can use
|
|
8
|
+
these flags directly (no ``getattr``). Enforced by system check ``admin_api.E001``.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
def __init__(self, get_response):
|
|
12
|
+
self.get_response = get_response
|
|
13
|
+
|
|
14
|
+
def __call__(self, request):
|
|
15
|
+
request.is_api = False
|
|
16
|
+
request.is_mcp = False
|
|
17
|
+
request.is_dry_run = False
|
|
18
|
+
return self.get_response(request)
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
# Generated by Django 6.1.2 on 2026-11-02 11:01
|
|
2
|
+
|
|
3
|
+
import django.db.models.deletion
|
|
4
|
+
from django.conf import settings
|
|
5
|
+
from django.db import migrations, models
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class Migration(migrations.Migration):
|
|
9
|
+
|
|
10
|
+
initial = True
|
|
11
|
+
|
|
12
|
+
dependencies = [
|
|
13
|
+
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
|
|
14
|
+
]
|
|
15
|
+
|
|
16
|
+
operations = [
|
|
17
|
+
migrations.CreateModel(
|
|
18
|
+
name='ApiToken',
|
|
19
|
+
fields=[
|
|
20
|
+
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
|
|
21
|
+
('name', models.CharField(help_text='What is this token for?', max_length=100, verbose_name='name')),
|
|
22
|
+
('prefix', models.CharField(editable=False, max_length=16, unique=True, verbose_name='prefix')),
|
|
23
|
+
('key_hash', models.CharField(editable=False, max_length=64)),
|
|
24
|
+
('created', models.DateTimeField(auto_now_add=True, verbose_name='created')),
|
|
25
|
+
('expires_at', models.DateTimeField(blank=True, null=True, verbose_name='expires at')),
|
|
26
|
+
('last_used_at', models.DateTimeField(blank=True, editable=False, null=True, verbose_name='last used at')),
|
|
27
|
+
('revoked_at', models.DateTimeField(blank=True, editable=False, null=True, verbose_name='revoked at')),
|
|
28
|
+
('scopes', models.JSONField(blank=True, default=list, editable=False)),
|
|
29
|
+
('kind', models.CharField(choices=[('pat', 'Personal access token'), ('mcp', 'MCP client'), ('service', 'Service')], default='pat', max_length=20, verbose_name='kind')),
|
|
30
|
+
('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='api_tokens', to=settings.AUTH_USER_MODEL, verbose_name='user')),
|
|
31
|
+
],
|
|
32
|
+
options={
|
|
33
|
+
'verbose_name': 'API token',
|
|
34
|
+
'verbose_name_plural': 'API tokens',
|
|
35
|
+
'ordering': ['-created'],
|
|
36
|
+
'abstract': False,
|
|
37
|
+
'swappable': 'ADMIN_API_TOKEN_MODEL',
|
|
38
|
+
},
|
|
39
|
+
),
|
|
40
|
+
]
|
|
File without changes
|