django-admin-api-mcp 0.1.0__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 (73) hide show
  1. admin_api_mcp/__init__.py +9 -0
  2. admin_api_mcp/actions.py +197 -0
  3. admin_api_mcp/admin.py +131 -0
  4. admin_api_mcp/apps.py +10 -0
  5. admin_api_mcp/auth.py +62 -0
  6. admin_api_mcp/changelist.py +261 -0
  7. admin_api_mcp/checks.py +35 -0
  8. admin_api_mcp/confirm.py +97 -0
  9. admin_api_mcp/contrib/__init__.py +1 -0
  10. admin_api_mcp/contrib/search/__init__.py +0 -0
  11. admin_api_mcp/contrib/search/apps.py +21 -0
  12. admin_api_mcp/contrib/search/backend.py +121 -0
  13. admin_api_mcp/contrib/search/checks.py +12 -0
  14. admin_api_mcp/contrib/search/conf.py +42 -0
  15. admin_api_mcp/contrib/search/engines/__init__.py +0 -0
  16. admin_api_mcp/contrib/search/engines/base.py +99 -0
  17. admin_api_mcp/contrib/search/engines/db.py +265 -0
  18. admin_api_mcp/contrib/search/fold.py +41 -0
  19. admin_api_mcp/contrib/search/indexer.py +364 -0
  20. admin_api_mcp/contrib/search/management/__init__.py +0 -0
  21. admin_api_mcp/contrib/search/management/commands/__init__.py +0 -0
  22. admin_api_mcp/contrib/search/management/commands/rebuild_search_index.py +29 -0
  23. admin_api_mcp/contrib/search/management/commands/search_index.py +25 -0
  24. admin_api_mcp/contrib/search/migrations/0001_initial.py +83 -0
  25. admin_api_mcp/contrib/search/migrations/__init__.py +0 -0
  26. admin_api_mcp/contrib/search/models.py +43 -0
  27. admin_api_mcp/contrib/subadmin.py +37 -0
  28. admin_api_mcp/custom_views.py +471 -0
  29. admin_api_mcp/decorators.py +26 -0
  30. admin_api_mcp/deletion.py +58 -0
  31. admin_api_mcp/detail.py +115 -0
  32. admin_api_mcp/encoders.py +72 -0
  33. admin_api_mcp/errors.py +82 -0
  34. admin_api_mcp/jsonschema.py +225 -0
  35. admin_api_mcp/management/__init__.py +0 -0
  36. admin_api_mcp/management/commands/__init__.py +0 -0
  37. admin_api_mcp/management/commands/create_api_token.py +40 -0
  38. admin_api_mcp/management/commands/mcp_serve.py +86 -0
  39. admin_api_mcp/management/commands/migrate_from_admin_api.py +153 -0
  40. admin_api_mcp/mcp/__init__.py +7 -0
  41. admin_api_mcp/mcp/bridge.py +71 -0
  42. admin_api_mcp/mcp/handlers.py +771 -0
  43. admin_api_mcp/mcp/resolve.py +410 -0
  44. admin_api_mcp/mcp/server.py +76 -0
  45. admin_api_mcp/mcp/sites.py +284 -0
  46. admin_api_mcp/mcp/stdio.py +53 -0
  47. admin_api_mcp/mcp/tools.py +84 -0
  48. admin_api_mcp/mcp/views.py +74 -0
  49. admin_api_mcp/middleware.py +18 -0
  50. admin_api_mcp/migrations/0001_initial.py +40 -0
  51. admin_api_mcp/migrations/0002_mcp_confirmation.py +27 -0
  52. admin_api_mcp/migrations/0003_mcp_user_instructions.py +28 -0
  53. admin_api_mcp/migrations/__init__.py +0 -0
  54. admin_api_mcp/mixins.py +173 -0
  55. admin_api_mcp/models.py +145 -0
  56. admin_api_mcp/nested.py +122 -0
  57. admin_api_mcp/resolver.py +95 -0
  58. admin_api_mcp/scopes.py +142 -0
  59. admin_api_mcp/sensitive.py +67 -0
  60. admin_api_mcp/services.py +652 -0
  61. admin_api_mcp/sites.py +242 -0
  62. admin_api_mcp/templates/admin_api_mcp/token_created.html +17 -0
  63. admin_api_mcp/views/__init__.py +0 -0
  64. admin_api_mcp/views/changelist.py +70 -0
  65. admin_api_mcp/views/custom.py +33 -0
  66. admin_api_mcp/views/detail.py +50 -0
  67. admin_api_mcp/views/nested.py +73 -0
  68. admin_api_mcp/views/registry.py +15 -0
  69. admin_api_mcp/writes.py +530 -0
  70. django_admin_api_mcp-0.1.0.dist-info/METADATA +280 -0
  71. django_admin_api_mcp-0.1.0.dist-info/RECORD +73 -0
  72. django_admin_api_mcp-0.1.0.dist-info/WHEEL +4 -0
  73. django_admin_api_mcp-0.1.0.dist-info/licenses/LICENSE +21 -0
@@ -0,0 +1,771 @@
1
+ """The MCP tools: thin adapters over :mod:`admin_api_mcp.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_mcp.errors.ApiError` on failure.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import copy
10
+ import math
11
+
12
+ from django.contrib.admin.utils import NotRelationField, get_fields_from_path
13
+ from django.contrib.admin.views.main import ORDER_VAR, PAGE_VAR, SEARCH_VAR
14
+ from django.core.exceptions import FieldDoesNotExist
15
+ from django.http import QueryDict
16
+ from django.utils.translation import gettext
17
+
18
+ from .. import actions, custom_views, services
19
+ from ..changelist import PER_PAGE_PARAM, SHAPE_PARAM, describe_columns, get_columns
20
+ from ..errors import InvalidArguments, NotFound, PermissionDeniedError
21
+ from ..nested import ModelPath
22
+ from ..scopes import OPS
23
+ from .resolve import DEFAULT_LIMIT, MAX_LIMIT, MAX_TERMS, resolve_entities
24
+ from .tools import (
25
+ ANY_OBJECT,
26
+ CONFIRM_TOKEN_ARG,
27
+ DATA_ARG,
28
+ DRY_RUN_ARG,
29
+ FILTERS_ARG,
30
+ ID_ARG,
31
+ MODEL_ARG,
32
+ PARENTS_ARG,
33
+ PK_ALIAS_ARG,
34
+ ToolSpec,
35
+ obj,
36
+ )
37
+
38
+ # The query keys list_objects sets itself, each with the argument that sets it (None: no argument).
39
+ RESERVED_FILTER_KEYS = {
40
+ SEARCH_VAR: "search",
41
+ ORDER_VAR: "ordering",
42
+ PAGE_VAR: "page",
43
+ PER_PAGE_PARAM: "per_page",
44
+ SHAPE_PARAM: None,
45
+ "all": None,
46
+ }
47
+
48
+
49
+ # --------------------------------------------------------------------------------------------
50
+ # helpers
51
+ # --------------------------------------------------------------------------------------------
52
+ def _arg(args: dict, name: str, types=None, *, required=True, default=None):
53
+ value = args.get(name)
54
+ if value is None:
55
+ if required:
56
+ raise InvalidArguments(f"'{name}' is required.")
57
+ return default
58
+ if types is not None and not isinstance(value, types):
59
+ raise InvalidArguments(f"'{name}' has the wrong type.")
60
+ return value
61
+
62
+
63
+ def _id_arg(args: dict, *, required=True):
64
+ """The record ID argument: ``id``, or its deprecated alias ``pk``."""
65
+ value = _arg({"id": args.get("id", args.get("pk"))}, "id", (int, str), required=required)
66
+ if isinstance(value, bool):
67
+ raise InvalidArguments("'id' has the wrong type.")
68
+ return value
69
+
70
+
71
+ def mcp_keys(value):
72
+ """REST keys to MCP keys: a record reference ``{"pk", "str"}`` becomes ``{"id", "label"}``, anywhere."""
73
+ if isinstance(value, list):
74
+ return [mcp_keys(v) for v in value]
75
+ if isinstance(value, dict):
76
+ if value.keys() == {"pk", "str"}:
77
+ return {"id": value["pk"], "label": value["str"]}
78
+ return {k: mcp_keys(v) for k, v in value.items()}
79
+ return value
80
+
81
+
82
+ def _object_keys(data: dict) -> dict:
83
+ """A serialized object for MCP: ``id`` and ``label`` first, inline rows keyed by ``id``."""
84
+ out = {"id": data.pop("pk")}
85
+ if "str" in data:
86
+ out["label"] = data.pop("str")
87
+ out.update(mcp_keys(data))
88
+ for prefix, rows in out.get("inlines", {}).items():
89
+ out["inlines"][prefix] = [{"id": row.pop("pk"), **row} if "pk" in row else row for row in rows]
90
+ return out
91
+
92
+
93
+ def _input_row(row):
94
+ if not isinstance(row, dict) or "id" not in row or "pk" in row:
95
+ return row
96
+ return {**{k: v for k, v in row.items() if k != "id"}, "pk": row["id"]}
97
+
98
+
99
+ def _input_data(data: dict) -> dict:
100
+ """MCP write data for the services: an inline row's ``id`` is the row's ``pk``."""
101
+ inlines = data.get("inlines")
102
+ if not isinstance(inlines, dict):
103
+ return data
104
+ rows = {prefix: [_input_row(r) for r in rs] if isinstance(rs, list) else rs for prefix, rs in inlines.items()}
105
+ return {**data, "inlines": rows}
106
+
107
+
108
+ def _model_admin(site, request, args):
109
+ """The admin for ``model`` (a model path) inside ``parents``. Hiding an admin from MCP hides
110
+ the admins nested under it too."""
111
+ path = ModelPath.parse(_arg(args, "model", str))
112
+ parents = _arg(args, "parents", list, required=False, default=[])
113
+ if any(not isinstance(pk, (int, str)) or isinstance(pk, bool) for pk in parents):
114
+ raise InvalidArguments("'parents' must be a list of IDs.")
115
+ chain = site.api_site.get_admin_chain(path)
116
+ if chain is not None and not all(site.is_exposed(a) for a in chain):
117
+ raise NotFound()
118
+ model_admin = services.get_model_admin_by_label(site.api_site, request, path.label, parents)
119
+ return model_admin, path.label
120
+
121
+
122
+ def _children(site, request, model_admin, pk=None) -> list[dict]:
123
+ return [link for link in services.child_links(request, model_admin, pk) if site.is_exposed(link["admin"])]
124
+
125
+
126
+ def _with_query(request, query: QueryDict):
127
+ """A shallow copy of ``request`` whose GET is ``query`` (the changelist reads request.GET)."""
128
+ req = copy.copy(request)
129
+ query._mutable = False
130
+ req.GET = query
131
+ return req
132
+
133
+
134
+ def _qvalue(value) -> str:
135
+ if value is True:
136
+ return "1"
137
+ if value is False:
138
+ return "0"
139
+ return "" if value is None else str(value)
140
+
141
+
142
+ def _filters_query(args) -> QueryDict:
143
+ filters = _arg(args, "filters", dict, required=False, default={})
144
+ query = QueryDict(mutable=True)
145
+ for key, value in filters.items():
146
+ if key in RESERVED_FILTER_KEYS:
147
+ argument = RESERVED_FILTER_KEYS[key]
148
+ hint = (
149
+ f"pass the '{argument}' argument"
150
+ if argument
151
+ else "list_objects returns one page; pass 'page' and 'per_page' for the others"
152
+ )
153
+ raise InvalidArguments(f"'{key}' is not a filter; {hint}.")
154
+ values = value if isinstance(value, list) else [value]
155
+ query.setlist(str(key), [_qvalue(v) for v in values])
156
+ return query
157
+
158
+
159
+ def _can(site, perms: dict) -> list[str]:
160
+ """The operations of ``perms`` (``get_model_perms``) allowed on this site: only view when read-only."""
161
+ return [op for op in OPS if perms.get(op) and (op == "view" or not site.read_only)]
162
+
163
+
164
+ def _ordering_param(model_admin, request, ordering) -> str:
165
+ names = ordering if isinstance(ordering, list) else str(ordering).split(",")
166
+ columns = {c["name"]: c for c in describe_columns(get_columns(model_admin, request), model_admin, request)}
167
+ sortable = sorted(n for n, c in columns.items() if c["sortable"])
168
+ parts = []
169
+ for raw in names:
170
+ name = str(raw).strip()
171
+ desc = name.startswith("-")
172
+ name = name.lstrip("-")
173
+ column = columns.get(name)
174
+ if column is None or not column["sortable"]:
175
+ raise InvalidArguments(f"Cannot order by {name!r}. Sortable columns: {', '.join(sortable) or 'none'}.")
176
+ parts.append(f"{'-' if desc else ''}{column['order_index']}")
177
+ return ".".join(parts)
178
+
179
+
180
+ def _id_filters(model_admin, request) -> list:
181
+ """The changelist parameters that take a related record's ID, as Django's RelatedFieldListFilter names them."""
182
+ out = []
183
+ for entry in model_admin.get_list_filter(request):
184
+ path = entry[0] if isinstance(entry, (list, tuple)) else entry
185
+ if not isinstance(path, str):
186
+ continue # a SimpleListFilter class
187
+ try:
188
+ field = get_fields_from_path(model_admin.model, path)[-1]
189
+ except (FieldDoesNotExist, NotRelationField):
190
+ continue
191
+ if field.is_relation and getattr(field, "target_field", None) is not None:
192
+ out.append(f"{path}__{field.target_field.name}__exact")
193
+ return out
194
+
195
+
196
+ def _empty_search_hint(model_admin, request) -> dict:
197
+ """For a search that found nothing: the fields it looked at and the filters that take a related record's ID."""
198
+ return {
199
+ "searched_fields": list(model_admin.get_search_fields(request) or ()),
200
+ "id_filters": _id_filters(model_admin, request),
201
+ "hint": gettext(
202
+ "Nothing matched the search text in these fields. To find records of a related record, "
203
+ "resolve it with resolve_entities and pass its ID to one of these filters."
204
+ ),
205
+ }
206
+
207
+
208
+ def _too_many_rows_hint(max_rows) -> str:
209
+ return gettext(
210
+ "list_objects pages through the first %(max_rows)s records of a query. For totals, counts or "
211
+ "groupings run a report (a view under 'views' in list_models); to find records, add filters or search."
212
+ ) % {"max_rows": max_rows}
213
+
214
+
215
+ def _ensure_writable(site):
216
+ if site.read_only:
217
+ raise PermissionDeniedError("This MCP server is read-only.", code="read_only")
218
+
219
+
220
+ def _write_result(data: dict, dry_run: bool) -> dict:
221
+ """A create/update result for MCP: the dry run's answer, or ``{"object", "totals", "messages"}``."""
222
+ if dry_run:
223
+ return mcp_keys(data)
224
+ extras = {key: data.pop(key, None) for key in ("totals", "messages")}
225
+ return {"object": _object_keys(data), **{key: value for key, value in extras.items() if value}}
226
+
227
+
228
+ def _views(site, request, model_admin) -> list:
229
+ """The custom views of ``model_admin`` the user may run through this MCP site."""
230
+ return [
231
+ spec
232
+ for spec in custom_views.available_views(model_admin, request, mcp=True, read_only=site.read_only)
233
+ if site.is_view_exposed(model_admin, spec)
234
+ ]
235
+
236
+
237
+ def _view_summary(spec) -> dict:
238
+ out = {"name": spec.name, "description": spec.description or spec.title, "detail": spec.detail}
239
+ if spec.writes:
240
+ out["writes"] = True
241
+ if spec.mcp_tool:
242
+ out["mcp_tool"] = spec.mcp_tool
243
+ return out
244
+
245
+
246
+ def _describe_view(spec) -> dict:
247
+ out = spec.describe()
248
+ out.pop("permissions", None)
249
+ if not spec.mcp_tool:
250
+ out.pop("mcp_tool", None)
251
+ return out
252
+
253
+
254
+ def execute_view(site, request, model_admin, name, *, pk=None, params=None, dry_run=False, confirm_token=None) -> dict:
255
+ """Run a custom view for MCP (``run_view`` and the promoted view tools) through :func:`services.run_view`."""
256
+ spec = custom_views.get_view(model_admin, request, name, mcp=True, read_only=site.read_only)
257
+ if not site.is_view_exposed(model_admin, spec):
258
+ raise NotFound(gettext("No view '%(view)s'.") % {"view": name})
259
+ if params is not None and not isinstance(params, dict):
260
+ raise InvalidArguments("'params' must be an object.")
261
+ out = services.run_view(
262
+ model_admin,
263
+ request,
264
+ name,
265
+ object_id=pk,
266
+ data=params or {},
267
+ dry_run=dry_run,
268
+ confirm_token=confirm_token,
269
+ mcp=True,
270
+ read_only=site.read_only,
271
+ )
272
+ out = mcp_keys(out)
273
+ if "pk" in out:
274
+ out["id"] = out.pop("pk")
275
+ return out
276
+
277
+
278
+ # --------------------------------------------------------------------------------------------
279
+ # handlers
280
+ # --------------------------------------------------------------------------------------------
281
+ def list_models(site, request, args) -> dict:
282
+ data = services.registry(site.api_site, request)
283
+ models = []
284
+ for app in data["apps"]:
285
+ for entry in app["models"]:
286
+ path = ModelPath.parse(entry.get("path") or f"{app['app_label']}.{entry['model']}")
287
+ chain = site.api_site.get_admin_chain(path)
288
+ if chain is None or not all(site.is_exposed(a) for a in chain):
289
+ continue
290
+ item = {
291
+ "name": entry["name"],
292
+ "name_plural": entry["name_plural"],
293
+ "model": path.label,
294
+ "app": app["name"],
295
+ "can": _can(site, entry["perms"]),
296
+ }
297
+ if path.depth:
298
+ item["nested_under"] = entry["nested_under"]
299
+ description = site.get_model_description(chain[-1], request)
300
+ if description:
301
+ item["description"] = description
302
+ if chain[-1].has_view_or_change_permission(request):
303
+ if not site.read_only and (action_names := list(actions.available_actions(chain[-1], request))):
304
+ item["actions"] = action_names
305
+ views = _views(site, request, chain[-1])
306
+ if views:
307
+ item["views"] = [_view_summary(spec) for spec in views]
308
+ models.append(item)
309
+ return {"models": models}
310
+
311
+
312
+ def describe_model(site, request, args) -> dict:
313
+ model_admin, label = _model_admin(site, request, args)
314
+ pk = _id_arg(args, required=False)
315
+ instance = None
316
+ if pk is not None:
317
+ instance = services.get_object(model_admin, request, pk)
318
+ services.check_view_permission(model_admin, request, instance)
319
+
320
+ query_free = _with_query(request, QueryDict(mutable=True))
321
+ schema = services.schema(site.api_site, model_admin, query_free, instance=instance, row_id="id")
322
+ out = {
323
+ "name": schema["model"]["name"],
324
+ "name_plural": schema["model"]["name_plural"],
325
+ "model": label,
326
+ "id_field": schema["model"]["pk"],
327
+ "can": _can(site, schema["perms"]),
328
+ "columns": [
329
+ {k: c[k] for k in ("name", "label", "type", "sortable", "choices") if k in c} for c in schema["columns"]
330
+ ],
331
+ "filters": [
332
+ {
333
+ "title": f["title"],
334
+ "parameters": f["parameters"],
335
+ "choices": [{"display": c["display"], "params": c["params"]} for c in f["choices"]],
336
+ }
337
+ for f in schema["filters"]
338
+ ],
339
+ "search": {"enabled": schema["search"]["enabled"], "help_text": schema["search"]["help_text"]},
340
+ "default_ordering": schema["ordering"]["default"],
341
+ "date_hierarchy": schema["date_hierarchy"],
342
+ "per_page": {"default": site.default_per_page, "max": site.api_site.max_page_size},
343
+ }
344
+ if "parents" in schema["model"]:
345
+ out["parents"] = schema["model"]["parents"]
346
+ children = _children(site, request, model_admin)
347
+ if children:
348
+ out["children"] = [{k: c[k] for k in ("model", "name", "name_plural")} for c in children]
349
+ description = site.get_model_description(model_admin, request)
350
+ if description:
351
+ out["description"] = description
352
+ if site.read_only:
353
+ out["actions"] = []
354
+ out["input_schema"] = {"create": None, "update": None}
355
+ else:
356
+ out["actions"] = schema["actions"]
357
+ out["input_schema"] = schema["input_schema"]
358
+ views = _views(site, request, model_admin)
359
+ if instance is not None:
360
+ views = [
361
+ v for v in views if not v.detail or custom_views.has_view_permission(model_admin, request, v, instance)
362
+ ]
363
+ out["views"] = [_describe_view(spec) for spec in views]
364
+ return out
365
+
366
+
367
+ def list_objects(site, request, args) -> dict:
368
+ model_admin, label = _model_admin(site, request, args)
369
+ query = _filters_query(args)
370
+ search = _arg(args, "search", str, required=False)
371
+ if search:
372
+ query[SEARCH_VAR] = search
373
+ ordering = _arg(args, "ordering", (list, str), required=False)
374
+ if ordering:
375
+ query[ORDER_VAR] = _ordering_param(model_admin, request, ordering)
376
+ page = _arg(args, "page", int, required=False)
377
+ if page is not None:
378
+ query[PAGE_VAR] = str(page)
379
+ per_page = _arg(args, "per_page", int, required=False, default=site.default_per_page)
380
+ query[PER_PAGE_PARAM] = str(per_page)
381
+ max_rows = site.list_max_rows
382
+ if max_rows and ((page or 1) - 1) * per_page >= max_rows:
383
+ raise InvalidArguments(_too_many_rows_hint(max_rows))
384
+ query[SHAPE_PARAM] = "columnar"
385
+ data = services.changelist(site.api_site, model_admin, _with_query(request, query))
386
+ data.pop("next", None)
387
+ data.pop("previous", None)
388
+ head = {"model": label}
389
+ if request.admin_api_target.parents:
390
+ head["parents"] = request.admin_api_target.parents
391
+ data["columns"] = ["id", *data["columns"][1:]]
392
+ data["rows"] = mcp_keys(data["rows"])
393
+ if search and data["count"] == 0:
394
+ data.update(_empty_search_hint(model_admin, request))
395
+ if max_rows and data["count"] > max_rows:
396
+ data["pages"] = math.ceil(max_rows / per_page)
397
+ data["hint"] = _too_many_rows_hint(max_rows)
398
+ return {**head, **data}
399
+
400
+
401
+ def get_object(site, request, args) -> dict:
402
+ model_admin, _label = _model_admin(site, request, args)
403
+ data = _object_keys(services.detail(model_admin, request, _id_arg(args)))
404
+ data.pop("children", None) # REST urls; MCP addresses children by model path + parents
405
+ children = _children(site, request, model_admin, data["id"])
406
+ if children:
407
+ data["children"] = {c["segment"]: {"model": c["model"], "parents": c["parents"]} for c in children}
408
+ # REST gives urls; MCP gives the names of the detail views (run them with run_view)
409
+ declared = custom_views.declared_views(model_admin)
410
+ views = [name for name in data.pop("views", {}) if site._view_listed(model_admin, declared[name])]
411
+ if views:
412
+ data["views"] = views
413
+ return data
414
+
415
+
416
+ def get_history(site, request, args) -> dict:
417
+ model_admin, _label = _model_admin(site, request, args)
418
+ limit = _arg(args, "limit", int, required=False)
419
+ return mcp_keys(services.history(model_admin, request, _id_arg(args), limit))
420
+
421
+
422
+ def create_object(site, request, args) -> dict:
423
+ _ensure_writable(site)
424
+ model_admin, _label = _model_admin(site, request, args)
425
+ data = _input_data(_arg(args, "data", dict))
426
+ dry_run = _arg(args, "dry_run", bool, required=False, default=False)
427
+ out = services.create(model_admin, request, data, dry_run=dry_run, confirm_token=args.get("confirm_token"))
428
+ return _write_result(out, dry_run)
429
+
430
+
431
+ def update_object(site, request, args) -> dict:
432
+ _ensure_writable(site)
433
+ model_admin, _label = _model_admin(site, request, args)
434
+ pk = _id_arg(args)
435
+ data = _input_data(_arg(args, "data", dict))
436
+ dry_run = _arg(args, "dry_run", bool, required=False, default=False)
437
+ token = args.get("confirm_token")
438
+ out = services.update(model_admin, request, pk, data, partial=True, dry_run=dry_run, confirm_token=token)
439
+ return _write_result(out, dry_run)
440
+
441
+
442
+ def _not_deleted_note() -> str:
443
+ return gettext("Nothing was deleted. Call again with confirm=true to delete.")
444
+
445
+
446
+ def delete_object(site, request, args) -> dict:
447
+ """A preview of the delete; with confirm=true, the delete. With ``require_dry_run`` the preview
448
+ issues a confirm_token bound to the object and its cascades, and the delete needs it."""
449
+ _ensure_writable(site)
450
+ model_admin, _label = _model_admin(site, request, args)
451
+ pk = _id_arg(args)
452
+ if _arg(args, "confirm", bool, required=False, default=False):
453
+ out = services.delete(model_admin, request, pk, confirm_token=args.get("confirm_token"))
454
+ return {"deleted": True, "object": mcp_keys(out["deleted"])}
455
+ preview = services.delete_preview(model_admin, request, pk)
456
+ token = preview.pop("confirm_token", None)
457
+ out = {"deleted": False, "confirm_required": True, "preview": mcp_keys(preview), "note": _not_deleted_note()}
458
+ if token:
459
+ out["confirm_token"] = token
460
+ out["note"] = gettext("Nothing was deleted. To delete, call again with confirm=true and this confirm_token.")
461
+ return out
462
+
463
+
464
+ def run_action(site, request, args) -> dict:
465
+ """A preview of the action on the selection; with confirm=true, its run. With ``require_dry_run`` the
466
+ preview issues a confirm_token bound to the selection, and the run needs it."""
467
+ _ensure_writable(site)
468
+ model_admin, _label = _model_admin(site, request, args)
469
+ payload: dict = {}
470
+ if _arg(args, "all", bool, required=False, default=False):
471
+ payload["all"] = True
472
+ else:
473
+ payload["pks"] = _arg({"ids": args.get("ids", args.get("pks"))}, "ids", list, required=False, default=[])
474
+ payload["confirm"] = _arg(args, "confirm", bool, required=False, default=False)
475
+ request = _with_query(request, _filters_query(args))
476
+ name, token = _arg(args, "action", str), args.get("confirm_token")
477
+ out = mcp_keys(services.run_action(model_admin, request, name, payload, confirm_token=token))
478
+ if payload["confirm"]:
479
+ return out
480
+ if "confirm_token" in out:
481
+ out["note"] = gettext("Nothing ran. To run it, call again with confirm=true and this confirm_token.")
482
+ elif "preview" in out:
483
+ out["note"] = _not_deleted_note()
484
+ else:
485
+ out["note"] = gettext("Nothing ran. Call again with confirm=true to run it.")
486
+ return out
487
+
488
+
489
+ def run_view(site, request, args) -> dict:
490
+ model_admin, _label = _model_admin(site, request, args)
491
+ name, pk = _arg(args, "view", str), _id_arg(args, required=False)
492
+ params = _arg(args, "params", dict, required=False, default={})
493
+ dry_run = _arg(args, "dry_run", bool, required=False, default=False)
494
+ return execute_view(
495
+ site, request, model_admin, name, pk=pk, params=params, dry_run=dry_run, confirm_token=args.get("confirm_token")
496
+ )
497
+
498
+
499
+ # --------------------------------------------------------------------------------------------
500
+ # catalogue
501
+ # --------------------------------------------------------------------------------------------
502
+ READ = {"readOnlyHint": True, "openWorldHint": False}
503
+ _WRITE = {"readOnlyHint": False, "destructiveHint": True, "openWorldHint": False}
504
+ _IDEMPOTENT_WRITE = {"readOnlyHint": False, "destructiveHint": True, "idempotentHint": True, "openWorldHint": False}
505
+ _RECORD = {"id": ID_ARG, "pk": PK_ALIAS_ARG}
506
+
507
+
508
+ def _tool(handler, title: str, description: str, input_schema: dict, annotations=READ, writes=False) -> ToolSpec:
509
+ return ToolSpec(handler.__name__, title, description, input_schema, handler, ANY_OBJECT, writes, annotations)
510
+
511
+
512
+ def _model_args(properties: dict, required=()) -> dict:
513
+ """A tool's arguments: ``model`` and ``parents``, then ``properties``."""
514
+ return obj({"model": MODEL_ARG, "parents": PARENTS_ARG, **properties}, ["model", *required])
515
+
516
+
517
+ TOOLS = [
518
+ _tool(
519
+ list_models,
520
+ "List models",
521
+ "List the data models you can access, with what you may do on each: 'can' (view, add, "
522
+ "change, delete), 'actions' and 'views'. Start here, and check it after a permission error.",
523
+ obj({}),
524
+ ),
525
+ _tool(
526
+ describe_model,
527
+ "Describe a model",
528
+ "Columns, filters, search, actions and the JSON Schema of the data accepted by "
529
+ "create_object/update_object. Call this before listing with filters or writing. Pass id to get the "
530
+ "update schema for one record (some fields may be read-only per record).",
531
+ _model_args(_RECORD),
532
+ ),
533
+ _tool(
534
+ list_objects,
535
+ "List objects",
536
+ "List objects the way the admin changelist does: filters, search, ordering and paging. "
537
+ "A search that finds nothing returns the fields it searched and the filters that take a related ID. "
538
+ "Returns columnar data: 'columns' names each position in every 'rows' entry; the first is the record 'id', "
539
+ "and a related record is {'id', 'label'}.",
540
+ _model_args(
541
+ {
542
+ "filters": FILTERS_ARG,
543
+ "search": {"type": "string", "description": "Free-text search (when describe_model says enabled)."},
544
+ "ordering": {
545
+ "type": ["array", "string"],
546
+ "items": {"type": "string"},
547
+ "description": "Sortable column names; prefix '-' for descending, e.g. ['-date', 'slug'].",
548
+ },
549
+ "page": {"type": "integer", "minimum": 1, "default": 1},
550
+ "per_page": {"type": "integer", "minimum": 1, "description": "Rows per page (default 25)."},
551
+ }
552
+ ),
553
+ ),
554
+ _tool(
555
+ resolve_entities,
556
+ "Resolve names to ids",
557
+ "Turn names the user typed into object ids and models, across every model you can see. "
558
+ "Each term returns 'objects' (records whose search fields match) and 'models' (models whose name "
559
+ "matches, e.g. 'invoices'), each with status 'unique', 'ambiguous' or 'none' and ranked candidates. "
560
+ "Use it before filtering, reporting or writing with a name.",
561
+ obj(
562
+ {
563
+ "terms": {
564
+ "type": "array",
565
+ "minItems": 1,
566
+ "maxItems": MAX_TERMS,
567
+ "items": obj(
568
+ {
569
+ "text": {"type": "string", "description": "The user's words, unchanged."},
570
+ "kind": {
571
+ "enum": ["any", "objects", "models"],
572
+ "default": "any",
573
+ "description": "Search objects, models or both.",
574
+ },
575
+ "models": {
576
+ "type": "array",
577
+ "items": {"type": "string"},
578
+ "description": "Only these models (e.g. a parameter's x-related-model).",
579
+ },
580
+ "for_field": obj(
581
+ {
582
+ "model": {"type": "string", "description": "The model being written."},
583
+ "field": {
584
+ "type": "string",
585
+ "description": "A relation field of its input_schema, or "
586
+ "'inlines.<prefix>.<field>' for an inline row field.",
587
+ },
588
+ },
589
+ ["model", "field"],
590
+ description="Resolve a value for this create/update field: searches the "
591
+ "related model, with the field's own choice limits.",
592
+ ),
593
+ },
594
+ ["text"],
595
+ ),
596
+ },
597
+ "models": {
598
+ "type": "array",
599
+ "items": {"type": "string"},
600
+ "description": "Default 'models' for every term without its own 'models' or 'for_field'.",
601
+ },
602
+ "limit": {"type": "integer", "minimum": 1, "maximum": MAX_LIMIT, "default": DEFAULT_LIMIT},
603
+ "verbose": {
604
+ "type": "boolean",
605
+ "default": False,
606
+ "description": "Also list the models searched when objects were found ('none' always lists them).",
607
+ },
608
+ },
609
+ ["terms"],
610
+ ),
611
+ ),
612
+ _tool(
613
+ get_object,
614
+ "Get one object",
615
+ "All fields of one record ('id', 'label', then the fields), including its inline rows.",
616
+ _model_args(_RECORD),
617
+ ),
618
+ _tool(
619
+ get_history,
620
+ "Get a record's history",
621
+ "Who changed one record, when and how, newest first: the admin's history page.",
622
+ _model_args(
623
+ {
624
+ "id": ID_ARG,
625
+ "limit": {
626
+ "type": "integer",
627
+ "minimum": 1,
628
+ "maximum": services.HISTORY_MAX_LIMIT,
629
+ "default": services.HISTORY_LIMIT,
630
+ },
631
+ },
632
+ ["id"],
633
+ ),
634
+ ),
635
+ _tool(
636
+ create_object,
637
+ "Create an object",
638
+ "Create an object through the admin's own form and save pipeline (same validation and "
639
+ "business rules as the admin). 'data' must match describe_model's input_schema.create. "
640
+ "Use dry_run=true first to check it. The result carries the document's computed 'totals' when the "
641
+ "admin declares them.",
642
+ _model_args({"data": DATA_ARG, "dry_run": DRY_RUN_ARG, "confirm_token": CONFIRM_TOKEN_ARG}, ["data"]),
643
+ {"readOnlyHint": False, "destructiveHint": False, "openWorldHint": False},
644
+ writes=True,
645
+ ),
646
+ _tool(
647
+ update_object,
648
+ "Update an object",
649
+ "Change some fields of an object (fields not given are kept). Inline rows: a row with "
650
+ "'id' updates that row, '_delete': true deletes it, a row without 'id' is added. 'data' must match "
651
+ "describe_model's input_schema.update. Use dry_run=true first to check it. The result carries the "
652
+ "document's computed 'totals' when the admin declares them.",
653
+ _model_args(
654
+ {**_RECORD, "data": DATA_ARG, "dry_run": DRY_RUN_ARG, "confirm_token": CONFIRM_TOKEN_ARG}, ["data"]
655
+ ),
656
+ _IDEMPOTENT_WRITE,
657
+ writes=True,
658
+ ),
659
+ _tool(
660
+ delete_object,
661
+ "Delete an object",
662
+ "Without confirm: returns what would be deleted (cascades, protected objects) and deletes "
663
+ "nothing. With confirm=true: deletes the object.",
664
+ _model_args(
665
+ {
666
+ **_RECORD,
667
+ "confirm": {"type": "boolean", "default": False, "description": "Actually delete."},
668
+ "confirm_token": {
669
+ **CONFIRM_TOKEN_ARG,
670
+ "description": "Only when the server requires a dry run first: the confirm_token returned "
671
+ "by the preview of this delete.",
672
+ },
673
+ }
674
+ ),
675
+ _IDEMPOTENT_WRITE,
676
+ writes=True,
677
+ ),
678
+ _tool(
679
+ run_action,
680
+ "Run an admin action",
681
+ "Run one of the model's admin actions (listed by describe_model) on the given ids, or on "
682
+ "all objects matching 'filters' with all=true. Without confirm=true it runs nothing and returns a "
683
+ "preview: what the action does, how many records and which (delete_selected: what would be deleted).",
684
+ _model_args(
685
+ {
686
+ "action": {"type": "string", "description": "Action name from describe_model's actions."},
687
+ "ids": {"type": "array", "items": ID_ARG, "description": "IDs of the records to run the action on."},
688
+ "pks": {"type": "array", "items": ID_ARG, "description": "Deprecated alias of 'ids'."},
689
+ "all": {"type": "boolean", "default": False, "description": "Run on all objects matching filters."},
690
+ "filters": FILTERS_ARG,
691
+ "confirm": {"type": "boolean", "default": False, "description": "Actually run the action."},
692
+ "confirm_token": {
693
+ **CONFIRM_TOKEN_ARG,
694
+ "description": "Only when the server requires a dry run first: the confirm_token returned "
695
+ "by the preview of this exact action and selection.",
696
+ },
697
+ },
698
+ ["action"],
699
+ ),
700
+ _WRITE,
701
+ writes=True,
702
+ ),
703
+ _tool(
704
+ run_view,
705
+ "Run a custom view",
706
+ "Run one of a model's custom views: reports, statements, computed pages or business "
707
+ "operations. They are listed under 'views' by list_models (names) and describe_model (parameters as "
708
+ "params_schema). Views with detail=true run on one record (give id). Views with writes=true change "
709
+ "data: use dry_run=true first to check them.",
710
+ _model_args(
711
+ {
712
+ "view": {"type": "string", "description": "View name from list_models / describe_model."},
713
+ "id": {**ID_ARG, "description": "The record, for views with detail=true."},
714
+ "pk": PK_ALIAS_ARG,
715
+ "params": {"type": "object", "description": "Parameters matching the view's params_schema."},
716
+ "dry_run": {
717
+ **DRY_RUN_ARG,
718
+ "description": "For views with writes=true: check permissions and params; the view does not run.",
719
+ },
720
+ "confirm_token": CONFIRM_TOKEN_ARG,
721
+ },
722
+ ["view"],
723
+ ),
724
+ _WRITE, # stays on read-only sites, where write views are hidden and refused
725
+ ),
726
+ ]
727
+
728
+
729
+ def view_tool(site, model_admin, spec) -> ToolSpec:
730
+ """A view published as its own tool (``@admin_api_mcp.view(mcp_tool="name")``). Its parameters
731
+ are flattened next to ``pk`` (detail views) and ``dry_run`` (write views)."""
732
+ opts = model_admin.model._meta
733
+ label = opts.label_lower
734
+ params = spec.params_schema()
735
+ properties = {}
736
+ required = list(params.get("required", ()))
737
+ # a view param named 'id' keeps its name; the record ID then goes in 'pk'
738
+ id_name = "id" if "id" not in params["properties"] else "pk"
739
+ if spec.detail:
740
+ properties[id_name] = {**ID_ARG, "description": gettext("ID of the %(model)s.") % {"model": opts.verbose_name}}
741
+ if id_name == "id":
742
+ properties["pk"] = PK_ALIAS_ARG
743
+ properties.update(params["properties"])
744
+ if spec.writes:
745
+ properties["dry_run"] = DRY_RUN_ARG
746
+ properties["confirm_token"] = CONFIRM_TOKEN_ARG
747
+ description = str(spec.description or spec.title)
748
+ description += " " + gettext("(Same as run_view '%(view)s' on %(models)s.)") % {
749
+ "view": spec.name,
750
+ "models": opts.verbose_name_plural,
751
+ }
752
+ reserved = custom_views.TOOL_RESERVED | ({"id"} if spec.detail and id_name == "id" else set())
753
+
754
+ def handler(site, request, args):
755
+ model_admin = services.get_model_admin_by_label(site.api_site, request, label)
756
+ if not site.is_exposed(model_admin):
757
+ raise NotFound()
758
+ params = {k: v for k, v in args.items() if k not in reserved}
759
+ pk = (args.get("id", args.get("pk")) if id_name == "id" else args.get("pk")) if spec.detail else None
760
+ if spec.detail and pk is None:
761
+ raise InvalidArguments(f"'{id_name}' is required.")
762
+ dry_run = bool(args.get("dry_run")) if spec.writes else False
763
+ token = args.get("confirm_token")
764
+ return execute_view(
765
+ site, request, model_admin, spec.name, pk=pk, params=params, dry_run=dry_run, confirm_token=token
766
+ )
767
+
768
+ annotations = _WRITE if spec.writes else READ
769
+ return ToolSpec(
770
+ spec.mcp_tool, spec.title, description, obj(properties, required), handler, ANY_OBJECT, spec.writes, annotations
771
+ )