IamBishal

Module 2Lesson 2 of 2Hands-on

2.2 Resources, limits and long calls

Helpline's MCP server gets two resource templates, one for full tickets and one for knowledge-base articles. It also gets a limit on every path the model can reach: an opaque cursor on search_tickets, a 4,000-character output budget on get_ticket that reports what it cut, and a knowledge-base timeout that returns a tool-result error. The search also sends progress notifications, and cancelling it stops the server's work. Each limit ends in a test, and the suite finishes at 25 tests.

Lesson 2 ended with two gaps. get_ticket returns a whole ticket however long it is, and nothing stops a slow call from hanging the agent. A model reads everything a tool returns, and every character spends context, so an unbounded response is a cost and a reliability problem at once. This lesson bounds Helpline's responses and makes its slow call well-behaved.

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

  1. expose tickets and knowledge-base articles as resource templates, and read one by URI
  2. explain why a full ticket history fits a resource the host attaches, while get_ticket stays a budgeted tool
  3. page search_tickets with an opaque cursor that the server refuses to reuse for a different query
  4. cut get_ticket to an output budget in a way the model can see
  5. give a slow call a timeout that returns a tool-result error the model can act on
  6. send progress notifications and receive them through Client
  7. cancel an in-flight call and prove the server stopped the work

Before you start. You need Lesson 2's server and tests, and a little anyio (introduced in Step 4). The companion folder is a complete copy of it with this lesson's changes: helpline/limits.py is new, helpline/server.py grows, and tests/test_limits.py holds the new tests. The fixture gains one long ticket, HL-1011, with 16 messages. Every listing and output below comes from that folder, run against mcp 2.3.0 on 2026-11-21.

You can either apply the changes below to your Lesson 2 copy or read them in the companion folder and run its tests. Every snippet says which file it belongs to; snippets from helpline/server.py sit inside build_server() unless they're models, which live at module level. The new imports in helpline/server.py are:

python
import anyio
from mcp.server.mcpserver import Context, MCPServer
from mcp.server.mcpserver.exceptions import ResourceNotFoundError, ToolError

from helpline.limits import BadCursor, decode_cursor, newest_within_budget, page

A module-level constant sets the slow service's deadline:

python
# The knowledge-base search calls a slow service; give up rather than hang the agent.
KB_TIMEOUT_SECONDS = 2.0

build_server() gains two parameters for the simulated slow service, used from Step 4:

python
def build_server(
    store: HelplineStore | None = None,
    kb_delay_seconds: float = 0.05,
    kb_timeout_seconds: float = KB_TIMEOUT_SECONDS,
) -> MCPServer:

and HelplineStore.__init__ in helpline/store.py gains one counter, used in Step 6:

python
        self.cancelled_searches = 0  # knowledge-base searches the client abandoned

The long ticket HL-1011 is added to data/helpline.json, with a new article KB-109; copy that file from the companion folder rather than typing it. Everything else from Lesson 2 (require_ticket, _summary, the two write tools) is unchanged. The new test file, tests/test_limits.py, starts with:

python
import anyio
import pytest
from helpline.limits import OUTPUT_BUDGET_CHARS, BadCursor, decode_cursor, encode_cursor
from helpline.server import build_server
from helpline.store import HelplineStore
from mcp import Client
from mcp.shared.exceptions import MCPError

pytestmark = pytest.mark.anyio

1. Tools, resources and prompts: who decides what gets read

Lesson 1 sorted the primitives by who controls them. Tools are model-controlled, resources are application-controlled, and prompts are user-controlled. That split decides where a limit belongs.

When the model calls get_ticket, nobody has looked at the ticket yet. The model asked for it mid-task, and whatever comes back lands in its context. That response needs a budget. When a user says "attach HL-1011" in a host, the host reads a resource and puts it in front of the model on purpose. Cutting that would hide what the user asked for. So in Helpline the full history is a resource, returned whole, and get_ticket is a tool that returns only what fits and says where the rest is.

Returning the resource whole is a trade-off. A very long ticket attached by a host goes into context in full, and only the host's own limits stop it. A production system with tickets thousands of messages long might cap or page that resource too. Helpline doesn't, because its longest ticket is 16 messages and the host made a deliberate choice to attach it.

Prompts are the third primitive, templates the user picks from a menu. Helpline doesn't define any, and this series doesn't build one.

2. The four limits, and what the model sees

LimitWhereWhat the model sees when it applies
Cursorsearch_ticketsnext_cursor to pass back; null on the last page
Output budgetget_ticketomitted_messages above zero and a full_history URI
Timeoutsearch_knowledge_baseA tool-result error saying how far it got and what to try
Cancellationsearch_knowledge_baseNothing: the MCP client gave up, and the server stops

Every limit either says what happened or happens because the MCP client asked for it. None of them silently drops data.

3. Step 1: Ticket and article resource templates

A resource template is a URI pattern for a family of resources. Helpline registers two, in helpline/server.py inside build_server():

python
    @server.resource(
        "helpline://tickets/{ticket_id}",
        title="Ticket with full history",
        mime_type="text/markdown",
    )
    def ticket_resource(ticket_id: str) -> str:
        row = store.ticket(ticket_id)
        if row is None:
            raise ResourceNotFoundError(f"No ticket {ticket_id!r}")
        lines = [f"# {row['id']}: {row['subject']}", ""]
        lines.append(f"Customer: {row['customer_name']} ({row['plan']}) · Status: {row['status']}")
        for m in store.messages(row["id"]):
            lines += ["", f"## {m['author']} · {m['at']}", "", m["body"]]
        return "\n".join(lines)

    @server.resource(
        "helpline://kb/{article_id}", title="Knowledge-base article", mime_type="text/markdown"
    )
    def article_resource(article_id: str) -> str:
        row = store.article(article_id)
        if row is None:
            raise ResourceNotFoundError(f"No article {article_id!r}")
        return f"# {row['title']}\n\n{row['body']}"

MCPServer sees the {ticket_id} placeholder and passes the matching part of the URI to the function. Through Client, list_resource_templates() returns exactly these two URI templates, and reading one returns Markdown. The first lines of helpline://tickets/HL-1011 are:

text
# HL-1011: Nightly CSV import fails with 'unexpected column count'

Customer: Brightleaf Foods (team) · Status: open

## customer · 2026-11-19T08:02:00Z

Our nightly CSV import into Helpline failed again. The error says 'row 18233: unexpected column count'. We did not change the file format.

The test confirms it is whole: all 16 messages, no budget applied.

python
async def test_ticket_resource_has_the_full_history():
    async with Client(build_server()) as client:
        result = await client.read_resource("helpline://tickets/HL-1011")
    text = result.contents[0].text
    assert text.startswith("# HL-1011: Nightly CSV import fails")
    assert text.count("\n## ") == 16  # every message, no budget applied

A missing ticket raises ResourceNotFoundError, which reaches the MCP client as a protocol error, not a result. In 2026-07-28 its code is -32602. Over Client that is an exception:

python
async def test_missing_resource_is_a_protocol_error():
    async with Client(build_server()) as client:
        with pytest.raises(MCPError) as caught:
            await client.read_resource("helpline://tickets/HL-0000")
    assert caught.value.error.code == -32602

The message is No ticket 'HL-0000'. A resource read is the host's request, not the model's, so a protocol error is the right shape: there's no model waiting to correct its call.

4. Step 2: An opaque cursor for search_tickets

MCP's own list methods, such as resources/list, resources/templates/list and tools/list, page with an opaque cursor rather than page numbers: a result carries nextCursor, and the MCP client sends it back to get more. With the SDK you follow that cursor yourself: Client.list_tools() takes a cursor= argument, and you pass the previous result's next_cursor. search_tickets is a tool, so the protocol doesn't page it. Helpline carries its own cursor input and next_cursor output in the tool's schemas, and the model, not the SDK, sends it back. The rule is the same: treat the cursor as an opaque string and return it unchanged.

The model for the result gains a field, in helpline/server.py at module level:

python
class TicketSearch(BaseModel):
    tickets: list[TicketSummary]
    total: int = Field(description="How many tickets matched in all")
    next_cursor: str | None = Field(
        description="Pass as `cursor` to get the next page; null on the last page"
    )

The server-side encoding lives in the new file helpline/limits.py, which starts with import base64, hashlib and json and from collections.abc import Sequence:

python
class BadCursor(ValueError):
    """The cursor is malformed or belongs to a different query."""

def _fingerprint(query: dict) -> str:
    return hashlib.sha256(json.dumps(query, sort_keys=True).encode()).hexdigest()[:12]

def encode_cursor(offset: int, query: dict) -> str:
    """An opaque token for "the next page of this exact query"."""
    raw = json.dumps({"o": offset, "q": _fingerprint(query)}).encode()
    return base64.urlsafe_b64encode(raw).decode().rstrip("=")

def decode_cursor(cursor: str, query: dict) -> int:
    """Return the offset, refusing cursors from another query or ones that were edited."""
    try:
        padded = cursor + "=" * (-len(cursor) % 4)
        data = json.loads(base64.urlsafe_b64decode(padded))
        offset, fingerprint = int(data["o"]), data["q"]
    except (ValueError, KeyError, TypeError) as exc:
        raise BadCursor("cursor is not valid") from exc
    if fingerprint != _fingerprint(query) or offset < 0:
        raise BadCursor("cursor belongs to a different query")
    return offset

def page[T](items: Sequence[T], offset: int, size: int, query: dict) -> tuple[list[T], str | None]:
    """One page of items and the cursor for the next page, or None on the last page."""
    chunk = list(items[offset : offset + size])
    end = offset + len(chunk)
    return chunk, (encode_cursor(end, query) if end < len(items) else None)

The fingerprint binds a cursor to the filters that produced it. Without it, a model that kept a cursor from a search for open tickets and reused it on a search for pending ones would skip results it never saw. search_tickets gains the cursor input, and its limit bound tightens to 1–10, default 5, so one page stays small:

python
    @server.tool(title="Search 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=10)] = 5,
        cursor: Annotated[
            str | None, Field(description="next_cursor from the previous page, unchanged")
        ] = None,
    ) -> TicketSearch:
        """Search tickets by words, status or customer, newest first, one page at a time.

        Use this to get a ticket id before calling get_ticket, draft_reply or escalate_ticket.
        """

The body decodes the cursor against its current filters and turns a mismatch into a tool-result error with a fix:

python
        filters = {"query": query, "status": status, "customer": customer, "limit": limit}
        offset = 0
        if cursor:
            try:
                offset = decode_cursor(cursor, filters)
            except BadCursor as exc:
                raise ToolError(
                    f"{exc}. Repeat the search with the same filters and no cursor."
                ) from exc
        rows = store.search_tickets(query, status, customer)
        chunk, next_cursor = page(rows, offset, limit, filters)
        return TicketSearch(
            tickets=[_summary(r) for r in chunk], total=len(rows), next_cursor=next_cursor
        )

With limit=4, the first page returns HL-1011, HL-1009, HL-1010 and HL-1008, a total of 11 and a next_cursor of eyJvIjogNCwgInEiOiAiYzJjY2E4YzUxNTEwIn0. Reusing a cursor from a search for open tickets on a search for pending ones gives:

text
Error executing tool search_tickets: cursor belongs to a different query. Repeat the search with the same filters and no cursor.

Two tests cover refusal. One reuses a cursor across filters through Client; the other edits a cursor directly:

python
async def test_cursor_from_another_query_is_refused():
    async with Client(build_server()) as client:
        first = await client.call_tool("search_tickets", {"status": "open", "limit": 2})
        cursor = first.structured_content["next_cursor"]
        reused = await client.call_tool("search_tickets", {"status": "pending", "cursor": cursor})
    assert reused.is_error is True
    assert "different query" in reused.content[0].text

def test_edited_cursor_is_refused():
    query = {"query": "", "status": None, "customer": None, "limit": 5}
    good = encode_cursor(5, query)
    assert decode_cursor(good, query) == 5
    with pytest.raises(BadCursor):
        decode_cursor(good[:-3] + "AAA", query)

Be precise about what this protects against. The fingerprint is a plain hash, not a signature, so it catches a cursor reused with other filters and a garbled token, but someone who decodes the base64 could change the offset and re-encode a valid cursor. Here that's harmless: the worst outcome is skipping to another page of results the caller could already search. If a cursor ever guarded something that mattered, you would sign it with an HMAC and a server secret. Note too that limit is part of the fingerprint, so changing the page size mid-walk is refused as a different query.

The third test walks every page and proves no ticket appears twice or goes missing:

python
async def test_pages_walk_every_ticket_once():
    seen, cursor, pages = [], None, 0
    async with Client(build_server()) as client:
        while True:
            args = {"limit": 4} | ({"cursor": cursor} if cursor else {})
            data = (await client.call_tool("search_tickets", args)).structured_content
            seen += [t["id"] for t in data["tickets"]]
            pages += 1
            cursor = data["next_cursor"]
            if cursor is None:
                break
    assert pages == 3
    assert len(seen) == len(set(seen)) == data["total"] == 11

An offset inside a cursor is fine for a fixture that doesn't change. If tickets arrived between pages, an offset would shift; a production cursor would encode the last item's sort key instead. The contract stays the same either way, which is the point of keeping it opaque.

5. Step 3: An output budget on get_ticket that shows where it cut

HL-1011 has 16 messages and about 7,600 characters of text. Returned whole, it would crowd out the rest of the model's work. helpline/limits.py defines the budget and the rule for what to keep:

python
# Characters of message text get_ticket may return. Roughly 1,000 tokens of English.
OUTPUT_BUDGET_CHARS = 4000

def newest_within_budget(texts: Sequence[str], budget: int = OUTPUT_BUDGET_CHARS) -> int:
    """How many of the newest texts fit in the budget (always at least one)."""
    used = kept = 0
    for text in reversed(texts):
        if kept and used + len(text) > budget:
            break
        used += len(text)
        kept += 1
    return kept

The newest messages are the ones a support agent acts on, so they are kept, and the newest one is kept even if it alone exceeds the budget. The model gains two fields, at module level in helpline/server.py:

python
class TicketDetail(TicketSummary):
    plan: str = Field(description="The customer's plan: starter, team or enterprise")
    messages: list[Message] = Field(description="The newest messages that fit, oldest first")
    omitted_messages: int = Field(description="Older messages left out to stay within budget")
    full_history: str = Field(description="Resource URI with every message")

and the body of get_ticket uses them:

python
        row = require_ticket(ticket_id)
        rows = store.messages(row["id"])
        kept = newest_within_budget([m["body"] for m in rows])
        messages = [Message(author=m["author"], at=m["at"], body=m["body"]) for m in rows[-kept:]]
        return TicketDetail(
            **_summary(row).model_dump(),
            plan=row["plan"],
            messages=messages,
            omitted_messages=len(rows) - kept,
            full_history=f"helpline://tickets/{row['id']}",
        )

For HL-1011 the result holds 7 messages (3,698 characters), omitted_messages is 9, and full_history is helpline://tickets/HL-1011. The kept list starts at "Update 8" and ends with "Update 14", the newest. Two tests pin this down:

python
async def test_long_ticket_is_truncated_visibly():
    async with Client(build_server()) as client:
        data = (await client.call_tool("get_ticket", {"ticket_id": "HL-1011"})).structured_content
    kept = sum(len(m["body"]) for m in data["messages"])
    assert kept <= OUTPUT_BUDGET_CHARS
    assert data["omitted_messages"] > 0
    assert data["omitted_messages"] + len(data["messages"]) == 16
    assert data["full_history"] == "helpline://tickets/HL-1011"
    # The newest message is always kept.
    assert data["messages"][-1]["body"].startswith("Update 14:")

async def test_short_ticket_is_not_truncated():
    async with Client(build_server()) as client:
        data = (await client.call_tool("get_ticket", {"ticket_id": "HL-1003"})).structured_content
    assert data["omitted_messages"] == 0
    assert len(data["messages"]) == 3

Run just these two with uv run pytest tests/test_limits.py -k truncated; pytest reports 2 passed, 9 deselected.

The tool description tells the model what the fields mean ("When omitted_messages is above zero, older messages were left out; they are in the full_history resource"). The URI is a pointer, not the content. Because resources are application-controlled, a host or user then reads it, or the host offers the model a way to request a resource. A host that offers neither leaves the model knowing the history exists but unable to fetch it, so it should tell the user what's missing rather than guess.

That's visible truncation: the response says it was cut and how to get the rest. Silent truncation, returning 7 messages as if they were all, would let the model reason confidently over half a conversation.

Both responses keep the same seven messages, but only the one on the right tells the model what it left out.

Be clear about what the budget measures. It counts message text only, as a proxy for response size: authors, timestamps and JSON overhead aren't counted, and the result carries the messages twice, once in structuredContent and once in the text block. So the serialised response is roughly twice the budget. Message text is what grows without limit, which is why it's the part measured; the rest is small and fixed per message. The budget is also soft: one oversized newest message passes on its own. It's a server-side limit on what the tool returns, not the model's context window, which the server can't see. Lesson 5 keeps it under test.

6. Step 4: A timeout that returns a result the model can act on

First, the anyio you need for Steps 4 to 6. MCPServer runs tools on anyio, which works over asyncio. anyio cancels work through cancel scopes, and a cancellation takes effect only at the next await. anyio.fail_after(seconds) is a scope that cancels its body when time runs out and then raises TimeoutError. anyio.move_on_after(seconds) does the same but carries on silently, and the test in Step 6 uses it. When a scope is cancelled, the code inside sees anyio's cancellation exception, which anyio.get_cancelled_exc_class() returns (on asyncio it is asyncio.CancelledError). That exception must be allowed to propagate, or the cancellation never finishes. Context is the per-request object MCPServer passes to a tool that asks for one; it is how a tool sends progress.

search_knowledge_base calls a slow service. In the companion code that service is simulated with anyio.sleep: each article costs kb_delay_seconds, 0.05 seconds by default, and the whole search must finish within KB_TIMEOUT_SECONDS, 2.0. build_server() takes both as parameters so tests can make the service slow on purpose. The tool is now async and takes a Context:

python
    @server.tool(title="Search the knowledge base", annotations=READ_ONLY)
    async def search_knowledge_base(
        query: Annotated[str, Field(min_length=3, description="What the customer is asking")],
        ctx: Context,
        limit: Annotated[int, Field(ge=1, le=5)] = 3,
    ) -> ArticleSearch:
        """Find knowledge-base articles that answer a customer's question, best match first.

        It can take a few seconds; it reports progress and gives up after a timeout.
        """
        candidates = store.search_articles(query)
        scanned = []
        try:
            with anyio.fail_after(kb_timeout_seconds):
                for i, (_, row) in enumerate(candidates, start=1):
                    await anyio.sleep(kb_delay_seconds)  # one call to the slow service
                    scanned.append(row)
                    await ctx.report_progress(i, len(candidates), f"checked {row['id']}")
        except TimeoutError:
            raise ToolError(
                f"The knowledge base did not answer within {kb_timeout_seconds:g}s "
                f"({len(scanned)} of {len(candidates)} articles checked). "
                "Try a narrower query."
            ) from None
        except anyio.get_cancelled_exc_class():
            store.cancelled_searches += 1  # the client gave up; stop work and record it
            raise
        hits = [
            ArticleHit(id=row["id"], title=row["title"], snippet=row["body"].split(". ")[0] + ".")
            for row in scanned[:limit]
        ]
        return ArticleSearch(articles=hits)

ctx doesn't appear in the input schema; MCPServer injects it. anyio.fail_after raises TimeoutError when the deadline passes, and the tool turns that into a ToolError. With a 0.5-second delay and a 0.2-second timeout, as in the test, the result is:

text
Error executing tool search_knowledge_base: The knowledge base did not answer within 0.2s (0 of 2 articles checked). Try a narrower query.

The test that produces it:

python
async def test_kb_search_times_out_with_a_useful_error():
    async with Client(build_server(kb_delay_seconds=0.5, kb_timeout_seconds=0.2)) as client:
        result = await client.call_tool("search_knowledge_base", {"query": "webhook secret"})
    assert result.is_error is True
    text = result.content[0].text
    assert "did not answer within 0.2s" in text
    assert "narrower query" in text

Run it alone with uv run pytest tests/test_limits.py -k times_out. A timeout is a failure the model can respond to, by narrowing the query or telling the user, so it belongs in a tool-result error. Letting the call hang would leave the agent stuck.

Notice what the timeout does not cover. store.search_articles(query) runs before the guarded loop, synchronously, and a timeout or cancellation can only take effect at an await. Here that query is a fast in-memory SQLite lookup, so it doesn't matter. A real slow service call must be awaitable (an async HTTP client, for example) or run in a worker thread that anyio can abandon, and it must sit inside the fail_after block.

A caller that wants progress puts a progressToken in the request's _meta. The server then sends notifications/progress messages naming that token, each with progress, an optional total and a message. ctx.report_progress(i, len(candidates), ...) in the loop above sends one per article. On the MCP client side, passing progress_callback to call_tool makes Client attach the token and route the notifications to your function:

python
async def test_kb_search_reports_progress():
    updates = []

    async def on_progress(progress, total, message):
        updates.append((progress, total, message))

    async with Client(build_server()) as client:
        result = await client.call_tool(
            "search_knowledge_base",
            {"query": "webhook secret rotation 401"},
            progress_callback=on_progress,
        )
    assert result.structured_content["articles"][0]["id"] == "KB-103"
    assert updates, "expected progress notifications"
    assert updates[-1][0] == updates[-1][1]  # last update: done == total

For that query the callback receives (1, 2, 'checked KB-103') and then (2, 2, 'checked KB-104'), and the result lists KB-103 then KB-104. Progress is a notification, not a request: the client sends no reply. In 2026-07-28, there is no session to hang it on, so it travels with the request it describes.

8. Step 6: Cancellation that stops the work

A user who loses patience, or a host that hits its own deadline, abandons a call. On stdio the MCP client then sends notifications/cancelled with the requestId; on Streamable HTTP it closes that request's response stream, and the server must treat a disconnect as cancellation. Either way, the useful outcome is that the server stops working, not just that the answer is thrown away.

In search_knowledge_base, cancellation arrives as anyio's cancellation exception at the next await, which is the anyio.sleep standing in for the service call. The tool records it and re-raises, so the work ends and the SDK can clean up. Never swallow that exception: a tool that catches it (with a bare except:, except BaseException, or the cancellation class itself) and carries on keeps calling the slow service for an answer nobody will read. A plain except Exception doesn't catch it, because cancellation exceptions derive from BaseException.

On stdio the cancellation is a notification; on Streamable HTTP, closing the response stream does the same job.

The test abandons a call partway and waits for the server to notice:

python
async def test_abandoned_kb_search_stops_on_the_server():
    store = HelplineStore()
    async with Client(build_server(store, kb_delay_seconds=0.3, kb_timeout_seconds=10)) as client:
        with anyio.move_on_after(0.4):
            await client.call_tool("search_knowledge_base", {"query": "webhook secret rotation"})
        # Give the server a moment to receive notifications/cancelled.
        with anyio.fail_after(2):
            while store.cancelled_searches == 0:
                await anyio.sleep(0.05)
    assert store.cancelled_searches == 1

Each article step takes 0.3 seconds and the caller gives up after 0.4, so the search is cut during its second step. Client sends the cancellation when the call is abandoned, and the server's cancellation branch runs. The counter is there for the test; a production server would log the event.

9. Run the full suite

bash
uv run pytest -v tests
text
tests/test_limits.py::test_resource_templates_are_listed PASSED
tests/test_limits.py::test_ticket_resource_has_the_full_history PASSED
tests/test_limits.py::test_missing_resource_is_a_protocol_error PASSED
tests/test_limits.py::test_pages_walk_every_ticket_once PASSED
tests/test_limits.py::test_cursor_from_another_query_is_refused PASSED
tests/test_limits.py::test_edited_cursor_is_refused PASSED
tests/test_limits.py::test_long_ticket_is_truncated_visibly PASSED
tests/test_limits.py::test_short_ticket_is_not_truncated PASSED
tests/test_limits.py::test_kb_search_reports_progress PASSED
tests/test_limits.py::test_kb_search_times_out_with_a_useful_error PASSED
tests/test_limits.py::test_abandoned_kb_search_stops_on_the_server PASSED
tests/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
============================== 25 passed in 1.97s ==============================

tests/test_tools.py is Lesson 2's suite carried forward, with its limit assertions updated to the new 1–10 bound. All 25 pass.

10. When it doesn't work

test_kb_search_reports_progress fails with "expected progress notifications". The callback never fired. Check that the tool takes ctx: Context and awaits ctx.report_progress(...), and that the test passes progress_callback= to call_tool.

test_abandoned_kb_search_stops_on_the_server fails with TimeoutError from fail_after(2). store.cancelled_searches never reached 1, so the tool's cancellation branch never ran. Either the cancellation never arrived at an await inside the guarded loop, or something caught it first. Look for a handler that swallows anyio's cancellation exception: a bare except:, an except BaseException:, or an except anyio.get_cancelled_exc_class(): that doesn't re-raise. except Exception is not the culprit: on asyncio, CancelledError derives from BaseException, so except Exception never catches it. Re-raise as Step 6 does.

The second page says "cursor belongs to a different query". Something in the filters changed between calls, often limit. Send exactly the same arguments plus the cursor.

An unhandled TimeoutError loses the hint. If the tool let TimeoutError escape, the SDK would treat it as a crash, and the model would get only the generic text from Lessons 1 and 2 instead of "Try a narrower query". (Inferred from that crash behaviour; not run here.)

The model loops on next_cursor. Paging is the model's choice. If it walks every page to answer "is there an open ticket about SSO?", the description should push it toward filters first; ours says to search by words, status or customer.

11. Exercise: give the knowledge-base search a cursor

Add cursor to search_knowledge_base the way Step 2 added it to search_tickets, reusing page() and decode_cursor() from helpline/limits.py, and return next_cursor in ArticleSearch.

Expected result. With limit=1, a query that matches two articles returns one article and a cursor; passing the cursor back returns the second article and next_cursor of None. Reusing the cursor with a different query is a tool-result error.

Hints. The fingerprint must include query and limit. Decide whether progress should cover the whole candidate list or only the page.

Verify with a test modelled on test_pages_walk_every_ticket_once, then run uv run pytest tests.

12. What we built, and what Lesson 4 needs from it

Helpline's responses are now bounded: resources for what the host attaches, a cursor bound to its filters, a budget that shows its cut, a timeout that explains itself, progress, and cancellation that stops the work. The server still runs only over stdio, where the person who starts it is the caller. Lesson 4 puts it on Streamable HTTP, where anyone on the network could call it, and adds OAuth.

Key Takeaways

  • Explain who controls each primitive: the model calls tools, the host chooses resources and the user picks prompts. Explain why that puts a ticket's full history in a resource while get_ticket stays a budgeted tool.
  • Register the resource templates helpline://tickets/{ticket_id} and helpline://kb/{article_id}, list them, and read one by URI through the in-process Client.
  • Raise ResourceNotFoundError for a missing resource, and explain why the MCP client sees protocol error -32602 rather than a tool-result error.
  • Paginate search_tickets with an opaque next_cursor tied to its filters, and refuse a reused or edited cursor with a tool-result error.
  • Tell Helpline's tool-level cursor apart from the protocol's cursor pagination on list methods such as resources/list, and treat both as opaque in the MCP client.
  • Trim get_ticket to an output budget of 4,000 characters. Keep the newest messages, always including the latest one, and report omitted_messages and a full_history resource URI.
  • Wrap the knowledge-base search in anyio.fail_after so a timeout returns a tool-result error that says how far the search got and suggests a narrower query.
  • Send progress notifications with ctx.report_progress when the caller supplies a progress token, and receive them with the Client's progress_callback.
  • Cancel an in-flight search from the Client, and show in a test that the cancelled exception reached the tool and was re-raised.
  • Name both cancellation bindings: notifications/cancelled on stdio, and closing the request's response stream on Streamable HTTP.

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.