django-mcp-ucp
This server does not currently have a deployable release on Glama. Follow the repository's setup instructions to install and configure it for your MCP client, including any required credentials and local dependencies.
django-mcp-ucp
Serve a Django shop's catalog to AI shopping agents through the Universal Commerce Protocol (UCP) Catalog Search capability over the Model Context Protocol (MCP).
You write one function that searches your catalog and maps products to official UCP JSON. The package does the rest:
the
/.well-known/ucpdiscovery profilethe MCP endpoint and its
search_catalogtoolcapability 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 UCP2026-08-25over 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
Related MCP server: UCP MCP Storefront
Requirements
Python 3.10+, Django 4.2+
mcp>=2.3,<3, the official MCP Python SDK. Only its public low-levelServerAPI is used; the package never reimplements MCP.jsonschema4.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
pip install -e . # not on PyPI yet# settings.py
INSTALLED_APPS = [..., "django_mcp_ucp"] # enables system checks; the package has no models# 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",
),
)# 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/mcpIt runs under WSGI (Gunicorn and similar) and ASGI (Uvicorn, Daphne). For a complete, tested shop, see
examples/django_shop.
How it works
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 → structuredContentOne server per endpoint. A
UCPServerinstance 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 |
| Free text, optional. |
|
|
| Buyer hints: |
|
|
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 |
| The negotiated UCP version. |
| The negotiated capabilities relevant to this call. |
| The platform profile URL the agent claimed. |
| What your |
| The Django |
SearchPage
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
productslist is a normal, successful result.Required product fields. Every product needs
id,title,description,price_rangeand at least one variant. Each variant needsid,title,descriptionandprice.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
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_KEYand expire aftermax_ageseconds.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,signalsandattributionmay 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 OpenSearchsearch_after.
If your code fails
Invalid response. If your products don't match the official schema, or contain
Decimal,datetimeorNaN, 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 | |
| required | Identifies the server in URL names and errors. |
| required |
|
|
| The MCP endpoint path. |
| the | UCP version. Pinned schemas must exist for it. |
|
| For example |
| accepts no platform | See Platform profiles. |
|
|
|
| required with |
|
|
|
|
commerce.urls gives the two URL patterns, commerce.profile the generated business profile, and
commerce.endpoint the advertised MCP URL.
CatalogSearchToolset(...)
Argument | Default | |
| the | |
|
| Page size when the client gives none. The spec recommends 10. |
|
| Larger requested limits are capped to this. |
|
| Validates every response against |
Django setting
DJANGO_MCP_UCP = {"VERSION": "2026-08-25"} # the defaultThe system checks report these errors:
Code | Problem |
| Unknown key in |
| Version with no pinned schemas. |
| 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) | Accepts no platform, and never fetches anything. |
| A pre-approved platform registry, validated at startup. |
| Fetches allow-listed hosts over HTTPS. |
| Permissionless onboarding. Add rate limits at your edge. |
| 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.
CachedProfileResolverstores only validated profiles. A broken cache falls back to a fresh, validated fetch.Local development.
allow_loopback=Trueallows loopback addresses.
Negotiation also drops platform capability entries whose schema URL fails UCP's namespace authority
binding.
Authentication
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.
authenticateruns before any MCP processing. ANoneresult returns HTTP 401 with JSON-RPC-32000"Unauthorized".authorize_profileenforces 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_principaland passed to your hook ascontext.principal.
Errors and HTTP status codes
Situation | JSON-RPC |
| HTTP |
Profile URL missing, malformed, not allowed or unresolvable |
|
| 400 |
Profile fetch failed (non-200, timeout, TLS) |
|
| 424 |
Profile not JSON, too big or violates the schema |
|
| 422 |
Platform speaks another UCP version |
|
| 422 |
No shared capability | result with | message | 200 |
Invalid |
| — | 400 |
Not authenticated / not authorized for the profile |
| — | 401 / 403 |
Invalid merchant output, unexpected exception |
| — | 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.inputSchemaandoutputSchemaare 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 tohttps://ucp.devwould fail for them.outputSchemaisanyOf[search_response, error_response]. The result is a search response, except forcapabilities_incompatible, which the spec requires to have the error-response shape.
tools/call. The UCP payload is instructuredContent. The identical JSON text is also incontent[0].text, for clients that don't read structured content.Response envelope.
ucpcontains the version and only the negotiated capability relevant to this operation, for example:{"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/ucpreturns the business profile withCache-Control: public, max-age=300and a strongETag;If-None-Matchgets a 304. There are no redirects, and no trailing-slash alias.
Examples
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
Existssubquery, 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 overname^3,brand^2anddescription, nested same-variant filters withinner_hits, andsearch_afterwith aproduct_idtie-breaker. It uses the same product mapping as the ORM backend.
cd examples/django_shop
docker compose up --build # ORM backend on :8000
SHOP_BACKEND=opensearch docker compose --profile opensearch up --build # OpenSearch backendTry a search:
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.
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
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 setUpdating the bundled schemas
git clone https://github.com/Universal-Commerce-Protocol/ucp vendor/ucp
python scripts/import_ucp_schemas.py --ucp-repo vendor/ucp --tag v2026-08-25The 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.
Repository layout
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 |
Build on the official | |
Ship as a separate package with three runtime dependencies. | |
Official schemas are bundled from the git tag, verified by checksum and never fetched. | |
Discovery, negotiation, profile resolution and SSRF controls, plus the HTTP status mapping. | |
The |
The implementation backlog tracks the remaining milestones: release and Lookup.
Limitations
Scope. Catalog Search only.
lookup_catalogandget_productare planned for v0.2.Single version. One UCP version per server, and no
supported_versions. A platform using any other version getsversion_unsupported.No signing. Message signatures and
keys[]are not supported. Identity comes from yourauthenticateandauthorize_profilehooks.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/listresponses are about 130 KiB because the schemas are embedded.
License
MIT, see 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, licensed under
Apache-2.0. Their licence text ships with them in
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.
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelog…
This server cannot be deployed
Maintenance
Related MCP Connectors
Federated commerce search across independent WooCommerce merchants. Keyless, read-only MCP server.
Universal Commerce Protocol (UCP 2026-08-25) MCP storefront for AI shopping agents and @shopify/ucp-cli: catalog search, batch lookup, product detail pages, stateful carts, Stripe & USDC checkouts, and order tracking.
Hosted MCP for e-commerce: live product catalog, stock, and pricing for AI agents.
UCP Catalog for independent WooCommerce stores: consented, federated, with live price checks.
Related MCP Servers
- AlicenseAqualityDmaintenanceAn MCP server that wraps the Universal Commerce Protocol (UCP) Discovery and Catalog capabilities, letting you search and compare products across UCP merchants directly from Claude.4MIT
- AlicenseAqualityDmaintenanceA UCP-compliant MCP storefront server that exposes product catalog operations (search, cart, checkout) as MCP tools, following UCP schema version 2026-04-08.5MIT
- AlicenseNot gradedqualityBmaintenanceFederated commerce search MCP server enabling AI agents to query real product offers, prices, and availability across independent WooCommerce stores without API keys or registration.MIT
- FlicenseAqualityDmaintenanceThis MCP server bridges XiaoYi to Shopify's catalog search by translating SSE requests to Streamable HTTP and providing the required UCP agent profile, enabling the search_catalog tool.1-