Lesson 1 named four threats, and two of them live in the tool surface itself. An over-broad tool gives the model far more power than any task needs. A careless description becomes instructions the model follows. This lesson builds Helpline's five tools against both, then proves they behave with a test suite.
By the end of this lesson you will be able to:
- design five task-shaped tools around what a support agent actually does
- declare typed, constrained inputs on
MCPServerand inspect the input schema the model receives - write tool descriptions that say what a tool does, when to use it and what it won't do
- publish an output schema for every tool and return structured content with it
- return tool-result errors that tell the model what to try next
- drive every tool from a pytest suite through the in-process
Client - run the server over stdio and prove it answers
Before you start. You need these ideas from Lesson 1: host, MCP client and MCP server; tools, resources and prompts; stateless requests with per-request _meta and server/discover; stdio; and tool-result errors versus protocol errors. The series pins Python 3.12, uv 0.12 and mcp 2.3.0.
How to use this lesson. It is a guided read of the finished server, which is already in the companion folder. Each step explains one design decision and shows the part of helpline/server.py that carries it; the file itself defines the output models first, then the tools inside build_server(), so read the listings as excerpts, not as a file to type top to bottom. The checks run once the server is complete: the pytest suite and the stdio run after Step 6. Then you extend it in the exercise.
What we build. The companion folder holds helpline/store.py, helpline/server.py, main.py, explore.py, data/helpline.json and tests/test_tools.py, with 15 tests. Every listing and output below is copied from that folder and from a run against mcp 2.3.0 on 2026-11-21.
1. Designing Helpline around support tasks, not tables
A task-shaped tool covers one thing a support agent actually does, such as finding open tickets about webhooks or escalating a ticket that needs a human, and it accepts only the inputs that task needs. The alternative mirrors the system underneath: one tool per table or per REST route, so the model assembles a task out of raw operations. That design looks flexible. It also hands the model far more power than any support task requires.
The extreme version is a single generic tool. It is shown here as a counter-example and does not exist in the repository:
# Counter-example only: never ship this.
@server.tool()
def run_sql(query: str) -> list[dict]:
"""Run a SQL query against the Helpline database."""
return db.execute(query).fetchall()This is the over-broad tool from Lesson 1. Its input is any string the database accepts, so DELETE FROM tickets passes validation as easily as a SELECT. No description can narrow it, a reviewer can't predict what it will do, and a scope added later can only grant all of it or none of it. It is also a confused deputy waiting to happen: the query runs with the server's database credential, so whoever steers the model borrows that authority.
Helpline exposes five tools instead:
| Tool | Task | Inputs | Effect | Annotations |
|---|---|---|---|---|
search_tickets | Find tickets matching a problem | query, optional status (open, pending, solved), optional customer, limit 1–20 | read | readOnlyHint: true |
get_ticket | Read one ticket with its history | ticket_id | read | readOnlyHint: true |
search_knowledge_base | Find articles that answer a question | query (3+ characters), limit 1–5 | read | readOnlyHint: true |
draft_reply | Prepare a reply for a person to review | ticket_id, message, up to 3 article_ids | writes a draft row | readOnlyHint: false, destructiveHint: false |
escalate_ticket | Hand a ticket to the on-call engineer | ticket_id, severity (high, urgent), reason | writes an escalation | idempotentHint: true |
Each one is safer than run_sql for the same three reasons: its inputs are bounded, its effect is known in advance, and that effect is something a person can review. The three read tools can't change anything. draft_reply writes, but only a draft row that a person reviews, and it returns sent: false. escalate_ticket is the write that matters, and calling it twice produces one escalation.
Annotations are hints to the host, which may use them to decide when to ask the user before a call. They enforce nothing, and the spec tells MCP clients to treat annotations as untrusted unless they come from a trusted server. The code behind each tool is what makes these promises true.
These are tools because the model decides when to call them. MCP splits control three ways: tools are model-controlled, resources are application-controlled, and prompts are user-controlled. Everything Helpline does in this lesson is something the model chooses mid-task, so all five are tools. Lesson 3 adds resources for content the host attaches on purpose. Prompts, templates a user picks from a menu, are explained in this series but never built.
Narrow tools don't remove the need for authorization. In this lesson escalate_ticket runs unprotected over stdio, and the tickets:escalate scope that guards it arrives in Lesson 4.
2. Step 1: The project, the fixture and the SDK v2 names
Clone the repository and install the series' environment. The dependencies live in one pyproject.toml at the series level, two folders above this lesson:
git clone https://github.com/bishal-saha/tutorials-code.git
cd tutorials-code/build-a-production-mcp-server
uv sync
cd 01-foundations/02-task-shaped-toolsuv sync installs mcp 2.3.0, PyJWT and uvicorn (used from Lesson 4), plus pytest and anyio for the tests.
The data is in data/helpline.json. It is synthetic: four customers, ten tickets (HL-1001 to HL-1010) and eight knowledge-base articles (KB-101 to KB-108). HelplineStore in helpline/store.py loads that file into an in-memory SQLite database and exposes the queries and writes the tools call. The tools never build SQL themselves. Here is the search query, which binds every value as a parameter:
def search_tickets(
self, query: str = "", status: str | None = None, customer: str | None = None
) -> list[sqlite3.Row]:
"""Tickets matching every word of `query` in the subject or messages, newest first."""
sql = (
"SELECT t.*, c.name AS customer_name FROM tickets t "
"JOIN customers c ON c.id = t.customer WHERE 1=1"
)
args: list[str] = []
if status:
sql += " AND t.status = ?"
args.append(status)
if customer:
sql += " AND (t.customer = ? OR lower(c.name) = lower(?))"
args += [customer, customer]
for word in _words(query):
sql += (
" AND (lower(t.subject) LIKE ? OR EXISTS (SELECT 1 FROM messages m "
"WHERE m.ticket_id = t.id AND lower(m.body) LIKE ?))"
)
args += [f"%{word}%", f"%{word}%"]
sql += " ORDER BY t.created_at DESC"
return self.db.execute(sql, args).fetchall()Because the database lives in memory, every new HelplineStore starts from the same fixture. That matters for the tests: a fresh server per test means one test's escalation never leaks into the next.
For the rest of the series we use two names from SDK v2: MCPServer declares and runs the server, and Client connects to it. These are the imports at the top of helpline/server.py:
from __future__ import annotations
from typing import Annotated, Literal
from mcp.server.mcpserver import MCPServer
from mcp.server.mcpserver.exceptions import ToolError
from mcp.types import ToolAnnotations
from pydantic import BaseModel, Field
from helpline.store import HelplineStoreTests and explore.py import Client with from mcp import Client.
If you are coming from an older guide, this is the one place v1 appears. In v1 you would have written from mcp.server.fastmcp import FastMCP. In mcp 2.x that import raises ModuleNotFoundError, and the message says FastMCP was renamed to MCPServer and points to the migration guide. On the other side, Client is the one class for connecting to a server: give it a server object (in-process, for tests), a URL (Streamable HTTP) or a command to launch (stdio). It sends the protocol version and capabilities in each request's _meta. Its default mode="auto" probes server/discover and falls back to the legacy initialize handshake for older servers; handed an in-process server, it skips JSON-RPC framing altogether. None of the code in this series has to deal with protocol versions.
helpline/server.py wraps everything in a build_server() factory. The tests and main.py both call it, so the server you test is the server you run:
def build_server(store: HelplineStore | None = None) -> MCPServer:
store = store or HelplineStore()
server = MCPServer(
"helpline",
version="0.2.0",
instructions=(
"Tools for Helpline's support desk. Find a ticket before acting on it; "
"drafts are never sent automatically."
),
)
def require_ticket(ticket_id: str):
row = store.ticket(ticket_id)
if row is None:
raise ToolError(
f"No ticket with id {ticket_id!r}. Ticket ids look like HL-1003; "
"use search_tickets to look one up."
)
return rowrequire_ticket is shared by the three tools that take a ticket id (get_ticket, draft_reply and escalate_ticket), so every "no such ticket" failure carries the same hint. Step 5 explains why that hint matters.
3. Step 2: Typed inputs and the schema the model receives
The model never sees your Python. It sees the input schema that MCPServer generates from your type hints, so the hints are where you decide what a caller may ask for:
Status = Literal["open", "pending", "solved"]
READ_ONLY = ToolAnnotations(readOnlyHint=True, openWorldHint=False)
@server.tool(title="Find support tickets", annotations=READ_ONLY)
def search_tickets(
query: Annotated[
str, Field(description="Words to match in the subject or messages; empty for all")
] = "",
status: Status | None = None,
customer: Annotated[
str | None, Field(description="Customer id or company name, e.g. 'Corvid Analytics'")
] = None,
limit: Annotated[int, Field(ge=1, le=20)] = 10,
) -> TicketSearch:
"""Find tickets by words, status or customer, newest first.
Use this to get a ticket id before calling get_ticket, draft_reply or escalate_ticket.
"""
rows = store.search_tickets(query, status, customer)
return TicketSearch(tickets=[_summary(r) for r in rows[:limit]], total=len(rows))Two details matter. The bounds sit inside Annotated, which is where pydantic picks them up for the schema. The status filter is a Literal, not a plain str.
You don't have to wait for the test suite to see the result. explore.py in the lesson folder connects to build_server() through the in-process Client, lists the tools and makes two calls:
async def main() -> None:
async with Client(build_server()) as client:
tools = {t.name: t for t in (await client.list_tools()).tools}
print("tools:", ", ".join(tools))
schema = tools["search_tickets"].input_schema["properties"]
show("search_tickets input: status and limit", {k: schema[k] for k in ("status", "limit")})
draft = tools["draft_reply"]
show("draft_reply description", draft.description)
show(
"draft_reply annotations",
draft.annotations.model_dump(by_alias=True, exclude_none=True),
)
show("draft_reply outputSchema", draft.output_schema)
result = await client.call_tool("search_tickets", {"query": "webhook", "status": "open"})
show(
"search_tickets result",
result.model_dump(mode="json", by_alias=True, exclude_none=True, exclude={"meta"}),
)
refused = await client.call_tool("search_tickets", {"limit": 500})
show(
"search_tickets limit=500",
refused.model_dump(mode="json", by_alias=True, exclude_none=True, exclude={"meta"}),
)show() prints a label and the value as indented JSON. Run uv run python explore.py. The first line names the five tools, and the next block is what the model receives for the two inputs:
"status": {
"anyOf": [
{ "enum": ["open", "pending", "solved"], "type": "string" },
{ "type": "null" }
],
"default": null,
"title": "Status"
},
"limit": {
"default": 10,
"maximum": 20,
"minimum": 1,
"title": "Limit",
"type": "integer"
}The last block in explore.py's output breaks the bounds. Calling search_tickets with limit=500 doesn't raise in your code. It comes back as a result with isError: true and pydantic's message:
{
"content": [
{
"type": "text",
"text": "Error executing tool search_tickets: 1 validation error for search_ticketsArguments\nlimit\n Input should be less than or equal to 20 [type=less_than_equal, input_value=500, input_type=int]\n For further information visit https://errors.pydantic.dev/2.14/v/less_than_equal"
}
],
"isError": true,
"resultType": "complete"
}Every 2026-07-28 result carries resultType, and "complete" marks an ordinary one.
Validation runs before the tool body, so the store is never queried. An enum and a bounded integer shrink what the model can ask for, and the schema states that limit wherever the tool is listed. They also become part of your contract: Lesson 5 snapshots these schemas, and narrowing a type after that point counts as a breaking change.
The other two read tools follow the same pattern. get_ticket takes one id and returns the ticket with its messages; search_knowledge_base bounds both the query length and the number of hits:
@server.tool(title="Read a ticket", annotations=READ_ONLY)
def get_ticket(
ticket_id: Annotated[str, Field(description="Ticket id, e.g. HL-1003")],
) -> TicketDetail:
"""Read one ticket with its full message history and the customer's plan."""
row = require_ticket(ticket_id)
messages = [
Message(author=m["author"], at=m["at"], body=m["body"])
for m in store.messages(row["id"])
]
return TicketDetail(**_summary(row).model_dump(), plan=row["plan"], messages=messages)
@server.tool(title="Search the knowledge base", annotations=READ_ONLY)
def search_knowledge_base(
query: Annotated[str, Field(min_length=3, description="What the customer is asking")],
limit: Annotated[int, Field(ge=1, le=5)] = 3,
) -> ArticleSearch:
"""Find knowledge-base articles that answer a customer's question, best match first."""
hits = [
ArticleHit(id=row["id"], title=row["title"], snippet=row["body"].split(". ")[0] + ".")
for _, row in store.search_articles(query)[:limit]
]
return ArticleSearch(articles=hits)_summary() copies a database row into a TicketSummary; Step 4 shows that model.
4. Step 3: Descriptions written for the model
Each tool's docstring becomes its description, and title= gives the host a display name. The host passes the description to the model with the input schema. The model doesn't treat it as documentation. It reads it as instructions, so write it that way:
- What the tool does.
get_ticketsays: "Read one ticket with its full message history and the customer's plan." - When to use it.
search_ticketssays: "Use this to get a ticket id before calling get_ticket, draft_reply or escalate_ticket." - What it won't do.
draft_replyends with "It is never sent."escalate_ticketsays that calling it again for the same ticket "returns the existing escalation instead of paging twice."
The negative statements do the most work. "It is never sent" gives the model what it needs to avoid telling a user a reply went out, and knowing a second escalation is harmless lets it retry after an unclear result. These are expectations, not guarantees: a model may still ignore a description, which is why the server enforces both promises in code. explore.py prints the description exactly as the model receives it: "Save a draft reply on a ticket for a person to review. It is never sent." The server-level instructions ("Find a ticket before acting on it") give the same guidance once for the whole server.
Because descriptions are input to the model, they belong to the attack surface Lesson 1 called tool-description poisoning. Review a description change the way you review a code change; Lesson 5's contract snapshot flags every reworded description for review. Careful descriptions protect only our own tools, though. They do nothing against a poisoned tool on another MCP server in the same host.
5. Step 4: Output schemas and structured content
A text answer is fine for a person and awkward for everything else. A test that picks a ticket id out of a sentence breaks the first time someone rewords the sentence. So every Helpline tool returns a pydantic model, and MCPServer turns its return type into the tool's output schema:
class TicketSummary(BaseModel):
id: str = Field(description="Ticket id, e.g. HL-1003")
subject: str
customer: str = Field(description="Customer company name")
status: Status
priority: Literal["low", "normal", "high", "urgent"]
created_at: str
class TicketSearch(BaseModel):
tickets: list[TicketSummary]
total: int = Field(description="How many tickets matched, before the limit")The other models, all at module level in helpline/server.py:
class Message(BaseModel):
author: Literal["customer", "agent"]
at: str
body: str
class TicketDetail(TicketSummary):
plan: str = Field(description="The customer's plan: starter, team or enterprise")
messages: list[Message]
class ArticleHit(BaseModel):
id: str
title: str
snippet: str = Field(description="The first sentence of the article")
class ArticleSearch(BaseModel):
articles: list[ArticleHit]
class Draft(BaseModel):
draft_id: int
ticket_id: str
body: str
sent: Literal[False] = Field(
default=False, description="Always false: a person reviews and sends drafts"
)
class Escalation(BaseModel):
escalation_id: int
ticket_id: str
severity: Literal["high", "urgent"]
reason: str
already_escalated: bool = Field(
description="True when the ticket was escalated before and nothing new was created"
)When a tool declares an output schema, the spec requires its structured results to conform to it. explore.py prints draft_reply's full output schema and annotations, generated from the Draft model above:
{
"properties": {
"draft_id": {"title": "Draft Id", "type": "integer"},
"ticket_id": {"title": "Ticket Id", "type": "string"},
"body": {"title": "Body", "type": "string"},
"sent": {
"const": false,
"default": false,
"description": "Always false: a person reviews and sends drafts",
"title": "Sent",
"type": "boolean"
}
},
"required": ["draft_id", "ticket_id", "body"],
"title": "Draft",
"type": "object"
}{"readOnlyHint": false, "destructiveHint": false, "idempotentHint": false, "openWorldHint": false}And here is the whole search_tickets result for {"query": "webhook", "status": "open"}, as explore.py prints it:
{
"content": [
{
"type": "text",
"text": "{\n \"tickets\": [\n {\n \"id\": \"HL-1003\",\n \"subject\": \"Webhook deliveries failing with 401 since key rotation\",\n \"customer\": \"Corvid Analytics\",\n \"status\": \"open\",\n \"priority\": \"urgent\",\n \"created_at\": \"2026-11-14T07:55:00Z\"\n }\n ],\n \"total\": 1\n}"
}
],
"structuredContent": {
"tickets": [
{
"id": "HL-1003",
"subject": "Webhook deliveries failing with 401 since key rotation",
"customer": "Corvid Analytics",
"status": "open",
"priority": "urgent",
"created_at": "2026-11-14T07:55:00Z"
}
],
"total": 1
},
"isError": false,
"resultType": "complete"
}The text block carries the same JSON as structuredContent. The spec asks for this: a tool that returns structured content should also return the serialized JSON in a text block, for MCP clients that only read text. A test holds the SDK to it:
async def test_text_block_carries_the_same_data(client):
# MCP clients that only read text get the same answer as those reading structure.
result = await client.call_tool("search_tickets", {"query": "webhook", "status": "open"})
assert json.loads(result.content[0].text) == result.structured_content6. Step 5: Failures the model can act on
A support agent asks about a ticket that doesn't exist. The tool can't do its job, but the model can still recover if the result says what went wrong and what to try next. That is what a tool-result error is for.
require_ticket raises ToolError, and MCPServer turns it into a normal tool result with isError: true and our message as the text. Called with HL-9999:
Error executing tool get_ticket: No ticket with id 'HL-9999'. Ticket ids look like HL-1003; use search_tickets to look one up.The hint matters as much as the error. Told only "not found", the model may guess another id; told "use search_tickets", it has a next step that works. The two writes follow the same pattern. An unknown article id such as KB-999 in draft_reply points to search_knowledge_base. Escalating HL-1004, which is solved, returns:
Error executing tool escalate_ticket: HL-1004 is solved; reopen it before escalating.The limit=500 call from Step 2 also came back with isError: true, but with pydantic's text: input validation refused it before the tool body ran. An unhandled crash is different again. The suite adds a deliberately broken tool to a fresh server, only inside one test:
async def test_a_crash_shows_the_model_only_the_tool_name():
server = build_server()
@server.tool()
def explode() -> str:
"""A deliberately broken tool, added only in this test."""
raise RuntimeError("connection to db-primary.internal:5432 refused")
async with Client(server) as c:
result = await c.call_tool("explode", {})
assert result.is_error is True
assert result.content[0].text == "Error executing tool explode"
assert "db-primary" not in result.content[0].textIt passes: the model sees only Error executing tool explode, and the host name in the exception never leaves the server. The rule: an anticipated failure becomes a ToolError with a hint the model can act on, and a bug stays a bug you fix.
The boundary from Lesson 1 still holds. A request that isn't well-formed MCP never reaches a tool and gets a protocol error, a JSON-RPC error response. Everything in this step is a tool-result error reported inside the result.
7. Step 6: The two writes, draft_reply and an idempotent escalate_ticket
draft_reply checks the ticket and every article id, saves a draft row for a person to review, and returns the draft with sent: false:
@server.tool(
title="Draft a reply",
annotations=ToolAnnotations(
readOnlyHint=False, destructiveHint=False, idempotentHint=False, openWorldHint=False
),
)
def draft_reply(
ticket_id: Annotated[str, Field(description="Ticket id, e.g. HL-1003")],
message: Annotated[
str, Field(min_length=1, max_length=2000, description="The reply text to the customer")
],
article_ids: Annotated[
list[str], Field(max_length=3, description="Articles to link, e.g. KB-103")
] = [], # noqa: B006 - the SDK builds the schema from this default; it is never mutated
) -> Draft:
"""Save a draft reply on a ticket for a person to review. It is never sent."""
row = require_ticket(ticket_id)
links = []
for article_id in article_ids:
article = store.article(article_id)
if article is None:
raise ToolError(
f"No article {article_id!r}. Use search_knowledge_base to find ids."
)
links.append(f"- {article['title']} ({article['id']})")
body = message.strip()
if links:
body += "\n\nThese articles may help:\n" + "\n".join(links)
draft_id = store.save_draft(row["id"], body)
return Draft(draft_id=draft_id, ticket_id=row["id"], body=body)With KB-103 linked, the structured result is:
{
"draft_id": 1,
"ticket_id": "HL-1003",
"body": "Your receiver may still verify with the old secret.\n\nThese articles may help:\n- Rotate a webhook signing secret (KB-103)",
"sent": false
}sent is typed Literal[False], so the schema documents that a draft is never sent. The control is the person who reviews and sends the draft; that review is why Lesson 4 lets draft_reply run with tickets:read alone.
escalate_ticket is the write that matters. Agents retry: a model may call again after an ambiguous result, and a host may resend after a dropped connection. A retry must not page someone twice, and the tool body, not the annotation, guarantees that:
@server.tool(
title="Escalate a ticket",
annotations=ToolAnnotations(
readOnlyHint=False, destructiveHint=False, idempotentHint=True, openWorldHint=False
),
)
def escalate_ticket(
ticket_id: Annotated[str, Field(description="Ticket id, e.g. HL-1003")],
severity: Literal["high", "urgent"],
reason: Annotated[str, Field(min_length=10, max_length=500)],
) -> Escalation:
"""Escalate a ticket to the on-call engineer. Calling it again for the same ticket
returns the existing escalation instead of paging twice."""
row = require_ticket(ticket_id)
if row["status"] == "solved":
raise ToolError(f"{row['id']} is solved; reopen it before escalating.")
existing = store.open_escalation(row["id"])
if existing is not None:
return Escalation(
escalation_id=existing["id"],
ticket_id=row["id"],
severity=existing["severity"],
reason=existing["reason"],
already_escalated=True,
)
created = store.escalate(row["id"], severity, reason)
return Escalation(
escalation_id=created["id"],
ticket_id=row["id"],
severity=severity,
reason=reason,
already_escalated=False,
)Escalating HL-1003 twice gives:
{"escalation_id": 1, "ticket_id": "HL-1003", "severity": "urgent", "reason": "Orders not syncing for 14h", "already_escalated": false}
{"escalation_id": 1, "ticket_id": "HL-1003", "severity": "urgent", "reason": "Orders not syncing for 14h", "already_escalated": true}A repeat with a different severity or reason still returns the first escalation unchanged, with already_escalated: true: the first page stands. idempotentHint: true tells the host a repeat is safe, and the host takes that on trust, so the open_escalation check is what keeps the promise for sequential retries. It is a check followed by an insert, so two calls arriving at the same moment could both see no escalation. A production store closes that gap with a database constraint, such as a unique index on open escalations per ticket, rather than in the tool.
8. A pytest suite on the in-process Client
tests/test_tools.py makes every call above permanent. Thirteen of its fifteen tests hand a fresh server straight to Client through a fixture, with no network. One builds its own in-process server with the broken tool from Step 5, and one, shown in the next section, starts a real subprocess. Client plays the MCP client role inside the test process and builds the per-request _meta for you:
pytestmark = pytest.mark.anyio
@pytest.fixture
async def client():
async with Client(build_server()) as c:
yield c
async def test_unknown_ticket_is_a_tool_error_with_a_hint(client):
result = await client.call_tool("get_ticket", {"ticket_id": "HL-9999"})
assert result.is_error is True
text = result.content[0].text
assert "No ticket with id 'HL-9999'" in text
assert "search_tickets" in text
async def test_escalation_is_idempotent(client):
args = {"ticket_id": "HL-1003", "severity": "urgent", "reason": "Orders not syncing for 14h"}
first = (await client.call_tool("escalate_ticket", args)).structured_content
second = (await client.call_tool("escalate_ticket", args)).structured_content
assert first["already_escalated"] is False
assert second["already_escalated"] is True
assert first["escalation_id"] == second["escalation_id"]A validation failure comes back as a result over Client, not as an exception, which is why the tests assert on is_error instead of using pytest.raises. Run the suite from the lesson folder:
uv run pytest -v teststests/test_tools.py::test_lists_five_task_shaped_tools PASSED
tests/test_tools.py::test_input_schema_carries_bounds PASSED
tests/test_tools.py::test_search_tickets_returns_structured_content PASSED
tests/test_tools.py::test_find_by_customer_name PASSED
tests/test_tools.py::test_get_ticket_includes_history PASSED
tests/test_tools.py::test_unknown_ticket_is_a_tool_error_with_a_hint PASSED
tests/test_tools.py::test_out_of_range_limit_is_rejected_before_the_tool_runs PASSED
tests/test_tools.py::test_search_knowledge_base_ranks_by_overlap PASSED
tests/test_tools.py::test_draft_reply_is_never_sent PASSED
tests/test_tools.py::test_draft_with_unknown_article_fails_cleanly PASSED
tests/test_tools.py::test_escalation_is_idempotent PASSED
tests/test_tools.py::test_cannot_escalate_a_solved_ticket PASSED
tests/test_tools.py::test_text_block_carries_the_same_data PASSED
tests/test_tools.py::test_server_answers_over_stdio PASSED
tests/test_tools.py::test_a_crash_shows_the_model_only_the_tool_name PASSED
============================== 15 passed in 1.21s ==============================The listing above comes from a run on 2026-11-21; your timing will differ. These tests call tools and check what comes back. They don't freeze the contract; Lesson 5 adds that on the same harness.
9. Running Helpline over stdio
A host doesn't hand over a server object. It starts Helpline as a subprocess and exchanges JSON-RPC over its stdin and stdout. main.py is that entry point:
"""Run the Helpline MCP server over stdio.
An MCP client (Claude Code, Claude Desktop, MCP Inspector) starts this file as a
subprocess and speaks JSON-RPC over its stdin and stdout, so nothing else may
print to stdout.
"""
from helpline.server import build_server
if __name__ == "__main__":
build_server().run("stdio")Run by hand with uv run python main.py, it prints nothing and waits on stdin, which looks the same as a hung process. So the last test launches it exactly as a host would and asks for its tools:
async def test_server_answers_over_stdio():
# Launch main.py as a host would: a subprocess speaking JSON-RPC on stdin/stdout.
folder = Path(__file__).resolve().parent.parent
params = StdioServerParameters(command=sys.executable, args=[str(folder / "main.py")])
async with Client(params) as stdio_client:
tools = (await stdio_client.list_tools()).tools
assert len(tools) == 5That empty stdout is the rule from Lesson 1: over stdio, stdout carries protocol messages only. To see what breaking it does, print("loaded fixture") was added to HelplineStore.__init__ in a scratch copy and this test was run. It still passed, because mcp 2.3.0's stdio client logs the bad line and skips it:
ERROR mcp.client.stdio: Failed to parse JSONRPC message from server
...
Invalid JSON: expected value at line 1 column 1 [type=json_invalid, input_value='loaded fixture', input_type=str]So a stray print won't always break the connection, but it fills the host's log with errors and depends on the MCP client being forgiving. Other MCP clients may drop the connection instead. main.py configures no logging at all; if you add some, logging.basicConfig() writes to stderr by default, which keeps stdout clean.
In production, a host such as Claude Code starts this process and runs an MCP client inside it, and Helpline is the MCP server. In the tests, Client plays the MCP client role and no host is involved. As Step 1 said, Client handles the stateless protocol details, so none of this code mentions protocol versions.
10. Common problems
The host logs "Failed to parse JSONRPC message from server". Something writes to stdout. Search for stray print() calls, including in store.py, and check that no logging handler points at stdout.
Async tests are skipped or never run. Check the pytestmark = pytest.mark.anyio line and that anyio is in the dev dependencies. Without the marker, pytest doesn't run the coroutine.
ModuleNotFoundError mentions FastMCP. The code follows a v1 guide. Import MCPServer from mcp.server.mcpserver and Client from mcp.
Your bounds or enum are missing from the input schema. Field(ge=1, le=20) only reaches the schema inside Annotated[int, ...], and the status filter needs a Literal.
A call returns only Error executing tool <name>. The tool crashed instead of raising ToolError. If you expected the failure, raise ToolError with a hint. If you didn't, it's a bug.
11. Exercise: boundary tests for search_tickets
Add three tests to tests/test_tools.py: search_tickets with limit=0, with limit=20, and with status="closed".
Expected result. limit=0 and status="closed" both come back with is_error true, because input validation refuses them before the tool body runs. limit=20 sits exactly on the upper bound, so it succeeds and returns structured content with all ten tickets.
Hints. Use the client fixture. Assert on is_error, and check the text names the field that failed. Don't hard-code wording you haven't seen in your own run.
Verify with uv run pytest tests. The common mistake is wrapping the call in pytest.raises: over Client, a validation failure is a result, not an exception.
12. What we learned and what comes next
Helpline now has a tool surface built around support work. Five task-shaped tools take constrained inputs, their descriptions say what each tool won't do, every result carries structured content with a matching text block, expected failures come back with a hint, and escalating twice creates one escalation. Fifteen tests prove it: fourteen in-process, including one with a deliberately broken tool, and one over real stdio.
Two gaps remain. get_ticket returns a whole ticket however long it is, and no tool can report progress or be cancelled. Lesson 3, Resources, limits and long calls, closes both.

