Skip to content

16 min read

MCP: how to expose your backend to AI agents

In one sentence: MCP (Model Context Protocol) is a protocol that lets any AI agent discover a server's tools and use them, without writing a connector for every pair. The shop opens an MCP door at POST /mcp: with its API key, Fast Delivery sees four tools, and the price comparison site, two.

What you will learn

  • Explain what problem MCP solves and what the host, the client and the server do.
  • Tell tools, resources and prompts apart, and read the JSON-RPC messages of initialize, tools/list and tools/call.
  • Set up a stateless MCP server inside your API, with Streamable HTTP, and try it with curl and with the MCP Inspector.
  • Protect an MCP server with API keys and roles, knowing that the protocol doesn't decide who can do what.

Before you start, read: 03-tool-use.md phase-6/05-authorization.md

Imagine that Fast Delivery, the delivery company from Phase 6, swaps its program for an agent: a program in which a language model, like Claude, decides which tools to use until it finishes a task. Theirs checks which orders need delivering and marks them as shipped. A price comparison site wants its agent to browse your catalog. And you want to ask Claude Code what’s left to ship.

Your assistant’s tools, from lesson 3, live inside your loop: those agents can’t use them. You would have to write a connector for each agent, and each agent, one for each service.

MCPMCP stands for Model Context Protocol.An open protocol that lets an AI agent discover a server’s tools and use them, whichever the agent and whichever the server. Underneath it’s JSON-RPC messages: tools/list to see the list, tools/call to use one. Anthropic published it in 2024.Go to definition (Model Context Protocol) is the agreement that avoids it. Anthropic published it on November 25, 2024 as an open standard: an agent that speaks MCP uses any server that speaks MCP. In this lesson, the shop becomes one.

The analogy

A few years ago, every phone had its own charger, and a friend’s was no use to you. With USB-C, any charger charges any phone and many laptops: manufacturers don’t agree pair by pair, they all follow the same standard.

MCP is that standard for agents: an agent that speaks it connects to any server that follows it.

Where the analogy breaks down

  • A plug doesn’t say what the device does. An MCP server does: the agent asks for the list of tools, each with a description for the model.
  • Anyone with a cable can plug in. An MCP server has to decide who gets in and what they can do: the protocol doesn’t decide that for you.
  • A charger decides nothing. On the other side of MCP, a model chooses which tool to use, and it can get it wrong or be tricked.

Three agents (Claude Code, Fast Delivery’s and the price comparison site’s) and four services (the shop, GitHub, a calendar and a database):

Without a common protocol With MCP
What gets written A connector for every pair of agent and service An MCP client per agent and an MCP server per service
3 agents and 4 services 3 × 4 = 12 connectors 3 + 4 = 7 pieces
One more agent arrives 4 more connectors 1 more client

The price comparison site’s agent knows nothing about your shop: speaking MCP is enough.

  • The host is the application the person uses, with the model inside: Claude Code, Claude Desktop or Fast Delivery’s agent.
  • The client is the part of the host that keeps the connection with one server. A host connected to three servers has three clients.
  • The server is the program that offers the tools. Here, the shop, at POST /mcp.

The model never talks to the server. A question in Claude Code connected to the shop:

  1. Host (Claude Code) → Shop (MCP server)tools/list
  2. Shop (MCP server) → Host (Claude Code)four tools,
    with their description and schema
  3. Person → Host (Claude Code)“Which orders are there to ship?”
  4. Host (Claude Code) → Modelthe question and the tools
  5. Model → Host (Claude Code)tool_use: orders_to_ship
  6. Host (Claude Code) → Shop (MCP server)tools/call orders_to_ship
  7. Shop (MCP server) → Host (Claude Code)the orders, in JSON
  8. Host (Claude Code) → Modeltool_result with the orders
  9. Model → Host (Claude Code)the answer for the person

In the middle, lesson 3’s tool_use and tool_result. MCP is the two sides: how the host knows which tools there are and how it calls them. To the model, a tool from an MCP server is one more tool.

What a server offers: tools, resources and prompts

Section titled “What a server offers: tools, resources and prompts”

An MCP server can offer three things, and someone different decides to use each one:

What What it is Who decides to use it An example
Tools Functions that do or look something up The model search_products, mark_shipped
Resources Data to read, each with its address (a URI) The application, or the person who attaches it A file, a help page
Prompts Message templates with gaps The person, by picking one from a menu “Summarize today’s orders”

The shop only offers tools: what an agent that acts needs.

Every MCP message is JSON-RPCJSON stands for JavaScript Object Notation.A way to call a function in another program with a JSON message: the function’s name (method), its arguments (params) and an id, which the response repeats. A message without an id is a notification and expects no response. RPC stands for remote procedure call.Go to definition 2.0: calling a function of another program with a JSON message. It’s the idea of gRPC, from Phase 4, in text you can read. This is how a client asks the shop to search for caps:

{
"jsonrpc": "2.0",
"id": 3,
"method": "tools/call",
"params": { "name": "search_products", "arguments": { "query": "cap" } }
}
  • method: the function being called. params: its arguments.
  • id: a number the client chooses. The response carries the same one: that’s how it knows which response belongs to which question.
  • The response brings result, or error with a code and a sentence if the message isn’t valid.
  • A message without an id is a notification: it reports something and expects no response.

And this is how the shop answered:

{
"result": {
"content": [
{
"type": "text",
"text": "[{\"id\":4,\"name\":\"Cap\",\"priceCents\":1500,\"stock\":15}]"
}
]
},
"jsonrpc": "2.0",
"id": 3
}

result.content is a list of blocks. Here, one text block with the result as JSON inside (the \" are its quotes): any client can read text.

Before asking for anything, client and server introduce themselves:

  1. Client → Shop (MCP server)initialize: I speak version 2025-11-25,
    I'm curl, I can do this
  2. Shop (MCP server) → Clientwe use 2025-11-25,
    I'm shop-api, I offer tools
  3. Client → Shop (MCP server)notifications/initialized (no id)
  4. Shop (MCP server) → Client202, no body
  5. Client → Shop (MCP server)tools/list, tools/call…
    with MCP-Protocol-Version: 2025-11-25
  6. Shop (MCP server) → Clienteach response, with its question's id

The protocol version is a date, the one of the specification both follow: on November 21, 2026, the shop answered 2025-11-25. notifications/initialized has no id, and gets a 202 Accepted with no body.

MCP has two ways of carrying the messages, two transports:

  • stdio: the host starts the server on your computer, and they talk through stdinStandard input, the channel through which a program receives data. Unless you say otherwise, it’s what you type; with a pipe, it’s what the previous program writes.Go to definition and stdoutStandard output, the channel through which a program writes its results. Unless you say otherwise, it goes to the screen; it can be sent to a file or to another program.Go to definition. For local tools, like one that reads your files.
  • Streamable HTTP: the server is on the network. Each message is a POST to a single address, and the response, a JSON or a stream of SSESSE stands for Server-Sent Events.A way for the server to notify the client as soon as something happens. The client makes a normal HTTP request and the server leaves the response open, writing an event into it, a few lines of text, every time there’s news. It only goes one way, from the server to the client.Go to definition events like the ones in lesson 2.

The shop uses Streamable HTTP, with the official MCP SDK for TypeScript, in src/mcp.ts:

src/mcp.ts
// Each POST, its own server and transport, with this request's key. sessionIdGenerator: undefined
// is stateless mode (there's no Mcp-Session-Id header), and enableJsonResponse: true makes each
// response a whole JSON, instead of a Server-Sent Events stream: these tools answer at once, and
// nginx needs nothing special (nginx/shop.conf). The transport works with the web's Request and
// Response (fetch's): the same as Hono's, so it takes the request as is (c.req.raw). It makes its
// response itself, not Hono, and it lacks what the shop had already set with c.header(), like
// requestId()'s X-Request-Id (app.ts): c.newResponse makes it again, with its status, its body and
// its headers, and those too.
mcp.post('/', async (c) => {
const server = createServer(c.var.apiKey!, c.get('requestId'));
const transport = new WebStandardStreamableHTTPServerTransport({
sessionIdGenerator: undefined,
enableJsonResponse: true,
});
await server.connect(transport);
try {
const response = await transport.handleRequest(c.req.raw);
return c.newResponse(response.body, response);
} finally {
// The response is already whole: this request's server and transport are no longer needed.
await server.close();
}
});
// GET would open a stream for the server to send messages whenever it wants, and DELETE would close
// a session. Stateless, there's neither: 405, as the SDK recommends, and in Allow, what there is.
// An MCP client understands the GET's 405 and carries on without that stream.
mcp.all('/', (c) =>
httpProblem(c, 405, 'This MCP server keeps no sessions: it only accepts POST', {
Allow: 'POST',
}),
);
  • Each POST creates its own server and transport, with that request’s key, and throws them away at the end. It’s StatelessSaid of a server that remembers nothing from one request to the next. Each request carries everything needed to understand it, such as who you are or which page you want, and that’s why any copy of the server can handle it. What it does keep is the data, such as the orders.Go to definition mode: there’s no Mcp-Session-Id header, and it doesn’t matter which copy of the API answers, as in Phase 9.
  • enableJsonResponse: true: the response, a whole JSON, not a stream. nginx needs nothing special.
  • GET and DELETE would open a stream and close a session: with no sessions, 405.

The client has to send Accept: application/json, text/event-stream. With only one type, 406 Not Acceptable.

This is how the shop registers search_products:

src/mcp.ts
// The catalogue's two, for any key. The description is for the agent: it reads it to decide when
// to use it, what to pass and how to read what it returns. The Zod schema does two jobs: the SDK
// turns it into the JSON Schema the agent sees in tools/list, and checks each call against it
// before running anything (one that doesn't match never gets here: the agent gets isError with
// what fails). annotations are hints for the client (readOnlyHint: it only reads, and a client
// may use it without asking the person), never security: the security is the key.
server.registerTool(
'search_products',
{
title: 'Search products',
description:
"Searches the shop's catalogue for products by name. Search by one word of the name, in the singular (mug, hoodie, cap): it doesn't understand sentences or descriptions. Returns a JSON list of at most 10 products, each with its id, its name, its price in euro cents (priceCents: 850 is €8.50) and the units left (stock: 0 means it's sold out). An empty list means there's none with that name.",
inputSchema: z.strictObject({
query: z
.string()
.trim()
.min(1)
.max(100)
.describe("One word of the product's name, in the singular: mug, t-shirt, hoodie."),
}),
annotations: { readOnlyHint: true },
},
// The same function as the assistant's search_products tool.
async ({ query }) =>
use('search_products', async () => asJson(await searchProductsByName(query))),
);
  • description is for the model: it reads it to decide when to use it, what to pass and how to read what it returns.
  • inputSchema, the Zod schema, does two jobs. The SDK turns it into the JSON SchemaJSON stands for JavaScript Object Notation.A format, written in JSON, to describe what a piece of JSON data must look like: which fields it has, the type of each and which are required. A program can use it to validate data automatically.Go to definition the agent sees in tools/list, and checks every call against it before running anything.
  • annotations: { readOnlyHint: true } is a hint for the client, “it only reads”: it may use it without asking the person. It’s never security.
  • searchProductsByName is the same function the assistant uses: one way to search, two doors.

What each tool returns goes through two helpers:

src/mcp.ts
// What an MCP tool returns: a list of content blocks. Here, one text block with the result as JSON,
// which any agent can read. Always bounded: at most 10 products, 50 orders or a single one. (MCP
// also has structuredContent, with an output schema; text is understood by every client, including
// the ones that don't read it.)
const asJson = (data: unknown): CallToolResult => ({
content: [{ type: 'text', text: JSON.stringify(data) }],
});
// An error the agent has to see: isError: true, and a sentence that says what happened, so it can
// decide what to do (try another id, tell the person). It isn't a protocol error: the call arrived
// fine, and it's the tool that couldn't do it.
const failure = (text: string): CallToolResult => ({
content: [{ type: 'text', text }],
isError: true,
});
// The largest number a PostgreSQL integer column holds, as in get_order: no id can be larger.
const MAX_ID = 2_147_483_647;
const idSchema = (description: string) =>
z.number().int().positive().max(MAX_ID).describe(description);

asJson puts the result in a text block, and failure, a sentence with isError: true. Every result is bounded, to 10 products or 50 orders: it goes into the model’s conversation, and everything the model reads is paid for (lesson 1).

  • A protocol error comes in error, with a JSON-RPC code (-32601: that method doesn’t exist). The client reads it.
  • A tool error comes in result, with isError: true and a sentence. The model reads it and decides: try another id, tell the person.

With the shop’s SDK, an input that doesn’t match the schema, or a tool that doesn’t exist, is a tool error, with the code in the text: MCP error -32602: ….

If something breaks inside a tool, the agent gets a short sentence, and the log, the whole error. use does it:

src/mcp.ts
// Each tool works inside this function: one log line per call (which one, with which key and
// whether it failed; what the agent passed, no) and, if something breaks inside, a short sentence
// for the agent and the whole error to the log. Without this, the SDK would send the agent the
// error's message as is, with whatever it carries (an internal network address, a piece of SQL).
async function use(tool: string, work: () => Promise<CallToolResult>): Promise<CallToolResult> {
const data = { requestId, apiKey: apiKey.id, tool };
try {
const result = await work();
log.info({ ...data, error: result.isError === true }, 'an agent uses a tool (MCP)');
return result;
} catch (error) {
log.error({ ...data, err: error }, 'an MCP tool has failed');
return failure('The tool has failed: it cannot be looked up right now.');
}
}

Without it, the agent would get the error as is, with a SQL query or a server’s address inside.

Before MCP, the shop checks who’s calling, with the key that loadApiKey, Phase 6’s MiddlewareA function a server runs with the requests of the routes it’s registered on (all of them, or only some), before the code that answers them. It can answer the request itself or pass it on to the next one, and it sees the response on its way back. It’s used for what affects many requests, like writing them to the log, granting CORS permission or asking for a credential.Go to definition, already looked up:

src/mcp.ts
// Before MCP, the key: without an API key that exists (loadApiKey, in app.ts, has already looked it
// up), 401, with the same WWW-Authenticate header as the rest of the shop. Keys only: a person's
// session (the cookie, or its id as Bearer) doesn't work here, because an agent works with a role,
// not as a customer. The MCP specification also asks to check the Origin header, in case a website
// makes the browser call a password-less MCP server on your computer (DNS rebinding); here the key
// stops that, since the browser never sends it on its own.
mcp.use(async (c, next) => {
if (c.var.apiKey === undefined) {
return httpProblem(
c,
401,
'Identify yourself with a shop API key: Authorization: Bearer shop_…',
{
'WWW-Authenticate': 'Bearer realm="shop-api"',
},
);
}
await next();
});
  • Only an API keyAPI stands for Application Programming Interface.A long, random piece of text that identifies a program, not a person, when it calls an API. It travels with every request, usually in the Authorization header. A good server keeps only its hash, and to take away its access, deleting it is enough.Go to definition gets in, the one from Phase 6. An agent works with a role, like a company, not as a customer: Carmen’s session gets 401.
  • The 401 arrives before MCP, with the usual WWW-Authenticate header. Without a key, not even the list of tools.

The MCP specification proposes OAuthA standard that lets an app get limited permission on your account with another service, like viewing your photos, without knowing your password. You give the permission on the service’s own website, and the service hands the app a key that opens only that and that you can take back whenever you want.Go to definition 2.1, the one from Phase 6, for public servers. Claude Code and the MCP Inspector also accept a fixed header, and that’s what the shop uses.

From this step there’s one more role, catalogue, with no permissions at all: that of an agent that only browses the catalog. Migration 013 adds it:

src/permissions.ts
// catalogue (Phase 11, lesson 4) is only for API keys: a program that browses the catalogue (a
// price comparison site's agent, for example) and nothing else.
export type Role = 'customer' | 'delivery' | 'admin' | 'catalogue';
export type Permission =
| 'orders:create'
| 'orders:view-own'
| 'orders:view-all'
| 'orders:change-own' // change the quantity and cancel
| 'orders:change-all'
| 'orders:ship' // mark a paid order as shipped
| 'products:manage' // create and delete products
| 'notifications:configure' // where to notify of the paid orders (lesson 7)
| 'assistant:use'; // ask the shop's assistant (Phase 11)
// Each role, with just what its job needs (least privilege): the delivery company sees the orders
// and marks them as shipped, but it doesn't create products or cancel anything. If its key leaks,
// the damage stays at that. The assistant, only for customers: every question costs the shop money.
// catalogue has no permission at all: the catalogue is public, and its key only says who it is and
// lets it in through MCP (src/mcp.ts), where it only sees the catalogue's tools.
const PERMISSIONS: Record<Role, readonly Permission[]> = {
customer: ['orders:create', 'orders:view-own', 'orders:change-own', 'assistant:use'],
delivery: ['orders:view-all', 'orders:ship', 'notifications:configure'],
admin: ['orders:view-all', 'orders:change-all', 'orders:ship', 'products:manage'],
catalogue: [],
};

Each request’s server only registers the tools its key’s role can use. The order tools go inside an if, with the permissions of the /v2 routes:

src/mcp.ts
// This one changes something: no readOnlyHint, and a client may ask the person to confirm before
// using it. destructiveHint: false (it deletes nothing) and idempotentHint: true (calling it
// twice with the same id changes nothing more: the second says it's already shipped).
if (roleCan(apiKey.role, 'orders:ship')) {
server.registerTool(
'mark_shipped',
{
title: 'Mark an order as shipped',
description:
"Marks a paid order as shipped, once the delivery company has it. It only works on an order in the paid status: one pending payment, cancelled or already shipped doesn't change, and the tool says which status it's in. Returns the order, now in the shipped status. It can't be undone.",
inputSchema: z.strictObject({ id: idSchema('The order number: 13.') }),
annotations: { destructiveHint: false, idempotentHint: true },
},
// The same function as POST /v2/orders/{id}/shipment (data.ts).
async ({ id }) =>
use('mark_shipped', async () => {
const result = await shipOrder(id);
if (!('error' in result)) return asJson(result.order);
if (result.error === 'not-found') return failure('There is no order with that number.');
return failure(`The order is ${result.status}: only a paid one is shipped.`);
}),
);
}
Key Role What it sees in tools/list
Price comparison site catalogue search_products and get_product
Fast Delivery delivery Those two, plus orders_to_ship and mark_shipped
One of Ana’s or Luis’s admin All four

A tool the key can’t use doesn’t exist in its server. It doesn’t show up in the list, and if the agent calls it anyway, it gets Tool mark_shipped not found. And inside, mark_shipped only ships a paid order, whoever calls it.

From step 52, the one for lesson 6, there will be one more tool for any key, search_help: the price comparison site will see three, and Fast Delivery, five.

MCP carries the call; it doesn’t know who can do what. Your code decides: the key, its role and each tool’s rules, the usual AuthorizationDeciding whether whoever makes a request can do what they ask, like viewing an order or creating a product. It comes after authentication, on every request: first the server knows who you are, then what you can do.Go to definition. These protect nothing:

  • The description. “Only for the delivery company” is text for a model.
  • The annotations. They’re hints for the client, and the client is someone else’s.
  • The agent’s instructions. They aren’t yours, and a model can be tricked with text hidden in the data: lesson 3’s prompt injection.

An agent’s power is its key’s. For the price comparison site, catalogue; never admin “just in case.” It’s Phase 6’s Least privilegeThe rule of giving each user and each program only the permissions it needs, and no more. If something fails or someone gets in where they shouldn’t, the damage stays within the little it could touch.Go to definition: if the key leaks, or someone tricks the agent, the damage stays within what it could touch.

The goal: find out what an agent sees of your shop with each key, ship an order as Fast Delivery’s agent would, and check that the price comparison site’s can’t, even if it tries. Only the last part, which is optional, uses a model and costs money.

The outputs are from Node 26, on Linux, on November 21, 2026, on a MacBook with Docker in Colima. Your keys, orders and times will be different.

Put your project on step 50, as in the introduction:

Ventana de terminal
cd ~/backend-course/phase-3
curl -O https://backenddesdecero.com/practicas/shop-api/50-mcp.tar.gz
tar -xzf 50-mcp.tar.gz
cp -R 50-mcp/. shop-api/
cd shop-api
npm install
docker compose up -d --build --wait

npm install brings @modelcontextprotocol/sdk, and migrate applies migration 013. Save the API’s address, as in Phase 10:

Ventana de terminal
API=$(docker compose port api 3000)

1. Fast Delivery’s and the price comparison site’s keys

Ventana de terminal
docker compose exec api node scripts/create-key.ts "Fast Delivery"
docker compose exec api node scripts/create-key.ts "Price Comparison" catalogue

What you will see:

Key 1, for "Fast Delivery" (role delivery):
shop_Kp4vR8nYc2XwT6mBq0sLd9hFz3gJa7eUu1oPiN5tVxM
Copy it now: the shop only keeps its hash and cannot show it to you again.
Key 2, for "Price Comparison" (role catalogue):
shop_Zt2mW9qXb4cNk7vRy0pLs3dGh8jFa5eUi1oTx6wBn_Q
Copy it now: the shop only keeps its hash and cannot show it to you again.

With no role after the name, the key is delivery’s. We’ve replaced the keys with example ones; yours are shown only once: copy them. If you already had a Fast Delivery key from Phase 6, this is another one, and both work.

Save them in two variables, with your keys, and define a function so you don’t repeat the whole curl:

Ventana de terminal
DELIVERY=shop_…
CATALOGUE=shop_…
mcp() { curl -s "http://$API/mcp" -H "Authorization: Bearer $1" -H 'Accept: application/json, text/event-stream' --json "$2"; }

mcp is a shell function, like the ones in Phase 9: $1 is the key, and $2, the message, which --json sends as JSON.

First, the introduction. With curl -si, to see the headers:

2. initialize

Ventana de terminal
curl -si "http://$API/mcp" -H "Authorization: Bearer $CATALOGUE" -H 'Accept: application/json, text/event-stream' \
--json '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-11-25","capabilities":{},"clientInfo":{"name":"curl","version":"8"}}}'

What you will see:

HTTP/1.1 200 OK
content-type: application/json
…
content-length: 163
Date: Sat, 21 Nov 2026 12:51:56 GMT
…
{"result":{"protocolVersion":"2025-11-25","capabilities":{"tools":{"listChanged":true}},"serverInfo":{"name":"shop-api","version":"1.0.0"}},"jsonrpc":"2.0","id":1}

We’ve removed the security headers and x-request-id. Notice that there’s no mcp-session-id header, because the shop keeps no sessions, and capabilities, with only tools (the SDK adds listChanged). If you get 406 Not Acceptable, check the Accept.

The same question, tools/list, with each key. jq -r keeps only the names:

3. tools/list, with both keys

Ventana de terminal
mcp "$CATALOGUE" '{"jsonrpc":"2.0","id":2,"method":"tools/list"}' | jq -r '.result.tools[].name'
echo ---
mcp "$DELIVERY" '{"jsonrpc":"2.0","id":2,"method":"tools/list"}' | jq -r '.result.tools[].name'

What you will see:

search_products
get_product
---
search_products
get_product
orders_to_ship
mark_shipped

Two tools with the price comparison site’s key, four with Fast Delivery’s, at the same address. If jq gives an error, remove | jq … and look at what the shop answered.

You didn’t send initialize, and it worked: stateless, each POST stands on its own. A real client always sends it first.

Now, what the model knows about a tool:

4. search_products, as an agent sees it

Ventana de terminal
mcp "$CATALOGUE" '{"jsonrpc":"2.0","id":2,"method":"tools/list"}' | jq '.result.tools[0]'

What you will see:

{
"name": "search_products",
"title": "Search products",
"description": "Searches the shop's catalogue for products by name. Search by one word of the name, in the singular (mug, hoodie, cap): it doesn't understand sentences or descriptions. Returns a JSON list of at most 10 products, each with its id, its name, its price in euro cents (priceCents: 850 is €8.50) and the units left (stock: 0 means it's sold out). An empty list means there's none with that name.",
"inputSchema": {
"$schema": "http://json-schema.org/draft-07/schema#",
"type": "object",
"properties": {
"query": {
"type": "string",
"minLength": 1,
"maxLength": 100,
"description": "One word of the product's name, in the singular: mug, t-shirt, hoodie."
}
},
"required": [
"query"
],
"additionalProperties": false
},
"annotations": {
"readOnlyHint": true
},
"execution": {
"taskSupport": "forbidden"
}
}

Everything the agent knows about it. minLength and maxLength are Zod’s .min(1) and .max(100). The SDK adds execution: it can’t run as a long task.

5. The orders to ship

Ventana de terminal
mcp "$DELIVERY" '{"jsonrpc":"2.0","id":3,"method":"tools/call","params":{"name":"orders_to_ship","arguments":{"limit":2}}}' \
| jq -r '.result.content[0].text' | jq .

What you will see:

{
"orders": [
{
"id": 20,
"productId": 3,
"quantity": 1,
"status": "paid",
"createdAt": "2026-10-06T22:00:00.000Z",
"customerId": 4
},
{
"id": 19,
"productId": 2,
"quantity": 4,
"status": "paid",
"createdAt": "2026-10-06T15:00:00.000Z",
"customerId": 3
}
],
"next": "WyIyMDI2LTEwLTA2VDE1OjAwOjAwLjAwMFoiLDE5XQ"
}

The first jq takes out the text; the second reads its JSON. The two newest paid orders and the cursor from Phase 4.

Save the first one’s id (in our run, 20). fromjson does what the second jq did:

Ventana de terminal
ORDER=$(mcp "$DELIVERY" '{"jsonrpc":"2.0","id":3,"method":"tools/call","params":{"name":"orders_to_ship","arguments":{"limit":1}}}' \
| jq -r '.result.content[0].text | fromjson | .orders[0].id')
echo $ORDER

jq -n builds the message without reading anything, with the number as $id. The price comparison site tries first:

6. The price comparison site tries to ship it

Ventana de terminal
SHIP=$(jq -nc --argjson id "$ORDER" '{jsonrpc:"2.0",id:4,method:"tools/call",params:{name:"mark_shipped",arguments:{id:$id}}}')
mcp "$CATALOGUE" "$SHIP" | jq .

What you will see:

{
"result": {
"content": [
{
"type": "text",
"text": "MCP error -32602: Tool mark_shipped not found"
}
],
"isError": true
},
"jsonrpc": "2.0",
"id": 4
}

Tool mark_shipped not found: in its server, the tool doesn’t exist. The order is still paid.

Now Fast Delivery, twice in a row:

7. Fast Delivery ships it

Ventana de terminal
mcp "$DELIVERY" "$SHIP" | jq -r '.result.content[0].text'
mcp "$DELIVERY" "$SHIP" | jq '.result'

What you will see:

{"id":20,"productId":3,"quantity":1,"status":"shipped","createdAt":"2026-10-06T22:00:00.000Z","customerId":4}
{
"content": [
{
"type": "text",
"text": "The order is shipped: only a paid one is shipped."
}
],
"isError": true
}

The first time, the order comes back "shipped". The second, isError: true and why not. That’s why it carries idempotentHint: true: calling it twice changes nothing more.

And without a key:

8. Without a key

Ventana de terminal
curl -si "http://$API/mcp" -H 'Accept: application/json, text/event-stream' --json '{"jsonrpc":"2.0","id":2,"method":"tools/list"}'

What you will see:

HTTP/1.1 401 Unauthorized
content-type: application/problem+json
…
www-authenticate: Bearer realm="shop-api"
…
{"type":"about:blank","title":"Unauthorized","status":401,"detail":"Identify yourself with a shop API key: Authorization: Bearer shop_…"}

401, with www-authenticate and a Problem Details like the ones in Phase 4: the request never reached MCP.

9. Every tool used, in the log

Ventana de terminal
docker compose logs api --no-log-prefix | grep '(MCP)' | jq -c '{tool, apiKey, error}'

What you will see:

{"tool":"orders_to_ship","apiKey":1,"error":false}
{"tool":"orders_to_ship","apiKey":1,"error":false}
{"tool":"mark_shipped","apiKey":1,"error":false}
{"tool":"mark_shipped","apiKey":1,"error":true}

One line per tool that did some work, without what the agent passed it. The price comparison site’s attempt doesn’t appear: in its server, mark_shipped didn’t exist, and use never ran.

The MCP Inspector is the official tool for trying MCP servers. It uses no model: you choose which tool to call. It needs Node 22.23.4, 24.22.1, 26.12.1 or later (node --version).

10. The Inspector, connected to the shop

Ventana de terminal
npx @modelcontextprotocol/inspector@2.15.0 --transport http --server-url "http://$API/mcp" --header "Authorization: Bearer $DELIVERY"

What you will see:

Starting MCP inspector...
…
MCP Inspector Web is up and running at:
http://127.0.0.1:6274?MCP_INSPECTOR_API_TOKEN=4e7d…
Sandbox (MCP Apps): http://127.0.0.1:6275/sandbox
Auth token: 4e7d…
…
Opening browser...

npx downloads it into its cache, without touching your project, and opens your browser on port 6274, with a token that’s only good this time (we’ve shortened it). The removed lines say where it keeps secrets, and they change with your system. Stop it with Ctrl + C.

In the browser:

  1. The shop shows up on a card, Disconnected. Flip its switch: Connected, MCP 2025-11-25.
  2. On the right, Messages: initialize, notifications/initialized, the only one without OK because it expects no response, and tools/list.
  3. At the top, Tools: “Tools (4)”. Pick Orders to ship: the READ-ONLY label (its readOnlyHint) and one field per property of the schema. Put 2 in limit and press Execute Tool: Results shows the orders.
  4. Mark an order as shipped carries the IDEMPOTENT label.

With $CATALOGUE, the list shrinks to two. With --cli in front and --method tools/list at the end, it answers in the terminal, with no browser.

If you use Claude Code, connect it with the key that can do the least, the price comparison site’s:

11. The shop, in Claude Code

Ventana de terminal
claude mcp add --transport http shop "http://$API/mcp" --header "Authorization: Bearer $CATALOGUE"
claude mcp list

What you will see:

Added HTTP MCP server shop with URL: http://127.0.0.1:3000/mcp to local config
Headers: {
"Authorization": "[REDACTED]"
}
File modified: /Users/ana/.claude.json [project: /Users/ana/backend-course/phase-3/shop-api]
Checking MCP server health…
shop: http://127.0.0.1:3000/mcp (HTTP) - ✔ Connected

local config is the scope it uses unless told otherwise: just you, in this folder. The key stays in ~/.claude.json: the output hides it, but the file keeps it as is. ✔ Connected: the shop answered, and no model has worked yet.

Open Claude Code in that folder (claude) and ask it “What mugs do you have and how much are they?” This does use a model, and costs money. It will ask your permission to use mcp__shop__search_products, the tool’s full name. Its answer changes every time: we don’t copy it. If you ask it to ship an order, it can’t: that tool doesn’t exist for its key. When you’re done, claude mcp remove shop.

Phase 8’s timer deploys step 50 with its migration. /mcp goes through nginx’s location /, and there it’s on the internet: only whoever has a key gets in. Create one per company, with the smallest role that works for it:

Ventana de terminal
docker compose -f compose.production.yaml exec api-a node scripts/create-key.ts "Price Comparison" catalogue

To shut an agent out, delete its key’s row, as in Phase 6.

  • The connectors you can add to Claude, on claude.ai and in Claude Desktop: underneath they’re MCP servers, like your shop, and Claude is the host.
  • The OpenAPI document from Phase 4 describes /v2 for people who write code; tools/list describes /mcp for a model. That’s why /mcp isn’t in the contract.
  • Protecting with the description. “Only for delivery” stops nobody.
  • Taking the annotations for security. readOnlyHint is a hint the client can ignore.
  • Giving an agent a key with a bigger role than it needs. Its power is its key’s, also when it’s tricked.
  • Returning lists with no limit. Every result goes into the model’s conversation, and is paid for.
  • Sending the agent the whole error. To the agent, a sentence; to the log, the error.
  • MCP is an open protocol for any agent to use any server. The host is the application with the model; the client, its connection with one server, and the server offers tools, resources and prompts.
  • Underneath it’s JSON-RPC 2.0: initialize, tools/list and tools/call, each response with its question’s id.
  • The shop is an MCP server at POST /mcp, with Streamable HTTP and stateless.
  • An API key gets in, and each request builds a server with what its role allows: catalogue sees two tools; delivery, four.
  • MCP is not authorization: descriptions, hints and instructions protect nothing. The key, its role and the code do.
You use Claude Code connected to three MCP servers: your shop, GitHub and your calendar. How many hosts, clients and servers are there?

A price comparison site wants its agent to browse your catalog through MCP. Which key do you give it?

The price comparison site’s agent, with its catalogue key, calls mark_shipped with order 14, because it read the tool’s name on a forum. What happens?

To save the if per role, someone proposes giving all four tools to every key and writing in mark_shipped’s description “Only for the delivery company.” What do you tell them?

Your client sends notifications/initialized, and the shop answers 202, with no body and no result. Why?

In production, the shop has two copies of the API behind nginx, which spreads the requests. Does Fast Delivery’s agent always have to go to the same copy?

phase-11 · lesson 4/7