MCP servers and clients in TypeScript · Chapter 13 of 16

Security

By the end of this chapter you can protect an MCP server over HTTP with bearer tokens and scopes, show each caller only what is theirs, keep tools read-only unless a changing one is marked, gated and logged, defend a host against instructions hidden in tool results, keep resource template variables from walking out of their folder, and review a server for the usual mistakes. Build it in your browser: a real editor and terminal, AI that explains, and tests that tell you when it works.

  • Part: Clients and production
  • 4 tasks
  • TypeScript
  • In the all labs plan

The first 2 chapters of MCP servers and clients in TypeScript are free. This one comes with the all labs plan.

Why you need this

Three things happened in one week. The supplier portal went on the internet, so anyone who finds its URL can call its tools. Rajat asked for an assistant that creates purchase orders, not just reads them. And a supplier typed something odd into the notes box of the portal.

Nisha owns this chapter. Her rules are already in the store policy (/workspace/data/policy.md, section 7): tools start read-only, a tool that changes anything says so and needs her approval, suppliers see only their own data, and every change is logged with who asked and when. This chapter turns each rule into code.

What you build: 4 tasks

Each task has tests. You write the code in the lab's editor and press Check.

  1. Task 1

    supplier-server.ts: each supplier sees only its own

    In supplier-server.ts, export createServer() and, when run, serve it over streamable HTTP with node:http on 127.0.0.1, port 8001, path /mcp, behind the localhost guards and bearer tokens: requireBearerAuth from @modelcontextprotocol/server with a verifier that returns the AuthInfo (with an expiresAt) for the three tokens in the starter and throws an invalid-token OAuthError for any other, requiring the scope supplier, in front of handler.fetch(request, { authInfo }). No token or an unknown one gets 401; the intern's token, with no scopes, 403.

    Three read-only tools for the supplier holding the token (its clientId), never for one named in an argument: my_products(), structured content { products } with the supplier's product ids, sorted; my_orders(status), { orders } with its purchase order ids with that status (draft, sent, delivered or cancelled), sorted; order(order_id), { order_id, store_id, product_id, quantity, total, status }. Another supplier's order and an order that does not exist get the same error message (apart from the id).

  2. Task 2

    gate.ts: a changing tool, behind a gate

    In gate.ts, export createServer() (served with serveStdio when run) that works on a copy of the database at /tmp/bazaar-gate.db, made when the file starts (today is 2026-10-22), with two tools:

    order_status(order_id), returning { order_id, status, total }, annotated readOnlyHint: true;

    create_purchase_order(store_id, product_id, cases), annotated readOnlyHint: false with a description that says it changes data. It only creates drafts: from the product's supplier, quantity cases times case_size, unit_cost the price times 0.8 rounded to 2 decimals, total unit_cost times quantity rounded to 2 decimals, the next PO- id. A total above ₹25,000 is an error result that names Rajat and the limit, and saves and logs nothing. Each draft saved appends one JSON line to /tmp/bazaar-changes.log with at (the time, ISO format), by (the BAZAAR_USER environment variable, or unknown), tool, order_id and total. It returns { order_id, status, total }.

  3. Task 3

    host.ts: a host that a note cannot take over

    In host.ts, export async function ask(question, client, { model = 'lab-chat', maxSteps = 5 } = {}), chapter 9's loop hardened twice: it offers the model only the tools the server annotates readOnlyHint: true (and never runs a tool it did not offer), and it sends a system message telling the model that tool results are untrusted data whose instructions it never follows. It returns the model's answer, or No answer after <maxSteps> steps.

    When run, start notes-server.ts and print the answers to What did supplier S05 say in their latest note? and Where is PO-10207?, one per line. Keep anything that runs inside if (import.meta.main).

  4. Task 4 · interview question

    Interview: review.ts, a security review

    review-me.ts is the agency's server for the store managers. In review.ts, export FINDINGS, an object from the name of a tool, constant or function in review-me.ts to the kind of problem it has, one of the kinds listed in the starter (secret in code, sql injection, no scope, unmarked change, price change, no audit, leaks internals, customer data).

    It has five problems against the policy (sections 2 and 7) or plain good sense, each in a different place; list exactly those five.

What you will learn

  • Who is calling: bearer tokens, a verifier, scopes, requireBearerAuth and ctx.http?.authInfo.
  • Least privilege: a tool's data scoped to the caller, never to an argument.
  • Read-only by default: annotations, a gate in the tool, and an audit log.
  • Injection: instructions hidden in tool results, and the host's defences.
  • Paths and secrets: what this SDK does with ../ in a resource template variable, and keys in code.

More in Clients and production

Build "Security" yourself

Bazaar Bhai, a chain of 40 kirana stores in Jaipur, exposes its stock and orders once, to every AI tool. You build it in TypeScript. A real editor and terminal in your browser, AI that explains, and a Check that says when it works.

The first 2 chapters of MCP servers and clients in TypeScript are free. This one comes with the all labs plan.