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.
- admin_api_mcp/__init__.py +9 -0
- admin_api_mcp/actions.py +197 -0
- admin_api_mcp/admin.py +131 -0
- admin_api_mcp/apps.py +10 -0
- admin_api_mcp/auth.py +62 -0
- admin_api_mcp/changelist.py +261 -0
- admin_api_mcp/checks.py +35 -0
- admin_api_mcp/confirm.py +97 -0
- admin_api_mcp/contrib/__init__.py +1 -0
- admin_api_mcp/contrib/search/__init__.py +0 -0
- admin_api_mcp/contrib/search/apps.py +21 -0
- admin_api_mcp/contrib/search/backend.py +121 -0
- admin_api_mcp/contrib/search/checks.py +12 -0
- admin_api_mcp/contrib/search/conf.py +42 -0
- admin_api_mcp/contrib/search/engines/__init__.py +0 -0
- admin_api_mcp/contrib/search/engines/base.py +99 -0
- admin_api_mcp/contrib/search/engines/db.py +265 -0
- admin_api_mcp/contrib/search/fold.py +41 -0
- admin_api_mcp/contrib/search/indexer.py +364 -0
- admin_api_mcp/contrib/search/management/__init__.py +0 -0
- admin_api_mcp/contrib/search/management/commands/__init__.py +0 -0
- admin_api_mcp/contrib/search/management/commands/rebuild_search_index.py +29 -0
- admin_api_mcp/contrib/search/management/commands/search_index.py +25 -0
- admin_api_mcp/contrib/search/migrations/0001_initial.py +83 -0
- admin_api_mcp/contrib/search/migrations/__init__.py +0 -0
- admin_api_mcp/contrib/search/models.py +43 -0
- admin_api_mcp/contrib/subadmin.py +37 -0
- admin_api_mcp/custom_views.py +471 -0
- admin_api_mcp/decorators.py +26 -0
- admin_api_mcp/deletion.py +58 -0
- admin_api_mcp/detail.py +115 -0
- admin_api_mcp/encoders.py +72 -0
- admin_api_mcp/errors.py +82 -0
- admin_api_mcp/jsonschema.py +225 -0
- admin_api_mcp/management/__init__.py +0 -0
- admin_api_mcp/management/commands/__init__.py +0 -0
- admin_api_mcp/management/commands/create_api_token.py +40 -0
- admin_api_mcp/management/commands/mcp_serve.py +86 -0
- admin_api_mcp/management/commands/migrate_from_admin_api.py +153 -0
- admin_api_mcp/mcp/__init__.py +7 -0
- admin_api_mcp/mcp/bridge.py +71 -0
- admin_api_mcp/mcp/handlers.py +771 -0
- admin_api_mcp/mcp/resolve.py +410 -0
- admin_api_mcp/mcp/server.py +76 -0
- admin_api_mcp/mcp/sites.py +284 -0
- admin_api_mcp/mcp/stdio.py +53 -0
- admin_api_mcp/mcp/tools.py +84 -0
- admin_api_mcp/mcp/views.py +74 -0
- admin_api_mcp/middleware.py +18 -0
- admin_api_mcp/migrations/0001_initial.py +40 -0
- admin_api_mcp/migrations/0002_mcp_confirmation.py +27 -0
- admin_api_mcp/migrations/0003_mcp_user_instructions.py +28 -0
- admin_api_mcp/migrations/__init__.py +0 -0
- admin_api_mcp/mixins.py +173 -0
- admin_api_mcp/models.py +145 -0
- admin_api_mcp/nested.py +122 -0
- admin_api_mcp/resolver.py +95 -0
- admin_api_mcp/scopes.py +142 -0
- admin_api_mcp/sensitive.py +67 -0
- admin_api_mcp/services.py +652 -0
- admin_api_mcp/sites.py +242 -0
- admin_api_mcp/templates/admin_api_mcp/token_created.html +17 -0
- admin_api_mcp/views/__init__.py +0 -0
- admin_api_mcp/views/changelist.py +70 -0
- admin_api_mcp/views/custom.py +33 -0
- admin_api_mcp/views/detail.py +50 -0
- admin_api_mcp/views/nested.py +73 -0
- admin_api_mcp/views/registry.py +15 -0
- admin_api_mcp/writes.py +530 -0
- django_admin_api_mcp-0.1.0.dist-info/METADATA +280 -0
- django_admin_api_mcp-0.1.0.dist-info/RECORD +73 -0
- django_admin_api_mcp-0.1.0.dist-info/WHEEL +4 -0
- django_admin_api_mcp-0.1.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
"""Python value → JSON-ready value."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import datetime
|
|
6
|
+
|
|
7
|
+
from django.contrib.auth import get_user_model
|
|
8
|
+
from django.contrib.auth.hashers import identify_hasher
|
|
9
|
+
from django.core.serializers.json import DjangoJSONEncoder
|
|
10
|
+
from django.db import models
|
|
11
|
+
from django.db.models.fields.files import FieldFile
|
|
12
|
+
from django.utils import timezone
|
|
13
|
+
|
|
14
|
+
_encoder = DjangoJSONEncoder()
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def encode_value(value):
|
|
18
|
+
if value is None or isinstance(value, (bool, int, float, str)):
|
|
19
|
+
return value
|
|
20
|
+
if isinstance(value, models.Model):
|
|
21
|
+
return {"pk": encode_value(value.pk), "str": str(value)}
|
|
22
|
+
if isinstance(value, FieldFile):
|
|
23
|
+
return {"name": value.name, "url": value.url} if value else None
|
|
24
|
+
if isinstance(value, (list, tuple, set, frozenset)):
|
|
25
|
+
return [encode_value(v) for v in value]
|
|
26
|
+
if isinstance(value, dict):
|
|
27
|
+
return {str(k): encode_value(v) for k, v in value.items()}
|
|
28
|
+
if isinstance(value, datetime.datetime) and timezone.is_aware(value):
|
|
29
|
+
# One representation everywhere (list, detail, after save): the current time zone,
|
|
30
|
+
# like the admin displays it.
|
|
31
|
+
value = timezone.localtime(value)
|
|
32
|
+
try:
|
|
33
|
+
# datetime/date/time (ISO 8601), timedelta, Decimal, UUID, lazy translation strings
|
|
34
|
+
return _encoder.default(value)
|
|
35
|
+
except TypeError:
|
|
36
|
+
return str(value)
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def encode_field_value(field, value):
|
|
40
|
+
"""``value`` of the model ``field`` as JSON. The user's password becomes the masked summary
|
|
41
|
+
the admin shows (Django's ``display_for_field`` rule), ``None`` when unusable."""
|
|
42
|
+
if field is not None and field.name == "password" and field.model == get_user_model():
|
|
43
|
+
try:
|
|
44
|
+
value = identify_hasher(value).safe_summary(value)
|
|
45
|
+
except ValueError:
|
|
46
|
+
value = None
|
|
47
|
+
return encode_value(value)
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
_FIELD_TYPES = [
|
|
51
|
+
(models.BooleanField, "boolean"),
|
|
52
|
+
(models.AutoField, "integer"),
|
|
53
|
+
(models.IntegerField, "integer"),
|
|
54
|
+
(models.DecimalField, "decimal"),
|
|
55
|
+
(models.FloatField, "number"),
|
|
56
|
+
(models.DateTimeField, "datetime"), # before DateField (subclass)
|
|
57
|
+
(models.DateField, "date"),
|
|
58
|
+
(models.TimeField, "time"),
|
|
59
|
+
(models.DurationField, "duration"),
|
|
60
|
+
(models.UUIDField, "uuid"),
|
|
61
|
+
(models.FileField, "file"),
|
|
62
|
+
(models.JSONField, "json"),
|
|
63
|
+
(models.ForeignKey, "related"), # covers OneToOneField
|
|
64
|
+
(models.ManyToManyField, "related_many"),
|
|
65
|
+
]
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def field_type(field) -> str:
|
|
69
|
+
for cls, name in _FIELD_TYPES:
|
|
70
|
+
if isinstance(field, cls):
|
|
71
|
+
return name
|
|
72
|
+
return "string"
|
admin_api_mcp/errors.py
ADDED
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from django.db import connections
|
|
4
|
+
from django.http import JsonResponse
|
|
5
|
+
from django.utils.translation import gettext_lazy
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class ApiError(Exception):
|
|
9
|
+
status = 400
|
|
10
|
+
code = "bad_request"
|
|
11
|
+
default_detail: str | None = None # a gettext_lazy string, translated when raised
|
|
12
|
+
hint_capabilities = False # a denial the user's list of models and permissions explains
|
|
13
|
+
|
|
14
|
+
def __init__(self, detail: str | None = None, *, status: int | None = None, code: str | None = None, **extra):
|
|
15
|
+
if detail is None and self.default_detail:
|
|
16
|
+
detail = str(self.default_detail)
|
|
17
|
+
super().__init__(detail or self.code)
|
|
18
|
+
self.detail = detail
|
|
19
|
+
if status is not None:
|
|
20
|
+
self.status = status
|
|
21
|
+
if code is not None:
|
|
22
|
+
self.code = code
|
|
23
|
+
self.extra = extra
|
|
24
|
+
|
|
25
|
+
def as_response(self) -> JsonResponse:
|
|
26
|
+
payload = {"error": self.code}
|
|
27
|
+
if self.detail:
|
|
28
|
+
payload["detail"] = self.detail
|
|
29
|
+
payload.update(self.extra)
|
|
30
|
+
return JsonResponse(payload, status=self.status)
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
class InvalidArguments(ApiError):
|
|
34
|
+
status = 400
|
|
35
|
+
code = "invalid_arguments"
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
class NotAuthenticated(ApiError):
|
|
39
|
+
status = 401
|
|
40
|
+
code = "not_authenticated"
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
class PermissionDeniedError(ApiError):
|
|
44
|
+
status = 403
|
|
45
|
+
code = "permission_denied"
|
|
46
|
+
default_detail = gettext_lazy("You do not have permission to do this.")
|
|
47
|
+
hint_capabilities = True
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
class NotFound(ApiError):
|
|
51
|
+
status = 404
|
|
52
|
+
code = "not_found"
|
|
53
|
+
default_detail = gettext_lazy("This kind of record is not available here.")
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
class MethodNotAllowed(ApiError):
|
|
57
|
+
status = 405
|
|
58
|
+
code = "method_not_allowed"
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
class PayloadTooLarge(ApiError):
|
|
62
|
+
status = 413
|
|
63
|
+
code = "payload_too_large"
|
|
64
|
+
default_detail = gettext_lazy("The request body is larger than the server's DATA_UPLOAD_MAX_MEMORY_SIZE.")
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
class ServerError(ApiError):
|
|
68
|
+
"""An unhandled exception in a REST view or an MCP tool (see :func:`server_error`)."""
|
|
69
|
+
|
|
70
|
+
status = 500
|
|
71
|
+
code = "server_error"
|
|
72
|
+
default_detail = gettext_lazy("The request failed; see the server log.")
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def server_error(logger, message: str, *args) -> ServerError:
|
|
76
|
+
"""Log the exception being handled, roll back an ``ATOMIC_REQUESTS`` transaction (as DRF does) and
|
|
77
|
+
return the 500 to answer. REST views and MCP tools both end here."""
|
|
78
|
+
logger.exception(message, *args)
|
|
79
|
+
for connection in connections.all(initialized_only=True):
|
|
80
|
+
if connection.settings_dict.get("ATOMIC_REQUESTS") and connection.in_atomic_block:
|
|
81
|
+
connection.set_rollback(True)
|
|
82
|
+
return ServerError()
|
|
@@ -0,0 +1,225 @@
|
|
|
1
|
+
"""JSON Schema (draft 2020-12) for write payloads, generated from the admin's own forms.
|
|
2
|
+
|
|
3
|
+
The schema describes what :func:`admin_api_mcp.writes.build_post_data` accepts: the fields of
|
|
4
|
+
``get_form()`` (readonly fields are already excluded by the admin) and, under ``"inlines"``,
|
|
5
|
+
one array of rows per inline formset prefix.
|
|
6
|
+
|
|
7
|
+
Two variants:
|
|
8
|
+
|
|
9
|
+
* ``create``: required = the form's required fields without an initial value (the API fills
|
|
10
|
+
missing fields from the add form's initial values, given as ``default``); inline rows are new.
|
|
11
|
+
* ``update``: PATCH semantics, nothing is required; inline rows may carry ``pk`` (``id`` on MCP:
|
|
12
|
+
update that row) and ``"_delete": true``. Rows without it are new rows.
|
|
13
|
+
|
|
14
|
+
File fields take ``{"filename", "content_base64"}``; ``null`` clears an optional file.
|
|
15
|
+
|
|
16
|
+
Vendor keywords: ``x-related-model`` (``"app_label.model_name"``) on relation fields.
|
|
17
|
+
"""
|
|
18
|
+
|
|
19
|
+
from __future__ import annotations
|
|
20
|
+
|
|
21
|
+
from django import forms
|
|
22
|
+
from django.db import models
|
|
23
|
+
from django.utils.html import strip_tags
|
|
24
|
+
from django.utils.translation import gettext_lazy as _
|
|
25
|
+
|
|
26
|
+
from .detail import inline_prefixes
|
|
27
|
+
from .encoders import encode_value
|
|
28
|
+
from .writes import INLINES_KEY, ROW_DELETE_KEY, UPLOAD_KEYS, form_initial
|
|
29
|
+
|
|
30
|
+
# ModelAdmin.formfield_for_manytomany appends this widget hint to M2M help texts
|
|
31
|
+
_M2M_WIDGET_HINT = _("Hold down “Control”, or “Command” on a Mac, to select more than one.")
|
|
32
|
+
|
|
33
|
+
SCHEMA_DIALECT = "https://json-schema.org/draft/2020-12/schema"
|
|
34
|
+
DECIMAL_PATTERN = r"^-?\d+(\.\d+)?$"
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def _nullable(schema: dict) -> dict:
|
|
38
|
+
if "enum" in schema:
|
|
39
|
+
return {**schema, "enum": [*schema["enum"], None]}
|
|
40
|
+
t = schema.get("type")
|
|
41
|
+
if t is None:
|
|
42
|
+
return schema
|
|
43
|
+
types = t if isinstance(t, list) else [t]
|
|
44
|
+
return {**schema, "type": [*types, "null"]} if "null" not in types else schema
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def _pk_schema(model, to_field_name=None) -> dict:
|
|
48
|
+
field = model._meta.get_field(to_field_name) if to_field_name else model._meta.pk
|
|
49
|
+
if isinstance(field, (models.AutoField, models.IntegerField)):
|
|
50
|
+
return {"type": "integer"}
|
|
51
|
+
if isinstance(field, models.UUIDField):
|
|
52
|
+
return {"type": "string", "format": "uuid"}
|
|
53
|
+
return {"type": "string"}
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def field_schema(form_field) -> dict:
|
|
57
|
+
"""JSON Schema for one form field."""
|
|
58
|
+
f = form_field
|
|
59
|
+
if isinstance(f, forms.FileField):
|
|
60
|
+
filename, content = UPLOAD_KEYS
|
|
61
|
+
schema = {
|
|
62
|
+
"type": "object",
|
|
63
|
+
"properties": {
|
|
64
|
+
filename: {"type": "string", "minLength": 1},
|
|
65
|
+
content: {"type": "string", "contentEncoding": "base64"},
|
|
66
|
+
},
|
|
67
|
+
"required": list(UPLOAD_KEYS),
|
|
68
|
+
"additionalProperties": False,
|
|
69
|
+
"description": "Upload: the file name and the content in base64. Leave the field out to keep the file.",
|
|
70
|
+
}
|
|
71
|
+
elif isinstance(f, forms.ModelMultipleChoiceField):
|
|
72
|
+
model = f.queryset.model
|
|
73
|
+
schema = {"type": "array", "items": _pk_schema(model, f.to_field_name), "uniqueItems": True}
|
|
74
|
+
schema["x-related-model"] = model._meta.label_lower
|
|
75
|
+
elif isinstance(f, forms.ModelChoiceField):
|
|
76
|
+
model = f.queryset.model
|
|
77
|
+
schema = {**_pk_schema(model, f.to_field_name), "x-related-model": model._meta.label_lower}
|
|
78
|
+
elif isinstance(f, forms.MultipleChoiceField):
|
|
79
|
+
schema = {"type": "array", "items": {"enum": _choice_values(f)}, "uniqueItems": True}
|
|
80
|
+
elif isinstance(f, forms.ChoiceField):
|
|
81
|
+
schema = {"enum": _choice_values(f)}
|
|
82
|
+
elif isinstance(f, forms.NullBooleanField):
|
|
83
|
+
schema = {"type": ["boolean", "null"]}
|
|
84
|
+
elif isinstance(f, forms.BooleanField):
|
|
85
|
+
schema = {"type": "boolean"}
|
|
86
|
+
elif isinstance(f, forms.DecimalField):
|
|
87
|
+
# strings keep precision; plain JSON numbers are accepted too
|
|
88
|
+
schema = {"type": ["string", "number"], "pattern": DECIMAL_PATTERN}
|
|
89
|
+
if f.max_digits is not None and f.decimal_places is not None:
|
|
90
|
+
schema["description"] = f"Decimal: max {f.max_digits} digits, {f.decimal_places} decimal places."
|
|
91
|
+
elif isinstance(f, forms.FloatField):
|
|
92
|
+
schema = {"type": "number"}
|
|
93
|
+
elif isinstance(f, forms.IntegerField):
|
|
94
|
+
schema = {"type": "integer"}
|
|
95
|
+
if f.min_value is not None:
|
|
96
|
+
schema["minimum"] = f.min_value
|
|
97
|
+
if f.max_value is not None:
|
|
98
|
+
schema["maximum"] = f.max_value
|
|
99
|
+
elif isinstance(f, (forms.SplitDateTimeField, forms.DateTimeField)):
|
|
100
|
+
schema = {"type": "string", "format": "date-time"}
|
|
101
|
+
elif isinstance(f, forms.DateField):
|
|
102
|
+
schema = {"type": "string", "format": "date"}
|
|
103
|
+
elif isinstance(f, forms.TimeField):
|
|
104
|
+
schema = {"type": "string", "format": "time"}
|
|
105
|
+
elif isinstance(f, forms.DurationField):
|
|
106
|
+
schema = {"type": "string", "description": "Duration, e.g. '1 02:03:04' or ISO 8601 'P1DT2H'."}
|
|
107
|
+
elif isinstance(f, forms.UUIDField):
|
|
108
|
+
schema = {"type": "string", "format": "uuid"}
|
|
109
|
+
elif isinstance(f, forms.JSONField):
|
|
110
|
+
schema = {}
|
|
111
|
+
elif isinstance(f, forms.EmailField):
|
|
112
|
+
schema = {"type": "string", "format": "email"}
|
|
113
|
+
elif isinstance(f, forms.URLField):
|
|
114
|
+
schema = {"type": "string", "format": "uri"}
|
|
115
|
+
else:
|
|
116
|
+
schema = {"type": "string"}
|
|
117
|
+
if getattr(f, "max_length", None):
|
|
118
|
+
schema["maxLength"] = f.max_length
|
|
119
|
+
if getattr(f, "min_length", None):
|
|
120
|
+
schema["minLength"] = f.min_length
|
|
121
|
+
|
|
122
|
+
if f.label:
|
|
123
|
+
schema["title"] = str(f.label)
|
|
124
|
+
help_text = strip_tags(str(f.help_text or "")).replace(str(_M2M_WIDGET_HINT), "").strip()
|
|
125
|
+
if help_text:
|
|
126
|
+
schema["description"] = f"{schema['description']} {help_text}" if "description" in schema else help_text
|
|
127
|
+
if not f.required and not isinstance(f, (forms.BooleanField, forms.JSONField)) and schema.get("type") != "array":
|
|
128
|
+
schema = _nullable(schema)
|
|
129
|
+
return schema
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def _choice_values(f) -> list:
|
|
133
|
+
out = []
|
|
134
|
+
for value, label in f.choices:
|
|
135
|
+
if isinstance(label, (list, tuple)): # optgroup
|
|
136
|
+
out.extend(encode_value(v) for v, _ in label if v != "")
|
|
137
|
+
elif value != "":
|
|
138
|
+
out.append(encode_value(value))
|
|
139
|
+
return out
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
def _has_value(value) -> bool:
|
|
143
|
+
return value not in (None, "", [], ())
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
def form_object_schema(form_class, *, required: bool, exclude=()) -> dict:
|
|
147
|
+
"""Object schema for a form class. With ``required``, a form-required field is only required
|
|
148
|
+
in the payload when the add form has no initial value for it (the API fills those in)."""
|
|
149
|
+
initial = form_initial(form_class, None) if required else {}
|
|
150
|
+
properties, required_names = {}, []
|
|
151
|
+
for name, f in form_class.base_fields.items():
|
|
152
|
+
if name in exclude:
|
|
153
|
+
continue
|
|
154
|
+
schema = field_schema(f)
|
|
155
|
+
if required and _has_value(initial.get(name)):
|
|
156
|
+
default = encode_value(initial[name])
|
|
157
|
+
if isinstance(default, (str, int, float, bool, list)) or default is None:
|
|
158
|
+
schema["default"] = default
|
|
159
|
+
properties[name] = schema
|
|
160
|
+
if required and f.required and not _has_value(initial.get(name)):
|
|
161
|
+
required_names.append(name)
|
|
162
|
+
out = {"type": "object", "properties": properties, "additionalProperties": False}
|
|
163
|
+
if required_names:
|
|
164
|
+
out["required"] = required_names
|
|
165
|
+
return out
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
def _inline_schemas(model_admin, request, obj, *, change: bool, row_id: str) -> dict:
|
|
169
|
+
out = {}
|
|
170
|
+
for prefix, FormSet, inline in inline_prefixes(model_admin, request, obj, change):
|
|
171
|
+
fk = getattr(FormSet, "fk", None)
|
|
172
|
+
exclude = {fk.name} if fk is not None else set()
|
|
173
|
+
row = form_object_schema(FormSet.form, required=not change, exclude=exclude)
|
|
174
|
+
opts = FormSet.model._meta
|
|
175
|
+
description = f"Rows of {opts.verbose_name_plural}."
|
|
176
|
+
if change:
|
|
177
|
+
row["properties"] = {
|
|
178
|
+
row_id: {**_pk_schema(FormSet.model), "description": "Existing row to update; omit for a new row."},
|
|
179
|
+
ROW_DELETE_KEY: {"type": "boolean", "description": f"Delete the existing row given by {row_id}."},
|
|
180
|
+
**row["properties"],
|
|
181
|
+
}
|
|
182
|
+
initial = form_initial(FormSet.form, None)
|
|
183
|
+
required = [
|
|
184
|
+
n
|
|
185
|
+
for n, f in FormSet.form.base_fields.items()
|
|
186
|
+
if f.required and n not in exclude and not _has_value(initial.get(n))
|
|
187
|
+
]
|
|
188
|
+
description += " Rows not mentioned are kept unchanged."
|
|
189
|
+
if required:
|
|
190
|
+
description += f" New rows (without {row_id}) need: {', '.join(required)}."
|
|
191
|
+
schema = {"type": "array", "items": row, "description": description}
|
|
192
|
+
if not change and FormSet.max_num is not None:
|
|
193
|
+
schema["maxItems"] = FormSet.max_num
|
|
194
|
+
if not change and FormSet.min_num:
|
|
195
|
+
schema["minItems"] = FormSet.min_num
|
|
196
|
+
schema["x-related-model"] = opts.label_lower
|
|
197
|
+
out[prefix] = schema
|
|
198
|
+
return out
|
|
199
|
+
|
|
200
|
+
|
|
201
|
+
def payload_schema(model_admin, request, obj=None, *, change: bool, row_id: str = "pk") -> dict:
|
|
202
|
+
"""Schema of the JSON body for create (``change=False``) or update (``change=True``)."""
|
|
203
|
+
form_class = model_admin.get_form(request, obj, change=change)
|
|
204
|
+
schema = {"$schema": SCHEMA_DIALECT, **form_object_schema(form_class, required=not change)}
|
|
205
|
+
inlines = _inline_schemas(model_admin, request, obj, change=change, row_id=row_id)
|
|
206
|
+
if inlines:
|
|
207
|
+
schema["properties"][INLINES_KEY] = {
|
|
208
|
+
"type": "object",
|
|
209
|
+
"properties": inlines,
|
|
210
|
+
"additionalProperties": False,
|
|
211
|
+
"description": "Inline rows, keyed by inline prefix.",
|
|
212
|
+
}
|
|
213
|
+
return schema
|
|
214
|
+
|
|
215
|
+
|
|
216
|
+
def input_schemas(model_admin, request, obj=None, *, row_id: str = "pk") -> dict:
|
|
217
|
+
"""``{"create": schema | None, "update": schema | None}`` for what ``request.user`` may do."""
|
|
218
|
+
return {
|
|
219
|
+
"create": payload_schema(model_admin, request, None, change=False)
|
|
220
|
+
if obj is None and model_admin.has_add_permission(request)
|
|
221
|
+
else None,
|
|
222
|
+
"update": payload_schema(model_admin, request, obj, change=True, row_id=row_id)
|
|
223
|
+
if model_admin.has_change_permission(request, obj)
|
|
224
|
+
else None,
|
|
225
|
+
}
|
|
File without changes
|
|
File without changes
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import datetime
|
|
2
|
+
|
|
3
|
+
from django.contrib.auth import get_user_model
|
|
4
|
+
from django.core.exceptions import ValidationError
|
|
5
|
+
from django.core.management.base import BaseCommand, CommandError
|
|
6
|
+
from django.utils import timezone
|
|
7
|
+
|
|
8
|
+
from admin_api_mcp.auth import get_token_model
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class Command(BaseCommand):
|
|
12
|
+
help = "Create an API token for a user and print it (shown only once)."
|
|
13
|
+
|
|
14
|
+
def add_arguments(self, parser):
|
|
15
|
+
parser.add_argument("username")
|
|
16
|
+
parser.add_argument("--name", default="cli")
|
|
17
|
+
parser.add_argument("--kind", default="pat", choices=["pat", "mcp", "service"])
|
|
18
|
+
parser.add_argument("--expires-days", type=int, default=None)
|
|
19
|
+
parser.add_argument(
|
|
20
|
+
"--scope",
|
|
21
|
+
action="append",
|
|
22
|
+
default=[],
|
|
23
|
+
dest="scopes",
|
|
24
|
+
help="Narrow the token, e.g. --scope store.sales:view --scope 'cash.*:*'. Repeatable.",
|
|
25
|
+
)
|
|
26
|
+
|
|
27
|
+
def handle(self, username, name, kind, expires_days, scopes, **options):
|
|
28
|
+
User = get_user_model()
|
|
29
|
+
try:
|
|
30
|
+
user = User.objects.get(**{User.USERNAME_FIELD: username})
|
|
31
|
+
except User.DoesNotExist as exc:
|
|
32
|
+
raise CommandError(f"No user {username!r}.") from exc
|
|
33
|
+
expires_at = timezone.now() + datetime.timedelta(days=expires_days) if expires_days else None
|
|
34
|
+
try:
|
|
35
|
+
_token, raw = get_token_model().objects.create_token(
|
|
36
|
+
user, name, expires_at=expires_at, kind=kind, scopes=scopes
|
|
37
|
+
)
|
|
38
|
+
except ValidationError as exc:
|
|
39
|
+
raise CommandError("; ".join(exc.messages)) from exc
|
|
40
|
+
self.stdout.write(raw)
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
"""Serve an AdminMcpSite over stdio, for local MCP clients (Claude Code, Claude Desktop, ...).
|
|
2
|
+
|
|
3
|
+
claude mcp add erp -e ADMIN_API_TOKEN=aapi_... -- python manage.py mcp_serve
|
|
4
|
+
|
|
5
|
+
Off when ``ADMIN_API_MCP_ENABLED = False``. Logs go to stderr; stdout carries the protocol.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
import os
|
|
9
|
+
from importlib import import_module
|
|
10
|
+
|
|
11
|
+
from django.conf import settings
|
|
12
|
+
from django.contrib.auth import get_user_model
|
|
13
|
+
from django.core.management.base import BaseCommand, CommandError
|
|
14
|
+
from django.utils.module_loading import import_string
|
|
15
|
+
|
|
16
|
+
TOKEN_ENV = "ADMIN_API_TOKEN"
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class Command(BaseCommand):
|
|
20
|
+
help = "Serve the admin as an MCP server over stdio."
|
|
21
|
+
requires_system_checks = [] # checks print to stdout, which belongs to the protocol
|
|
22
|
+
|
|
23
|
+
def add_arguments(self, parser):
|
|
24
|
+
parser.add_argument(
|
|
25
|
+
"--token",
|
|
26
|
+
help=f"API token to act as (default: ${TOKEN_ENV}; the env var keeps it out of the process list).",
|
|
27
|
+
)
|
|
28
|
+
parser.add_argument("--user", help="Act as this user without a token. Only allowed with DEBUG=True.")
|
|
29
|
+
parser.add_argument(
|
|
30
|
+
"--site",
|
|
31
|
+
help="Dotted path to the AdminMcpSite instance. Default: the only one defined in your URLconf.",
|
|
32
|
+
)
|
|
33
|
+
|
|
34
|
+
def handle(self, *args, token=None, user=None, site=None, **options):
|
|
35
|
+
from admin_api_mcp.auth import get_token_model
|
|
36
|
+
from admin_api_mcp.mcp.sites import mcp_enabled
|
|
37
|
+
from admin_api_mcp.mcp.stdio import StdioRequestFactory, serve
|
|
38
|
+
|
|
39
|
+
if not mcp_enabled():
|
|
40
|
+
raise CommandError("MCP is disabled (ADMIN_API_MCP_ENABLED = False).")
|
|
41
|
+
mcp_site = self.get_site(site)
|
|
42
|
+
raw = token or os.environ.get(TOKEN_ENV)
|
|
43
|
+
if raw and user:
|
|
44
|
+
raise CommandError("Use either a token or --user, not both.")
|
|
45
|
+
if raw:
|
|
46
|
+
api_token = get_token_model().objects.get_for_raw(raw)
|
|
47
|
+
if api_token is None or not api_token.user.is_active:
|
|
48
|
+
raise CommandError("Invalid, revoked or expired token.")
|
|
49
|
+
factory = StdioRequestFactory(mcp_site, raw_token=raw)
|
|
50
|
+
who = f"{api_token.user} (token {api_token.prefix})"
|
|
51
|
+
elif user:
|
|
52
|
+
if not settings.DEBUG:
|
|
53
|
+
raise CommandError("--user is only allowed with DEBUG=True. Use an API token.")
|
|
54
|
+
User = get_user_model()
|
|
55
|
+
try:
|
|
56
|
+
account = User.objects.get(**{User.USERNAME_FIELD: user})
|
|
57
|
+
except User.DoesNotExist as exc:
|
|
58
|
+
raise CommandError(f"No user {user!r}.") from exc
|
|
59
|
+
factory = StdioRequestFactory(mcp_site, user=account)
|
|
60
|
+
who = f"{account} (no token, DEBUG)"
|
|
61
|
+
else:
|
|
62
|
+
raise CommandError(f"Give --token, set ${TOKEN_ENV}, or (DEBUG only) --user.")
|
|
63
|
+
|
|
64
|
+
self.stderr.write(f"admin_api_mcp MCP server '{mcp_site.server_name}' on stdio as {who}")
|
|
65
|
+
serve(mcp_site, factory)
|
|
66
|
+
|
|
67
|
+
def get_site(self, dotted):
|
|
68
|
+
from admin_api_mcp.mcp import AdminMcpSite
|
|
69
|
+
from admin_api_mcp.mcp.sites import all_mcp_sites
|
|
70
|
+
|
|
71
|
+
if dotted:
|
|
72
|
+
try:
|
|
73
|
+
site = import_string(dotted)
|
|
74
|
+
except ImportError as exc:
|
|
75
|
+
raise CommandError(f"Cannot import {dotted!r}: {exc}") from exc
|
|
76
|
+
if not isinstance(site, AdminMcpSite):
|
|
77
|
+
raise CommandError(f"{dotted!r} is not an AdminMcpSite.")
|
|
78
|
+
return site
|
|
79
|
+
import_module(settings.ROOT_URLCONF) # sites are usually created in urls.py
|
|
80
|
+
sites = all_mcp_sites()
|
|
81
|
+
if len(sites) == 1:
|
|
82
|
+
return sites[0]
|
|
83
|
+
if not sites:
|
|
84
|
+
raise CommandError("No AdminMcpSite found. Create one (see admin_api_mcp.mcp) or pass --site.")
|
|
85
|
+
names = ", ".join(sorted(s.name for s in sites))
|
|
86
|
+
raise CommandError(f"Several AdminMcpSites ({names}); pick one with --site dotted.path.")
|
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
"""Copy an install's data from the labels of 0.1.0a3 and earlier (``admin_api``, ``admin_api_search``)
|
|
2
|
+
to ``admin_api_mcp`` and ``admin_api_mcp_search``. Steps and order: CHANGELOG, 0.1.0.
|
|
3
|
+
|
|
4
|
+
python manage.py migrate_from_admin_api --dry-run
|
|
5
|
+
python manage.py migrate_from_admin_api
|
|
6
|
+
python manage.py migrate
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from django.apps import apps
|
|
10
|
+
from django.core.management.base import BaseCommand
|
|
11
|
+
from django.core.management.color import no_style
|
|
12
|
+
from django.db import DEFAULT_DB_ALIAS, connections, transaction
|
|
13
|
+
from django.db.migrations.executor import MigrationExecutor
|
|
14
|
+
from django.db.migrations.recorder import MigrationRecorder
|
|
15
|
+
|
|
16
|
+
LABELS = {"admin_api_mcp": "admin_api", "admin_api_mcp_search": "admin_api_search"} # new label: old label
|
|
17
|
+
DERIVED = {"admin_api_mcp_search"} # the search index: rebuilt, not copied (post_migrate rewrites its model rows)
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class Command(BaseCommand):
|
|
21
|
+
help = (
|
|
22
|
+
"Copy the tables, migration history, content types, permissions and admin log entries of the old "
|
|
23
|
+
"admin_api labels to admin_api_mcp. Idempotent; old data stays in place. Run it before migrate."
|
|
24
|
+
)
|
|
25
|
+
|
|
26
|
+
def add_arguments(self, parser):
|
|
27
|
+
parser.add_argument("--dry-run", action="store_true", help="Print what would be copied and write nothing.")
|
|
28
|
+
parser.add_argument("--database", default=DEFAULT_DB_ALIAS)
|
|
29
|
+
|
|
30
|
+
def handle(self, dry_run, database, **options):
|
|
31
|
+
self.dry_run = dry_run
|
|
32
|
+
self.connection = connections[database]
|
|
33
|
+
self.using = database
|
|
34
|
+
recorder = MigrationRecorder(self.connection)
|
|
35
|
+
for new_label, old_label in LABELS.items():
|
|
36
|
+
applied = set()
|
|
37
|
+
if recorder.has_table():
|
|
38
|
+
applied = set(recorder.migration_qs.filter(app=old_label).values_list("name", flat=True))
|
|
39
|
+
if new_label not in apps.app_configs:
|
|
40
|
+
if applied:
|
|
41
|
+
self.stdout.write(f"{old_label}: skipped, {new_label} is not in INSTALLED_APPS.")
|
|
42
|
+
continue
|
|
43
|
+
self.migrate_schema(new_label, applied)
|
|
44
|
+
if new_label not in DERIVED:
|
|
45
|
+
self.copy_rows(new_label, old_label)
|
|
46
|
+
elif applied:
|
|
47
|
+
self.stdout.write(f"{old_label}: rows not copied, run `manage.py search_index ensure` after migrate.")
|
|
48
|
+
self.copy_content_types(new_label, old_label)
|
|
49
|
+
if dry_run:
|
|
50
|
+
self.stdout.write("Dry run: nothing was written.")
|
|
51
|
+
else:
|
|
52
|
+
self.stdout.write("Done. The old tables and rows are left in place. Next: manage.py migrate.")
|
|
53
|
+
|
|
54
|
+
def say(self, text):
|
|
55
|
+
self.stdout.write(("would " if self.dry_run else "") + text)
|
|
56
|
+
|
|
57
|
+
def migrate_schema(self, new_label, applied):
|
|
58
|
+
"""Apply the new app's migrations up to the last one the old app had applied."""
|
|
59
|
+
executor = MigrationExecutor(self.connection)
|
|
60
|
+
names = sorted(name for name in applied if (new_label, name) in executor.loader.graph.nodes)
|
|
61
|
+
if not names or (new_label, names[-1]) in executor.loader.applied_migrations:
|
|
62
|
+
return
|
|
63
|
+
target = [(new_label, names[-1])]
|
|
64
|
+
plan = executor.migration_plan(target)
|
|
65
|
+
self.say(f"migrate {new_label} to {names[-1]}: {', '.join(m.name for m, _backwards in plan)}")
|
|
66
|
+
if not self.dry_run:
|
|
67
|
+
executor.migrate(target, plan=plan)
|
|
68
|
+
|
|
69
|
+
def copy_rows(self, new_label, old_label):
|
|
70
|
+
"""Copy each old table's rows, primary keys included, that the new table does not have yet."""
|
|
71
|
+
introspection, quote = self.connection.introspection, self.connection.ops.quote_name
|
|
72
|
+
with self.connection.cursor() as cursor:
|
|
73
|
+
tables = set(introspection.table_names(cursor))
|
|
74
|
+
for model in apps.get_app_config(new_label).get_models():
|
|
75
|
+
new_table = model._meta.db_table
|
|
76
|
+
old_table = old_label + new_table.removeprefix(new_label)
|
|
77
|
+
if old_table not in tables:
|
|
78
|
+
continue
|
|
79
|
+
if new_table not in tables and not self.dry_run:
|
|
80
|
+
self.stdout.write(f"skipped {old_table}: no {new_table} table, run migrate first.")
|
|
81
|
+
continue
|
|
82
|
+
with self.connection.cursor() as cursor:
|
|
83
|
+
old_columns = {c.name for c in introspection.get_table_description(cursor, old_table)}
|
|
84
|
+
columns = ", ".join(quote(f.column) for f in model._meta.local_concrete_fields if f.column in old_columns)
|
|
85
|
+
pk = quote(model._meta.pk.column)
|
|
86
|
+
source = f"FROM {quote(old_table)}"
|
|
87
|
+
if new_table in tables:
|
|
88
|
+
source += f" WHERE {pk} NOT IN (SELECT {pk} FROM {quote(new_table)})"
|
|
89
|
+
with transaction.atomic(using=self.using), self.connection.cursor() as cursor:
|
|
90
|
+
cursor.execute(f"SELECT COUNT(*) {source}")
|
|
91
|
+
(count,) = cursor.fetchone()
|
|
92
|
+
self.say(f"copy {count} rows {old_table} -> {new_table}")
|
|
93
|
+
if count and not self.dry_run:
|
|
94
|
+
cursor.execute(f"INSERT INTO {quote(new_table)} ({columns}) SELECT {columns} {source}")
|
|
95
|
+
for sql in self.connection.ops.sequence_reset_sql(no_style(), [model]):
|
|
96
|
+
cursor.execute(sql)
|
|
97
|
+
|
|
98
|
+
def copy_content_types(self, new_label, old_label):
|
|
99
|
+
if not apps.is_installed("django.contrib.contenttypes"):
|
|
100
|
+
return
|
|
101
|
+
from django.contrib.contenttypes.models import ContentType
|
|
102
|
+
|
|
103
|
+
content_types = ContentType.objects.db_manager(self.using)
|
|
104
|
+
with transaction.atomic(using=self.using):
|
|
105
|
+
for old in content_types.filter(app_label=old_label).order_by("model"):
|
|
106
|
+
new = content_types.filter(app_label=new_label, model=old.model).first()
|
|
107
|
+
if new is None:
|
|
108
|
+
self.say(f"create content type {new_label}.{old.model}")
|
|
109
|
+
if not self.dry_run:
|
|
110
|
+
new = content_types.create(app_label=new_label, model=old.model)
|
|
111
|
+
self.copy_permissions(old, new, new_label)
|
|
112
|
+
self.move_log_entries(old, new, new_label)
|
|
113
|
+
ContentType.objects.clear_cache()
|
|
114
|
+
|
|
115
|
+
def copy_permissions(self, old_ct, new_ct, new_label):
|
|
116
|
+
"""Copy the old content type's permissions and their user and group grants; ``new_ct`` is None
|
|
117
|
+
in a dry run that would create it."""
|
|
118
|
+
if not apps.is_installed("django.contrib.auth"):
|
|
119
|
+
return
|
|
120
|
+
from django.contrib.auth.models import Permission
|
|
121
|
+
|
|
122
|
+
perms = Permission.objects.using(self.using)
|
|
123
|
+
for old in perms.filter(content_type=old_ct).order_by("codename"):
|
|
124
|
+
new = perms.filter(content_type=new_ct, codename=old.codename).first() if new_ct else None
|
|
125
|
+
if new is None:
|
|
126
|
+
self.say(f"create permission {new_label}.{old.codename}")
|
|
127
|
+
if not self.dry_run:
|
|
128
|
+
new = perms.create(content_type=new_ct, codename=old.codename, name=old.name)
|
|
129
|
+
for relation in (getattr(Permission, "user_set", None), getattr(Permission, "group_set", None)):
|
|
130
|
+
if relation is None: # a custom user model without PermissionsMixin
|
|
131
|
+
continue
|
|
132
|
+
holder = relation.field.m2m_field_name() # "user" (or the custom user model's name), "group"
|
|
133
|
+
through = relation.through.objects.using(self.using)
|
|
134
|
+
holders = set(through.filter(permission=old).values_list(f"{holder}_id", flat=True))
|
|
135
|
+
if new is not None:
|
|
136
|
+
holders -= set(through.filter(permission=new).values_list(f"{holder}_id", flat=True))
|
|
137
|
+
if holders:
|
|
138
|
+
self.say(f"grant {new_label}.{old.codename} to {len(holders)} {holder}(s)")
|
|
139
|
+
if not self.dry_run:
|
|
140
|
+
rows = [relation.through(permission=new, **{f"{holder}_id": pk}) for pk in holders]
|
|
141
|
+
through.bulk_create(rows)
|
|
142
|
+
|
|
143
|
+
def move_log_entries(self, old_ct, new_ct, new_label):
|
|
144
|
+
if not apps.is_installed("django.contrib.admin"):
|
|
145
|
+
return
|
|
146
|
+
from django.contrib.admin.models import LogEntry
|
|
147
|
+
|
|
148
|
+
entries = LogEntry.objects.using(self.using).filter(content_type=old_ct)
|
|
149
|
+
count = entries.count()
|
|
150
|
+
if count:
|
|
151
|
+
self.say(f"move {count} admin log entries {old_ct.app_label}.{old_ct.model} -> {new_label}")
|
|
152
|
+
if not self.dry_run:
|
|
153
|
+
entries.update(content_type=new_ct)
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
"""MCP for admin_api_mcp: the tool layer plus the transports (Streamable HTTP view, ``manage.py mcp_serve``).
|
|
2
|
+
Set ``ADMIN_API_MCP_ENABLED = False`` to turn both transports off."""
|
|
3
|
+
|
|
4
|
+
from .sites import AdminMcpSite
|
|
5
|
+
from .tools import ToolResult, ToolSpec
|
|
6
|
+
|
|
7
|
+
__all__ = ["AdminMcpSite", "ToolResult", "ToolSpec"]
|