django-mcp-ucp
by frutik
README.md
# django-mcp-ucp
Serve a Django shop's catalog to AI shopping agents through the
[Universal Commerce Protocol](https://github.com/Universal-Commerce-Protocol/ucp) (UCP) Catalog Search
capability over the [Model Context Protocol](https://modelcontextprotocol.io/specification/) (MCP).
You write one function that searches your catalog and maps products to official UCP JSON. The package does
the rest:
- the `/.well-known/ucp` discovery profile
- the MCP endpoint and its `search_catalog` tool
- capability and version negotiation with the agent's platform
- safe fetching of platform profiles
- request and response validation against the pinned official schemas
- error envelopes and HTTP status codes
- signed pagination cursors
> **Status: 0.1.0.dev0, not released.** Scope is Catalog Search only (`dev.ucp.shopping.catalog.search`),
> for UCP `2026-08-25` over MCP. Catalog Lookup, checkout, carts, orders and payments are out of scope. The
> official example request and response round-trip exactly, and there are tests for C001–C030 except C023
> (timeouts, out of scope). That is evidence for what is tested; **no claim of UCP conformance** is made.
## Contents
- [Requirements](#requirements)
- [Quick start](#quick-start)
- [How it works](#how-it-works)
- [Writing your search backend](#writing-your-search-backend)
- [Configuration reference](#configuration-reference)
- [Platform profiles and security](#platform-profiles-and-security)
- [Authentication](#authentication)
- [Errors and HTTP status codes](#errors-and-http-status-codes)
- [What goes over the wire](#what-goes-over-the-wire)
- [Examples](#examples)
- [Performance](#performance)
- [Development](#development)
- [Design records](#design-records)
- [Limitations](#limitations)
## Requirements
- Python 3.10+, Django 4.2+
- [`mcp`](https://github.com/modelcontextprotocol/python-sdk) `>=2.3,<3`, the official MCP Python SDK.
Only its public low-level `Server` API is used; the package never reimplements MCP.
- `jsonschema` 4.18+
- No database models, migrations, search engine or network access at import time.
The official UCP schemas for `2026-08-25` are bundled. Each file is pinned to commit `87dd4b1` and has its
SHA-256 checked, and none is ever fetched at runtime.
## Quick start
```sh
pip install -e . # not on PyPI yet
```
```python
# settings.py
INSTALLED_APPS = [..., "django_mcp_ucp"] # enables system checks; the package has no models
```
```python
# shop/ucp.py
from django_mcp_ucp.catalog import CatalogSearchToolset, SearchPage
from django_mcp_ucp.protocol.profiles import CachedProfileResolver, HttpProfileResolver
from django_mcp_ucp.server import UCPServer
class Catalog(CatalogSearchToolset):
def _search(self, request, context):
# request: the validated `catalog` argument; request["pagination"]["limit"] is always set
rows = my_search(request.get("query"), request.get("filters", {}), request["pagination"]["limit"])
return SearchPage(products=[to_ucp_product(r) for r in rows], pagination={"has_next_page": False})
commerce = UCPServer(
name="shop",
public_base_url="https://shop.example.com", # https, no trailing slash: advertised to agents
mcp_path="/ucp/mcp",
toolsets=[Catalog()],
profile_resolver=CachedProfileResolver(
HttpProfileResolver("2026-08-25", allowed_hosts={"agent-platform.example"}),
key_prefix="shop",
),
)
```
```python
# urls.py: both paths must be at the site root
from django.urls import include, path
from shop.ucp import commerce
urlpatterns = [path("", include(commerce.urls))] # /.well-known/ucp and /ucp/mcp
```
It runs under WSGI (Gunicorn and similar) and ASGI (Uvicorn, Daphne). For a complete, tested shop, see
[`examples/django_shop`](examples/django_shop).
## How it works
```text
agent ──POST /ucp/mcp──▶ Django view (raw body, auth, HTTP status)
│
▼
mcp SDK low-level Server (JSON-RPC, MCP protocol versions, stateless)
│ tools/call search_catalog
▼
UCPServer
1. meta.ucp-agent.profile valid? else -32001 invalid_profile_url
2. principal may act for that profile? else -32000 Forbidden
3. resolve + validate platform profile else -32001 profile_*
4. same UCP version? else -32001 version_unsupported
5. capability intersection empty → capabilities_incompatible result
│
▼
CatalogSearchToolset
validate `catalog` → your _search() → build response → validate → structuredContent
```
- **One server per endpoint.** A `UCPServer` instance owns one discovery profile, one capability
registry, one MCP server and one Django view. All configuration is passed to the constructor, so
several instances in one project keep separate policies. The only global setting is the UCP version.
- **Fixed at startup.** The registry and the discovery profile are built and validated against the
official business-profile schema when the server is constructed. Nothing changes afterwards.
- **Stateless.** Each HTTP request gets its own MCP session manager, with no session state between
requests. Every request runs in its own context and is isolated from concurrent requests.
## Writing your search backend
Subclass `CatalogSearchToolset` and implement `_search(request, context) -> SearchPage`. It may be sync or
async. Sync hooks run in Django's thread-sensitive executor, so the ORM works.
### `request`
`request` is the `catalog` argument, already validated against the official `search_request` schema.
| Key | Meaning |
|---|---|
| `query` | Free text, optional. |
| `filters` | `categories` (match any), `price` (`min`/`max` in minor units), plus any merchant filters you accept. |
| `context` | Buyer hints: `address_country`, `currency`, `language`, `intent`, ... |
| `pagination` | `limit` is always set: the client's value capped at `max_limit`, or `default_limit` (10). `cursor` appears on later pages. |
The toolset has already rejected requests with neither a non-blank `query` nor non-empty `filters`, as the
spec requires.
### `context`
`context` is an immutable `UCPRequestContext`:
| Field | Meaning |
|---|---|
| `version` | The negotiated UCP version. |
| `capabilities` | The negotiated capabilities relevant to this call. |
| `profile_url` | The platform profile URL the agent claimed. |
| `principal` | What your `authenticate` hook returned, or `None`. |
| `request` | The Django `HttpRequest`. |
### `SearchPage`
```python
SearchPage(
products=[...], # official product.json objects, plain JSON values, in your ranking order
pagination={"has_next_page": True, "cursor": "..."}, # cursor required when has_next_page is true
messages=[...], # optional official messages, e.g. a warning that a filter was ignored
policies=[...], # optional
)
```
- **Order.** Products are returned in your order, never reranked or deduplicated. An empty `products`
list is a normal, successful result.
- **Required product fields.** Every product needs `id`, `title`, `description`, `price_range` and at
least one variant. Each variant needs `id`, `title`, `description` and `price`.
- **Money.** Use integers in ISO 4217 minor units, never floats.
- **Variant order.** The first variant is the featured one, so put the best match for the query and
filters first.
### Rejecting requests
Raise `InvalidSearchRequest("message")` for your own input rules, such as an unsupported filter or a query
that is too short. The client receives JSON-RPC `-32602` with HTTP 400. Never drop an unsupported filter
silently. The price filter is the one exception: if you can't convert it to the presentment currency, the
spec lets you ignore it, provided you return a warning message saying so.
### Pagination cursors
```python
from django_mcp_ucp.catalog import CursorCodec
codec = CursorCodec(namespace="my-shop", max_age=900)
position = codec.decode(request, context) # None on the first page
...
cursor = codec.encode([last_score, last_id], request, context)
```
- **Signing and expiry.** Cursors are signed with Django's `SECRET_KEY` and expire after `max_age`
seconds.
- **Binding.** Each cursor is bound to `query`, `filters`, `context`, the UCP version, the platform
profile, the principal and the namespace. A cursor reused anywhere else is rejected with `-32602`, just
like a tampered one. `limit`, `signals` and `attribution` may change between pages.
- **Not encrypted.** Clients can decode a cursor's position, so never put secrets in it.
- **Stable ordering.** Use keyset positions with a unique tie-breaker, such as `(score, id)` or
OpenSearch `search_after`.
### If your code fails
- **Invalid response.** If your products don't match the official schema, or contain `Decimal`,
`datetime` or `NaN`, the client gets a generic `-32603` "Internal server error" with HTTP 500. The log
records the JSON path that failed, never your data.
- **Unexpected exceptions** are hidden the same way.
## Configuration reference
### `UCPServer(...)`
| Argument | Default | |
|---|---|---|
| `name` | required | Identifies the server in URL names and errors. |
| `public_base_url` | required | `https://host[:port][/prefix]`, no trailing slash. It is advertised to agents and never taken from the `Host` header. |
| `mcp_path` | `"/ucp/mcp"` | The MCP endpoint path. |
| `version` | the `VERSION` setting | UCP version. Pinned schemas must exist for it. |
| `toolsets` | `()` | For example `[MyCatalog()]`. Only the capabilities of these toolsets are advertised. |
| `profile_resolver` | accepts no platform | See [Platform profiles](#platform-profiles-and-security). |
| `authenticate` | `None` (public) | `authenticate(request) -> principal or None` (`None` means 401). |
| `authorize_profile` | required with `authenticate` | `authorize_profile(principal, profile_url) -> bool` (`False` means 403). |
| `discovery_max_age` | `300` | `Cache-Control: public, max-age` for discovery, at least 60. |
`commerce.urls` gives the two URL patterns, `commerce.profile` the generated business profile, and
`commerce.endpoint` the advertised MCP URL.
### `CatalogSearchToolset(...)`
| Argument | Default | |
|---|---|---|
| `version` | the `VERSION` setting | |
| `default_limit` | `10` | Page size when the client gives none. The spec recommends 10. |
| `max_limit` | `50` | Larger requested limits are capped to this. |
| `validate_responses` | `True` | Validates every response against `search_response`. This is about 85% of the protocol overhead. Turn it off only if your tests prove the product mapping produces valid responses; strict JSON serialization stays on. |
### Django setting
```python
DJANGO_MCP_UCP = {"VERSION": "2026-08-25"} # the default
```
The system checks report these errors:
| Code | Problem |
|---|---|
| `E001` | Unknown key in `DJANGO_MCP_UCP`. |
| `E002` | Version with no pinned schemas. |
| `E003` | A bundled schema file was modified (checksum mismatch). |
## Platform profiles and security
Each call names a platform profile URL in `meta.ucp-agent.profile`. The business must fetch and validate
that profile before negotiating. The URL and the profile's contents come from an untrusted client, so
fetching them is where SSRF risk lives.
| Resolver | Use |
|---|---|
| *(default)* `StaticProfileResolver({}, version)` | Accepts no platform, and never fetches anything. |
| `StaticProfileResolver({url: profile}, version)` | A pre-approved platform registry, validated at startup. |
| `HttpProfileResolver(version, allowed_hosts={...})` | Fetches allow-listed hosts over HTTPS. |
| `HttpProfileResolver(version, allow_any_public_host=True)` | Permissionless onboarding. Add rate limits at your edge. |
| `CachedProfileResolver(resolver, key_prefix=..., ttl=300)` | Django cache in front of another resolver. TTL is at least 60 s. |
**`HttpProfileResolver` controls:**
- **URL policy, checked before DNS.** HTTPS only, no credentials in the URL, the host must be allowed,
and URLs with backslashes or whitespace are refused.
- **One DNS lookup.** Every resolved address must be public. Loopback, private, link-local (including
`169.254.169.254`), CGNAT, multicast, reserved and IPv4-mapped forms of these are all refused.
- **Pinned connection.** The TLS connection goes to the checked address, with certificate and hostname
verification, so DNS rebinding cannot redirect it.
- **Limits.**
- Redirects are never followed.
- A 3-second wall-clock deadline covers the whole fetch, so a server that trickles bytes can't hold it
open.
- Bodies are capped at 256 KiB.
- JSON nested too deeply to parse is refused.
- **Validation.** The profile is validated against the official platform schema.
- **Cache.** `CachedProfileResolver` stores only validated profiles. A broken cache falls back to a
fresh, validated fetch.
- **Local development.** `allow_loopback=True` allows loopback addresses.
Negotiation also drops platform capability entries whose `schema` URL fails UCP's namespace authority
binding.
## Authentication
```python
UCPServer(
...,
authenticate=lambda request: verify_bearer(request.headers.get("Authorization")), # principal or None
authorize_profile=lambda principal, profile_url: profile_url in principal.allowed_profiles,
)
```
- **Not authentication.** Negotiation and profiles say what a platform supports, not who is calling.
- **`authenticate`** runs before any MCP processing. A `None` result returns HTTP 401 with JSON-RPC
`-32000` "Unauthorized".
- **`authorize_profile`** enforces UCP Identity Binding: the authenticated caller must be allowed to act
for the profile it claims. A refusal returns 403 "Forbidden".
- **Where the principal goes.** It is stored on `request.ucp_principal` and passed to your hook as
`context.principal`.
## Errors and HTTP status codes
| Situation | JSON-RPC | `error.data.code` | HTTP |
|---|---|---|---|
| Profile URL missing, malformed, not allowed or unresolvable | `-32001` "UCP discovery failed" | `invalid_profile_url` | 400 |
| Profile fetch failed (non-200, timeout, TLS) | `-32001` | `profile_unreachable` | 424 |
| Profile not JSON, too big or violates the schema | `-32001` | `profile_malformed` | 422 |
| Platform speaks another UCP version | `-32001` "Protocol version not supported" | `version_unsupported` | 422 |
| No shared capability | **result** with `ucp.status: "error"` | message `capabilities_incompatible` | 200 |
| Invalid `catalog`, unknown tool, bad cursor, `InvalidSearchRequest` | `-32602` | — | 400 |
| Not authenticated / not authorized for the profile | `-32000` "Unauthorized" / "Forbidden" | — | 401 / 403 |
| Invalid merchant output, unexpected exception | `-32603` "Internal server error" | — | 500 |
UCP's MCP binding makes the HTTP status the primary signal. The official MCP SDK client reads the JSON-RPC
error from non-2xx JSON responses, so callers using it still see the `-32001` and `data.code` details.
## What goes over the wire
- **`tools/list`.** It returns exactly one tool, `search_catalog`, with the official description.
- `inputSchema` and `outputSchema` are self-contained JSON Schema 2020-12 documents. Every official
schema file they need, about 64 KiB, is embedded under `$defs`, keeping its `$id`. MCP clients
validate with an empty registry, so a schema that pointed to `https://ucp.dev` would fail for them.
- `outputSchema` is `anyOf[search_response, error_response]`. The result is a search response, except
for `capabilities_incompatible`, which the spec requires to have the error-response shape.
- **`tools/call`.** The UCP payload is in `structuredContent`. The identical JSON text is also in
`content[0].text`, for clients that don't read structured content.
- **Response envelope.** `ucp` contains the version and only the negotiated capability relevant to this
operation, for example:
```json
{"ucp": {"version": "2026-08-25",
"capabilities": {"dev.ucp.shopping.catalog.search": [{"version": "2026-08-25"}]}},
"products": [...], "pagination": {"has_next_page": false}}
```
- **Discovery.** `GET /.well-known/ucp` returns the business profile with `Cache-Control: public,
max-age=300` and a strong `ETag`; `If-None-Match` gets a 304. There are no redirects, and no
trailing-slash alias.
## Examples
[`examples/django_shop`](examples/django_shop) is a complete synthetic shop: 1,000 products, 5,000
variants, Unicode text, two currencies, unpublished products and unsellable records. It has two
interchangeable backends behind the same protocol code.
- **ORM (default):** SQLite. All of a variant's constraints go in one `Exists` subquery, so "black, size
44" never matches a product that only has black 42 and blue 44. Uses keyset pagination with a constant
query count.
- **OpenSearch** (`SHOP_BACKEND=opensearch`): BM25 over `name^3`, `brand^2` and `description`, nested
same-variant filters with `inner_hits`, and `search_after` with a `product_id` tie-breaker. It uses the
same product mapping as the ORM backend.
```sh
cd examples/django_shop
docker compose up --build # ORM backend on :8000
SHOP_BACKEND=opensearch docker compose --profile opensearch up --build # OpenSearch backend
```
Try a search:
```sh
curl -s -X POST localhost:8000/ucp/mcp \
-H 'Content-Type: application/json' -H 'Accept: application/json, text/event-stream' \
-H 'MCP-Protocol-Version: 2026-07-28' -H 'MCP-Method: tools/call' -H 'MCP-Name: search_catalog' \
-d '{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"search_catalog",
"arguments":{"meta":{"ucp-agent":{"profile":"https://platform.example/profile.json"}},
"catalog":{"query":"waterproof boot","filters":{"color":"black","size":"44",
"price":{"max":15000}},"pagination":{"limit":5}}},
"_meta":{"io.modelcontextprotocol/protocolVersion":"2026-07-28",
"io.modelcontextprotocol/clientCapabilities":{},
"io.modelcontextprotocol/clientInfo":{"name":"curl","version":"0"}}}}'
```
### Example tests
The example's tests compare 54 reproducible shopping tasks against an independent pure-Python oracle. Each
task goes through the real MCP SDK client over ASGI, and every page is checked.
- **ORM backend:** results must equal the oracle exactly.
- **OpenSearch backend:**
- browse-only tasks must equal the oracle exactly;
- text queries use BM25 token matching, so they must be a subset of the oracle's results, with identical
variants.
See the [example README](examples/django_shop/README.md).
## Performance
`examples/django_shop/bench.py` runs in-process on one machine: no network, a warm profile cache and
SQLite. Overhead is the full UCP request over ASGI minus calling the merchant search directly, at
concurrency 1:
| Page size | Response validation on (default), p50 / p95 | Off, p50 / p95 |
|---|---|---|
| 10 | +9.4 / +9.5 ms | +4.5 / +4.6 ms |
| 20 | +14.7 / +15.0 ms | +5.1 / +5.2 ms |
| 50 | +32.2 / +46.4 ms | +7.7 / +22.3 ms |
- **Validation cost.** Most of the overhead is validating each response against the official schema. It
grows with page size.
- **Scaling.** Run several worker processes. In one process, sync ORM hooks share Django's single
thread-sensitive executor.
- **Not measured:** a cold profile fetch over HTTPS, and a real network.
## Development
```sh
python -m venv .venv && . .venv/bin/activate
pip install -e ".[dev]"
ruff check . && ruff format --check .
pytest # package tests
(cd examples/django_shop && pytest) # example tests; OpenSearch tests run when OPENSEARCH_URL is set
```
### Updating the bundled schemas
```sh
git clone https://github.com/Universal-Commerce-Protocol/ucp vendor/ucp
python scripts/import_ucp_schemas.py --ucp-repo vendor/ucp --tag v2026-08-25
```
The import reads directly from git objects at the tag. It writes the schema manifest with checksums and
extracts the official examples into `tests/fixtures`. CI re-runs it and fails if the output differs.
### Test coverage
- Wire tests with the real MCP SDK under both WSGI and ASGI.
- Stateless and concurrent-isolation tests.
- SSRF tests against a real local TLS server, covering DNS rebinding, redirects, private addresses,
oversized bodies and slow trickled responses.
- Cursor tampering, expiry and cross-tenant reuse.
- Merchant output failures.
- An internal MCP endpoint in the same project is shown not to leak its tools.
The C001–C030 mapping is in [`ucp-spec/docs/05-testing.md`](ucp-spec/docs/05-testing.md).
### Repository layout
```text
src/django_mcp_ucp/
server.py UCPServer: discovery, negotiation, MCP server, URLs
transport.py the Django view adapter around the mcp SDK
catalog/ CatalogSearchToolset, SearchPage, InvalidSearchRequest, CursorCodec
protocol/ schema store and bundling, registry, negotiation, profiles, errors
schemas/v2026_08_25/ pinned official UCP schemas + manifest
examples/django_shop/ ORM and OpenSearch example, oracle tests, benchmark
tests/ package tests (official fixtures under tests/fixtures)
scripts/ schema import
ucp-spec/ design documents, backlog and ADRs
audit/ Milestone 0 probes and the SDK spike (historical)
```
## Design records
| ADR | Decision |
|---|---|
| [0001](ucp-spec/docs/adr/0001-base-framework-integration.md) | Build on the official `mcp` SDK with a thin Django view; django-mcp-server is not used. |
| [0002](ucp-spec/docs/adr/0002-separate-package.md) | Ship as a separate package with three runtime dependencies. |
| [0003](ucp-spec/docs/adr/0003-schema-authority.md) | Official schemas are bundled from the git tag, verified by checksum and never fetched. |
| [0007](ucp-spec/docs/adr/0007-discovery-negotiation-profile-resolution.md) | Discovery, negotiation, profile resolution and SSRF controls, plus the HTTP status mapping. |
| [0008](ucp-spec/docs/adr/0008-catalog-search-tool.md) | The `search_catalog` tool: schema bundling, `outputSchema`, validation, page size, cursors and the response-validation switch. |
The [implementation backlog](ucp-spec/IMPLEMENTATION.md) tracks the remaining milestones: release and
Lookup.
## Limitations
- **Scope.** Catalog Search only. `lookup_catalog` and `get_product` are planned for v0.2.
- **Single version.** One UCP version per server, and no `supported_versions`. A platform using any other
version gets `version_unsupported`.
- **No signing.** Message signatures and `keys[]` are not supported. Identity comes from your
`authenticate` and `authorize_profile` hooks.
- **No search deadline.** The package sets none on your search hook; enforce timeouts in your search
backend.
- **Discovery budget not implemented.** The spec's global fetch rate limits and backoff for permissionless
profile fetching are left to your deployment.
- **Concurrent cache misses** for the same profile URL each fetch it.
- **`tools/list`** responses are about 130 KiB because the schemas are embedded.
## License
MIT, see [LICENSE](LICENSE).
The bundled official UCP schemas (`src/django_mcp_ucp/schemas/*/official/`) and the official examples in
`tests/fixtures/ucp_*/` are unmodified copies of, or extracts from, the
[Universal Commerce Protocol](https://github.com/Universal-Commerce-Protocol/ucp), licensed under
Apache-2.0. Their licence text ships with them in
[`src/django_mcp_ucp/schemas/v2026_08_25/official/LICENSE`](src/django_mcp_ucp/schemas/v2026_08_25/official/LICENSE).
Each file's SHA-256 is recorded in the manifest. The package metadata declares `MIT AND Apache-2.0`.
This server cannot be deployed
Maintenance
ActivityMaintained
ResponsivenessNo recent community issues