Metadata-Version: 2.4
Name: django-admin-oauth-mcp
Version: 0.1.0
Summary: An MCP server for Django that reads and changes exactly what the admin allows.
License-Expression: MIT
License-File: LICENSE
Classifier: Framework :: Django
Classifier: Framework :: Django :: 5.2
Classifier: Framework :: Django :: 6.0
Classifier: Framework :: Django :: 6.1
Classifier: Programming Language :: Python :: 3
Requires-Dist: django>=5.2
Requires-Dist: django-oauth-toolkit>=3.4
Requires-Dist: mcp-types>=2.3
Requires-Dist: pydantic>=2.12
Requires-Dist: structlog>=25.4
Requires-Dist: django-guardian>=3.0 ; extra == 'guardian'
Requires-Dist: pillow>=11.0 ; extra == 'images'
Requires-Python: >=3.12
Project-URL: Repository, https://github.com/Tirzono/django-admin-oauth-mcp
Provides-Extra: guardian
Provides-Extra: images
Description-Content-Type: text/markdown

# django-admin-oauth-mcp

An MCP server for Django. It lets Claude, or another MCP client, read and
change exactly what the Django admin lets the person who connected it, and
nothing more.

- `POST /mcp` speaks both eras of the protocol: the 2025 versions with the
  `initialize` handshake, and 2026-07-28. Each request gets one JSON answer,
  and there are no sessions, so any web process can answer any request.
  What a message may hold is checked with `mcp-types`, the official SDK's
  schema package.
- Signing in is OAuth 2.1 through django-oauth-toolkit, with dynamic client
  registration and the RFC 8414 and RFC 9728 documents. Anybody may
  register a client, but a client can only send people back to Claude's
  redirect URIs (or the ones you list) or to their own machine.
- The rules are the admin's own. A model is readable if its admin would
  let the person open its list. Its rows are the admin's `get_queryset`,
  and its fields are the ones its pages show. Adding, changing and deleting
  go through the admin's form, `save_model`, `delete_model` and log
  entries. A new admin needs nothing here.
- The person ticks what a client may do, per admin section (application)
  and kind: `orders.read`, `orders.write`, `orders.delete`.
- Credentials are never read: passwords, OAuth tokens, sessions, and
  whatever you add.

- Rows the admin edits only inside another's page, as an inline, are added,
  changed and deleted through that page: the inline's form and permissions,
  and the parent's page saved with them.
- The admin list's actions run as ticking rows and choosing one would. One
  that asks something first on a page of its own says what it asks, and
  runs once answered. `NO_ACTIONS` keeps some to a person's click.
- Somebody changes what a connection may do at `/o/connections/`, without
  connecting again.

The tools are `list_models`, `describe_model`, `query_records`, `get_record`
and `count_records`. With *Change* ticked somewhere, `describe_form`,
`create_record`, `update_record`, `list_actions`, `run_action`,
`list_object_permissions` and `set_object_permissions` are added (the last
two answer only for an admin with django-guardian's Object permissions page:
install the `[guardian]` extra). With *Delete* ticked somewhere,
`delete_record` is added.

A display method that draws a model's fields (a table of what was sent,
say) says which with `@shows`, so the tools read them as its page shows
them:

```python
from django_admin_oauth_mcp import shows


@shows("data", "before")
@admin.display(description="what changed")
def the_change(self, submission): ...
```

## Installing

```bash
uv add django-admin-oauth-mcp
```

With `[images]` to name pictures sent without an extension by what they are,
through Pillow, and `[guardian]` for the tools that say who may do what with
one record.

## Setting it up

```python
# settings.py
from django_admin_oauth_mcp import oauth2_provider_settings

INSTALLED_APPS = [
    "django.contrib.admin",
    ...
    "oauth2_provider",
    "django_admin_oauth_mcp",  # after oauth2_provider, whose admins it replaces
]

OAUTH2_PROVIDER = oauth2_provider_settings("Shop")

DJANGO_ADMIN_OAUTH_MCP = {
    "NAME": "shop",
    "TITLE": "Shop",
    "INSTRUCTIONS": "Shop is where our orders are kept. ...",
    "SECRET_MODEL_FIELDS": {"customers.customer": ["api_key"]},
    "MAX_UPLOAD_BYTES": 25 * 1024 * 1024,
}

# urls.py: at the root, where clients look for the discovery documents.
urlpatterns = [
    ...,
    path("", include("django_admin_oauth_mcp.urls")),
]
```

`settings.LOGIN_URL` is where somebody signs in before saying yes. Then run
`python manage.py migrate` for django-oauth-toolkit's tables. Schedule
`python manage.py forget_unused_mcp_clients` (or `services.forget_unused()`
from a task queue) every night.

To connect from Claude, go to Settings, Connectors, *Add custom
connector*, and enter `https://<host>/mcp`, with no client ID or secret. In
Claude Code: `claude mcp add --transport http <name> https://<host>/mcp`,
then `/mcp` to sign in.

### `DJANGO_ADMIN_OAUTH_MCP`

Every key is optional.

| Key | Default | What it is |
|---|---|---|
| `NAME` | `"django"` | `serverInfo.name` |
| `TITLE` | `"Django"` | What the pages and the tools call the site ("the Shop admin") |
| `INSTRUCTIONS` | a sentence from `TITLE` | What the model is told the tools are for |
| `VERSION` | `settings.VERSION`, or this package's | `serverInfo.version` |
| `AUTHENTICATE` | none: this package's OAuth tokens | A callable, or its dotted path, given the request to `/mcp` and answering a `Caller(user, scopes)` or `None`, for a site that something in front of it already signs people in to. See below |
| `MAY_CONNECT` | active staff | A callable, or its dotted path, given the user. Only ever narrows: somebody inactive or signed out never connects |
| `ADMIN_SITE` | `django.contrib.admin.site` | The admin whose rules apply |
| `SECRET_APPS`, `SECRET_MODELS`, `SECRET_FIELDS` | none | Credentials besides the built-in ones: applications, `app.model`s, and field names on any model |
| `SECRET_MODEL_FIELDS` | none | `{"app.model": ["field"]}` |
| `NO_ACTIONS` | none | Admin actions never run, as `app.model.action`, besides allauth's address verifying and procrastinate's job actions |
| `MAX_UPLOAD_BYTES` | 10 MB | The biggest file a client may send |
| `REDIRECT_URIS` | Claude's | Exact redirect URIs a client may register, besides http on this machine |
| `ALLOWED_ORIGINS` | `settings.CORS_ALLOWED_ORIGINS` | Origins a browser page may call `/mcp` from, besides the site's own |
| `AUTHORIZE_TEMPLATE`, `REFUSED_TEMPLATE` | plain pages in this package | The page where somebody says yes, and the one for somebody who may not connect |
| `CONNECTIONS_TEMPLATE`, `CONNECTION_TEMPLATE` | plain pages in this package | Somebody's connected clients, and changing what one may do |
| `REGISTER_ADMIN` | `True` | Replace django-oauth-toolkit's admins with one list of connected clients |
| `ADMIN_CLASS` | `django.contrib.admin.ModelAdmin` | What that list is made from, such as `unfold.admin.ModelAdmin` |

The consent page's context has `title`, `sections` (each with `name` and
`ticks`), `kinds`, `every` (a tick per column for every section at once),
`returns_to` and the OAuth `form`. The connection page has the same grid,
and `application` and `error`. Both include
`templates/django_admin_oauth_mcp/_ticks.html`; copy the pages to start your own.

### Behind an identity-aware proxy

A site that should not be reachable from the internet at all can sit behind
a proxy that signs people in itself, such as Cloudflare Access with Managed
OAuth, where Access is the OAuth server an MCP client talks to. Access then
owns the `Authorization` header, so this package's tokens cannot be used.
`AUTHENTICATE` says who a request is from instead: verify what the proxy
sends (for Access, the `Cf-Access-Jwt-Assertion` JWT, against the team's keys
and the application's audience) and answer the person and what they may do.

```python
from django_admin_oauth_mcp import Caller


def from_access(request) -> Caller | None:
    email = verified_access_email(request)  # None unless the JWT checks out
    user = User.objects.filter(email=email).first() if email else None
    return Caller(user=user, scopes=frozenset({"read"})) if user else None
```

The scopes are a token's: `{"read"}` reads every section and changes
nothing, and `{"orders.read", "orders.write"}` reads and changes one. There
is no page to tick them on, so the project decides. Who may connect
(`MAY_CONNECT`) is still asked on every request. Without the OAuth server,
only `path("mcp", django_admin_oauth_mcp.views.mcp)` needs mounting, and only
`/mcp` needs to be reachable through the proxy.

## Developing

```bash
uv sync
uv run poe check   # ruff, mypy and the tests: what CI runs
```

The tests run against a small project in `tests/` (`tests/apps`) and need
Postgres, because reading runs in a read-only transaction with a statement
timeout. They use `localhost:5432` as `postgres`, or `POSTGRES_HOST`,
`POSTGRES_USER` and `POSTGRES_PASSWORD`.

A new protocol version is served by adding it to `HANDSHAKE_VERSIONS` or
`MODERN_VERSIONS` in `protocol.py` once `mcp-types` knows it and the tests
pass for it. Never by default.

## Releasing

Releases are automatic. Every push to `master` runs
[release-it](https://github.com/release-it/release-it) once lint and tests
pass. It reads the conventional commits
since the last tag and picks the next version: `fix:` is a patch, `feat:` a
minor, and a `BREAKING CHANGE:` footer a major. It then writes that version
into `pyproject.toml`, `uv.lock` and `CHANGELOG.md`, tags `v<version>`,
creates the GitHub release, and publishes the wheel to PyPI through trusted
publishing, so no token is stored anywhere. A push that is
only chores or docs releases nothing. Never set the version by hand.

`uv run poe next-version` prints what the next release would be, without
making one.
