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.
Files changed (49) hide show
  1. admin_api/__init__.py +9 -0
  2. admin_api/actions.py +115 -0
  3. admin_api/admin.py +108 -0
  4. admin_api/apps.py +9 -0
  5. admin_api/auth.py +62 -0
  6. admin_api/changelist.py +194 -0
  7. admin_api/checks.py +35 -0
  8. admin_api/contrib/__init__.py +1 -0
  9. admin_api/contrib/subadmin.py +37 -0
  10. admin_api/custom_views.py +458 -0
  11. admin_api/decorators.py +26 -0
  12. admin_api/deletion.py +54 -0
  13. admin_api/detail.py +127 -0
  14. admin_api/encoders.py +59 -0
  15. admin_api/errors.py +44 -0
  16. admin_api/jsonschema.py +216 -0
  17. admin_api/management/__init__.py +0 -0
  18. admin_api/management/commands/__init__.py +0 -0
  19. admin_api/management/commands/create_api_token.py +40 -0
  20. admin_api/management/commands/mcp_serve.py +86 -0
  21. admin_api/mcp/__init__.py +7 -0
  22. admin_api/mcp/bridge.py +71 -0
  23. admin_api/mcp/confirm.py +54 -0
  24. admin_api/mcp/handlers.py +665 -0
  25. admin_api/mcp/server.py +75 -0
  26. admin_api/mcp/sites.py +198 -0
  27. admin_api/mcp/stdio.py +53 -0
  28. admin_api/mcp/tools.py +84 -0
  29. admin_api/mcp/views.py +69 -0
  30. admin_api/middleware.py +18 -0
  31. admin_api/migrations/0001_initial.py +40 -0
  32. admin_api/migrations/__init__.py +0 -0
  33. admin_api/mixins.py +144 -0
  34. admin_api/models.py +113 -0
  35. admin_api/nested.py +122 -0
  36. admin_api/resolver.py +95 -0
  37. admin_api/scopes.py +121 -0
  38. admin_api/services.py +423 -0
  39. admin_api/sites.py +225 -0
  40. admin_api/views/__init__.py +0 -0
  41. admin_api/views/changelist.py +50 -0
  42. admin_api/views/custom.py +31 -0
  43. admin_api/views/detail.py +39 -0
  44. admin_api/views/nested.py +70 -0
  45. admin_api/views/registry.py +15 -0
  46. admin_api/writes.py +479 -0
  47. django_admin_api_mcp-0.1.0a2.dist-info/METADATA +274 -0
  48. django_admin_api_mcp-0.1.0a2.dist-info/RECORD +49 -0
  49. django_admin_api_mcp-0.1.0a2.dist-info/WHEEL +4 -0
@@ -0,0 +1,665 @@
1
+ """The MCP tools: thin adapters over :mod:`admin_api.services`.
2
+
3
+ Each handler is ``handler(mcp_site, request, arguments) -> dict``. They run synchronously in
4
+ a Django request context and raise :class:`admin_api.errors.ApiError` on failure.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import copy
10
+
11
+ from django.contrib.admin.views.main import ORDER_VAR, PAGE_VAR, SEARCH_VAR
12
+ from django.db import router, transaction
13
+ from django.http import QueryDict
14
+
15
+ from .. import custom_views, services
16
+ from ..changelist import PER_PAGE_PARAM, SHAPE_PARAM, describe_columns, get_columns
17
+ from ..errors import ApiError, NotFound, PermissionDeniedError
18
+ from ..nested import ModelPath
19
+ from ..writes import ValidationFailed
20
+ from . import confirm
21
+ from .tools import (
22
+ ANY_OBJECT,
23
+ CONFIRM_TOKEN_ARG,
24
+ DATA_ARG,
25
+ DRY_RUN_ARG,
26
+ FILTERS_ARG,
27
+ MODEL_ARG,
28
+ PARENTS_ARG,
29
+ PK_ARG,
30
+ ToolSpec,
31
+ obj,
32
+ )
33
+
34
+ RESERVED_FILTER_KEYS = frozenset({SEARCH_VAR, ORDER_VAR, PAGE_VAR, SHAPE_PARAM, PER_PAGE_PARAM, "all"})
35
+
36
+
37
+ class InvalidArguments(ApiError):
38
+ status = 400
39
+ code = "invalid_arguments"
40
+
41
+
42
+ # --------------------------------------------------------------------------------------------
43
+ # helpers
44
+ # --------------------------------------------------------------------------------------------
45
+ def _arg(args: dict, name: str, types=None, *, required=True, default=None):
46
+ value = args.get(name)
47
+ if value is None:
48
+ if required:
49
+ raise InvalidArguments(f"'{name}' is required.")
50
+ return default
51
+ if types is not None and not isinstance(value, types):
52
+ raise InvalidArguments(f"'{name}' has the wrong type.")
53
+ return value
54
+
55
+
56
+ def _model_admin(site, request, args):
57
+ """The admin for ``model`` (a model path) inside ``parents``. Hiding an admin from MCP hides
58
+ the admins nested under it too."""
59
+ path = ModelPath.parse(_arg(args, "model", str))
60
+ parents = _arg(args, "parents", list, required=False, default=[])
61
+ if any(not isinstance(pk, (int, str)) or isinstance(pk, bool) for pk in parents):
62
+ raise InvalidArguments("'parents' must be a list of primary keys.")
63
+ chain = site.api_site.get_admin_chain(path)
64
+ if chain is not None and not all(site.is_exposed(a) for a in chain):
65
+ raise NotFound(f"No MCP access to {path.label}.")
66
+ model_admin = services.get_model_admin_by_label(site.api_site, request, path.label, parents)
67
+ return model_admin, path.label
68
+
69
+
70
+ def _children(site, request, model_admin, pk=None) -> list[dict]:
71
+ return [link for link in services.child_links(request, model_admin, pk) if site.is_exposed(link["admin"])]
72
+
73
+
74
+ def _with_query(request, query: QueryDict):
75
+ """A shallow copy of ``request`` whose GET is ``query`` (the changelist reads request.GET)."""
76
+ req = copy.copy(request)
77
+ query._mutable = False
78
+ req.GET = query
79
+ return req
80
+
81
+
82
+ def _qvalue(value) -> str:
83
+ if value is True:
84
+ return "1"
85
+ if value is False:
86
+ return "0"
87
+ return "" if value is None else str(value)
88
+
89
+
90
+ def _filters_query(args) -> QueryDict:
91
+ filters = _arg(args, "filters", dict, required=False, default={})
92
+ query = QueryDict(mutable=True)
93
+ for key, value in filters.items():
94
+ if key in RESERVED_FILTER_KEYS:
95
+ raise InvalidArguments(f"'{key}' is not a filter; use the dedicated argument instead.")
96
+ values = value if isinstance(value, list) else [value]
97
+ query.setlist(str(key), [_qvalue(v) for v in values])
98
+ return query
99
+
100
+
101
+ def _effective_perms(site, perms: dict) -> dict:
102
+ if site.read_only:
103
+ return {k: (v if k == "view" else False) for k, v in perms.items()}
104
+ return perms
105
+
106
+
107
+ def _ordering_param(model_admin, request, ordering) -> str:
108
+ names = ordering if isinstance(ordering, list) else str(ordering).split(",")
109
+ columns = {c["name"]: c for c in describe_columns(get_columns(model_admin, request), model_admin, request)}
110
+ sortable = sorted(n for n, c in columns.items() if c["sortable"])
111
+ parts = []
112
+ for raw in names:
113
+ name = str(raw).strip()
114
+ desc = name.startswith("-")
115
+ name = name.lstrip("-")
116
+ column = columns.get(name)
117
+ if column is None or not column["sortable"]:
118
+ raise InvalidArguments(f"Cannot order by {name!r}. Sortable columns: {', '.join(sortable) or 'none'}.")
119
+ parts.append(f"{'-' if desc else ''}{column['order_index']}")
120
+ return ".".join(parts)
121
+
122
+
123
+ def _ensure_writable(site):
124
+ if site.read_only:
125
+ raise PermissionDeniedError("This MCP server is read-only.", code="read_only")
126
+
127
+
128
+ def _write_result(data: dict) -> dict:
129
+ messages = data.pop("messages", None)
130
+ totals = data.pop("totals", None)
131
+ out = {"object": data}
132
+ if totals:
133
+ out["totals"] = totals
134
+ if messages:
135
+ out["messages"] = messages
136
+ return out
137
+
138
+
139
+ def _dry_run(model_admin, request, fn) -> dict:
140
+ """Run ``fn`` (a write service) and roll everything back, including on_commit callbacks."""
141
+ request.is_dry_run = True
142
+ try:
143
+ with transaction.atomic(using=router.db_for_write(model_admin.model)):
144
+ try:
145
+ out = {"dry_run": True, "valid": True, **_write_result(fn())}
146
+ except ValidationFailed as exc:
147
+ out = {"dry_run": True, "valid": False, "errors": exc.extra}
148
+ transaction.set_rollback(True)
149
+ finally:
150
+ request.is_dry_run = False
151
+ if out["valid"]:
152
+ out["note"] = "Nothing was saved; the pk shown is provisional."
153
+ return out
154
+
155
+
156
+ def _write_scope(request, **arguments) -> dict:
157
+ """What a confirm token covers: the target model and parents plus the write's own arguments."""
158
+ target = request.admin_api_target
159
+ return {"model": target.path.label, "parents": target.parents, **arguments}
160
+
161
+
162
+ def _issue_confirm_token(site, request, out: dict, operation: str, scope: dict) -> dict:
163
+ out["confirm_token"] = confirm.issue(site.confirm_salt, request, operation, scope)
164
+ out["note"] = (
165
+ "Nothing was saved; the pk shown is provisional. To save, repeat the call without dry_run "
166
+ "and pass this confirm_token."
167
+ )
168
+ return out
169
+
170
+
171
+ def _guarded_write(site, request, model_admin, args, run, operation: str, scope: dict) -> dict:
172
+ """A create/update: with ``require_dry_run``, a valid dry run issues the ``confirm_token`` that
173
+ the real write must present."""
174
+ gated = site.requires_dry_run(model_admin)
175
+ if _arg(args, "dry_run", bool, required=False, default=False):
176
+ out = _dry_run(model_admin, request, run)
177
+ return _issue_confirm_token(site, request, out, operation, scope) if gated and out["valid"] else out
178
+ if gated:
179
+ confirm.verify(
180
+ site.confirm_salt, site.confirm_token_max_age, args.get("confirm_token"), request, operation, scope
181
+ )
182
+ return _write_result(run())
183
+
184
+
185
+ def _views(site, request, model_admin) -> list:
186
+ """The custom views of ``model_admin`` the user may run through this MCP site."""
187
+ return [
188
+ spec
189
+ for spec in custom_views.available_views(model_admin, request, mcp=True, read_only=site.read_only)
190
+ if site.is_view_exposed(model_admin, spec)
191
+ ]
192
+
193
+
194
+ def _view_summary(spec) -> dict:
195
+ out = {"name": spec.name, "description": spec.description or spec.title, "detail": spec.detail}
196
+ if spec.writes:
197
+ out["writes"] = True
198
+ if spec.mcp_tool:
199
+ out["mcp_tool"] = spec.mcp_tool
200
+ return out
201
+
202
+
203
+ def _describe_view(spec) -> dict:
204
+ out = spec.describe()
205
+ out.pop("permissions", None)
206
+ if not spec.mcp_tool:
207
+ out.pop("mcp_tool", None)
208
+ return out
209
+
210
+
211
+ def execute_view(site, request, model_admin, name, *, pk=None, params=None, dry_run=False, confirm_token=None) -> dict:
212
+ """Run a custom view for MCP (``run_view`` and the promoted view tools)."""
213
+ spec = custom_views.get_view(model_admin, request, name, mcp=True, read_only=site.read_only)
214
+ if not site.is_view_exposed(model_admin, spec):
215
+ raise NotFound(f"No view {name!r}.")
216
+ if params is not None and not isinstance(params, dict):
217
+ raise InvalidArguments("'params' must be an object.")
218
+
219
+ def run():
220
+ return services.run_view(model_admin, request, name, object_id=pk, data=params or {})
221
+
222
+ gated = spec.writes and site.requires_dry_run(model_admin)
223
+ scope = _write_scope(request, view=name, pk=None if pk is None else str(pk), params=params or {})
224
+ if not dry_run:
225
+ if gated:
226
+ confirm.verify(site.confirm_salt, site.confirm_token_max_age, confirm_token, request, "run_view", scope)
227
+ return run()
228
+ if not spec.writes:
229
+ return {**run(), "dry_run": True, "note": "A read-only view; nothing to roll back."}
230
+ request.is_dry_run = True
231
+ try:
232
+ with transaction.atomic(using=router.db_for_write(model_admin.model)):
233
+ out = {**run(), "dry_run": True, "note": "Nothing was saved: the view ran and was rolled back."}
234
+ transaction.set_rollback(True)
235
+ finally:
236
+ request.is_dry_run = False
237
+ return _issue_confirm_token(site, request, out, "run_view", scope) if gated else out
238
+
239
+
240
+ # --------------------------------------------------------------------------------------------
241
+ # handlers
242
+ # --------------------------------------------------------------------------------------------
243
+ def list_models(site, request, args) -> dict:
244
+ data = services.registry(site.api_site, request)
245
+ models = []
246
+ for app in data["apps"]:
247
+ for entry in app["models"]:
248
+ path = ModelPath.parse(entry.get("path") or f"{app['app_label']}.{entry['model']}")
249
+ chain = site.api_site.get_admin_chain(path)
250
+ if chain is None or not all(site.is_exposed(a) for a in chain):
251
+ continue
252
+ item = {
253
+ "model": path.label,
254
+ "name": entry["name"],
255
+ "name_plural": entry["name_plural"],
256
+ "app": app["name"],
257
+ "perms": _effective_perms(site, entry["perms"]),
258
+ }
259
+ if path.depth:
260
+ item["nested_under"] = entry["nested_under"]
261
+ description = site.get_model_description(chain[-1], request)
262
+ if description:
263
+ item["description"] = description
264
+ if chain[-1].has_view_or_change_permission(request):
265
+ views = _views(site, request, chain[-1])
266
+ if views:
267
+ item["views"] = [_view_summary(spec) for spec in views]
268
+ models.append(item)
269
+ return {"models": models}
270
+
271
+
272
+ def describe_model(site, request, args) -> dict:
273
+ from ..jsonschema import input_schemas
274
+
275
+ model_admin, label = _model_admin(site, request, args)
276
+ pk = _arg(args, "pk", (int, str), required=False)
277
+ instance = None
278
+ if pk is not None:
279
+ instance = services.get_object(model_admin, request, pk)
280
+ if not model_admin.has_view_or_change_permission(request, instance):
281
+ raise PermissionDeniedError()
282
+
283
+ schema = services.schema(site.api_site, model_admin, _with_query(request, QueryDict(mutable=True)))
284
+ out = {
285
+ "model": label,
286
+ "name": schema["model"]["name"],
287
+ "name_plural": schema["model"]["name_plural"],
288
+ "pk_field": schema["model"]["pk"],
289
+ "perms": _effective_perms(site, schema["perms"]),
290
+ "columns": [
291
+ {k: c[k] for k in ("name", "label", "type", "sortable", "choices") if k in c} for c in schema["columns"]
292
+ ],
293
+ "filters": [
294
+ {
295
+ "title": f["title"],
296
+ "parameters": f["parameters"],
297
+ "choices": [{"display": c["display"], "params": c["params"]} for c in f["choices"]],
298
+ }
299
+ for f in schema["filters"]
300
+ ],
301
+ "search": {"enabled": schema["search"]["enabled"], "help_text": schema["search"]["help_text"]},
302
+ "default_ordering": schema["ordering"]["default"],
303
+ "date_hierarchy": schema["date_hierarchy"],
304
+ "per_page": {"default": site.default_per_page, "max": site.api_site.max_page_size},
305
+ }
306
+ if "parents" in schema["model"]:
307
+ out["parents"] = schema["model"]["parents"]
308
+ children = _children(site, request, model_admin)
309
+ if children:
310
+ out["children"] = [{k: c[k] for k in ("model", "name", "name_plural")} for c in children]
311
+ description = site.get_model_description(model_admin, request)
312
+ if description:
313
+ out["description"] = description
314
+ if site.read_only:
315
+ out["actions"] = []
316
+ out["input_schema"] = {"create": None, "update": None}
317
+ else:
318
+ out["actions"] = schema["actions"]
319
+ out["input_schema"] = input_schemas(model_admin, request, instance)
320
+ views = _views(site, request, model_admin)
321
+ if instance is not None:
322
+ views = [
323
+ v for v in views if not v.detail or custom_views.has_view_permission(model_admin, request, v, instance)
324
+ ]
325
+ out["views"] = [_describe_view(spec) for spec in views]
326
+ return out
327
+
328
+
329
+ def list_objects(site, request, args) -> dict:
330
+ model_admin, label = _model_admin(site, request, args)
331
+ query = _filters_query(args)
332
+ search = _arg(args, "search", str, required=False)
333
+ if search:
334
+ query[SEARCH_VAR] = search
335
+ ordering = _arg(args, "ordering", (list, str), required=False)
336
+ if ordering:
337
+ query[ORDER_VAR] = _ordering_param(model_admin, request, ordering)
338
+ page = _arg(args, "page", int, required=False)
339
+ if page is not None:
340
+ query[PAGE_VAR] = str(page)
341
+ per_page = _arg(args, "per_page", int, required=False, default=site.default_per_page)
342
+ query[PER_PAGE_PARAM] = str(per_page)
343
+ query[SHAPE_PARAM] = "columnar"
344
+ data = services.changelist(site.api_site, model_admin, _with_query(request, query))
345
+ data.pop("next", None)
346
+ data.pop("previous", None)
347
+ head = {"model": label}
348
+ if request.admin_api_target.parents:
349
+ head["parents"] = request.admin_api_target.parents
350
+ return {**head, **data}
351
+
352
+
353
+ def get_object(site, request, args) -> dict:
354
+ model_admin, _label = _model_admin(site, request, args)
355
+ data = services.detail(model_admin, request, _arg(args, "pk", (int, str)))
356
+ data.pop("children", None) # REST urls; MCP addresses children by model path + parents
357
+ children = _children(site, request, model_admin, data["pk"])
358
+ if children:
359
+ data["children"] = {c["segment"]: {"model": c["model"], "parents": c["parents"]} for c in children}
360
+ # REST gives urls; MCP gives the names of the detail views (run them with run_view)
361
+ declared = custom_views.declared_views(model_admin)
362
+ views = [
363
+ name
364
+ for name in data.pop("views", {})
365
+ if declared[name].mcp_enabled
366
+ and not (site.read_only and declared[name].writes)
367
+ and site.is_view_exposed(model_admin, declared[name])
368
+ ]
369
+ if views:
370
+ data["views"] = views
371
+ return data
372
+
373
+
374
+ def create_object(site, request, args) -> dict:
375
+ _ensure_writable(site)
376
+ model_admin, _label = _model_admin(site, request, args)
377
+ data = _arg(args, "data", dict)
378
+ return _guarded_write(
379
+ site,
380
+ request,
381
+ model_admin,
382
+ args,
383
+ lambda: services.create(model_admin, request, data),
384
+ "create_object",
385
+ _write_scope(request, data=data),
386
+ )
387
+
388
+
389
+ def update_object(site, request, args) -> dict:
390
+ _ensure_writable(site)
391
+ model_admin, _label = _model_admin(site, request, args)
392
+ pk = _arg(args, "pk", (int, str))
393
+ data = _arg(args, "data", dict)
394
+ return _guarded_write(
395
+ site,
396
+ request,
397
+ model_admin,
398
+ args,
399
+ lambda: services.update(model_admin, request, pk, data, partial=True),
400
+ "update_object",
401
+ _write_scope(request, pk=str(pk), data=data),
402
+ )
403
+
404
+
405
+ def delete_object(site, request, args) -> dict:
406
+ _ensure_writable(site)
407
+ model_admin, _label = _model_admin(site, request, args)
408
+ pk = _arg(args, "pk", (int, str))
409
+ if not _arg(args, "confirm", bool, required=False, default=False):
410
+ preview = services.delete_preview(model_admin, request, pk)
411
+ return {
412
+ "deleted": False,
413
+ "confirm_required": True,
414
+ "preview": preview,
415
+ "note": "Nothing was deleted. Call again with confirm=true to delete.",
416
+ }
417
+ return {"deleted": True, "object": services.delete(model_admin, request, pk)["deleted"]}
418
+
419
+
420
+ def run_action(site, request, args) -> dict:
421
+ _ensure_writable(site)
422
+ model_admin, _label = _model_admin(site, request, args)
423
+ action = _arg(args, "action", str)
424
+ payload: dict = {}
425
+ if _arg(args, "all", bool, required=False, default=False):
426
+ payload["all"] = True
427
+ else:
428
+ payload["pks"] = _arg(args, "pks", list, required=False, default=[])
429
+ return services.run_action(model_admin, _with_query(request, _filters_query(args)), action, payload)
430
+
431
+
432
+ def run_view(site, request, args) -> dict:
433
+ model_admin, _label = _model_admin(site, request, args)
434
+ return execute_view(
435
+ site,
436
+ request,
437
+ model_admin,
438
+ _arg(args, "view", str),
439
+ pk=_arg(args, "pk", (int, str), required=False),
440
+ params=_arg(args, "params", dict, required=False, default={}),
441
+ dry_run=_arg(args, "dry_run", bool, required=False, default=False),
442
+ confirm_token=args.get("confirm_token"),
443
+ )
444
+
445
+
446
+ # --------------------------------------------------------------------------------------------
447
+ # catalogue
448
+ # --------------------------------------------------------------------------------------------
449
+ READ = {"readOnlyHint": True, "openWorldHint": False}
450
+
451
+ TOOLS = [
452
+ ToolSpec(
453
+ name="list_models",
454
+ title="List models",
455
+ description="List the data models you can access, with your permissions on each. Start here.",
456
+ input_schema=obj({}),
457
+ output_schema=ANY_OBJECT,
458
+ handler=list_models,
459
+ annotations=READ,
460
+ ),
461
+ ToolSpec(
462
+ name="describe_model",
463
+ title="Describe a model",
464
+ description="Columns, filters, search, actions and the JSON Schema of the data accepted by "
465
+ "create_object/update_object. Call this before listing with filters or writing. Pass pk to get the "
466
+ "update schema for one object (some fields may be read-only per object).",
467
+ input_schema=obj({"model": MODEL_ARG, "parents": PARENTS_ARG, "pk": PK_ARG}, ["model"]),
468
+ output_schema=ANY_OBJECT,
469
+ handler=describe_model,
470
+ annotations=READ,
471
+ ),
472
+ ToolSpec(
473
+ name="list_objects",
474
+ title="List objects",
475
+ description="List objects the way the admin changelist does: filters, search, ordering and paging. "
476
+ "Returns columnar data: 'columns' names each position in every 'rows' entry.",
477
+ input_schema=obj(
478
+ {
479
+ "model": MODEL_ARG,
480
+ "parents": PARENTS_ARG,
481
+ "filters": FILTERS_ARG,
482
+ "search": {"type": "string", "description": "Free-text search (when describe_model says enabled)."},
483
+ "ordering": {
484
+ "type": ["array", "string"],
485
+ "items": {"type": "string"},
486
+ "description": "Sortable column names; prefix '-' for descending, e.g. ['-date', 'slug'].",
487
+ },
488
+ "page": {"type": "integer", "minimum": 1, "default": 1},
489
+ "per_page": {"type": "integer", "minimum": 1, "description": "Rows per page (default 25)."},
490
+ },
491
+ ["model"],
492
+ ),
493
+ output_schema=ANY_OBJECT,
494
+ handler=list_objects,
495
+ annotations=READ,
496
+ ),
497
+ ToolSpec(
498
+ name="get_object",
499
+ title="Get one object",
500
+ description="All fields of one object, including its inline rows.",
501
+ input_schema=obj({"model": MODEL_ARG, "parents": PARENTS_ARG, "pk": PK_ARG}, ["model", "pk"]),
502
+ output_schema=ANY_OBJECT,
503
+ handler=get_object,
504
+ annotations=READ,
505
+ ),
506
+ ToolSpec(
507
+ name="create_object",
508
+ title="Create an object",
509
+ description="Create an object through the admin's own form and save pipeline (same validation and "
510
+ "business rules as the admin). 'data' must match describe_model's input_schema.create. "
511
+ "Use dry_run=true first to check it. The result carries the document's computed 'totals' when the "
512
+ "admin declares them.",
513
+ input_schema=obj(
514
+ {
515
+ "model": MODEL_ARG,
516
+ "parents": PARENTS_ARG,
517
+ "data": DATA_ARG,
518
+ "dry_run": DRY_RUN_ARG,
519
+ "confirm_token": CONFIRM_TOKEN_ARG,
520
+ },
521
+ ["model", "data"],
522
+ ),
523
+ output_schema=ANY_OBJECT,
524
+ handler=create_object,
525
+ writes=True,
526
+ annotations={"readOnlyHint": False, "destructiveHint": False, "openWorldHint": False},
527
+ ),
528
+ ToolSpec(
529
+ name="update_object",
530
+ title="Update an object",
531
+ description="Change some fields of an object (fields not given are kept). Inline rows: a row with "
532
+ "'pk' updates that row, '_delete': true deletes it, a row without 'pk' is added. 'data' must match "
533
+ "describe_model's input_schema.update. Use dry_run=true first to check it. The result carries the "
534
+ "document's computed 'totals' when the admin declares them.",
535
+ input_schema=obj(
536
+ {
537
+ "model": MODEL_ARG,
538
+ "parents": PARENTS_ARG,
539
+ "pk": PK_ARG,
540
+ "data": DATA_ARG,
541
+ "dry_run": DRY_RUN_ARG,
542
+ "confirm_token": CONFIRM_TOKEN_ARG,
543
+ },
544
+ ["model", "pk", "data"],
545
+ ),
546
+ output_schema=ANY_OBJECT,
547
+ handler=update_object,
548
+ writes=True,
549
+ annotations={"readOnlyHint": False, "destructiveHint": True, "idempotentHint": True, "openWorldHint": False},
550
+ ),
551
+ ToolSpec(
552
+ name="delete_object",
553
+ title="Delete an object",
554
+ description="Without confirm: returns what would be deleted (cascades, protected objects) and deletes "
555
+ "nothing. With confirm=true: deletes the object.",
556
+ input_schema=obj(
557
+ {
558
+ "model": MODEL_ARG,
559
+ "parents": PARENTS_ARG,
560
+ "pk": PK_ARG,
561
+ "confirm": {"type": "boolean", "default": False, "description": "Actually delete."},
562
+ },
563
+ ["model", "pk"],
564
+ ),
565
+ output_schema=ANY_OBJECT,
566
+ handler=delete_object,
567
+ writes=True,
568
+ annotations={"readOnlyHint": False, "destructiveHint": True, "idempotentHint": True, "openWorldHint": False},
569
+ ),
570
+ ToolSpec(
571
+ name="run_action",
572
+ title="Run an admin action",
573
+ description="Run one of the model's admin actions (listed by describe_model) on the given pks, or on "
574
+ "all objects matching 'filters' with all=true. Actions have no dry run.",
575
+ input_schema=obj(
576
+ {
577
+ "model": MODEL_ARG,
578
+ "parents": PARENTS_ARG,
579
+ "action": {"type": "string", "description": "Action name from describe_model's actions."},
580
+ "pks": {"type": "array", "items": PK_ARG, "description": "Objects to run the action on."},
581
+ "all": {"type": "boolean", "default": False, "description": "Run on all objects matching filters."},
582
+ "filters": FILTERS_ARG,
583
+ },
584
+ ["model", "action"],
585
+ ),
586
+ output_schema=ANY_OBJECT,
587
+ handler=run_action,
588
+ writes=True,
589
+ annotations={"readOnlyHint": False, "destructiveHint": True, "openWorldHint": False},
590
+ ),
591
+ ToolSpec(
592
+ name="run_view",
593
+ title="Run a custom view",
594
+ description="Run one of a model's custom views: reports, statements, computed pages or business "
595
+ "operations. They are listed under 'views' by list_models (names) and describe_model (parameters as "
596
+ "params_schema). Views with detail=true run on one object (give pk). Views with writes=true change "
597
+ "data: use dry_run=true first to check them.",
598
+ input_schema=obj(
599
+ {
600
+ "model": MODEL_ARG,
601
+ "parents": PARENTS_ARG,
602
+ "view": {"type": "string", "description": "View name from list_models / describe_model."},
603
+ "pk": {**PK_ARG, "description": "The object, for views with detail=true."},
604
+ "params": {"type": "object", "description": "Parameters matching the view's params_schema."},
605
+ "dry_run": {
606
+ **DRY_RUN_ARG,
607
+ "description": "For views with writes=true: run the view, then roll everything back.",
608
+ },
609
+ "confirm_token": CONFIRM_TOKEN_ARG,
610
+ },
611
+ ["model", "view"],
612
+ ),
613
+ output_schema=ANY_OBJECT,
614
+ handler=run_view,
615
+ # stays on read-only sites, where write views are hidden and refused
616
+ annotations={"readOnlyHint": False, "destructiveHint": True, "openWorldHint": False},
617
+ ),
618
+ ]
619
+
620
+
621
+ def view_tool(site, model_admin, spec) -> ToolSpec:
622
+ """A view published as its own tool (``@admin_api.view(mcp_tool="name")``). Its parameters
623
+ are flattened next to ``pk`` (detail views) and ``dry_run`` (write views)."""
624
+ opts = model_admin.model._meta
625
+ label = f"{opts.app_label}.{opts.model_name}"
626
+ params = spec.params_schema()
627
+ properties = {}
628
+ required = list(params.get("required", ()))
629
+ if spec.detail:
630
+ properties["pk"] = {**PK_ARG, "description": f"Primary key of the {opts.verbose_name}."}
631
+ required.insert(0, "pk")
632
+ properties.update(params["properties"])
633
+ if spec.writes:
634
+ properties["dry_run"] = DRY_RUN_ARG
635
+ properties["confirm_token"] = CONFIRM_TOKEN_ARG
636
+ description = spec.description or spec.title
637
+ description += f" (Custom view {spec.name!r} of {label}; same as run_view.)"
638
+
639
+ def handler(site, request, args):
640
+ model_admin = services.get_model_admin_by_label(site.api_site, request, label)
641
+ if not site.is_exposed(model_admin):
642
+ raise NotFound(f"No MCP access to {label}.")
643
+ params = {k: v for k, v in args.items() if k not in custom_views.TOOL_RESERVED}
644
+ return execute_view(
645
+ site,
646
+ request,
647
+ model_admin,
648
+ spec.name,
649
+ pk=args.get("pk") if spec.detail else None,
650
+ params=params,
651
+ dry_run=bool(args.get("dry_run")) if spec.writes else False,
652
+ confirm_token=args.get("confirm_token"),
653
+ )
654
+
655
+ annotations = {"readOnlyHint": False, "destructiveHint": True, "openWorldHint": False} if spec.writes else READ
656
+ return ToolSpec(
657
+ name=spec.mcp_tool,
658
+ title=spec.title,
659
+ description=description,
660
+ input_schema=obj(properties, required),
661
+ output_schema=ANY_OBJECT,
662
+ handler=handler,
663
+ writes=spec.writes,
664
+ annotations=annotations,
665
+ )