IamBishal

Module 1Lesson 1 of 1

1.1 How an agent calls your server, and where it goes wrong

Reads real MCP 2026-07-28 traffic from a tiny stdio server: the host, MCP client and MCP server roles, who controls each primitive, JSON-RPC requests and notifications, and per-request _meta with server/discover. It contrasts stdio with Streamable HTTP and separates tool-result errors from protocol errors. It also defines Helpline and a four-threat checklist that later lessons close.

Put an internal support desk in front of an AI assistant and a model you don't control will read your tool descriptions, pick a tool, fill in its arguments and act on the result, for a user you may never see. Whether that's safe depends on two things: how the Model Context Protocol (MCP) carries those calls, and four threats that appear as soon as a model can reach your data.

This is a reading lesson. By the end you will be able to:

  1. name the host, the MCP client and the MCP server when Claude Code talks to Helpline
  2. say who controls each server primitive: tools, resources and prompts
  3. read a captured JSON-RPC exchange and pair each request with its response by id
  4. explain how capability negotiation works now that the pinned revision has no initialize handshake
  5. contrast stdio with Streamable HTTP, and explain the stdout rule
  6. sort a failure into a tool-result error or a protocol error
  7. write Helpline's four-threat checklist

Before you start. You need Python and a working knowledge of HTTP APIs. You don't need any MCP experience. The series pins Python 3.12, the MCP Python SDK (mcp) 2.3.0, the MCP specification at revision 2026-07-28, and uv 0.12. The companion folder is build-a-production-mcp-server/01-foundations/01-how-an-agent-calls-your-server. It holds tiny_server.py, wire.py and 10 tests. The only hands-on step is running wire.py. There's no Helpline code yet, because Lesson 2 builds it. This lesson produces two things for the rest of the series: the Helpline scenario, and a threat checklist that each later lesson closes.

1. Helpline: a support desk an AI host will reach

Helpline is a fictional SaaS support desk. Its data is a synthetic SQLite fixture that ships with the code, so nothing in this series touches real customer records. It offers five capabilities:

  • search tickets
  • read a ticket
  • search the knowledge base
  • draft a reply
  • escalate a ticket

Lesson 2 designs the tools and settles their final names. This lesson only needs names for the two writes, so it calls them draft_reply and escalate_ticket.

Three of the capabilities are reads and two are writes. draft_reply saves a draft and never sends anything, so a human still decides what reaches the customer. Assume, as Helpline does, that an escalation notifies a person. That makes escalate_ticket the write that needs its own scope, tickets:escalate, on top of the tickets:read scope the reads use. For now, scopes are only a preview. Lesson 4 enforces them.

A wrong search wastes a turn and a bad draft wastes a reviewer's minute, but a wrong escalation, on that assumption, interrupts a person. The design work in this series follows that difference in cost.

2. Host, MCP client, MCP server

Three roles are involved when Claude Code talks to Helpline.

Claude Code is the host: the application the user works in. It runs the model and one or more MCP clients. Claude Desktop is another host. Lesson 5 covers configuring hosts.

The MCP client is the protocol component inside the host that holds one connection to one MCP server and sends it requests. A host connected to three servers runs three MCP clients.

Helpline is the MCP server: a program that exposes tools, resources or prompts over MCP.

Keep the role separate from the code. The SDK's Client class is one implementation of the MCP client role, and Lesson 4 adds an OAuth client, a third meaning. So this series never says "client" on its own.

3. Who controls tools, resources and prompts

An MCP server can expose three primitives. The clearest way to tell them apart is to ask who decides to use each one.

Tools belong to the model. The model decides when to call one and with what arguments. A tool has a name, an input schema and, optionally, an output schema.

Resources are controlled by the application. They are read-only content at a URI that the host or the user pulls into context. That's all you need for now. Lesson 3 adds URIs and templates.

Prompts are the user's choice. They are reusable message templates the user picks in the host. This series explains prompts but never builds one.

All five of Helpline's capabilities are tools, because the model calls them in the middle of a task: search, read the ticket, check the knowledge base, draft. Tickets and knowledge-base articles also make sense as resources, and Lesson 3 adds them. Helpline offers no prompts.

Whoever controls a primitive is whoever you trust to invoke it. For tools that's the model, which is steered by whatever text reached its context, so every tool must be safe when called at the wrong moment with the wrong arguments. That applies to escalate_ticket most of all.

Sampling and elicitation, which run from server to MCP client, are non-goals for this series.

4. Reading the wire: requests, responses and notifications

MCP messages are JSON-RPC 2.0. To make them visible, the companion folder uses tiny_server.py instead of Helpline. It's a stand-in with three tools, small enough that the traffic stays readable. Two of them come up in this lesson. Here they are, minus the imports and the one-ticket dictionary:

python
server = MCPServer("helpline-tiny", version="0.1.0")

@server.tool()
def get_ticket(ticket_id: str) -> str:
    """Return a ticket's subject by id, e.g. HL-1003."""
    subject = TICKETS.get(ticket_id.upper())
    if subject is None:
        # An error the model can act on: it comes back as a tool result.
        raise ToolError(f"No ticket {ticket_id!r}. Ticket ids look like HL-1003.")
    return f"{ticket_id.upper()}: {subject}"

@server.tool()
def ticket_count() -> int:
    """How many tickets the desk holds."""
    return len(TICKETS)

@server.tool()
def broken_report() -> str:
    """A tool with a bug, to show what a crash looks like to the model."""
    raise RuntimeError("connection to db-primary.internal:5432 refused")

get_ticket finds a ticket or fails with a hint, ticket_count always works, and broken_report simulates a database outage. Lesson 2 builds the real server with MCPServer; here it only gives the wire something to talk to.

Clone the repository and run the read-along from the companion folder:

bash
git clone https://github.com/bishal-saha/tutorials-code.git
cd tutorials-code/build-a-production-mcp-server/01-foundations/01-how-an-agent-calls-your-server
uv run python wire.py

wire.py starts tiny_server.py as a subprocess and talks to it directly, standing in for the host and its MCP client. It sends the nine requests in STEPS, numbered by id, and prints each method and params (-->) followed by the server's reply (<--), minus the reply's _meta, which only repeats the server's name and version. Every output here comes from a run against mcp 2.3.0 on 2026-11-21.

python
STEPS: list[tuple[str, dict]] = [
    ("server/discover", {}),
    ("tools/list", {}),
    ("tools/call", {"name": "get_ticket", "arguments": {"ticket_id": "HL-1003"}}),
    ("tools/call", {"name": "get_ticket", "arguments": {"ticket_id": "HL-9"}}),
    ("tools/call", {"name": "broken_report", "arguments": {}}),
    ("tools/call", {"name": "delete_everything", "arguments": {}}),
    ("resources/read", {"uri": "helpline://tickets/HL-1003"}),
    ("tools/call", {"name": "get_ticket", "arguments": {}}),  # required argument missing
    ("tools/call", {"name": "get_ticket", "arguments": "HL-1003"}),  # not an object
]

Here is how wire.py builds each request. One JSON object per line goes to the server's stdin, and one comes back on its stdout:

python
PROTOCOL = "2026-07-28"

# Every modern request carries its protocol version and client capabilities.
META = {
    "io.modelcontextprotocol/protocolVersion": PROTOCOL,
    "io.modelcontextprotocol/clientInfo": {"name": "wire-demo", "version": "1.0"},
    "io.modelcontextprotocol/clientCapabilities": {},
}

message = {
    "jsonrpc": "2.0",
    "id": request_id,
    "method": method,
    "params": {**params, "_meta": META},
}
proc.stdin.write(json.dumps(message) + "\n")
proc.stdin.flush()
responses.append(json.loads(proc.stdout.readline()))

If wire.py stops with a JSONDecodeError, the server either wrote a non-JSON line to stdout (the stdout rule below explains why) or exited before replying. Run uv run python tiny_server.py on its own to see a startup error; a healthy server prints nothing and waits, so press Ctrl+C.

sequenceDiagram
    participant H as Host (wire.py stands in)
    participant C as MCP client
    participant S as MCP server (tiny_server.py, stdio subprocess)
    H->>C: what does this server offer?
    C->>S: server/discover {id, params._meta}
    S-->>C: result {same id}: supportedVersions, capabilities
    C->>S: tools/list {id, params._meta}
    S-->>C: result {same id}: tools
    H->>C: call get_ticket
    C->>S: tools/call {id, params._meta, name, arguments}
    S-->>C: result {same id}: content, isError

Every request has a method, params and an id. Every response carries the same id back, with either a result or an error, never both. The id is the only thing that ties a reply to its request. When requests overlap, JSON-RPC lets replies arrive in any order.

Go through your output now and pair each request with its response by id. wire.py numbers requests from 1, so the third reply should carry "id": 3. Here is what each id should come back with:

idRequestReply
1server/discoverresult: supported versions and capabilities
2tools/listresult: three tools
3get_ticket HL-1003result, isError: false
4get_ticket HL-9result, isError: true, with a hint
5broken_reportresult, isError: true, generic text
6delete_everythingresult, isError: true, Unknown tool
7resources/readerror, code -32602
8get_ticket, no argumentresult, isError: true, validation message
9get_ticket, string argumentserror, code -32602

The third reply in full:

text
--> tools/call {"name": "get_ticket", "arguments": {"ticket_id": "HL-1003"}}
<-- {
  "jsonrpc": "2.0",
  "id": 3,
  "result": {
    "content": [
      {
        "text": "HL-1003: Webhook deliveries failing with 401 since key rotation",
        "type": "text"
      }
    ],
    "isError": false,
    "resultType": "complete",
    "structuredContent": {
      "result": "HL-1003: Webhook deliveries failing with 401 since key rotation"
    }
  }
}

The second request's reply is the tools/list result: the three tools above with their input and output schemas, plus ttlMs and cacheScope.

A notification works differently. It has a method and params but no id, and nothing replies to it. wire.py sends none, so take the spec's example, notifications/cancelled. An MCP client uses it on stdio to say it has given up on a request. Its params name that request in requestId and may add a reason:

json
{
  "jsonrpc": "2.0",
  "method": "notifications/cancelled",
  "params": {
    "requestId": "123",
    "reason": "User requested cancellation"
  }
}

The notification has no id of its own because there's nothing to answer. Lesson 3 covers cancellation and progress.

The folder's tests check the same behaviour you just read on the wire. Run them from the lesson folder:

bash
uv run pytest tests
text
10 passed

5. No initialize: _meta on every request, and server/discover

The --> lines in your output show only each request's method and params, because wire.py adds _meta when it builds the message. Look at the listing above instead: the META dict and the line "params": {**params, "_meta": META}. So every request carries io.modelcontextprotocol/protocolVersion set to "2026-07-28", a clientInfo naming the sender, and clientCapabilities, which is {} because wire.py declares none. Nothing about the protocol is remembered between requests.

This is the stateless model of spec 2026-07-28. There's no initialize handshake and no Mcp-Session-Id. Instead, every server must implement server/discover, which advertises its supported protocol versions, its capabilities and its identity. An MCP client may call it before anything else.

No initialize step: each request carries its own _meta, so the server can answer it on its own.

Now read the server/discover result in your output:

text
--> server/discover {}
<-- {
  "jsonrpc": "2.0",
  "id": 1,
  "result": {
    "cacheScope": "private",
    "capabilities": {
      "prompts": {
        "listChanged": true
      },
      "resources": {
        "listChanged": true,
        "subscribe": true
      },
      "tools": {
        "listChanged": true
      }
    },
    "resultType": "complete",
    "supportedVersions": [
      "2026-07-28"
    ],
    "ttlMs": 0
  }
}

It returns supportedVersions ["2026-07-28"], capabilities for prompts, resources and tools, resultType "complete", ttlMs 0 and cacheScope "private". Before calling anything else, the MCP client knows which protocol version to speak and which features the server supports. Capabilities describe features, not contents: tiny_server.py advertises prompts and resources because MCPServer supports them, even though this server defines neither. tools/list is what returns the actual tools. Every 2026-07-28 result must include resultType, and "complete" marks an ordinary result. The tools/list result also carries ttlMs and cacheScope.

Because no request depends on an earlier one, each request can be understood on its own.

In Lesson 2, the in-process Client handles _meta and server/discover for you.

6. stdio and Streamable HTTP: who starts what, and where bytes go

With stdio, the host starts the MCP server as a subprocess and exchanges newline-delimited JSON-RPC over that subprocess's stdin and stdout. wire.py uses stdio. It means one user, one process, on the user's machine, with no network in between.

The consequence is that stdout belongs to the protocol. The server must not write anything to stdout that isn't a valid MCP message. A stray print(), or a logging handler pointed at stdout, puts bytes into the stream that the MCP client tries to parse as JSON-RPC. The connection breaks, often with an error that says nothing about logging. Send logs to stderr or to a file.

With Streamable HTTP, the MCP server runs on its own, as a long-lived service someone deployed. No host starts it. Each message is an HTTP POST to one URL, such as /mcp. The reply comes back either as a JSON object or as a server-sent events (SSE) stream scoped to that one request.

The real difference is ownership. Over stdio the server is the user's own process. Over Streamable HTTP it's a shared service many users reach across a network, so it has to know who each caller is. That's where access tokens come in, and Lesson 4 builds this transport.

With stdio, stdout belongs to the protocol; with Streamable HTTP, the server has to know who each caller is.

7. Tool-result errors and protocol errors

A failure comes back to the host in one of two ways. A tool-result error is a normal tool result with isError: true. Its text lands in the model's context, so the model can read it and change what it does next. A protocol error is a JSON-RPC error response, meaning the request itself couldn't be handled. The host deals with it, and the model usually never reasons over it.

get_ticket for HL-9 returns isError: true with this text:

text
Error executing tool get_ticket: No ticket 'HL-9'. Ticket ids look like HL-1003.

The tool raised a ToolError, so the hint reaches the model unchanged and the model can retry with a valid id.

broken_report raises RuntimeError('connection to db-primary.internal:5432 refused'), but the model sees only this:

text
Error executing tool broken_report

The hostname and port stay in the server logs, so your internal topology never reaches the model. The cost is that the model gets no hint about what to try next.

An unknown tool is where the SDK and the spec disagree. Call delete_everything against mcp 2.3.0 and you get a tool result with isError: true and the text Unknown tool: delete_everything. Spec 2026-07-28 lists an unknown tool as a protocol error, returned as a JSON-RPC error with code -32602. Anything that consumes these responses should handle both forms.

A resources/read for an unknown URI returns a JSON-RPC error with code -32602. Spec 2026-07-28 changed resource-not-found from -32002 to -32602.

The last two requests show where the line between the two kinds falls for bad arguments. A get_ticket call with no ticket_id passes the protocol layer and fails the tool's input schema, so it comes back as a tool-result error the model can read:

text
Error executing tool get_ticket: 1 validation error for get_ticketArguments
ticket_id
  Field required [type=missing, input_value={}, input_type=dict]

The spec puts input validation errors, such as a value in the wrong format or out of range, among tool execution errors for exactly this reason: the model can correct the call. A call whose arguments is the string "HL-1003" instead of an object never reaches the tool, because the request itself breaks the tools/call schema. That one is a protocol error:

json
{"jsonrpc": "2.0", "id": 9, "error": {"code": -32602, "message": "Invalid request parameters", "data": ""}}

So the dividing line is not "good or bad arguments". It is whether the request was well-formed MCP. A well-formed call with the wrong values is the model's to fix. A malformed request is the MCP client's bug.

FailureObserved with mcp 2.3.0Notes
get_ticket for HL-9 (not found)Tool-result error, text includes the hintThe model can retry with a valid id
broken_report (database refused)Tool-result error, generic text onlyInternal details stay in server logs
Unknown tool delete_everythingTool-result error, Unknown tool: delete_everythingThe spec says protocol error, -32602. Handle both
resources/read for an unknown URIProtocol error, -32602Was -32002 before 2026-07-28
get_ticket with ticket_id missingTool-result error, the validation messageInput validation is the model's to fix
get_ticket with arguments not an objectProtocol error, -32602The request breaks the tools/call schema

For Helpline that gives a rule of thumb: if the model could fix its next call by reading the message, return a tool-result error.

Lesson 3 adds timeouts to this picture. Lesson 4 adds HTTP 401 and 403, which are returned before MCP is involved at all.

8. Four ways Helpline goes wrong: the threat checklist

Over-broad tools. An over-broad tool accepts far more than any user task needs, such as a generic run_sql or call_api. Scopes and review can't limit it, because the danger is in the arguments the model chooses at run time. On Helpline, one run_sql tool could read every customer's tickets, or rewrite them in a single statement. The fix is task-shaped tools, each built around one thing a support engineer does, with only the inputs that task needs. Lesson 2 designs them. Lesson 4 adds per-tool scopes, which only mean something once the tools are narrow.

Tool-description poisoning. This is instructions planted in a tool's name, description or schema; to the model, a description and an instruction are both just text in its context. It can get in through routes you don't watch: an unreviewed change to a description, a description built from stored data, or another MCP server in the same host whose text steers the model as ours does. On Helpline, a poisoned description could push the model to escalate every ticket it reads, or to copy full ticket contents into every draft. A system prompt telling the model to ignore such text doesn't prevent it. Lesson 2 treats descriptions as input the model reads and writes them deliberately. Lesson 5's schema snapshot makes any change to a description visible in review.

Two of the threats need one OAuth preview. Over Streamable HTTP, Helpline acts as a resource server: it accepts access tokens issued by an authorization server and decides whether to honour each request. How it validates those tokens is Lesson 4's subject.

Token passthrough. This means accepting a token that wasn't issued for Helpline, or forwarding the caller's token to a downstream service instead of using Helpline's own credential. The MCP authorization specification explicitly forbids it. On Helpline, a token issued for some other service would get accepted as if it were meant for Helpline. Or the user's token would leak to the downstream ticket API, which should never see it. Lesson 4 closes this, with a test proving the incoming token never reaches the downstream service.

Confused deputy. Helpline needs authority of its own over the ticket store to do its job. A confused deputy is tricked into using that authority for a caller who lacks it. Suppose a caller holding only tickets:read gets a ticket escalated because the request came through Helpline, and Helpline is allowed to escalate. Helpline has then lent that caller authority they never had. Lesson 4 closes this with audience and scope checks, a per-customer check that limits each caller to its own customers' tickets, and the server's own downstream credential. Lesson 5's audit record shows who acted through the server.

ThreatHow it hits HelplineClosed inStatus
Over-broad toolsOne run_sql reads or rewrites every customer's ticketsLesson 2 (task-shaped tools), Lesson 4 (per-tool scopes)Open
Tool-description poisoningA description steers the model to escalate everything or leak tickets into draftsLesson 2 (deliberate descriptions), Lesson 5 (schema snapshot)Open
Token passthroughA foreign token is accepted, or the user's token reaches the downstream APILesson 4Open
Confused deputyA read-only caller, or one working another customer, gets a ticket escalated through Helpline's own authorityLesson 4 (scopes, per-customer check), with Lesson 5's audit recordOpen

Every row stays open until its lesson closes it.

9. Exercise: classify, then check against the wire

Part 1. Classify each of these Helpline failures as a tool-result error or a protocol error, and write down what the model can do next:

  1. ticket HL-42 doesn't exist
  2. get_ticket called with ticket_id set to the number 1003 instead of a string
  3. a call to a tool named close_all
  4. a tools/call with the required ticket id missing
  5. a tools/call whose arguments is a list instead of an object

Part 2. Someone proposes a sixth tool, update_ticket(fields: dict). Which checklist threats does it make worse, and why?

Answers to Part 2. It is an over-broad tool: fields can change any column, so the model chooses the blast radius at run time. That also weakens scopes, because one scope would have to grant every possible change, and it gives a poisoned description far more to trigger than an escalation.

How to check. Items 1 and 4 match requests 4 and 8 in wire.py's output. Items 3 and 5 are variants of requests 6 and 9, so predict them by analogy. For item 2, add this line to the end of STEPS in wire.py, predict the result, then run it:

python
("tools/call", {"name": "get_ticket", "arguments": {"ticket_id": 1003}}),

Expected classification: 1, 2 and 4 are tool-result errors the model can fix. For 1 it searches for the right id; for 2 it resends the id as a string; for 4 it adds the missing argument. 5 is a protocol error, because the request breaks the tools/call schema; the model can't fix that, so it's the MCP client's bug. 3 is a protocol error under the spec but a tool-result error from mcp 2.3.0, so handle both; either way the model should pick a tool that exists.

Common mistake. Calling the unknown tool harmless because nothing ran: it tells you the model is guessing tool names.

10. What to carry into Lesson 2

You can read the wire: requests paired by id, _meta on every request, server/discover instead of a handshake, and the two error kinds with the line between them. You have Helpline's four-threat checklist, every row still open. Lesson 2 builds Helpline with MCPServer and task-shaped tools.

Next: Lesson 2, Task-shaped tools with MCPServer.

Key Takeaways

  • Name the host, MCP client and MCP server in a Claude Code to Helpline connection, and keep the MCP client role separate from the SDK's Client class
  • Say who controls tools (model), resources (application) and prompts (user), and why that makes every tool's safety matter
  • Pair JSON-RPC requests with responses by id, and explain why a notification has no id and gets no reply
  • Find the protocol version and client capabilities in each request's _meta, and read what server/discover advertises
  • Contrast stdio and Streamable HTTP by who starts the server and where messages travel, and explain why stdout logging breaks stdio
  • Classify a failure as a tool-result error or a protocol error, and handle mcp 2.3.0's divergence from the spec for unknown tools
  • Write Helpline's checklist of over-broad tools, tool-description poisoning, token passthrough and confused deputy, with the lesson that closes each

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.