IamBishal

Module 4Lesson 1 of 1Project

4.1 Ship it: contract tests, audit and a breaking-change gate

Make Helpline shippable. Commit a schema snapshot that fails CI on breaking changes, and write one redacted audit record per tool call. Add per-caller rate limits that answer with results the model can read, build a non-root Docker image and connect Claude Code and Claude Desktop. Finish with what a green build proves and what it doesn't.

Helpline works. Lessons 2 to 4 built task-shaped tools, bounded every response and put OAuth in front of it. Shipping it means something different: making sure tomorrow's change can't silently break the hosts and models that depend on it, knowing who did what through it, keeping one caller from exhausting it, and running it somewhere other than your laptop. This project lesson does all four, then says plainly what a green build proves and what it doesn't.

By the end of this lesson you will be able to:

  1. capture Helpline's contract through the in-process Client, commit it, and check it on every build
  2. make the gate go red with a realistic breaking change, and tell breaking changes from additive ones
  3. write one redacted audit record per tool call
  4. add per-caller rate limits that answer with a tool-result error the model can read
  5. build and run a non-root container image, and check it end to end
  6. connect Claude Code over Streamable HTTP and Claude Desktop over stdio
  7. turn what a green build doesn't prove into a release checklist

Before you start. You need Lessons 1 to 4. The companion folder is Lesson 4's code plus helpline/ops.py, helpline/contract.py, contract/helpline-contract.json, check_contract.py, scripts/simulate_breaking_change.py, scripts/smoke_http.py, stdio_main.py, a Dockerfile with Dockerfile.dockerignore, clients/ and ci/github-actions.yml. It has 62 tests. Every listing and output below comes from that folder, run on Python 3.12 with mcp 2.3.0 on 2026-11-21.

1. What counts as a breaking change to an MCP server

An MCP server's contract is what MCP clients and models rely on: tool names, input and output schemas, annotations, the scopes each tool needs, and resource templates. A breaking change makes a call that worked yesterday fail, or a response an MCP client parsed yesterday unreadable. Removing a tool, adding a required input, lowering a maximum, dropping an output field or demanding a new scope all break. A new tool, a new optional input or a new output field don't: old MCP clients can ignore them.

Descriptions are a special case. Changing one breaks no parser, but the model reads descriptions as instructions, and Lesson 1 listed tool-description poisoning as a threat. So Helpline's gate lists every description change for a person to review.

2. Capturing Helpline's contract through the in-process Client

The contract is captured from the running server, not parsed from source, so it's exactly what an MCP client sees. helpline/contract.py:

python
async def capture(server: MCPServer) -> dict[str, Any]:
    """The contract as a client sees it, with a stable key order."""
    async with Client(server) as client:
        tools = (await client.list_tools()).tools
        templates = (await client.list_resource_templates()).resource_templates
    return {
        "tools": {
            t.name: {
                # cleandoc: Python 3.13 strips docstring indentation at compile time and
                # 3.12 doesn't, so normalise or the snapshot depends on the interpreter.
                "description": inspect.cleandoc(t.description or ""),
                "input": _clean(t.input_schema),
                "output": _clean(t.output_schema),
                "read_only": bool(t.annotations and t.annotations.read_only_hint),
                "scopes": TOOL_SCOPES.get(t.name, [READ_SCOPE]),
            }
            for t in sorted(tools, key=lambda t: t.name)
        },
        "resource_templates": sorted(t.uri_template for t in templates),
    }

_clean inlines local $refs and drops title keys, so two schemas compare by meaning rather than by how pydantic laid them out. scopes comes from Lesson 4's TOOL_SCOPES, because a scope requirement is part of the contract even though it isn't in the schema.

The cleandoc comment records a real failure. The snapshot was first written on Python 3.13; run on 3.12, the gate reported every multi-line description as changed. Python 3.13 removes the common leading indentation from docstrings when it compiles them, and 3.12 keeps it, so the same source produced different descriptions. Normalising makes the gate pass on both. It also means the descriptions your model receives depend on the interpreter, which is worth knowing when you compare traces across environments.

check_contract.py compares the running server with the committed contract/helpline-contract.json:

python
async def main(update: bool) -> int:
    current = await capture(build_server(kb_delay_seconds=0))
    if update or not SNAPSHOT.exists():
        write_snapshot(current)
        print(f"wrote {SNAPSHOT.name}")
        return 0
    breaking, additive = compare(load_snapshot(), current)
    for line in additive:
        print(f"  additive  {line}")
    for line in breaking:
        print(f"  BREAKING  {line}")
    if breaking:
        print(f"{len(breaking)} breaking change(s). Fix them, or ship a new version on purpose.")
        return 1
    print("contract OK" + (" (run --update to record the additive changes)" if additive else ""))
    return 0

On a clean tree:

bash
uv run python check_contract.py
text
contract OK

3. Making the gate go red on purpose

compare() encodes the rules from the first section. Here is the part for inputs:

python
        # Inputs: a call that was valid must stay valid.
        was_in, now_in = was["input"]["properties"], now["input"]["properties"]
        was_req = set(was["input"].get("required", []))
        now_req = set(now["input"].get("required", []))
        for arg in was_in.keys() - now_in.keys():
            breaking.append(f"{where}: input {arg} removed")
        for arg in now_req - was_req:
            breaking.append(f"{where}: input {arg} is now required")
        for arg in now_in.keys() - was_in.keys() - now_req:
            additive.append(f"{where}: optional input {arg} added")
        for arg in was_in.keys() & now_in.keys():
            a, b = was_in[arg], now_in[arg]
            if _type(a) != _type(b):
                breaking.append(f"{where}: input {arg} changed type")
            removed = set(_enum(a)) - set(_enum(b))
            if removed:
                breaking.append(f"{where}: input {arg} no longer accepts {sorted(removed)}")
            if b.get("maximum", float("inf")) < a.get("maximum", float("inf")):
                breaking.append(f"{where}: input {arg} maximum lowered")
            if b.get("minimum", float("-inf")) > a.get("minimum", float("-inf")):
                breaking.append(f"{where}: input {arg} minimum raised")

Outputs follow the same idea in reverse: a removed field, a field no longer always present, or a changed type breaks, and a new field is additive. Behaviour and permissions come last:

python
        # Behaviour and permissions.
        if was["read_only"] and not now["read_only"]:
            breaking.append(f"{where}: was read-only, now writes")
        for scope in set(now["scopes"]) - set(was["scopes"]):
            breaking.append(f"{where}: now needs scope {scope}")

A changed description is listed as description changed (review it).

scripts/simulate_breaking_change.py makes the kind of tidy-up that looks harmless in review: it renames get_ticket's ticket_id to id and drops total from search_tickets. Then it runs the comparison:

bash
uv run python scripts/simulate_breaking_change.py; echo "exit=$?"
text
  BREAKING  tool get_ticket: input ticket_id removed
  BREAKING  tool get_ticket: input id is now required
  BREAKING  tool search_tickets: output total removed
  BREAKING  tool search_tickets: output total is no longer always present
exit=1

Exit code 1 is what fails a CI job. The test suite runs the same check on every pytest run, and fails on additive changes too until someone records them, so nothing in the contract changes without a person running uv run python check_contract.py --update and committing the new snapshot:

python
@pytest.mark.anyio
async def test_server_matches_the_committed_contract():
    breaking, additive = compare(load_snapshot(), await capture(build_server(kb_delay_seconds=0)))
    assert breaking == []
    assert additive == [], "run `uv run python check_contract.py --update` and commit the result"

Other tests in tests/test_ship.py feed compare() hand-edited contracts: a removed tool, a new optional input, a narrower limit and enum, a new scope on draft_reply, and a reworded description, each with the exact line it must produce.

4. One audit record per tool call

An audit record answers "who did what through this server, and what happened". helpline/ops.py implements it as SDK server middleware, which wraps every request that reaches the server's request handling, on stdio and HTTP alike, before the tool runs. Over HTTP that means after authentication: a request refused with 401 or 403 never gets this far. Middleware receives the request context and a call_next function; ctx.method is the JSON-RPC method and ctx.params the raw parameters:

python
@dataclass
class AuditMiddleware:
    """Write one JSON audit record per tools/call: who, what, outcome, how long."""

    sink: Callable[[dict[str, Any]], None] = field(
        default=lambda record: audit_log.info(json.dumps(record))
    )
    clock: Callable[[], float] = time.monotonic

    async def __call__(self, ctx, call_next):
        if ctx.method != "tools/call":
            return await call_next(ctx)
        params = ctx.params or {}
        subject, client_id = caller()
        record: dict[str, Any] = {
            "at": datetime.now(UTC).isoformat(timespec="seconds").replace("+00:00", "Z"),
            "request_id": ctx.request_id,
            "subject": subject,
            "client_id": client_id,
            "tool": params.get("name"),
            "arguments": _redact(params.get("arguments") or {}),
        }
        started = self.clock()
        try:
            result = await call_next(ctx)
        except Exception as exc:
            record |= {"outcome": "protocol_error", "error": type(exc).__name__}
            raise
        else:
            is_error = isinstance(result, dict) and result.get("isError")
            record["outcome"] = "tool_error" if is_error else "ok"
            return result
        finally:
            record["duration_ms"] = round((self.clock() - started) * 1000, 1)
            self.sink(record)

caller() reads the verified token from Lesson 4 and returns ("local", "stdio") when there is none. _redact copies only the arguments in AUDITED_ARGS (ticket_id, status, severity, customer, article_ids, limit) and records free text such as a reply or a search query only as its length, because it may hold customer data. The token itself never appears. Here is a real record from the container in the next section:

text
helpline.audit {"at": "2026-11-20T19:31:31Z", "request_id": 2, "subject": "agent-maria", "client_id": "claude-code", "tool": "search_tickets", "arguments": {"query": "<7 chars>", "status": "open"}, "outcome": "ok", "duration_ms": 2.2}

The audit test proves redaction with a deliberately sensitive reply:

python
@pytest.mark.anyio
async def test_audit_keeps_ids_but_not_free_text():
    records = []
    server = build_server(kb_delay_seconds=0, middleware=[AuditMiddleware(sink=records.append)])
    async with Client(server) as client:
        await client.call_tool(
            "draft_reply",
            {"ticket_id": "HL-1003", "message": "Customer's secret detail: card 4242."},
        )
    args = records[0]["arguments"]
    assert args["ticket_id"] == "HL-1003"
    assert args["message"] == "<36 chars>"
    assert "4242" not in str(records)

Another test checks that a failed get_ticket is recorded with outcome tool_error and that tools/list leaves no record.

Know the record's limits. It has no scope field: the scope a call needed follows from the tool name through TOOL_SCOPES, so add the token's scopes to the record if your auditors want the grant itself. And it only sees calls that passed authentication. Rejected tokens and missing scopes are answered at the HTTP layer, so log those there (uvicorn's access log already records the 401 and 403 status codes) if you need a trail of refused attempts. For the confused-deputy row of Lesson 1's checklist, the record is what shows which subject acted through Helpline's authority. Over stdio, audit records must not go to stdout. stdio_main.py sends all logging to stderr:

python
if __name__ == "__main__":
    # stdout carries JSON-RPC; logs (including audit records) go to stderr.
    logging.basicConfig(stream=sys.stderr, level=logging.INFO, format="%(name)s %(message)s")
    build_server().run("stdio")

5. Rate limits the model can read and act on

The tools spec requires servers to rate-limit tool invocations. Helpline uses a token bucket per caller and per kind of call: 60 reads and 5 writes a minute by default, each starting with a full burst.

python
@dataclass
class RateLimitMiddleware:
    """Per caller: 60 reads and 5 writes a minute by default, each with a full burst."""

    reads_per_minute: int = 60
    writes_per_minute: int = 5
    clock: Callable[[], float] = time.monotonic
    buckets: dict[tuple[str, str], TokenBucket] = field(default_factory=dict)

    async def __call__(self, ctx, call_next):
        if ctx.method != "tools/call":
            return await call_next(ctx)
        tool = (ctx.params or {}).get("name", "")
        kind = "write" if tool in WRITE_TOOLS else "read"
        per_minute = self.writes_per_minute if kind == "write" else self.reads_per_minute
        subject, _ = caller()
        bucket = self.buckets.setdefault(
            (subject, kind), TokenBucket(capacity=per_minute, refill_per_second=per_minute / 60)
        )
        wait = bucket.take(self.clock())
        if wait:
            # A tool-result error: the model can read it and back off.
            return {
                "content": [
                    {
                        "type": "text",
                        "text": f"Rate limit: {per_minute} {kind} calls a minute. "
                        f"Retry {tool} in {wait:.0f}s.",
                    }
                ],
                "isError": True,
                "resultType": "complete",  # every 2026-07-28 result says what kind it is
            }
        return await call_next(ctx)

The limit is keyed on the token's subject, not the client IP, because behind a proxy every caller shares one IP. When a caller runs out, the middleware answers with a tool-result error instead of calling the tool. The model reads "Retry draft_reply in 30s" and can wait or tell the user.

The resultType line was found the hard way. The first version omitted it, and the SDK's own result validation rejected the dictionary with "resultType Field required". Every 2026-07-28 result must say what kind it is.

With writes_per_minute=2 and a fake clock, the third draft_reply is refused, a read still works, and half a minute later one write is allowed again:

text
Rate limit: 2 write calls a minute. Retry draft_reply in 30s.

build_server() installs [AuditMiddleware(), RateLimitMiddleware()] by default, outermost first, so rate-limited calls are audited too.

Audit is the outermost middleware, so calls refused by the rate limiter still get an audit record.

This limiter keeps its buckets in process memory. Run two replicas and each has its own buckets, so a caller gets twice the limit. A multi-replica deployment needs a shared store, such as Redis, or a limit at the gateway.

6. Packaging Helpline as a non-root container

The Dockerfile builds from the series folder, because pyproject.toml and uv.lock live there:

dockerfile
FROM python:3.12-slim

COPY --from=ghcr.io/astral-sh/uv:0.12 /uv /usr/local/bin/uv

WORKDIR /app
ENV UV_COMPILE_BYTECODE=1 UV_LINK_MODE=copy UV_PROJECT_ENVIRONMENT=/opt/venv

# Dependencies first, so code changes don't reinstall them.
COPY pyproject.toml uv.lock ./
RUN uv sync --frozen --no-dev --no-install-project

COPY 03-production/05-ship-it/ ./server/
WORKDIR /app/server

# Run as an unprivileged user.
RUN useradd --system --uid 10001 helpline
USER helpline

ENV PORT=8000
EXPOSE 8000
CMD ["/opt/venv/bin/python", "main.py", "--host", "0.0.0.0"]

COPY 03-production/05-ship-it/ copies the whole lesson folder, so anything sitting in it would land in an image layer, including a dev key. Dockerfile.dockerignore, next to the Dockerfile, keeps credentials and caches out. BuildKit reads a file with that name for this Dockerfile, which matters here because the build context is the series folder:

text
# Used by BuildKit for this Dockerfile (the build context is the series folder).
# Keep dev credentials, caches and environments out of every image layer.
**/*.pem
**/token.txt
**/.venv
**/__pycache__
**/.pytest_cache

To check it, a dummy dev-issuer.pem and token.txt were placed in the lesson folder before a build, and the image's folder was listed. Neither file is there:

bash
docker run --rm --entrypoint ls helpline-mcp -a /app/server
text
.
..
.gitignore
Dockerfile
Dockerfile.dockerignore
README.md
check_contract.py
ci
clients
contract
data
helpline
issue_token.py
main.py
scripts
stdio_main.py
tests

--frozen installs exactly what uv.lock records. main.py binds to 127.0.0.1 unless told otherwise, which would be unreachable from outside a container, hence --host 0.0.0.0.

Containerising found a second bug. In dev mode, Lesson 4's main.py writes the test issuer's key to .dev-issuer.pem next to itself, and the unprivileged user can't write to /app/server, so the container exited with PermissionError: [Errno 13] Permission denied: '/app/server/.dev-issuer.pem'. Lesson 5's main.py reads the key's path from HELPLINE_DEV_KEY, so a key can be supplied from outside. Dev mode also has to be switched on with HELPLINE_DEV=1; with neither dev mode nor the production variables, the container refuses to start rather than trust a key it made up:

text
Set HELPLINE_ISSUER and HELPLINE_JWKS_URI for a real authorization server, or HELPLINE_DEV=1 to trust the local test issuer.

In production you set HELPLINE_ISSUER, HELPLINE_JWKS_URI and HELPLINE_RESOURCE_URL, and no key exists in the container at all.

The end-to-end check, run with Docker 29.6.1 from the series folder. The dev key and token are kept outside the build folder, in a scratch directory, and the key is copied into the created container before it starts:

bash
docker build -f 03-production/05-ship-it/Dockerfile -t helpline-mcp .

SCRATCH=$(mktemp -d)
cd 03-production/05-ship-it
HELPLINE_DEV_KEY=$SCRATCH/dev-issuer.pem HELPLINE_RESOURCE_URL=http://127.0.0.1:8766/mcp \
  uv run python issue_token.py tickets:read > $SCRATCH/token.txt
chmod 644 $SCRATCH/dev-issuer.pem   # readable by the container's user; a throwaway dev key only

docker create --name helpline -p 127.0.0.1:8766:8000 -e HELPLINE_DEV=1 \
  -e HELPLINE_RESOURCE_URL=http://127.0.0.1:8766/mcp \
  -e HELPLINE_DEV_KEY=/tmp/dev-issuer.pem helpline-mcp
docker cp $SCRATCH/dev-issuer.pem helpline:/tmp/dev-issuer.pem
docker start helpline

Then check it from the host:

bash
curl -s http://127.0.0.1:8766/.well-known/oauth-protected-resource/mcp
json
{"resource":"http://127.0.0.1:8766/mcp","authorization_servers":["https://auth.helpline.test"],"scopes_supported":["tickets:read"],"bearer_methods_supported":["header"]}
bash
curl -si -X POST http://127.0.0.1:8766/mcp -H "Content-Type: application/json" -d "{}" | head -1
text
HTTP/1.1 401 Unauthorized
bash
docker exec helpline id
text
uid=10001(helpline) gid=999(helpline) groups=999(helpline)

The last check is a real MCP call. scripts/smoke_http.py connects with the token and calls search_tickets:

python
async def main(url: str, token: str) -> None:
    http = httpx2.AsyncClient(headers={"Authorization": f"Bearer {token}"})
    async with Client(streamable_http_client(url, http_client=http)) as client:
        print("protocol:", client.protocol_version)
        result = await client.call_tool("search_tickets", {"query": "webhook", "status": "open"})
        print("tickets:", [t["id"] for t in result.structured_content["tickets"]])
bash
uv run python scripts/smoke_http.py http://127.0.0.1:8766/mcp "$(cat $SCRATCH/token.txt)"
text
protocol: 2026-07-28
tickets: ['HL-1003']

docker logs helpline 2>&1 | grep helpline.audit then shows the audit record quoted earlier.

Delete $SCRATCH when you're done; it holds dev credentials. Making the key world-readable is acceptable only because it's a throwaway dev key on your own machine.

7. Connecting Claude Code and Claude Desktop

For Claude Code over Streamable HTTP, clients/claude-code.md gives:

bash
TOKEN=$(uv run python issue_token.py tickets:read)
claude mcp add --transport http helpline http://127.0.0.1:8000/mcp \
  --header "Authorization: Bearer $TOKEN"

The check for this lesson used the same command with two differences: the server ran on port 8765 (PORT=8765), and it was registered under the name helpline-tutorial-check so it couldn't clash with an existing entry. claude mcp list then reported:

text
helpline-tutorial-check: http://127.0.0.1:8765/mcp (HTTP) - ✔ Connected

The entry was removed afterwards with claude mcp remove helpline-tutorial-check.

The server's log showed the sequence from Lesson 4: a GET of the protected resource metadata, a POST answered 401, then authenticated POSTs answered 200. The dev token lasts an hour and the --header stores it in Claude Code's configuration, so treat it as a short-lived test credential, never a long-lived one. A production host would run the OAuth flow itself.

For Claude Desktop, clients/claude_desktop_config.json starts the stdio entry point:

json
{
  "mcpServers": {
    "helpline": {
      "command": "uv",
      "args": [
        "run",
        "--directory",
        "/absolute/path/to/build-a-production-mcp-server/03-production/05-ship-it",
        "python",
        "stdio_main.py"
      ]
    }
  }
}

That config is provided but wasn't run for this lesson. Over stdio there's no token, so scopes don't apply: whoever starts the process is the caller. Only give the stdio entry point to people allowed to escalate. The SDK also serves hosts that still speak the previous protocol revision, so older hosts can connect.

8. Wiring the gate into CI

ci/github-actions.yml is a workflow to copy into your server's repository. Its job, without the name, on and permissions header:

yaml
jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v7
      - uses: astral-sh/setup-uv@v7
      - run: uv sync --frozen
      - name: Lint
        run: uvx ruff check . && uvx ruff format --check .
      # The gate runs first so a breaking change fails a step that names it.
      # (The test suite checks the contract too, and also fails on unrecorded
      # additive changes, which this step only lists.)
      - name: Contract gate
        run: uv run python check_contract.py
      - name: Tests (no network, no keys)
        run: uv run pytest

The order matters. A breaking change fails the "Contract gate" step, so the red build names the cause, and later steps don't run. An additive change passes that step, because check_contract.py only lists additive changes, and then fails in "Tests", where test_server_matches_the_committed_contract insists the snapshot is updated. The tests need no network and no keys: the token tests use the local test issuer and a server on localhost. The workflow doesn't build the image; that was built and checked by hand in the previous section. Add a docker build step once your repository's layout is settled.

A breaking change fails the contract gate step by name, and the image is never built.

9. What a green build proves, and what it doesn't

A green build provesIt doesn't prove
The contract matches the committed snapshotThat a changed description is safe; the gate only makes it visible to a reviewer
Nothing in Helpline's own contract changed unreviewedAnything about descriptions on other MCP servers the same host connects to
Tokens with a wrong audience, issuer, key or expiry are refused, against the test issuerThat your production authorization server issues tokens the way the test issuer does
Scopes are enforced per tool, and a caller sees only the customers in its helpline_customers claimThat the scopes and customer lists your authorization server issues match your organisation's roles and accounts
Budgets, timeouts and cancellation behave (Lesson 3's tests run here too)Behaviour under real load, or with a real slow service
Per-caller rate limits answer with a readable errorThat one process's limits hold across replicas
Tools return what their schemas promiseHow a model behaves: whether it picks the right tool, reads hints or backs off after a rate-limit result
escalate_ticket is idempotent for sequential retries: a second call returns the same escalation_id with already_escalated: true (test_escalation_is_idempotent, built in Lesson 2 and still in this folder's suite)Safety under concurrent retries: two calls at the same instant can both pass the existence check, so that needs a database constraint
Every authenticated tool call that reaches the server leaves a redacted audit recordThat refused requests are logged, or that the records are shipped, kept and read

That right-hand column is the release checklist:

  1. Point HELPLINE_JWKS_URI and HELPLINE_ISSUER at the real authorization server, and test one real token, one wrong-audience token and one expired token against the deployed server.
  2. Confirm the authorization server puts Helpline's URL in aud and grants tickets:escalate only to people allowed to escalate.
  3. Read every description change in the snapshot diff before approving it.
  4. Add a unique constraint on open escalations per ticket in the real ticketing system. Lesson 2's check-then-insert makes sequential retries safe; only the database can make concurrent ones safe.
  5. Send audit records to storage your team keeps and reviews.
  6. Move rate limiting to a shared store or the gateway before running more than one replica.
  7. Load-test the knowledge-base search against the real service and set its timeout from the results.

10. Common problems

test_server_matches_the_committed_contract fails with "description changed (review it)" on every tool. You ran on a different Python version from the snapshot's without cleandoc, or someone reworded descriptions. Read the diff, then uv run python check_contract.py --update.

A dev key ended up in the image. Check that Dockerfile.dockerignore sits next to the Dockerfile and that you build with BuildKit (the default in current Docker). A plain .dockerignore in the lesson folder is ignored, because the build context is the series folder.

The container exits with PermissionError on .dev-issuer.pem. Set HELPLINE_DEV_KEY to a readable key supplied from outside, or configure the production variables.

Docker refuses to mount the key file. Docker Desktop shares only some host folders. Use docker cp into a created container, as above, or move the key into a shared folder.

Rate-limit results fail with a validation error. The middleware's result is missing "resultType": "complete".

Claude Code shows the server as failing to connect. The dev token expired. Mint a new one, claude mcp remove helpline, and add it again.

11. Exercise: classify a change before CI does

Predict the gate's output for each change, then make it in a scratch copy and run uv run python check_contract.py:

  1. add an optional include_drafts: bool = False input to get_ticket
  2. lower search_knowledge_base's limit maximum from 5 (its current le=5) to 3
  3. make draft_reply require tickets:escalate too, by adding "draft_reply": [READ_SCOPE, ESCALATE_SCOPE] to TOOL_SCOPES in helpline/auth.py

Expected result. Each change was run once against the companion folder:

text
  additive  tool get_ticket: optional input include_drafts added
contract OK (run --update to record the additive changes)
text
  BREAKING  tool search_knowledge_base: input limit maximum lowered
1 breaking change(s). Fix them, or ship a new version on purpose.
text
  BREAKING  tool draft_reply: now needs scope tickets:escalate
1 breaking change(s). Fix them, or ship a new version on purpose.

The first exits 0 and the other two exit 1. Remember that uv run pytest would still fail on the first one until the snapshot is updated.

Hints. Undo each change before the next with git checkout -- ., or work on a fresh copy each time.

Verify each exit code with echo $? straight after the command.

12. What we learned, and where Helpline stands

Helpline is shippable: a contract gate that catches breaking changes and surfaces description edits, a redacted audit record for every tool call, per-caller rate limits the model can read, a non-root image checked end to end, and host configs. Lesson 1's four threats now each have a defence. Over-broad tools: task-shaped tools, tested. Token passthrough and the confused deputy: audience, scope and per-customer checks and Helpline's own credential, tested, with the audit record showing who acted through the server. Tool-description poisoning is the exception: for Helpline's own descriptions it is mitigated by review, with the snapshot as the trigger, and nothing automated judges whether a description is safe. Descriptions from other servers in the same host are out of Helpline's reach. The checklist above is what stands between this build and production.

Key Takeaways

  • Capture an MCP server's contract through the in-process Client and commit it as a schema snapshot
  • Classify contract changes as breaking, additive or description changes listed for review, including new required inputs and newly required scopes
  • Explain why a rename produces two breaking changes and needs a deprecation path
  • Refresh the snapshot in the same pull request as an additive change so later removals are caught
  • Write audit records from SDK middleware that keep ids, reduce free text to its length and go to stderr on stdio
  • State what the audit record doesn't cover: authentication failures rejected at the HTTP layer and the scope used
  • Return rate limits as results with isError set and resultType "complete", keyed on subject and client_id rather than client IP
  • Explain why an in-memory limiter stops enforcing per-caller limits with more than one replica
  • Build a non-root container and supply the dev key read-only instead of writing it at runtime
  • Register Helpline in Claude Code with a short-lived bearer token and verify it with claude mcp list
  • Separate what a green build proves from what it doesn't, and turn the gaps into a release checklist

Discussion

Ask questions, share what you learned, and help others.

    Loading discussion…

    Bishal SahaLet's build together

    Have a system to design, or an AI feature to get right?

    Tell me about the problem. You'll get a clear, honest view of the best way forward.

    • Reply within 24 hoursOn business days, with my honest view and a next step.
    • Accepting select engagementsArchitecture, AI features and full builds.
    • Remote, worldwideWorking with startups, SMEs and enterprises.