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,9 @@
1
+ """admin_api_mcp: make Django ModelAdmin API-ready through ``api_`` twins."""
2
+
3
+ from .custom_views import view
4
+ from .decorators import display
5
+ from .mixins import ApiAdminMixin
6
+ from .resolver import api_value, resolve
7
+ from .sites import AdminApiSite
8
+
9
+ __all__ = ["AdminApiSite", "ApiAdminMixin", "api_value", "display", "resolve", "view"]
@@ -0,0 +1,197 @@
1
+ """Run admin actions through the API.
2
+
3
+ ``POST /v1/<app>/<model>/actions/<name>/`` with ``{"pks": [...]}`` or ``{"all": true}``
4
+ (``all`` honours the changelist filters passed as query parameters) returns a preview;
5
+ ``"confirm": true`` runs the action.
6
+
7
+ The action runs exactly like in the admin: same ``get_actions()`` (or the ``api_actions`` /
8
+ ``get_api_actions`` twin), same queryset (changelist filters + selection), and a POST request
9
+ carrying ``action``, ``_selected_action`` and ``post`` so confirmation-style actions such as
10
+ ``delete_selected`` complete. Permissions are stricter than the admin's: see :func:`available_actions`.
11
+
12
+ An action that returns an ``HttpResponse`` (file export, intermediate page) cannot be
13
+ represented in JSON: its transaction is rolled back and ``400 action_not_supported`` is
14
+ returned. Give it an API twin, a method ``api_<action_name>(self, request, queryset)``
15
+ returning JSON-serializable data, to expose it.
16
+ """
17
+
18
+ from __future__ import annotations
19
+
20
+ from dataclasses import dataclass
21
+ from functools import partial
22
+ from typing import Any
23
+
24
+ from django.contrib.admin import helpers
25
+ from django.contrib.admin.utils import model_format_dict
26
+ from django.core.exceptions import PermissionDenied
27
+ from django.db import router, transaction
28
+ from django.http import HttpResponseBase, QueryDict
29
+
30
+ from . import scopes
31
+ from .changelist import build_changelist, get_columns, split_api_params
32
+ from .deletion import deletion_summary
33
+ from .encoders import encode_value
34
+ from .errors import ApiError, NotFound, PermissionDeniedError
35
+ from .writes import InvalidJson, as_post_request
36
+
37
+
38
+ class ActionNotSupported(ApiError):
39
+ status = 400
40
+ code = "action_not_supported"
41
+
42
+
43
+ class UnknownAction(NotFound):
44
+ hint_capabilities = True # also raised for an action the user may not run
45
+
46
+
47
+ class NothingSelected(ApiError):
48
+ status = 400
49
+ code = "nothing_selected"
50
+
51
+
52
+ def action_parts(action):
53
+ """``(func, name, description)`` for Django < 6.1 tuples and >= 6.1 ``Action`` objects."""
54
+ if hasattr(action, "func"):
55
+ return action.func, action.name, action.description
56
+ return action[0], action[1], action[2]
57
+
58
+
59
+ def api_twin(model_admin, name):
60
+ twin = getattr(model_admin, f"api_{name}", None)
61
+ return twin if callable(twin) else None
62
+
63
+
64
+ def available_actions(model_admin, request) -> dict:
65
+ """``get_actions()`` less the actions the request may not run. Every operation in
66
+ :func:`scopes.required_ops` needs a scope; an action that declares no built-in permission also
67
+ needs the user's change permission (``get_actions()`` already checked the declared ones)."""
68
+ out = {}
69
+ can_change = None
70
+ for name, action in model_admin.get_actions(request).items():
71
+ declared = getattr(action_parts(action)[0], "allowed_permissions", ())
72
+ ops = scopes.required_ops(declared, writes="view" not in declared)
73
+ if not all(scopes.request_allows(request, model_admin.opts, op) for op in ops):
74
+ continue
75
+ if ops.isdisjoint(declared): # nothing built-in declared: ops is the implied {"change"}
76
+ if can_change is None:
77
+ can_change = model_admin.has_change_permission(request)
78
+ if not can_change:
79
+ continue
80
+ out[name] = action
81
+ return out
82
+
83
+
84
+ def describe_actions(model_admin, request) -> list[dict]:
85
+ out = []
86
+ names = model_format_dict(model_admin.opts)
87
+ for action in available_actions(model_admin, request).values():
88
+ _func, name, description = action_parts(action)
89
+ out.append(
90
+ {
91
+ "name": name,
92
+ "description": str(description % names),
93
+ "api_twin": api_twin(model_admin, name) is not None,
94
+ }
95
+ )
96
+ return out
97
+
98
+
99
+ PREVIEW_OBJECTS = 20 # objects an action preview names; "more" counts the rest
100
+
101
+
102
+ @dataclass
103
+ class Selection:
104
+ """An action the user may run and the objects it would run on."""
105
+
106
+ name: str
107
+ func: Any
108
+ description: str
109
+ queryset: Any
110
+ count: int
111
+ select_all: bool
112
+ pks: list
113
+
114
+ def state(self) -> list[str]:
115
+ """The pks the selection holds now, sorted: what an action's confirm token is bound to."""
116
+ return sorted(str(pk) for pk in self.queryset.values_list("pk", flat=True))
117
+
118
+
119
+ def select(model_admin, request, name, payload: dict) -> Selection:
120
+ """The action ``name`` and its objects: ``{"pks": [...]}`` or ``{"all": true}`` (with the
121
+ changelist filters in ``request.GET``). Raises before anything runs."""
122
+ if not isinstance(payload, dict):
123
+ raise InvalidJson("The action payload must be an object.")
124
+ actions = available_actions(model_admin, request)
125
+ if name not in actions:
126
+ raise UnknownAction(f"No action {name!r} (or no permission).")
127
+ func, name, description = action_parts(actions[name])
128
+
129
+ select_all = bool(payload.get("all"))
130
+ pks = payload.get("pks") or []
131
+ if not select_all and (not isinstance(pks, list) or not pks):
132
+ raise NothingSelected('Send {"pks": [...]} or {"all": true}.')
133
+
134
+ split_api_params(request)
135
+ cl = build_changelist(model_admin, request, get_columns(model_admin, request))
136
+ queryset = cl.get_queryset(request)
137
+ if not select_all:
138
+ queryset = queryset.filter(pk__in=pks)
139
+ count = queryset.count()
140
+ if not count:
141
+ raise NothingSelected("No objects match the selection.")
142
+ description = str(description % model_format_dict(model_admin.opts))
143
+ return Selection(name, func, description, queryset, count, select_all, pks)
144
+
145
+
146
+ def preview(model_admin, request, selection: Selection) -> dict:
147
+ """What running ``selection`` would do; runs nothing. ``delete_selected`` without an ``api_`` twin
148
+ adds the admin's delete confirmation data as ``preview``."""
149
+ objects = list(selection.queryset[:PREVIEW_OBJECTS])
150
+ out = {
151
+ "action": selection.name,
152
+ "description": selection.description,
153
+ "count": selection.count,
154
+ "objects": [encode_value(obj) for obj in objects],
155
+ }
156
+ if selection.count > len(objects):
157
+ out["more"] = selection.count - len(objects)
158
+ # by name: wrappers such as subadmin's keep it
159
+ if selection.name == "delete_selected" and not api_twin(model_admin, selection.name):
160
+ out["preview"] = deletion_summary(model_admin, request, selection.queryset)
161
+ out["confirm_required"] = True
162
+ return out
163
+
164
+
165
+ def execute(model_admin, request, selection: Selection) -> dict:
166
+ """Run ``selection`` the way the admin's changelist form does."""
167
+ name = selection.name
168
+ data = QueryDict(mutable=True)
169
+ data["action"] = name
170
+ data["post"] = "yes"
171
+ data["index"] = "0"
172
+ if selection.select_all:
173
+ data["select_across"] = "1"
174
+ else:
175
+ data.setlist(helpers.ACTION_CHECKBOX_NAME, [str(pk) for pk in selection.pks])
176
+ data._mutable = False
177
+ post_request = as_post_request(request, data)
178
+
179
+ twin = api_twin(model_admin, name)
180
+ try:
181
+ with transaction.atomic(using=router.db_for_write(model_admin.model)):
182
+ result = (twin or partial(selection.func, model_admin))(post_request, selection.queryset)
183
+ if isinstance(result, HttpResponseBase):
184
+ transaction.set_rollback(True)
185
+ except PermissionDenied as exc:
186
+ raise PermissionDeniedError(str(exc) or None) from exc
187
+ if isinstance(result, HttpResponseBase):
188
+ raise ActionNotSupported(
189
+ f"Action {name!r} returned a page/file (e.g. a confirmation or export); nothing was changed. "
190
+ f"Define api_{name}(self, request, queryset) on the admin to expose it in the API."
191
+ )
192
+ return {
193
+ "action": name,
194
+ "count": selection.count,
195
+ "messages": post_request._messages.captured(),
196
+ "result": encode_value(result),
197
+ }
admin_api_mcp/admin.py ADDED
@@ -0,0 +1,131 @@
1
+ """Admins for API tokens and MCP user instructions, registered by ``AdminApiSite`` (not autodiscovered)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from django import forms
6
+ from django.contrib import admin
7
+ from django.template.response import TemplateResponse
8
+ from django.urls import reverse
9
+ from django.utils.translation import gettext_lazy as _
10
+
11
+ from .scopes import normalize_scopes
12
+
13
+
14
+ class ApiTokenForm(forms.ModelForm):
15
+ scopes_text = forms.CharField(
16
+ label=_("scopes"),
17
+ required=False,
18
+ widget=forms.Textarea(attrs={"rows": 4, "placeholder": "store.sales:view\nstore.*:view\ncash.*:*"}),
19
+ help_text=_(
20
+ "One per line: <app_label>.<model_name>:<view|add|change|delete>, '*' allowed in any part. "
21
+ "Scopes only narrow the user's permissions. Leave empty for the user's full permissions."
22
+ ),
23
+ )
24
+
25
+ def __init__(self, *args, **kwargs):
26
+ super().__init__(*args, **kwargs)
27
+ if self.instance and self.instance.pk:
28
+ self.fields["scopes_text"].initial = "\n".join(self.instance.scopes or [])
29
+
30
+ def clean_scopes_text(self):
31
+ return normalize_scopes(self.cleaned_data.get("scopes_text") or "")
32
+
33
+ def save(self, commit=True):
34
+ self.instance.scopes = self.cleaned_data.get("scopes_text") or []
35
+ return super().save(commit)
36
+
37
+
38
+ class ApiTokenAdmin(admin.ModelAdmin):
39
+ api_enabled = False # never expose tokens through the API itself
40
+
41
+ list_display = [
42
+ "name",
43
+ "user",
44
+ "token_prefix",
45
+ "kind",
46
+ "scope_summary",
47
+ "created",
48
+ "expires_at",
49
+ "last_used_at",
50
+ "status",
51
+ ]
52
+ list_filter = ["kind"]
53
+ search_fields = ["name", "prefix", "user__username"]
54
+ actions = ["revoke_tokens"]
55
+ form = ApiTokenForm
56
+
57
+ @admin.display(description=_("token"))
58
+ def token_prefix(self, obj):
59
+ return f"aapi_{obj.prefix}_…"
60
+
61
+ @admin.display(description=_("scopes"))
62
+ def scope_summary(self, obj):
63
+ return ", ".join(obj.scopes) if obj.scopes else _("full user permissions")
64
+
65
+ @admin.display(description=_("status"))
66
+ def status(self, obj):
67
+ if obj.revoked_at:
68
+ return _("revoked")
69
+ if obj.is_expired:
70
+ return _("expired")
71
+ return _("active")
72
+
73
+ def get_queryset(self, request):
74
+ qs = super().get_queryset(request).select_related("user")
75
+ return qs if request.user.is_superuser else qs.filter(user=request.user)
76
+
77
+ def get_fields(self, request, obj=None):
78
+ fields = ["name", "kind", "expires_at", "scopes_text"]
79
+ if request.user.is_superuser:
80
+ fields.insert(0, "user")
81
+ if obj is not None:
82
+ fields += ["token_prefix", "created", "last_used_at", "revoked_at"]
83
+ return fields
84
+
85
+ def get_readonly_fields(self, request, obj=None):
86
+ if obj is None:
87
+ return []
88
+ return ["user", "kind", "token_prefix", "created", "last_used_at", "revoked_at"]
89
+
90
+ def save_model(self, request, obj, form, change):
91
+ if not change:
92
+ if not request.user.is_superuser or not obj.user_id:
93
+ obj.user = request.user
94
+ obj.raw_token = obj.set_new_secret() # read once by response_add
95
+ super().save_model(request, obj, form, change)
96
+
97
+ def response_add(self, request, obj, post_url_continue=None):
98
+ """Show the new raw token on this response page, not in a message (the messages cookie)."""
99
+ opts = self.opts
100
+ context = {
101
+ **self.admin_site.each_context(request),
102
+ "title": _("Token created"),
103
+ "opts": opts,
104
+ "original": obj,
105
+ "raw_token": obj.raw_token,
106
+ "change_url": reverse(f"admin:{opts.app_label}_{opts.model_name}_change", args=[obj.pk]),
107
+ "changelist_url": reverse(f"admin:{opts.app_label}_{opts.model_name}_changelist"),
108
+ }
109
+ return TemplateResponse(request, "admin_api_mcp/token_created.html", context)
110
+
111
+ @admin.action(description=_("Revoke selected tokens"), permissions=["change"])
112
+ def revoke_tokens(self, request, queryset):
113
+ count = 0
114
+ for token in queryset.filter(revoked_at__isnull=True):
115
+ token.revoke()
116
+ count += 1
117
+ self.message_user(request, _("%(count)d token(s) revoked.") % {"count": count})
118
+
119
+
120
+ class McpUserInstructionsAdmin(admin.ModelAdmin):
121
+ api_enabled = False # never expose instructions through the API itself
122
+
123
+ list_display = ["user", "instructions"]
124
+ search_fields = ["user__username", "instructions"]
125
+ raw_id_fields = ["user"]
126
+
127
+ def has_view_permission(self, request, obj=None):
128
+ """Superusers only: a row becomes server instructions for another user's agent."""
129
+ return request.user.is_superuser
130
+
131
+ has_add_permission = has_change_permission = has_delete_permission = has_view_permission
admin_api_mcp/apps.py ADDED
@@ -0,0 +1,10 @@
1
+ from django.apps import AppConfig
2
+
3
+
4
+ class AdminApiConfig(AppConfig):
5
+ name = "admin_api_mcp"
6
+ default_auto_field = "django.db.models.AutoField" # matches migration 0001
7
+ verbose_name = "Admin API"
8
+
9
+ def ready(self):
10
+ from . import checks # noqa: F401 (registers system checks)
admin_api_mcp/auth.py ADDED
@@ -0,0 +1,62 @@
1
+ """Pluggable authenticators. Each returns a user or ``None`` (= not mine, try the next one)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from django.middleware.csrf import CsrfViewMiddleware
6
+
7
+ from .errors import NotAuthenticated, PermissionDeniedError
8
+
9
+ SAFE_METHODS = ("GET", "HEAD", "OPTIONS")
10
+
11
+
12
+ class BaseAuthenticator:
13
+ def authenticate(self, request): # pragma: no cover - interface
14
+ raise NotImplementedError
15
+
16
+
17
+ class _CsrfCheck(CsrfViewMiddleware):
18
+ def _reject(self, request, reason):
19
+ return reason
20
+
21
+
22
+ class SessionAuthenticator(BaseAuthenticator):
23
+ """Uses the Django session (same login as the admin). Enforces CSRF on unsafe methods."""
24
+
25
+ def authenticate(self, request):
26
+ user = getattr(request, "user", None)
27
+ if user is None or not user.is_authenticated:
28
+ return None
29
+ if request.method not in SAFE_METHODS:
30
+ reason = _CsrfCheck(lambda r: None).process_view(request, None, (), {})
31
+ if reason:
32
+ raise PermissionDeniedError(f"CSRF failed: {reason}", code="csrf_failed")
33
+ return user
34
+
35
+
36
+ def get_token_model():
37
+ from django.apps import apps
38
+ from django.conf import settings
39
+
40
+ return apps.get_model(getattr(settings, "ADMIN_API_TOKEN_MODEL", "admin_api_mcp.ApiToken"), require_ready=True)
41
+
42
+
43
+ class TokenAuthenticator(BaseAuthenticator):
44
+ """``Authorization: Bearer aapi_<prefix>_<secret>``. No CSRF (not cookie based).
45
+
46
+ A request that sends a Bearer token is never authenticated by the session: an invalid,
47
+ revoked or expired token is a 401, not a fall-through.
48
+ """
49
+
50
+ keyword = "bearer"
51
+
52
+ def authenticate(self, request):
53
+ header = request.META.get("HTTP_AUTHORIZATION", "")
54
+ scheme, _, raw = header.partition(" ")
55
+ if scheme.lower() != self.keyword:
56
+ return None
57
+ token = get_token_model().objects.get_for_raw(raw.strip())
58
+ if token is None or not token.user.is_active:
59
+ raise NotAuthenticated("Invalid, revoked or expired token.", code="invalid_token")
60
+ token.touch()
61
+ request.api_token = token
62
+ return token.user
@@ -0,0 +1,261 @@
1
+ """The API changelist: Django's ``ChangeList`` driven by the resolved ``api_`` twins."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import contextlib
6
+ from dataclasses import dataclass
7
+ from typing import Any
8
+
9
+ from django.contrib.admin.exceptions import DisallowedModelAdminLookup
10
+ from django.contrib.admin.utils import label_for_field, lookup_field
11
+ from django.contrib.admin.views.main import ChangeList
12
+ from django.core.exceptions import FieldDoesNotExist
13
+ from django.db.models.constants import LOOKUP_SEP
14
+ from django.http import QueryDict
15
+
16
+ from .decorators import is_api_display
17
+ from .encoders import encode_field_value, encode_value, field_type
18
+ from .errors import ApiError
19
+ from .resolver import api_value, resolve
20
+ from .sensitive import Redactor
21
+
22
+ # Query parameters owned by the API. Removed from request.GET before ChangeList sees it,
23
+ # because ChangeList treats every unknown key as a field lookup. Admin's own params
24
+ # (o, q, p, all, _facets, _to_field, ...) are left alone.
25
+ SHAPE_PARAM = "_shape"
26
+ PER_PAGE_PARAM = "_per_page"
27
+ API_PARAMS = frozenset({SHAPE_PARAM, PER_PAGE_PARAM})
28
+ SHAPES = ("objects", "columnar")
29
+
30
+
31
+ class BadLookup(ApiError):
32
+ status = 400
33
+ code = "bad_lookup"
34
+
35
+
36
+ @dataclass(frozen=True)
37
+ class Column:
38
+ name: Any # list_display entry (str or callable)
39
+ key: str # key in the JSON row
40
+ kind: str # "str" | "field" | "callable"
41
+ field: Any = None
42
+
43
+ def label(self, model_admin) -> str:
44
+ if self.kind == "str":
45
+ return str(model_admin.model._meta.verbose_name)
46
+ return str(label_for_field(self.name, model_admin.model, model_admin))
47
+
48
+ def value(self, obj, model_admin):
49
+ if self.kind == "str":
50
+ return str(obj)
51
+ field, _attr, value = lookup_field(self.name, obj, model_admin)
52
+ return encode_field_value(field, value)
53
+
54
+
55
+ def _list_display_is_explicit(model_admin) -> bool:
56
+ """True when list_display comes from an api_ twin (``get_api_list_display`` / ``api_list_display``)."""
57
+ return (
58
+ getattr(model_admin, "get_api_list_display", None) is not None
59
+ or getattr(model_admin, "api_list_display", None) is not None
60
+ )
61
+
62
+
63
+ def _model_field(model, name):
64
+ if not isinstance(name, str):
65
+ return None
66
+ try:
67
+ return model._meta.get_field(name)
68
+ except FieldDoesNotExist:
69
+ return None
70
+
71
+
72
+ def _name_key(name):
73
+ return name if isinstance(name, str) else getattr(name, "__name__", repr(name))
74
+
75
+
76
+ def get_columns(model_admin, request) -> list[Column]:
77
+ """Resolve list_display for the API.
78
+
79
+ Model fields and ``__str__`` are always included. Anything else (admin methods, model
80
+ methods/properties, plain callables) is a *callable* and is only included when the list
81
+ comes from an api_ twin, or when it is decorated with ``@admin_api_mcp.display``.
82
+ """
83
+ explicit = _list_display_is_explicit(model_admin)
84
+ model = model_admin.model
85
+ columns = []
86
+ for name in api_value(model_admin, "list_display", request):
87
+ if name == "action_checkbox":
88
+ continue
89
+ if name == "__str__":
90
+ columns.append(Column(name, "str", "str"))
91
+ continue
92
+ field = _model_field(model, name)
93
+ if field is not None:
94
+ columns.append(Column(name, name, "field", field))
95
+ continue
96
+ if isinstance(name, str) and "__" in name and not hasattr(model_admin, name) and not hasattr(model, name):
97
+ # related lookup ("client__name"), supported by Django >= 5.1
98
+ columns.append(Column(name, name, "field"))
99
+ continue
100
+ func = name if callable(name) else getattr(model_admin, name, None) or getattr(model, name, None)
101
+ if explicit or is_api_display(func):
102
+ columns.append(Column(name, _name_key(name), "callable"))
103
+ return columns
104
+
105
+
106
+ def lookup_fields(model_admin, request) -> set[str]:
107
+ """Names of the fields a free-form filter lookup may start from: ``api_lookup_fields`` /
108
+ ``get_api_lookup_fields(request)``, else the fields the API shows (columns, filters, detail)."""
109
+ from .detail import detail_fields
110
+
111
+ model = model_admin.model
112
+ getter = getattr(model_admin, "get_api_lookup_fields", None)
113
+ explicit = getter(request) if getter else getattr(model_admin, "api_lookup_fields", None)
114
+ if explicit is not None:
115
+ names = list(explicit)
116
+ else:
117
+ names = [model._meta.pk.name, model_admin.date_hierarchy]
118
+ names += [c.name for c in get_columns(model_admin, request) if c.kind == "field"]
119
+ for item in model_admin.get_list_filter(request):
120
+ names.append(item[0] if isinstance(item, (list, tuple)) else item)
121
+ names += detail_fields(model_admin, request, None)[0] # the add form's fields
122
+ with contextlib.suppress(Exception): # the change form's fields, for a blank object
123
+ names += detail_fields(model_admin, request, model())[0]
124
+ roots = (_model_field(model, n.split(LOOKUP_SEP)[0]) for n in names if isinstance(n, str))
125
+ return {field.name for field in roots if field is not None}
126
+
127
+
128
+ class ApiChangeList(ChangeList):
129
+ """ChangeList that can skip fetching results (used by the schema endpoint), refuses free-form
130
+ filter lookups on fields the API does not show or redacts, and refuses a sort on a redacted column."""
131
+
132
+ def __init__(self, request, *args, schema_only=False, **kwargs):
133
+ self._schema_only = schema_only
134
+ self._request = request
135
+ super().__init__(request, *args, **kwargs)
136
+
137
+ def get_filters(self, request):
138
+ filters = super().get_filters(request) # runs the admin's own lookup_allowed
139
+ allowed = None
140
+ redactor = Redactor(self.model_admin, request)
141
+ for key in filters[2]: # the lookups no list filter consumed
142
+ if redactor.on_path(key): # a redacted value is not a filter either
143
+ raise DisallowedModelAdminLookup(f"Filtering by {key} not allowed")
144
+ field = _model_field(self.model, key.split(LOOKUP_SEP)[0])
145
+ if field is None:
146
+ continue
147
+ if allowed is None:
148
+ allowed = lookup_fields(self.model_admin, request)
149
+ if field.name not in allowed:
150
+ raise DisallowedModelAdminLookup(f"Filtering by {key} not allowed")
151
+ return filters
152
+
153
+ def get_ordering_field(self, field_name):
154
+ """The field ``?o=`` sorts ``field_name`` on; a redacted column or order field is refused."""
155
+ order_field = super().get_ordering_field(field_name)
156
+ key = _name_key(field_name)
157
+ if sorts_on_redacted(Redactor(self.model_admin, self._request), key, order_field):
158
+ raise DisallowedModelAdminLookup(f"Ordering by {key} not allowed")
159
+ return order_field
160
+
161
+ def get_results(self, request):
162
+ if self._schema_only:
163
+ self.result_count = self.full_result_count = None
164
+ self.result_list = []
165
+ self.can_show_all = self.multi_page = False
166
+ self.paginator = None
167
+ self.show_full_result_count = False
168
+ self.show_admin_actions = False
169
+ return
170
+ super().get_results(request)
171
+
172
+
173
+ def split_api_params(request) -> dict:
174
+ """Move API-owned params out of request.GET. Returns them; keeps the original as ``request.api_query``."""
175
+ original = request.GET
176
+ api = {k: original.get(k) for k in API_PARAMS if k in original}
177
+ cleaned = original.copy()
178
+ for k in API_PARAMS:
179
+ cleaned.pop(k, None)
180
+ cleaned._mutable = False
181
+ request.api_query = original
182
+ request.GET = cleaned
183
+ return api
184
+
185
+
186
+ def build_changelist(model_admin, request, columns, *, per_page=None, schema_only=False) -> ApiChangeList:
187
+ from django.contrib.admin.options import IncorrectLookupParameters
188
+ from django.core.exceptions import SuspiciousOperation
189
+
190
+ if per_page is None:
191
+ per_page = resolve(model_admin, "list_per_page", request)
192
+ try:
193
+ return ApiChangeList(
194
+ request,
195
+ model_admin.model,
196
+ [c.name for c in columns],
197
+ (),
198
+ model_admin.get_list_filter(request),
199
+ model_admin.date_hierarchy,
200
+ model_admin.get_search_fields(request),
201
+ model_admin.get_list_select_related(request),
202
+ per_page,
203
+ model_admin.list_max_show_all,
204
+ (),
205
+ model_admin,
206
+ model_admin.get_sortable_by(request),
207
+ model_admin.search_help_text,
208
+ schema_only=schema_only,
209
+ )
210
+ except DisallowedModelAdminLookup as exc:
211
+ raise BadLookup(str(exc)) from exc
212
+ except (IncorrectLookupParameters, SuspiciousOperation) as exc: # ORM text names the model's fields
213
+ raise BadLookup("Invalid filter, ordering or page parameter.") from exc
214
+
215
+
216
+ def describe_filters(cl: ApiChangeList) -> list[dict]:
217
+ out = []
218
+ for spec in cl.filter_specs:
219
+ expected = list(spec.expected_parameters())
220
+ choices = []
221
+ for choice in spec.choices(cl):
222
+ qs = QueryDict(choice.get("query_string", "").lstrip("?"))
223
+ choices.append(
224
+ {
225
+ "display": str(choice.get("display")),
226
+ "selected": bool(choice.get("selected")),
227
+ "params": {k: qs.get(k) for k in expected if k in qs},
228
+ }
229
+ )
230
+ out.append({"title": str(spec.title), "parameters": expected, "choices": choices})
231
+ return out
232
+
233
+
234
+ def sorts_on_redacted(redactor, key, order_field) -> bool:
235
+ """True when sorting column ``key`` on ``order_field`` would order rows by a redacted value."""
236
+ return redactor(key) or (isinstance(order_field, str) and redactor.on_path(order_field.lstrip("-")))
237
+
238
+
239
+ def describe_columns(columns, model_admin, request) -> list[dict]:
240
+ sortable = set(model_admin.get_sortable_by(request) or ())
241
+ redactor = Redactor(model_admin, request)
242
+ out = []
243
+ for index, col in enumerate(columns):
244
+ entry = {"name": col.key, "label": col.label(model_admin), "kind": col.kind, "type": None}
245
+ if col.field is not None:
246
+ entry["type"] = field_type(col.field)
247
+ if getattr(col.field, "choices", None):
248
+ entry["choices"] = [{"value": encode_value(v), "display": str(d)} for v, d in col.field.flatchoices]
249
+ order_field = col.name if col.kind == "field" else _order_field(col, model_admin)
250
+ entry["sortable"] = (
251
+ col.name in sortable and bool(order_field) and not sorts_on_redacted(redactor, col.key, order_field)
252
+ )
253
+ entry["order_index"] = index # value to use in ?o=
254
+ out.append(entry)
255
+ return out
256
+
257
+
258
+ def _order_field(col, model_admin):
259
+ """The ``admin_order_field`` of a callable column, or ``None``."""
260
+ func = col.name if callable(col.name) else getattr(model_admin, col.name, None)
261
+ return getattr(func, "admin_order_field", None)