AI Integration 10 min read

Django MCP Server on the Stateless 2026-07-28 Spec

Papan Sarkar
Papan Sarkar

The MCP server that runs my own portfolio keeps its sessions in a JavaScript Map. One process, one dictionary of open SSE connections, and a 404 Session not found the moment a request lands anywhere else. That design was normal a year ago. Under the protocol revision that shipped in July, it is the legacy path.

The Model Context Protocol 2026-07-28 release removed the initialize handshake and the Mcp-Session-Id header, and the same post puts Tier 1 SDK usage at close to half a billion downloads a month. For anyone running Django, that change matters more than it sounds: MCP is now plain request/response HTTP, which is the thing Django has always been good at.

TL;DR

  • An MCP endpoint is now a stateless POST endpoint. Any worker behind a normal load balancer can answer any request, so no sticky sessions and no separate single-process service.
  • On Django today, the most direct route is to mount the official Python SDK’s ASGI app next to Django in asgi.py. I ran the code below on Django 6.1 with two uvicorn workers and it answered every call.
  • If you are WSGI-only, look at django-stateless-mcp, but check its Django version support first.
  • The protocol going stateless does not make your tools safe to retry. Anything that sends an email or charges a card needs an idempotency key.
  • If your agents only run locally (Claude Desktop, Cursor, a coding agent), stdio is still fine. This post is about exposing a deployed product to agents.

What the 2026-07-28 revision actually removed

The headline is subtraction. Per the official release post:

  • The initialize/initialized handshake and the Mcp-Session-Id header are gone. Each request carries its protocol version and client capabilities in _meta.
  • Streamable HTTP requests must send Mcp-Method and Mcp-Name headers, so a gateway can route or rate-limit without parsing JSON.
  • Servers no longer send their own requests to clients. When a tool needs user input mid-call, it returns resultType: "input_required" and the client retries the call with the answers (the spec calls this MRTR).
  • Long-running work moved to a Tasks extension with polling.
  • The old HTTP+SSE transport is deprecated with a one-year offramp, and Roots, Sampling and Logging are deprecated with at least twelve months of support.

The Streamable HTTP section of the spec also drops the GET stream endpoint and resumable streams via Last-Event-ID. A server that only speaks the new revision should answer GET or DELETE on the MCP endpoint with 405 Method Not Allowed and ignore any session header it is sent.

Two security rules from that page matter for anyone shipping this inside an existing app. Servers must validate the Origin header and return 403 on a bad one, to block DNS rebinding. Servers must also reject a request with 400 and JSON-RPC error -32020 (HeaderMismatch) when the Mcp-Name header disagrees with the body. That second rule exists because a load balancer might route on the header while your code executes the body.

Why this is good news for a Django backend

Under the old model, an MCP server held per-client state in memory: a session, an open SSE stream, sometimes a blocked worker waiting for an elicitation reply. That fought every assumption a Django deployment makes. You ran a separate Node or Python process, pinned clients to it, and kept it out of your autoscaling group.

Now each tool call is a self-contained POST. It authenticates, runs a query, returns JSON. That is a Django view with a different envelope. Your ORM, permissions, settings and deployment pipeline all apply unchanged, and you scale MCP traffic the same way you scale the rest of the API.

The option I would pick: mount the official SDK in asgi.py

The Python SDK v2 renamed FastMCP to MCPServer and implements the 2026-07-28 revision while still serving 2025-11-25 clients from the same app. The current release on PyPI is 2.3.0. Its streamable_http_app() returns a Starlette app, and the SDK’s ASGI guide shows how to mount it inside a host app.

So the plan: Starlette becomes a thin outer router, /agents/... goes to MCP, and everything else goes to Django untouched.

First the tool, living next to the models it reads:

# orders/mcp.py
from mcp.server import MCPServer
from mcp.server.transport_security import TransportSecuritySettings

from orders.models import Order

mcp = MCPServer("acme-orders", version="1.0.0")


@mcp.tool()
async def order_status(order_number: str) -> dict:
    """Return the current status of an order by its public order number."""
    try:
        order = await Order.objects.only("status", "updated_at").aget(
            number=order_number
        )
    except Order.DoesNotExist:
        return {"found": False, "order_number": order_number}
    return {
        "found": True,
        "order_number": order_number,
        "status": order.status,
        "updated_at": order.updated_at.isoformat(),
    }


mcp_http_app = mcp.streamable_http_app(
    json_response=True,
    transport_security=TransportSecuritySettings(
        allowed_hosts=["api.example.com", "127.0.0.1:*"],
        allowed_origins=["https://api.example.com"],
    ),
)

Then the entry point:

# config/asgi.py
import os
from contextlib import asynccontextmanager

from django.core.asgi import get_asgi_application

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.settings")
django_app = get_asgi_application()  # must run before importing models

from starlette.applications import Starlette  # noqa: E402
from starlette.routing import Mount  # noqa: E402

from orders.mcp import mcp, mcp_http_app  # noqa: E402


@asynccontextmanager
async def lifespan(app):
    async with mcp.session_manager.run():
        yield


application = Starlette(
    routes=[
        Mount("/agents", app=mcp_http_app),  # serves /agents/mcp
        Mount("/", app=django_app),          # everything else stays Django
    ],
    lifespan=lifespan,
)

Three details that cost time if you miss them:

  1. Import order. get_asgi_application() sets Django up. Import your models before it and you get AppRegistryNotReady.
  2. Lifespan. The SDK guide warns that a mounted sub-app’s lifespan never runs, so the outer app must enter mcp.session_manager.run() itself. Skip it and the first call fails with a task group error. Despite the name, this does not reintroduce protocol sessions for 2026-07-28 clients. It manages the transport, and per the SDK’s notes, stateless_http only affects 2025-era clients.
  3. Host allowlist. Without transport_security, requests from a real hostname are rejected with 421 Misdirected Request. Put your public host in allowed_hosts and your real origins in allowed_origins.

What I tested

I ran exactly this on Django 6.1.3 (6.1 release notes) and mcp 2.3.0 with uvicorn config.asgi:application --workers 2, then sent raw POSTs with no handshake:

curl -s -X POST http://127.0.0.1:8765/agents/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: order_status" \
  -d '{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"order_status","arguments":{"order_number":"A-1042"},"_meta":{"io.modelcontextprotocol/protocolVersion":"2026-07-28","io.modelcontextprotocol/clientInfo":{"name":"curl","version":"1.0"},"io.modelcontextprotocol/clientCapabilities":{}}}}'

Results:

  • Four calls in a row, spread across both workers: all 200, all returned the order with "resultType":"complete". No session ID anywhere.
  • A normal Django URL on the same server kept working.
  • Changing Mcp-Name to a value that did not match the body: 400 with error code -32020.
  • Adding Origin: https://evil.example: 403.

That is a local test with curl, not a production rollout with a real agent client. Treat it as proof that the wiring is right, not as a load test.

The Django packages, compared

Several Django-specific packages exist. The difference that matters now is which spec they target.

OptionSpec targetRuns on WSGIDjango versions listedWatch out for
Official mcp SDK mounted in asgi.py2026-07-28 and 2025-11-25 (SDK docs)NoNot Django-specificYou own the ASGI wiring and auth
django-stateless-mcp 0.1.11 (PyPI)2026-07-28Yes5.2 LTS and 6.0Pins mcp 2.0.x; 6.1 not listed yet
django-mcp-server 0.5.7 (PyPI)Page references 2025-03-26YesClassifiers list 4 and 5Last release Oct 2025, before the stateless spec

django-stateless-mcp is the most Django-native design I have seen. Its mcp_view(server) is an ordinary view in urls.py, it autodiscovers an mcp.py per app the way the admin does, and its optional bearer auth resolves to a real Django user so user.has_perm() works inside tools. If you are on 6.0 or 5.2 LTS and run gunicorn with sync workers, start there. On 6.1 I would wait for it to list support, or test it yourself before relying on it.

django-mcp-server is the older and more widely used option, and it can convert DRF views to tools. But its PyPI page still documents the 2025-03-26 spec and is inconsistent about whether stateless is the default. I would not start a new integration on it today.

What going stateless does not fix

The WorkOS write-up of the change makes the point I would put first in any client conversation. Stream resumability is gone, so a dropped connection loses the in-flight call and the client reissues it. A test suite will pass while a retried refund_order runs twice.

My rules for tools that write anything:

  • Take an idempotency key as a tool argument. Store it with a unique constraint and return the earlier result on a repeat. Django makes this a model and an IntegrityError handler.
  • Keep workflow state in your database, not the protocol. If a flow spans several calls, return an opaque workflow_id and have the agent pass it back. That is the pattern WorkOS describes, and it is how I would build it anyway.
  • Anything slow goes to a queue. Use the Tasks extension or your own job table rather than holding a request open. I covered the Django side of background work in Django’s Tasks API ships without a worker.
  • Per-user tool lists move into auth. If you showed different tools per connection before, that logic now belongs in the authorization layer.

When not to do this

There is real pushback. The Register’s coverage quotes Anthropic’s David Soria Parra saying that if you built your own implementation, getting it right will be “a lot of uplift”. It also notes that new-revision servers may not work with older clients. Stateless also means every request carries its own metadata, which is a deliberate trade of bandwidth for simpler servers.

So my position:

  • Do not hand-roll the protocol. Use the official SDK or a package that tracks it. The header validation alone is easy to get subtly wrong.
  • Do not build an MCP endpoint because it is fashionable. If no customer’s agent will call your product, a documented REST API is enough.
  • Do build it if your users already work inside Claude, ChatGPT, Cursor or an internal agent, and your product holds data or actions they want there. That is now an afternoon of wiring plus a careful week on auth and idempotency, not a new service.

From the field: my own server is the “before” picture

The portfolio you are reading is managed partly through a custom MCP server I wrote in Node with the official TypeScript SDK (1.32.x in package.json). It exposes 29 tools for articles, case studies, courses and build checks, and runs over stdio for local agents or HTTP+SSE for remote ones.

The SSE mode is a textbook example of what the new spec retires. It creates an SSEServerTransport per connection, stores it in an in-memory Map keyed by session ID, and routes each POST to /messages?sessionId=... back to that object. It cannot run as more than one process. It also sets Access-Control-Allow-Origin: * and has no auth. That is acceptable only because it never leaves my laptop. It would be a serious hole on a public host.

What I am changing:

  1. Moving the HTTP mode from the deprecated SSE transport to stateless Streamable HTTP on an SDK release that supports 2026-07-28.
  2. Deleting the session map entirely.
  3. Adding an Origin allowlist and a bearer token before it ever binds to anything but localhost.
  4. Adding idempotency keys to create_article and delete_article, the two tools that would hurt if retried.

Checklist before you expose a Django app to agents

  • Is a remote agent actually going to call this? If not, stop at stdio or a REST API.
  • Official SDK 2.x or a package that states 2026-07-28 support, verified against your Django version.
  • Origin and host allowlists set; 421 and 403 behavior tested.
  • Every request authenticated, mapped to a real Django user, permissions checked inside each tool.
  • Idempotency key on every tool with side effects.
  • Multi-step state in the database, passed back as an opaque ID.
  • Slow work on a queue, not in the request.
  • Tested with two or more workers and no sticky sessions.

If you want an existing Django or Next.js product usable from Claude, ChatGPT or your team’s internal agents, that is the kind of integration I build. It covers auth, permissions and the boring retry-safety work that keeps it out of the incident channel. Get in touch here. For the model-calling side of the same backend, see how I integrate LLMs into a Django backend.

Sources

  1. MCP blog: the 2026-07-28 specification release
  2. MCP specification 2026-07-28: Streamable HTTP transport
  3. MCP Python SDK: what’s new in v2
  4. MCP Python SDK: add to an existing ASGI app
  5. mcp on PyPI
  6. django-stateless-mcp on PyPI
  7. django-mcp-server on PyPI
  8. WorkOS: MCP went stateless, what changed in the 2026-07-28 spec
  9. The Register: Model Context Protocol prepares to break with its stateful past
  10. Django 6.1 release notes

Discussion

No account needed. Be kind and keep it on topic.

Your email stays private. It's used to confirm you're a real person and, only if you tick the box, to tell you about replies (you'll confirm by email first; unsubscribe any time).

Every comment is reviewed for spam · ⌘↵ to post

No comments yet. Start the conversation.