Add MCP support
Open the course app to Claude and Codex. Write an MCP server by hand in Django: the Streamable HTTP transport at /mcp, JSON-RPC, personal tokens that are stored hashed, and the assistant's tools with clear names, tight schemas, read-only hints and helpful errors. Every tool runs as the token's user, with exactly the web app's permissions, and changes still wait for the user's Confirm.
Preview shown for one variant (Room bookings (manager tool)). You get your own when you start.
Why this quest
In quest 4 you gave the course app (the Lumo Community Centre) an AI assistant. People can use it only on the app's web page. With an MCP server, people can use the app from Claude or Codex: "Which of my bookings are next week?" typed in Claude Desktop reaches your app, runs your tools and comes back with the answer.
MCP (the Model Context Protocol) is an open standard for this. An AI app (the host, for example Claude Desktop) runs one client for each server it connects to. Your Django app becomes a server. You write it by hand, as a Django view, so you see every message of the protocol.
Doing it properly means three things, and this quest grades all three:
- Each person signs in as themselves, with a personal token. The token acts as that user.
- Exactly the web app's permissions. Tools run through the same registry and
hub/services.pyas the web assistant. A member never sees more over MCP than on the web page. - Changes still wait for Confirm. A model in Claude can call your write tool, but nothing changes until the user presses Confirm in the web app.
In the capstone, adding an MCP server to your own app is optional; if you add one, it follows the same contract.
Your variant: Room bookings. Your new staff tool is list_pending_approvals (for managers),
and your write tool is book_room.
What you start with
Your starter kit is quest 4's reference solution: the course app with a working assistant
(assistant/). Read README.md ("The service layer", "Roles", "The assistant") and
assistant/tools.py. The tools are already in one registry, written so that other programs can
use them: all_tools(), get_tool(name), check_arguments(tool, arguments), Tool.run(user,
arguments), and for write tools writes=True, preview and assistant.agent.propose(...), which
creates a pending action. The kit also has SUBMISSION.md, the public tests (eval/) and the
course's test fixtures in .neugen/shared/, including the MCP test client.
python -m venv .venv
source .venv/bin/activate # Windows: .venv\Scripts\activate
pip install -r requirements.txt # Django 5.2 and openai (Python 3.10 or newer)
python manage.py migrate
python manage.py seed_demo
python manage.py test # the starter's 153 tests pass
neugen test # the public tests: they fail until you build the server
You do not need an OpenAI key for this quest. (The assistant page still needs one if you use it.)
What you build
- The MCP endpoint
POST /mcp: a Django view that speaks JSON-RPC 2.0 and MCP. - Personal tokens: a model for them (stored hashed), a page
/account/mcp-tokens/to create and revoke them, and a commandpython manage.py mcp_token <username>. - The role rule in the registry: each tool says which roles may use it. Add your variant's staff tool with its role rule. The web assistant and the MCP server both use the rule.
- Your own tests (at least 3, all passing).
- A real client: connect Claude or Codex to your server, use it, and describe what happened.
SUBMISSION.md. Transcripts in.neugen/logs/are optional.
The rules of this quest:
- Write the endpoint as a Django view. The grader installs only Django and
openai: no MCP SDK, no HTTP libraries, no agent frameworks, no frontend build. - Keep quest 4 working. The starter's tests and the assistant must still pass. Keep the app
assistantand itsPendingActionmodel: the tests use them. - No key or token in code, in tests with real values, or in your logs.
The contract
The hidden tests (and the capstone's tests, when you enable MCP there) use exactly these URLs, codes and fields.
The endpoint: POST /mcp
- One JSON-RPC 2.0 message per POST. The protocol version is
2025-06-18. Answer a request withContent-Type: application/jsonand one JSON object. (Atext/event-streamanswer is also allowed, but you do not need it.) Your server may be stateless: you need no session id. - A notification (a message without
id, such asnotifications/initialized): answer HTTP 202 with no body. GET /mcp: answer 405 (your server opens no event stream).- CSRF-exempt, but only this URL. Clients are not browsers and send no CSRF token.
- Check these, in this order:
| Problem | Answer |
|---|---|
an Origin header from another web site |
403 |
no Authorization: Bearer <token>, or a token that is wrong, revoked, or of an inactive user |
401 with the header WWW-Authenticate: Bearer |
an MCP-Protocol-Version header with a version you do not speak |
400 |
| a body that is not JSON | 400, JSON-RPC error -32700 |
JSON that is not a request (no method) |
400, JSON-RPC error -32600 |
A login cookie is not a token. /mcp must answer 401 to a logged-in browser that sends no
bearer token. (Otherwise any web site could use your CSRF-exempt endpoint with the user's cookie.)
Why the version header matters: the newest MCP clients first try a newer protocol revision. When
your server answers 400, they fall back to the initialize handshake of 2025-06-18.
The methods
initialize -> {"protocolVersion": "2025-06-18", "capabilities": {"tools": {}},
"serverInfo": {"name": "...", "version": "..."}}
notifications/initialized -> HTTP 202, no body
tools/list -> {"tools": [{"name", "description", "inputSchema", "annotations"}, ...]}
tools/call -> {"content": [{"type": "text", "text": "..."}], "isError": false}
any other method -> JSON-RPC error -32601 (method not found)
A JSON-RPC answer always has "jsonrpc": "2.0" and the request's id, unchanged (it may be a
number or a string). If the client asks for another protocol version in initialize, answer
2025-06-18.
tools/list lists every tool the user's role may use, and no other, checked on every
request (a user who loses a role loses its tools at once). Each tool has:
name, and adescription: a full sentence on what it does and when to use it;inputSchema: a JSON schema object ("type": "object",propertieswith a type for each argument,requiredwith exactly the required arguments). Never auserargument: the token decides who the tool acts as;annotations:"readOnlyHint": trueon tools that only read. A write tool is not read-only.
tools/call ({"name": "...", "arguments": {...}}) runs the tool as the token's user:
| The call | The answer |
|---|---|
| it works | a result with the data as text (JSON text is fine), "isError": false |
| wrong or missing arguments | a result with "isError": true and a message that names the argument |
PermissionDenied, ValidationError, a record that does not exist |
a result with "isError": true and a helpful message |
| a tool that does not exist, or one the user's role may not use | JSON-RPC error -32602 |
no name |
JSON-RPC error -32602 |
Never answer 500, and never send a traceback. A "not found" and a "not allowed" record may get the same message.
Tokens
- A token is a long random string (for example
secrets.token_urlsafe(32)with a prefix). Store only a hash of it (for example SHA-256). The hidden tests search every table for the token. /account/mcp-tokens/(login required; visitors go to the login page):GETlists the user's own tokens by name (never their value);POSTwith the form fieldnamecreates a token and shows it once, in an element withid="new-token"(for example<code id="new-token">lumo_...</code>). Later visits never show it again;- each token has a form that POSTs to
/account/mcp-tokens/<id>/revoke. Users can revoke only their own tokens (another user's id: 404). A revoked token gets 401. - This page keeps Django's CSRF protection.
python manage.py mcp_token <username>creates a token for that user and prints it. The last line of the output is the token alone. An unknown username is an error.
Writes still need confirmation
When tools/call runs your write tool, nothing changes. Do what the web assistant does: check
the call as the user (a change that cannot work gets isError: true at once, and no pending action),
then create the same PendingAction (quest 4's assistant.agent.propose does both). The
result text says that nothing has changed, uses the word "confirm", and gives the path of a
web page (for example /assistant/?c=12) where this user sees the change and presses Confirm.
Only that user can confirm it, through quest 4's confirm API. No MCP tool can confirm.
Claude and Codex also ask the user before they call a tool. That is the client's choice. Your server cannot rely on it, so the rule stays in your code.
Your tools
Every variant offers quest 4's tools of that variant (same names and arguments) plus one new staff tool that only some roles may use. Build only your variant's new tool. You may also offer the starter's other tools, with the same rules.
Add the new tool to the registry in assistant/tools.py, with a role rule (for example a
roles= field on Tool and a tools_for(user) function). Use the rule in both places:
tools/list and tools/call over MCP, and the tools the web assistant offers. A tool that is
hidden must also be refused when someone calls it by name.
Variant "Room bookings"
| Tool | Arguments (required in bold) | Kind | Who |
|---|---|---|---|
search_handbook |
query |
read | everyone |
find_free_rooms |
date, start_time, end_time, attendees |
read | everyone |
list_my_bookings |
upcoming |
read | everyone |
get_booking |
booking_id |
read | everyone |
book_room |
room_id, date, start_time, end_time, purpose, attendees |
write | everyone |
list_pending_approvals |
room_id (integer) |
read | managers only |
list_pending_approvals lists the upcoming bookings that wait for a manager's approval
(services.list_pending_approvals), with each booking's id, room, date, times, purpose and member.
Staff who are not managers must not see it.
Variant "Help requests"
| Tool | Arguments (required in bold) | Kind | Who |
|---|---|---|---|
search_handbook |
query |
read | everyone |
list_my_requests |
status |
read | everyone |
get_request |
request_id |
read | everyone |
get_my_profile |
none | read | everyone |
create_request |
category, title, description |
write | everyone |
list_open_requests |
category (one of the categories) |
read | staff and managers |
list_open_requests lists every member's help requests with status open
(services.list_requests(user, status="open", ...)), with id, title, category and member. Careful:
for a member, list_requests quietly returns only their own requests, so the services alone do not
refuse a member. Your role rule must.
Variant "Member desk"
| Tool | Arguments (required in bold) | Kind | Who |
|---|---|---|---|
search_handbook |
query |
read | everyone |
get_my_profile |
none | read | everyone |
list_my_bookings |
upcoming |
read | everyone |
get_booking |
booking_id |
read | everyone |
cancel_booking |
booking_id, reason |
write | everyone |
find_members |
query (string) |
read | staff and managers |
find_members finds members by part of a name, username or phone number (services.list_members),
with name, username, phone and language, so staff can call a member back.
Connect a real client
Run your server (python manage.py runserver), create a token on /account/mcp-tokens/ (log in
as a demo user) and keep it in an environment variable, not in a file you commit:
export LUMO_MCP_TOKEN="lumo_..." # PowerShell: $env:LUMO_MCP_TOKEN = "lumo_..."
Then connect one of these clients. (Checked against the vendors' docs on 2026-09-29. These
tools change often: if a step does not work, read the current page and tell us in SUBMISSION.md.)
- Claude Code (MCP docs):
claude mcp add --transport http lumo http://127.0.0.1:8000/mcp --header "Authorization: Bearer $LUMO_MCP_TOKEN". Check it withclaude mcp list, or/mcpinside Claude Code. - Codex CLI or IDE extension (MCP docs): add to
~/.codex/config.toml
toml
[mcp_servers.lumo]
url = "http://127.0.0.1:8000/mcp"
bearer_token_env_var = "LUMO_MCP_TOKEN"
and check it with /mcp in the Codex TUI.
- Claude Desktop: its "custom connectors" connect from Anthropic's cloud (not from your
computer) and use OAuth, so they cannot reach localhost with a personal token. Use a local
bridge instead: install Node.js, open Settings → Developer → Edit Config
(claude_desktop_config.json), and add
json
{"mcpServers": {"lumo": {"command": "npx",
"args": ["mcp-remote", "http://127.0.0.1:8000/mcp", "--allow-http", "--header", "Authorization:${AUTH_HEADER}"],
"env": {"AUTH_HEADER": "Bearer lumo_..."}}}}
mcp-remote is a community bridge, not an Anthropic tool. Restart Claude Desktop. Never commit
this file with your token in it.
Then ask real questions: a handbook question, "my" records, something your role may not do (and,
with a staff or manager token, your staff tool), and one change. Confirm or cancel the change in the
web app. Watch how the model picks tools and reads your errors: improve your descriptions and
messages, and write down what happened and what you changed in SUBMISSION.md. Short quoted
excerpts are welcome. Saving the full transcript in .neugen/logs/ is optional; if you do,
remove your token from it first.
Try it: one app, two doors. Ask the same question about Amina's own records in the web assistant (logged in as
amina, at/assistant/) and in your client with Amina's token. Compare the answers. Then ask the client for a change: it gives you a link; open it in the web app as Amina, and the change is waiting for her Confirm. Last, make a token forgraceand ask the client which tools it has:list_pending_approvalsis there. With Amina's token it isn't, and the web assistant doesn't offer it to her either.Notice: both doors go through the same registry and
hub/services.py, as the same user. MCP adds a new way in, not new permissions.
Testing: the MCP test client
The hidden tests use the course's MCP test client, neugen_fixtures/mcp_client.py (in
.neugen/shared/). It talks to /mcp through Django's test client, so no server has to run. Your
own tests can use it too, or plain self.client.post("/mcp", ...):
import io, sys
from django.conf import settings
from django.core.management import call_command
from django.test import Client
from hub.tests.helpers import CentreTestCase
sys.path.insert(0, str(settings.BASE_DIR / ".neugen" / "shared")) # the grader has its own copy
from neugen_fixtures.mcp_client import MCPClient, django_transport
class MCPTests(CentreTestCase):
def test_member_sees_the_handbook_tool(self):
out = io.StringIO()
call_command("mcp_token", "amina", stdout=out)
mcp = MCPClient(django_transport(Client()), "/mcp", token=out.getvalue().strip().splitlines()[-1])
mcp.initialize()
self.assertIn("search_handbook", [tool["name"] for tool in mcp.list_tools()])
mcp.call_tool(name, arguments) returns the result (mcp.text(result) joins its text); a JSON-RPC
error or an HTTP error raises MCPError (with .status and .code). Read eval/mcptest.py and
eval/public/test_public.py to see how the tests use it.
What to submit
With neugen submit, from your quest folder:
- the course app with your MCP server, token model and migration, token page, command, the role rule and your staff tool, and your tests;
- your project instruction file (
AGENTS.md,CLAUDE.mdorGEMINI.md) if you use one; - optionally, transcripts in
.neugen/logs/(your coding agent's, or the real client's). They are not required and leaving them out never lowers your score; SUBMISSION.mdwith these sections: 1. My MCP server: how one POST to/mcpworks in your code, from the checks to the answer; howtools/listandtools/calluse the registry; how errors are answered. 2. Tokens and permissions: how tokens are made, stored, checked and revoked; how the token's user reaches every tool; your staff tool's role rule; what a write over MCP does. 3. A real client: the client, its version, the date, how you connected it (without the token), what you asked and what the model did, what worked, and what you changed after watching the model. 4. How I worked with the agent.
How you're graded
- Hidden tests drive your
/mcpwith the MCP test client (never a real model): - The protocol (gate 90%): the handshake, JSON-RPC ids and errors, 202 for notifications, broken requests, GET, CSRF, the version header, the Origin check, the result format. - Tokens (gate 100%): 401 for missing, wrong, revoked and badly sent tokens and for a login cookie alone; the command; hashed storage; the token page; inactive users. - Permissions (gate 100%): two roles of your variant; your staff tool; "my" records; other members' records; each token acts as its user; the current role counts; the web assistant follows the same rule. - Tools for models (gate 85%): your tools, descriptions, schemas, hints, results and errors. - Safety (gate 100%): writes wait for Confirm in the web app; no API key in your code. - Quest 4's assistant (gate 85%), stack checks (gate 100%) and your own tests (at least 3 new tests, all passing). - Rubric review by an AI grader: your tool design for models, your real-client report, and how you worked with your coding agent, judged from your write-up, code and tests.
- Defense: a short conversation about your server. For example: "Show me where the token becomes a user", "A member calls your staff tool by name. What happens, line by line?"
This is an AI-on quest: use your coding agent. The tutor explains ideas and gives hints, but it will not write the server for you.
Suggested path (about 6 hours)
- Read the required materials (about 1.5 hours).
- Read
assistant/tools.py,assistant/agent.py(propose),eval/mcptest.pyand the public tests. Runneugen test(30 minutes). - With your agent: the token model, the command and the 401 answers, with tests (1 hour).
- The endpoint:
initialize, notifications,tools/list,tools/call, the errors (1 hour). - The role rule, your staff tool, the write path, the token page (1 hour).
- Connect a real client, compare it with the web assistant (the Try it box), improve your
tools, write
SUBMISSION.md(1 hour).
Tips
- Tell your agent the rules in your instruction file: "A plain Django view, no MCP SDK. Tools run as
the token's user through the registry. Store only a hash of tokens. Write tools only create a
pending action." Agents often install the SDK, check a token with
==against a plain-text column, forget@csrf_exempt(or exempt the whole site), or run tools as an admin "to make it work". - Try your server by hand with
curlbefore you connect a client:curl -s localhost:8000/mcp -H "Authorization: Bearer $LUMO_MCP_TOKEN" -H "Content-Type: application/json" -d '{"jsonrpc":"2.0","id":1,"method":"tools/list"}' - Error messages are for a model: "'booking_id' must be an integer, e.g. 12" helps it fix the next call; "Bad request" does not.
Interface
POST /mcp one JSON-RPC 2.0 message; protocol version 2025-06-18; CSRF-exempt (only this URL)
Authorization: Bearer <token> missing, wrong, revoked or inactive user -> 401 + WWW-Authenticate: Bearer
Origin from another site -> 403 MCP-Protocol-Version not spoken -> 400
request -> 200 application/json (or text/event-stream) {"jsonrpc": "2.0", "id": ..., "result"|"error"}
notification -> 202, no body broken JSON -> 400 / -32700 no method -> 400 / -32600
initialize -> {"protocolVersion": "2025-06-18", "capabilities": {"tools": {}}, "serverInfo": {"name", "version"}}
tools/list -> {"tools": [{"name", "description", "inputSchema", "annotations": {"readOnlyHint": true for reads}}]}
only the tools the user's CURRENT role may use
tools/call -> {"content": [{"type": "text", "text": ...}], "isError": false}
bad arguments, PermissionDenied, ValidationError, not found -> "isError": true + a helpful text
unknown tool (or one the role may not use) -> JSON-RPC error -32602; unknown method -> -32601
write tool -> a PendingAction (quest 4's), no change; the text says to confirm at a web path
GET /mcp -> 405
GET /account/mcp-tokens/ login required; your tokens by name, never their value
POST /account/mcp-tokens/ field "name"; the page shows the new token once in id="new-token"
POST /account/mcp-tokens/<id>/revoke your own tokens only
python manage.py mcp_token <username> creates a token; the LAST line of the output is the token alone
Tokens are stored hashed (no token in plain text anywhere in the database).
Read now
Start here. Read 'Core Components' (host, clients, servers) and 'Capability Negotiation'. Your Django app is a server; Claude Code or Codex is the host, and it runs one client per server.
Only 'Initialization' and 'Version Negotiation': the initialize request and response, and the notifications/initialized message. Copy the shape of the response.
Read the 'Streamable HTTP' part: the Security Warning (Origin), 'Sending Messages to the Server' (202 for notifications, JSON or SSE for requests), GET and 405, and the 'Protocol Version Header' (400). Skip resumability; sessions are optional.
tools/list and tools/call, the Tool fields (name, title, description, inputSchema, annotations), text content, and 'Error Handling': protocol errors versus results with isError: true.
Use while building
Open these when a step needs them. No need to read them first.
'Principles for writing effective tools', after you watch a real client use your server: improve a name, description, result or error message.
Explore further
The official SDK serves MCP as an ASGI app and speaks the newer 2026-07-28 revision. This quest does not use it (the grader has only Django and openai), but its client is a handy way to try your server by hand.
Three stages. You only move on when the one before passes.
Automated gates
| Metric | Gate | What it checks |
|---|---|---|
| The protocol | ≥ 0.9 | Share of the protocol tests that pass: initialize, JSON-RPC responses with the request's id, 202 for notifications, -32601, broken JSON and invalid requests, GET, CSRF-exempt, the MCP-Protocol-Version header, the Origin check, the shape of tool results. |
| Tokens | ≥ 1.0 | Share of the token tests that pass: 401 with WWW-Authenticate for a missing, wrong, revoked or wrongly sent token and for a login cookie alone; the mcp_token command; tokens stored hashed; the token page (login, shown once, only your tokens, revoke only your own, CSRF); inactive users. All must pass. |
| Permissions | ≥ 1.0 | Share of the permission tests that pass: the staff tool is listed and works only for its roles, 'my' tools show the token user's own records, other members' records are refused, each token acts as its user, the current role counts, and the web assistant follows the same rule. All must pass. |
| Tools for models | ≥ 0.85 | Share of the tool tests that pass: your variant's tools are listed with descriptions, typed schemas and exactly the required arguments, read-only hints, results with the data, the handbook with file names, -32602 for unknown tools, and isError results that name the wrong argument. |
| Safety | ≥ 1.0 | Writes over MCP only create a pending action (nothing changes), the result names the web page where the user confirms, only that user can confirm, impossible changes are refused at once, no tool confirms; and no API key in your code or settings. All must pass. |
| Quest 4's assistant | ≥ 0.85 | Share of quest 4's assistant tests that still pass (the loop, tools, handbook, permissions, confirmation, the key). |
| Stack checks | ≥ 1.0 | The app loads, the starter's tests still pass, SQLite, migrations, the settings, the URLs, the mcp_token command, openai in requirements.txt, no packages the grader does not install, no frontend build. All must pass. |
| Your own tests | ≥ 3 | How many new tests (not the starter's hub/tests and assistant/tests) `python manage.py test` runs, counted only if all of them pass. You need at least 3. |
Gates run on the public set (which you have) and a hidden set with inputs you haven't seen.
Rubric review need ≥ 60%
The MCP tools are easy for a model to use well. Names are clear and consistent; each description says what the tool does, when to use it and what it returns; schemas are tight (types, enums, exactly the needed required arguments, argument descriptions with examples); annotations are right (readOnlyHint on reads; the write tool marked as not read-only, and destructive where it removes something); results carry the ids and facts the next step needs and stay short; error messages name the argument or the rule and say how to fix the call. The staff tool follows the same standard. The write-up explains at least one design choice.
SUBMISSION.md reports a session of a real MCP client (Claude Code, Claude Desktop or Codex) using the student's server: the client, its version and the date, how it was connected (without the token), and what happened for a handbook question, the user's own records, a refused request (a record or tool the role may not use), and a change that the model only prepared and the student then confirmed or cancelled in the web app. It reports what did not work and names one change made to a tool description or error after watching the model. The report is specific (tool names, arguments, errors, the model's next step) and consistent with the code. A transcript is optional: judge from the write-up when there is none. No token or key appears anywhere. A missing or clearly invented report caps this at 1.
The write-up shows the student directing and checking the coding agent: rules in the instruction file (a plain Django view, tools run as the token's user through the registry, tokens stored hashed, writes only create a pending action, CSRF exempt only for /mcp), tests written for the rules, the diff read, and a concrete decision, correction or check (for example catching or ruling out a plain-text token, an SDK dependency, a site-wide CSRF exemption, a hidden tool that could still be called), with the code and tests it names matching the submission. Transcripts are optional: judge from the write-up, code and tests when there are none.
Defense need ≥ 50%
A 4-question conversation with the AI examiner about your code. It isn't a trick: if you did it and understood it, it's the easy part. A weak defense on strong work gets you a new variant to redo.

