django-admin-api-mcp 0.1.0a2__tar.gz

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 (93) hide show
  1. django_admin_api_mcp-0.1.0a2/.github/workflows/ci.yml +59 -0
  2. django_admin_api_mcp-0.1.0a2/.github/workflows/release.yml +41 -0
  3. django_admin_api_mcp-0.1.0a2/.gitignore +10 -0
  4. django_admin_api_mcp-0.1.0a2/CHANGELOG.md +38 -0
  5. django_admin_api_mcp-0.1.0a2/PKG-INFO +274 -0
  6. django_admin_api_mcp-0.1.0a2/README.md +244 -0
  7. django_admin_api_mcp-0.1.0a2/RELEASING.md +35 -0
  8. django_admin_api_mcp-0.1.0a2/admin_api/__init__.py +9 -0
  9. django_admin_api_mcp-0.1.0a2/admin_api/actions.py +115 -0
  10. django_admin_api_mcp-0.1.0a2/admin_api/admin.py +108 -0
  11. django_admin_api_mcp-0.1.0a2/admin_api/apps.py +9 -0
  12. django_admin_api_mcp-0.1.0a2/admin_api/auth.py +62 -0
  13. django_admin_api_mcp-0.1.0a2/admin_api/changelist.py +194 -0
  14. django_admin_api_mcp-0.1.0a2/admin_api/checks.py +35 -0
  15. django_admin_api_mcp-0.1.0a2/admin_api/contrib/__init__.py +1 -0
  16. django_admin_api_mcp-0.1.0a2/admin_api/contrib/subadmin.py +37 -0
  17. django_admin_api_mcp-0.1.0a2/admin_api/custom_views.py +458 -0
  18. django_admin_api_mcp-0.1.0a2/admin_api/decorators.py +26 -0
  19. django_admin_api_mcp-0.1.0a2/admin_api/deletion.py +54 -0
  20. django_admin_api_mcp-0.1.0a2/admin_api/detail.py +127 -0
  21. django_admin_api_mcp-0.1.0a2/admin_api/encoders.py +59 -0
  22. django_admin_api_mcp-0.1.0a2/admin_api/errors.py +44 -0
  23. django_admin_api_mcp-0.1.0a2/admin_api/jsonschema.py +216 -0
  24. django_admin_api_mcp-0.1.0a2/admin_api/management/__init__.py +0 -0
  25. django_admin_api_mcp-0.1.0a2/admin_api/management/commands/__init__.py +0 -0
  26. django_admin_api_mcp-0.1.0a2/admin_api/management/commands/create_api_token.py +40 -0
  27. django_admin_api_mcp-0.1.0a2/admin_api/management/commands/mcp_serve.py +86 -0
  28. django_admin_api_mcp-0.1.0a2/admin_api/mcp/__init__.py +7 -0
  29. django_admin_api_mcp-0.1.0a2/admin_api/mcp/bridge.py +71 -0
  30. django_admin_api_mcp-0.1.0a2/admin_api/mcp/confirm.py +54 -0
  31. django_admin_api_mcp-0.1.0a2/admin_api/mcp/handlers.py +665 -0
  32. django_admin_api_mcp-0.1.0a2/admin_api/mcp/server.py +75 -0
  33. django_admin_api_mcp-0.1.0a2/admin_api/mcp/sites.py +198 -0
  34. django_admin_api_mcp-0.1.0a2/admin_api/mcp/stdio.py +53 -0
  35. django_admin_api_mcp-0.1.0a2/admin_api/mcp/tools.py +84 -0
  36. django_admin_api_mcp-0.1.0a2/admin_api/mcp/views.py +69 -0
  37. django_admin_api_mcp-0.1.0a2/admin_api/middleware.py +18 -0
  38. django_admin_api_mcp-0.1.0a2/admin_api/migrations/0001_initial.py +40 -0
  39. django_admin_api_mcp-0.1.0a2/admin_api/migrations/__init__.py +0 -0
  40. django_admin_api_mcp-0.1.0a2/admin_api/mixins.py +144 -0
  41. django_admin_api_mcp-0.1.0a2/admin_api/models.py +113 -0
  42. django_admin_api_mcp-0.1.0a2/admin_api/nested.py +122 -0
  43. django_admin_api_mcp-0.1.0a2/admin_api/resolver.py +95 -0
  44. django_admin_api_mcp-0.1.0a2/admin_api/scopes.py +121 -0
  45. django_admin_api_mcp-0.1.0a2/admin_api/services.py +423 -0
  46. django_admin_api_mcp-0.1.0a2/admin_api/sites.py +225 -0
  47. django_admin_api_mcp-0.1.0a2/admin_api/views/__init__.py +0 -0
  48. django_admin_api_mcp-0.1.0a2/admin_api/views/changelist.py +50 -0
  49. django_admin_api_mcp-0.1.0a2/admin_api/views/custom.py +31 -0
  50. django_admin_api_mcp-0.1.0a2/admin_api/views/detail.py +39 -0
  51. django_admin_api_mcp-0.1.0a2/admin_api/views/nested.py +70 -0
  52. django_admin_api_mcp-0.1.0a2/admin_api/views/registry.py +15 -0
  53. django_admin_api_mcp-0.1.0a2/admin_api/writes.py +479 -0
  54. django_admin_api_mcp-0.1.0a2/docs/DECISIONS.md +30 -0
  55. django_admin_api_mcp-0.1.0a2/docs/DESIGN.md +905 -0
  56. django_admin_api_mcp-0.1.0a2/docs/connect-claude-code.md +210 -0
  57. django_admin_api_mcp-0.1.0a2/examples/ra_erp_smoke/README.md +17 -0
  58. django_admin_api_mcp-0.1.0a2/examples/ra_erp_smoke/ra_smoke_settings.py +6 -0
  59. django_admin_api_mcp-0.1.0a2/examples/ra_erp_smoke/ra_smoke_tests.py +186 -0
  60. django_admin_api_mcp-0.1.0a2/examples/ra_erp_smoke/ra_smoke_urls.py +9 -0
  61. django_admin_api_mcp-0.1.0a2/noxfile.py +70 -0
  62. django_admin_api_mcp-0.1.0a2/pyproject.toml +63 -0
  63. django_admin_api_mcp-0.1.0a2/tests/__init__.py +0 -0
  64. django_admin_api_mcp-0.1.0a2/tests/conftest.py +53 -0
  65. django_admin_api_mcp-0.1.0a2/tests/settings.py +36 -0
  66. django_admin_api_mcp-0.1.0a2/tests/subadmin_site.py +48 -0
  67. django_admin_api_mcp-0.1.0a2/tests/subadmin_urls.py +8 -0
  68. django_admin_api_mcp-0.1.0a2/tests/test_actions.py +117 -0
  69. django_admin_api_mcp-0.1.0a2/tests/test_changelist.py +214 -0
  70. django_admin_api_mcp-0.1.0a2/tests/test_custom_views.py +486 -0
  71. django_admin_api_mcp-0.1.0a2/tests/test_detail.py +148 -0
  72. django_admin_api_mcp-0.1.0a2/tests/test_jsonschema.py +129 -0
  73. django_admin_api_mcp-0.1.0a2/tests/test_mcp_conformance.py +202 -0
  74. django_admin_api_mcp-0.1.0a2/tests/test_mcp_http.py +167 -0
  75. django_admin_api_mcp-0.1.0a2/tests/test_mcp_stdio.py +145 -0
  76. django_admin_api_mcp-0.1.0a2/tests/test_mcp_tools.py +298 -0
  77. django_admin_api_mcp-0.1.0a2/tests/test_mcp_write_safety.py +243 -0
  78. django_admin_api_mcp-0.1.0a2/tests/test_nested.py +47 -0
  79. django_admin_api_mcp-0.1.0a2/tests/test_resolver.py +107 -0
  80. django_admin_api_mcp-0.1.0a2/tests/test_scopes.py +232 -0
  81. django_admin_api_mcp-0.1.0a2/tests/test_services.py +86 -0
  82. django_admin_api_mcp-0.1.0a2/tests/test_site.py +108 -0
  83. django_admin_api_mcp-0.1.0a2/tests/test_subadmin.py +366 -0
  84. django_admin_api_mcp-0.1.0a2/tests/test_tokens.py +147 -0
  85. django_admin_api_mcp-0.1.0a2/tests/test_writes.py +275 -0
  86. django_admin_api_mcp-0.1.0a2/tests/testapp/__init__.py +0 -0
  87. django_admin_api_mcp-0.1.0a2/tests/testapp/admin.py +222 -0
  88. django_admin_api_mcp-0.1.0a2/tests/testapp/migrations/0001_initial.py +63 -0
  89. django_admin_api_mcp-0.1.0a2/tests/testapp/migrations/__init__.py +0 -0
  90. django_admin_api_mcp-0.1.0a2/tests/testapp/models.py +49 -0
  91. django_admin_api_mcp-0.1.0a2/tests/testapp/totals_admin.py +36 -0
  92. django_admin_api_mcp-0.1.0a2/tests/urls.py +14 -0
  93. django_admin_api_mcp-0.1.0a2/uv.lock +1374 -0
@@ -0,0 +1,59 @@
1
+ name: CI
2
+
3
+ on:
4
+ push:
5
+ branches: [main]
6
+ pull_request:
7
+ workflow_dispatch:
8
+ workflow_call: # reused by release.yml so a tag can only publish what CI passed
9
+
10
+ concurrency:
11
+ group: ci-${{ github.ref }}
12
+ cancel-in-progress: true
13
+
14
+ permissions:
15
+ contents: read
16
+
17
+ env:
18
+ FORCE_COLOR: "1"
19
+
20
+ jobs:
21
+ lint:
22
+ runs-on: ubuntu-latest
23
+ steps:
24
+ - uses: actions/checkout@v5
25
+ - uses: astral-sh/setup-uv@v6
26
+ - run: uvx nox -s lint
27
+
28
+ # The matrix comes from noxfile.py: one job per `tests(...)` session.
29
+ sessions:
30
+ runs-on: ubuntu-latest
31
+ outputs:
32
+ tests: ${{ steps.list.outputs.tests }}
33
+ steps:
34
+ - uses: actions/checkout@v5
35
+ - uses: astral-sh/setup-uv@v6
36
+ - id: list
37
+ run: |
38
+ tests=$(uvx nox -l --json -s tests | jq -c '[.[].session]')
39
+ echo "tests=$tests" >> "$GITHUB_OUTPUT"
40
+ echo "$tests" | jq .
41
+
42
+ tests:
43
+ needs: sessions
44
+ runs-on: ubuntu-latest
45
+ strategy:
46
+ fail-fast: false
47
+ matrix:
48
+ session: ${{ fromJSON(needs.sessions.outputs.tests) }}
49
+ name: ${{ matrix.session }}
50
+ steps:
51
+ - uses: actions/checkout@v5
52
+ - uses: astral-sh/setup-uv@v6
53
+ with:
54
+ enable-cache: true
55
+ cache-dependency-glob: |
56
+ pyproject.toml
57
+ noxfile.py
58
+ # uv downloads the Python each session asks for (3.10 / 3.12 / 3.13).
59
+ - run: uvx nox -s "${{ matrix.session }}"
@@ -0,0 +1,41 @@
1
+ name: Release
2
+
3
+ # Publish to PyPI on version tags (vX.Y.Z, incl. alphas like v0.1.0a1) via trusted
4
+ # publishing: no API token is stored anywhere. One-time setup in RELEASING.md.
5
+
6
+ on:
7
+ push:
8
+ tags: ["v*"]
9
+
10
+ permissions:
11
+ contents: read
12
+
13
+ jobs:
14
+ ci:
15
+ # The full lint + Django x MCP test matrix must pass before anything is published.
16
+ uses: ./.github/workflows/ci.yml
17
+
18
+ check-tag:
19
+ runs-on: ubuntu-latest
20
+ steps:
21
+ - uses: actions/checkout@v5
22
+ - name: Tag must match the pyproject version
23
+ run: |
24
+ tag="${GITHUB_REF_NAME#v}"
25
+ version=$(python3 -c "import tomllib; print(tomllib.load(open('pyproject.toml', 'rb'))['project']['version'])")
26
+ if [ "$tag" != "$version" ]; then
27
+ echo "tag v$tag does not match pyproject version $version"
28
+ exit 1
29
+ fi
30
+
31
+ publish:
32
+ needs: [ci, check-tag]
33
+ runs-on: ubuntu-latest
34
+ environment: pypi
35
+ permissions:
36
+ id-token: write # trusted publishing (OIDC) to PyPI
37
+ steps:
38
+ - uses: actions/checkout@v5
39
+ - uses: astral-sh/setup-uv@v6
40
+ - run: uv build
41
+ - uses: pypa/gh-action-pypi-publish@release/v1
@@ -0,0 +1,10 @@
1
+ .venv/
2
+ __pycache__/
3
+ *.pyc
4
+ *.sqlite3
5
+ .pytest_cache/
6
+ dist/
7
+ build/
8
+ *.egg-info/
9
+ .lavish/
10
+ .nox/
@@ -0,0 +1,38 @@
1
+ # Changelog
2
+
3
+ ## 0.1.0a2 (2026-11-19)
4
+
5
+ - The project is renamed to `django-admin-api-mcp` on PyPI from this release. The import name
6
+ `admin_api` is unchanged.
7
+ - The official `mcp` SDK is a core dependency and the `[mcp]` extra is gone: install with
8
+ `pip install --pre django-admin-api-mcp`.
9
+ - `ADMIN_API_MCP_ENABLED` setting (default `True`): when `False`, the MCP HTTP view answers 404
10
+ `mcp_disabled` and `manage.py mcp_serve` exits with an error.
11
+ - MCP `create_object` / `update_object` (and their dry runs) return the saved document's
12
+ `totals`, declared per admin with `api_totals`. The object is reloaded after the save, so
13
+ values written by signals are included (REST writes get the same reload and a `totals` entry).
14
+ - `AdminMcpSite(require_dry_run=True)` and `mcp_require_dry_run` on an admin: a real write
15
+ (create, update, write views) is refused unless it carries the `confirm_token` returned by a
16
+ matching, valid dry run. New error codes `dry_run_required` and `invalid_confirm_token`.
17
+ - LogEntry messages of MCP creates and updates end in `Via MCP.`.
18
+ - `get_mcp_description(request)` hook on `ApiAdminMixin`: override it to return another attribute
19
+ (e.g. the admin's `description`) as the MCP description. `mcp_description` keeps working.
20
+ - `confirm_token` is a reserved view parameter name, next to `pk` and `dry_run`.
21
+
22
+ ## 0.1.0a1 (published)
23
+
24
+ First alpha. Published as `django-admin-api2` (the `django-admin-api` name on PyPI is taken
25
+ by an unrelated package); the import package is `admin_api`.
26
+
27
+ - REST API from existing `ModelAdmin`s: changelist with admin filters/search/ordering,
28
+ detail, `/schema/`, writes through the admin's own change-form pipeline with inline
29
+ formsets, actions, delete with preview (decisions 8, 10, R4, 11a, 12, 13, R5).
30
+ - `api_` twins and `request.is_api` for API-specific behaviour; mixin-less admins are wrapped
31
+ at runtime (§3, R3.4).
32
+ - Session + personal-access-token auth, tokens narrowed by scopes (15, R6, R7, §9.3).
33
+ - MCP server: Streamable HTTP and stdio transports, generic tools with
34
+ `dry_run`, JSON Schema write payloads, official-client conformance tests (§14).
35
+ - Nested admins via django-subadmin; custom admin views via `@admin_api.view` (§15, §16).
36
+
37
+ Decision ids and section numbers refer to [docs/DESIGN.md](docs/DESIGN.md); the index with
38
+ the enforcing tests is [docs/DECISIONS.md](docs/DECISIONS.md).
@@ -0,0 +1,274 @@
1
+ Metadata-Version: 2.5
2
+ Name: django-admin-api-mcp
3
+ Version: 0.1.0a2
4
+ Summary: MCP-ready Django admin: a REST API and an MCP server for AI agents from your existing ModelAdmins, driven by api_ twins.
5
+ Project-URL: Homepage, https://github.com/RamezIssac/django-admin-api
6
+ Project-URL: Documentation, https://github.com/RamezIssac/django-admin-api#readme
7
+ Project-URL: Repository, https://github.com/RamezIssac/django-admin-api
8
+ Project-URL: Issues, https://github.com/RamezIssac/django-admin-api/issues
9
+ Author: Ramez Ashraf
10
+ License-Expression: MIT
11
+ Keywords: admin,ai-agents,api,django,mcp,model-context-protocol,rest
12
+ Classifier: Development Status :: 3 - Alpha
13
+ Classifier: Framework :: Django
14
+ Classifier: Framework :: Django :: 4.2
15
+ Classifier: Framework :: Django :: 5.2
16
+ Classifier: Framework :: Django :: 6.1
17
+ Classifier: Intended Audience :: Developers
18
+ Classifier: Operating System :: OS Independent
19
+ Classifier: Programming Language :: Python :: 3
20
+ Classifier: Programming Language :: Python :: 3 :: Only
21
+ Classifier: Programming Language :: Python :: 3.10
22
+ Classifier: Programming Language :: Python :: 3.11
23
+ Classifier: Programming Language :: Python :: 3.12
24
+ Classifier: Programming Language :: Python :: 3.13
25
+ Classifier: Topic :: Software Development :: Libraries
26
+ Requires-Python: >=3.10
27
+ Requires-Dist: django>=4.2
28
+ Requires-Dist: mcp<3,>=2.3
29
+ Description-Content-Type: text/markdown
30
+
31
+ # django-admin-api-mcp (import name: `admin_api`)
32
+
33
+ [![CI](https://github.com/RamezIssac/django-admin-api/actions/workflows/ci.yml/badge.svg)](https://github.com/RamezIssac/django-admin-api/actions/workflows/ci.yml)
34
+
35
+ **[Design doc](docs/DESIGN.md)** · **[Decision index](docs/DECISIONS.md)** · [Changelog](CHANGELOG.md) · [Releasing](RELEASING.md)
36
+
37
+ **MCP-ready out of the box.** Turn your existing Django `ModelAdmin`s into a REST API **and** an
38
+ [MCP](https://modelcontextprotocol.io) server for AI agents (Claude Code, Claude Desktop, any MCP
39
+ client) — with the admin's own permissions, validation and audit trail.
40
+
41
+ ```bash
42
+ pip install --pre django-admin-api-mcp # the REST API and the MCP server (pulls in the official MCP SDK)
43
+ ```
44
+
45
+ > **Why "-mcp"?** The `django-admin-api` name on PyPI is taken by an unrelated, inactive package, so
46
+ > this project is published as **django-admin-api-mcp**. The import package is still `admin_api`
47
+ > (`INSTALLED_APPS += ["admin_api"]`, `import admin_api`). Do not install it alongside the old
48
+ > `django-admin-api` package — the two share the `admin_api` import name.
49
+
50
+ A thin layer that makes Django `ModelAdmin` API-ready and MCP-ready.
51
+
52
+ ## Design-first, agent-built
53
+
54
+ The primary artifact of this project is the design: [docs/DESIGN.md](docs/DESIGN.md) records
55
+ the decisions (numbered, with the rejected options), and
56
+ [docs/DECISIONS.md](docs/DECISIONS.md) indexes each one next to the tests that enforce it.
57
+ Most of the implementation was written by AI coding agents — which is exactly why the design
58
+ is the asset: generated code is only as good as the decisions it is steered by and reviewed
59
+ against. The test suite is the executable form of those decisions (HTML-admin parity, query
60
+ budgets, permission matrices, MCP conformance), and releases are where it all comes under
61
+ control ([RELEASING.md](RELEASING.md)).
62
+
63
+ The same `ModelAdmin` drives the HTML admin and the JSON API. Where the API should behave
64
+ differently, write an `api_` twin:
65
+
66
+ ```python
67
+ class SalesAdmin(admin_api.ApiAdminMixin, admin.ModelAdmin):
68
+ list_display = ["slug", "client", "get_stats_icon", "value"]
69
+ api_list_display = ["slug", "client", "value"] # attribute twin
70
+
71
+ def get_api_queryset(self, request): # method twin
72
+ return super().get_queryset(request).select_related("client")
73
+ ```
74
+
75
+ Lookup order: `get_api_X(request)` → `api_X` → `get_X(request)` → `X`. Anything else can
76
+ branch on `request.is_api`.
77
+
78
+ Writes run the admin's own pipeline. The JSON is translated into the change form's POST data
79
+ and passed to `process_changeform(request, obj, change)` when the admin defines it (that's
80
+ how erp_framework's `whole_changeform_validation`/`pre_save`/`post_save` hooks run), or to a
81
+ default that mirrors `ModelAdmin._changeform_view`. LogEntry, reversion (`VersionAdmin`) and
82
+ `message_user` work as in the HTML admin.
83
+
84
+ ```python
85
+ # settings.py
86
+ INSTALLED_APPS += ["admin_api"]
87
+ MIDDLEWARE += ["admin_api.middleware.ApiRequestMiddleware"]
88
+
89
+ # urls.py
90
+ api_site = AdminApiSite(admin_site=admin.site)
91
+ urlpatterns += [path("api/", api_site.urls)] # → /api/v1/
92
+ ```
93
+
94
+ Status: **alpha** (`0.1.0a2`): REST API (milestones 1–8), MCP add-on (9–15) and custom admin
95
+ views (17–18). Tested on Django 4.2, 5.2 and 6.1.
96
+ The mixin is optional: admins without it are wrapped at runtime for API requests.
97
+
98
+ ### With erp_framework
99
+
100
+ ```python
101
+ # urls.py, after INSTALLED_APPS/MIDDLEWARE as above
102
+ from erp_framework.api import erp_api_site
103
+
104
+ urlpatterns += [path("api/", erp_api_site.urls)]
105
+ ```
106
+
107
+ ERP writes run `EntityAdmin.process_changeform`, the same pipeline as the HTML change form.
108
+ `examples/ra_erp_smoke/` exercises a full create/update/delete of a ra_erp `Sales` with item
109
+ lines.
110
+
111
+ | Endpoint | |
112
+ |---|---|
113
+ | `GET /api/v1/` | apps/models the user may use, with permissions |
114
+ | `GET /api/v1/<app>/<model>/` | changelist: admin filters (`?status__exact=`), search `?q=`, ordering `?o=`, page `?p=`, `_per_page`, `_shape=columnar` |
115
+ | `GET /api/v1/<app>/<model>/schema/` | columns, filters with their params, search, ordering, pagination, actions, `input_schema` (JSON Schema for create/update) |
116
+ | `POST /api/v1/<app>/<model>/` | create, through the admin form + inline formsets |
117
+ | `GET /api/v1/<app>/<model>/<pk>/` | detail: fieldsets (or `api_detail_fields`) + inlines |
118
+ | `PATCH`/`PUT /api/v1/<app>/<model>/<pk>/` | update; `{"inlines": {"items": [{"pk": 1, "quantity": 2}, {"pk": 2, "_delete": true}, {...new}]}}` |
119
+ | `DELETE /api/v1/<app>/<model>/<pk>/` | `delete_model` + LogEntry; 409 when protected |
120
+ | `GET /api/v1/<app>/<model>/<pk>/delete-preview/` | the admin's delete confirmation data as JSON |
121
+ | `POST /api/v1/<app>/<model>/actions/<name>/` | run an admin action on `{"pks": [...]}` or `{"all": true}` (+ filters); `api_<name>` twin for actions that return files/pages |
122
+ | `GET`/`POST /api/v1/<app>/<model>/views/<name>/` | run a custom view (`@admin_api.view`, below) |
123
+ | `GET`/`POST /api/v1/<app>/<model>/<pk>/views/<name>/` | run a custom view on one object |
124
+ Design: [docs/DESIGN.md](docs/DESIGN.md).
125
+
126
+ ## Authentication
127
+
128
+ * **Session**: same login as the admin. CSRF is enforced on unsafe methods.
129
+ * **Personal access tokens**: `Authorization: Bearer aapi_<prefix>_<secret>`. Create them in the
130
+ admin ("API tokens", registered on the wrapped site) or with
131
+ `manage.py create_api_token <username> --name ci`. Only a hash is stored. A token has the
132
+ permissions of its user, optionally **narrowed by scopes**:
133
+ `--scope store.sales:view --scope 'cash.*:*'` (`<app>.<model>:<view|add|change|delete>`, `*`
134
+ allowed). Scopes never grant more than the user has.
135
+
136
+ ## MCP
137
+
138
+ Let an AI agent (Claude Code, Claude Desktop, any MCP client) use the admin, with the same
139
+ permissions, validation, ERP hooks and audit trail as the HTML admin.
140
+
141
+ ```python
142
+ # urls.py
143
+ from admin_api.mcp import AdminMcpSite
144
+
145
+ mcp_site = AdminMcpSite(api_site) # AdminMcpSite(api_site, read_only=True) for reads only
146
+ urlpatterns += [path("mcp/", mcp_site.urls)] # Streamable HTTP
147
+ ```
148
+
149
+ ```bash
150
+ # a token for the agent (scopes recommended)
151
+ python manage.py create_api_token alice --kind mcp --name claude --scope 'store.*:view'
152
+
153
+ # local, stdio
154
+ claude mcp add erp -e ADMIN_API_TOKEN=aapi_… -- python manage.py mcp_serve
155
+ # remote, HTTP
156
+ claude mcp add --transport http erp https://erp.example.com/mcp/ --header "Authorization: Bearer aapi_…"
157
+ ```
158
+
159
+ Set `ADMIN_API_MCP_ENABLED = False` in settings to turn the MCP endpoints off (the HTTP view answers
160
+ 404 `mcp_disabled`, `manage.py mcp_serve` exits with an error). It defaults to `True`.
161
+
162
+ Step by step, with scopes, `.mcp.json` and troubleshooting: [Connect Claude Code](docs/connect-claude-code.md).
163
+
164
+ Tools: `list_models`, `describe_model` (columns, filters, actions, custom views, JSON Schema),
165
+ `list_objects` (admin filters, search, ordering, paging), `get_object`, `create_object` /
166
+ `update_object` (with `dry_run`: the full save pipeline, then rolled back), `delete_object`
167
+ (preview unless `confirm=true`), `run_action`, `run_view` (custom views), plus one tool per view
168
+ published with `mcp_tool=`.
169
+
170
+ On the admin: `mcp_description = "…"` (context for the LLM; a string or a callable of the request),
171
+ `mcp_enabled = False` (hide from MCP only). To reuse another attribute, override
172
+ `get_mcp_description(self, request)` (`ApiAdminMixin`):
173
+ `def get_mcp_description(self, request): return self.description`. In hooks: `request.is_mcp`, and
174
+ `request.is_dry_run` to skip side effects such as
175
+ e-mails during a dry run (or use `transaction.on_commit`, which a dry run discards).
176
+
177
+ ### Safer writes
178
+
179
+ - **Totals.** `api_totals = ["value", "quantity"]` on the admin (field names, admin methods or
180
+ model attributes) adds a `totals` entry to the result of `create_object`, `update_object` and
181
+ their dry runs. The saved document is read back first, so values written by signals are included.
182
+ - **Require a dry run.** `AdminMcpSite(api_site, require_dry_run=True)` makes `create_object`,
183
+ `update_object` and write views refuse a real write unless it passes the `confirm_token` that a
184
+ valid dry run of the same arguments returned (same user, model, pk and data, valid 15 minutes).
185
+ An admin overrides the site with `mcp_require_dry_run = True | False`. `delete_object` keeps its
186
+ `confirm`; `run_action` has no dry run and is not gated.
187
+ - **Audit.** The LogEntry of an MCP create or update reads, for example, `Changed Status. Via MCP.`
188
+
189
+ ## Custom views (custom admin pages)
190
+
191
+ A custom admin page (a statement, a stock balance, "post this invoice") is usually a view added
192
+ with `get_urls()` that computes data and renders a template. Move the computing part into a
193
+ method decorated with `@admin_api.view`. The HTML view keeps calling it, and the REST API and
194
+ MCP expose it with the same permissions:
195
+
196
+ ```python
197
+ class StatementForm(forms.Form):
198
+ date_from = forms.DateField(required=False)
199
+ date_to = forms.DateField(required=False)
200
+
201
+
202
+ class ClientAdmin(admin.ModelAdmin):
203
+ @admin_api.view(detail=True, params=StatementForm, mcp_tool="client_statement")
204
+ def statement(self, request, obj, date_from=None, date_to=None):
205
+ """Account statement of one client between two dates.""" # the description for the LLM
206
+ return {"opening": ..., "lines": [...], "closing": ...} # JSON-able; models/dates/Decimals encoded
207
+
208
+ @admin_api.view(detail=True, permissions=["change"], params={"note": {"type": "string"}})
209
+ def post(self, request, obj, note=""):
210
+ """Post a draft invoice."""
211
+ ...
212
+ self.message_user(request, "Posted.") # returned under "messages"
213
+ return {"status": obj.status}
214
+
215
+ def get_urls(self): # the HTML page, unchanged
216
+ return [path("<pk>/statement/", self.admin_site.admin_view(self.statement_page))] + super().get_urls()
217
+
218
+ def statement_page(self, request, pk):
219
+ obj = self.get_object(request, pk)
220
+ form = StatementForm(request.GET)
221
+ form.is_valid()
222
+ context = {**self.admin_site.each_context(request), **self.statement(request, obj, **form.cleaned_data)}
223
+ return TemplateResponse(request, "admin/client_statement.html", context)
224
+ ```
225
+
226
+ | Option | |
227
+ |---|---|
228
+ | `detail` | `True`: `method(request, obj, **params)`, at `<pk>/views/<name>/`. `False` (default): `method(request, **params)`, at `views/<name>/` |
229
+ | `params` | a `Form` class (validated; `cleaned_data` passed as arguments; JSON Schema generated from it) or a dict of JSON Schema properties (+ `required=[...]`; `format: date / date-time / time` arrive parsed) |
230
+ | `permissions` | like `@admin.action(permissions=...)`: every `has_<perm>_permission` must pass (`view` = view or change). Default `["view"]` |
231
+ | `writes` | default: `True` when `permissions` asks for more than `view`. Write views are POST only, run in a transaction, need a write token scope, are hidden from read-only MCP sites and support MCP `dry_run`. Read views take GET (query string) or POST (JSON body) |
232
+ | `name`, `title`, `description` | default: method name, derived title, docstring |
233
+ | `mcp_tool="name"` | also publish the view as its own MCP tool (top-level admins) |
234
+ | `api_enabled=False` / `mcp_enabled=False` | hide from both / from MCP only |
235
+
236
+ The response is `{"view", "pk" (detail), "result", "messages"}`. Errors use the usual envelope:
237
+ `400 invalid_params` (with `fields`), `ValidationError` → `400 validation_failed`,
238
+ `PermissionDenied` → `403`, a returned `HttpResponse` → `400 view_not_supported` (rolled back).
239
+
240
+ **How an agent finds them.** The MCP server instructions mention custom views; `list_models`
241
+ lists each model's views (name, description, `detail`, `writes`); `describe_model` gives each
242
+ view's `params_schema`; `get_object` names the views of that object; `run_view(model, view, pk?,
243
+ params, dry_run)` runs any of them. Views the agent uses often can also be published as their own
244
+ tool with `mcp_tool=` (typed arguments, listed in `tools/list` only for users who may run them).
245
+ REST clients get the same from `/schema/` (`views`, with `url` and `methods`) and object
246
+ details (`views: {name: url}`). `AdminMcpSite.is_view_exposed(model_admin, spec)` filters views
247
+ site-wide.
248
+
249
+ ## Nested admins (django-subadmin)
250
+
251
+ Admins nested with [django-subadmin](https://github.com/inueni/django-subadmin) work in the REST
252
+ API and in MCP with no configuration. The address follows the admin URL:
253
+
254
+ | | items of sale 7 of client 1 |
255
+ |---|---|
256
+ | HTML admin | `/admin/store/client/1/sales/7/salesitem/` |
257
+ | REST | `/api/v1/store/client/1/sales/7/salesitem/` (+ `schema/`, `actions/<name>/`, `views/<name>/`, `<pk>/`, `<pk>/delete-preview/`, `<pk>/views/<name>/`) |
258
+ | MCP | `model="store.client/sales/salesitem"`, `parents=[1, 7]` |
259
+
260
+ Lists are scoped to the parent, the parent FK is set on create (and is not accepted in payloads),
261
+ and every ancestor must be viewable by the user (and by the token's scopes). The registry /
262
+ `list_models` list nested admins with `nested_under`; object details and `/schema/` /
263
+ `describe_model` link to `children`. `api_enabled = False` / `mcp_enabled = False` on a
264
+ `SubAdmin` hides it and everything nested under it. Other nesting libraries can plug in with a
265
+ `NestedAdapter` (`admin_api.nested`).
266
+
267
+ ## Development
268
+
269
+ ```bash
270
+ uv sync
271
+ uv run pytest # everything; -m "not conformance" skips the live-server/subprocess tests
272
+ uvx nox # lint + matrix: Django 4.2 / 5.2 / 6.1 x mcp 2.3.0 / latest (+ django-subadmin on 5.2 / 6.1)
273
+ uvx nox -l # list sessions; run one with -s "tests(django=6.1, mcp=latest)"
274
+ ```