Learn
AI features 🤖 AI-on 💻 On your computer ⏱ ~6h Difficulty 3/5 v1

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.

Join free to start → Read the brief and materials. Join Build and Ship an AI App to start, submit and ask the tutor. Log in

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:

  1. Each person signs in as themselves, with a personal token. The token acts as that user.
  2. Exactly the web app's permissions. Tools run through the same registry and hub/services.py as the web assistant. A member never sees more over MCP than on the web page.
  3. 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

  1. The MCP endpoint POST /mcp: a Django view that speaks JSON-RPC 2.0 and MCP.
  2. Personal tokens: a model for them (stored hashed), a page /account/mcp-tokens/ to create and revoke them, and a command python manage.py mcp_token <username>.
  3. 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.
  4. Your own tests (at least 3, all passing).
  5. A real client: connect Claude or Codex to your server, use it, and describe what happened.
  6. 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 assistant and its PendingAction model: 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 with Content-Type: application/json and one JSON object. (A text/event-stream answer 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 as notifications/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 a description: a full sentence on what it does and when to use it;
  • inputSchema: a JSON schema object ("type": "object", properties with a type for each argument, required with exactly the required arguments). Never a user argument: the token decides who the tool acts as;
  • annotations: "readOnlyHint": true on 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):
  • GET lists the user's own tokens by name (never their value);
  • POST with the form field name creates a token and shows it once, in an element with id="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 with claude mcp list, or /mcp inside 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 for grace and ask the client which tools it has: list_pending_approvals is 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.md or GEMINI.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.md with these sections: 1. My MCP server: how one POST to /mcp works in your code, from the checks to the answer; how tools/list and tools/call use 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

  1. Hidden tests drive your /mcp with 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).
  2. 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.
  3. 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)

  1. Read the required materials (about 1.5 hours).
  2. Read assistant/tools.py, assistant/agent.py (propose), eval/mcptest.py and the public tests. Run neugen test (30 minutes).
  3. With your agent: the token model, the command and the 401 answers, with tests (1 hour).
  4. The endpoint: initialize, notifications, tools/list, tools/call, the errors (1 hour).
  5. The role rule, your staff tool, the write path, the token page (1 hour).
  6. 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 curl before 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).