Run long work as tasks

閱讀約需 101 分鐘 分鐘,8 節 中共有 4 個範例。

版次 2026.11.14 範例於 2026年11 月 19 通過測試 70 個範例中有 70 個通過 變更內容

由 AI 翻譯。經人工以英文驗證。 我們如何製作書籍

譯自英文書,版次 2026.11.14。 閱讀原文

此部分尚未翻譯,因此以英文呈現。

By the end of this chapter you can negotiate a Model Context Protocol extension, run a slow restock report as a task that the client polls, let tasks expire and cancel them, and say what MCP Apps add to a tool. What the chapter states is true of the specification at revision 2026-07-28 and of mcp 2.3.0, the Python SDK.

Before the shop places its weekly order for kitchen and garden goods with its suppliers, a lead on its support team asks the host for a restock report: every product recounted, and the ones with fewer than 30 units across both warehouses listed for reordering. That is more than a count. The shop's API has a slow endpoint, POST /stock/{sku}/recount, which recounts one product in both warehouses and by default takes 3 seconds. In Serve over Streamable HTTP, the shop's recount_stock tool walks all 64 products through that endpoint and streams a progress report after each one, while the client keeps the HTTP response open.

At the API's default speed, 64 products take more than three minutes, and a call that long has to survive the host's timeout, every proxy between the host and the server, and a lead who closes a laptop. Chapter 6 showed, in Cancel a call the client no longer needs, that a Streamable HTTP client cancels a call by closing its stream, so a call whose connection drops takes its work with it.

Work like this fits another shape that the Model Context Protocol (MCP) offers. With the Tasks extension, the server answers the call at once with a handle to a task: the call's work, whose status the client asks for as often as the server suggests, and whose result waits on the server until the client fetches it. Tasks is an extension, an optional addition to the protocol that both sides must agree to use. This chapter negotiates one, runs the restock report as a task, and ends with when not to.

Every example serves the shop's MCP server over loopback Streamable HTTP, as chapter 6's do, with the shop's API beside it. Setup they share lives in examples/lib/, and two modules there are new. lib.tasks is the book's own small Tasks extension, which Negotiate an extension introduces. lib.restock holds the restock report's work: it recounts every product through chapter 6's lib.recount, sets the task's status message after each one, and lists the products to reorder.

此部分尚未翻譯,因此以英文呈現。

Negotiate an extension

最近一次變動於第 2026.11.14 版

The core protocol is what every client and server must implement. An extension is something the protocol's maintainers, or anyone else, want to standardize without making it mandatory. Extensions became part of the protocol at revision 2026-07-28, when ClientCapabilities and ServerCapabilities gained an extensions field (changelog). The field maps each extension's identifier to a settings object, and an empty one means the extension is supported with no settings. An extension's identifier is a vendor prefix, a slash and a name. Official extensions use the prefix io.modelcontextprotocol, and anyone else uses a reversed domain they own (Extensions overview).

At the pinned revision, a client declares its extensions in every request, under _meta["io.modelcontextprotocol/clientCapabilities"].extensions, the same place it declares every other capability (Carry the version and capabilities on every request). A server lists its own in the result of server/discover (Extensions overview). Both sides leave extensions off by default and need an explicit opt-in. When only one side supports an extension, the specification says that side "MUST either revert to core protocol behavior or reject the request with an appropriate error" (versioning). So an extension is negotiated, not forked: a server that uses one still answers clients that don't.

Extensions also have a lifecycle. A policy adopted in September 2026, after the pinned revision, gives each extension a stage, Experimental, Beta or Stable, or a path into the core protocol (SEP-3392). Tasks is at Beta, to Core, and MCP Apps, which Know what MCP Apps add covers, is Stable (Extensions overview). A Beta extension may still change in ways that break clients.

The Tasks extension's identifier is io.modelcontextprotocol/tasks, and it defines no settings (SEP-2663). The Python SDK, mcp 2.3.0, ships the framework for writing extensions, but not the Tasks extension itself. A server-side extension subclasses mcp.server.extension.Extension, sets identifier, and can add tools, resources and new request methods, or wrap tools/call. A client-side extension is a ClientExtension, which declares the identifier and can claim result shapes that the core protocol doesn't have (mcp/server/extension.py, mcp/client/extension.py).

The SDK has no tasks/get handler and no types for the extension's handle. The task types it does define belong to the experimental tasks of revision 2025-11-25 (mcp_types). The extension's only official SDK package, @modelcontextprotocol/ext-tasks, is TypeScript, and for the pinned revision it covers only the requester, the client side; its receiver support is for the 2025-11-25 tasks. No official package implements the extension's server side at the pinned revision (ext-tasks).

So this book builds a small one. lib.tasks implements, on the SDK's framework, the part of the extension this chapter teaches: a Tasks server extension, a TasksClient client extension, and the methods tasks/get and tasks/cancel. It leaves out tasks/update and pushed notifications, and it keeps tasks in one process's memory. Use it to learn the protocol, and replace it with the SDK's own when a release ships one.

The shop's server passes tasks.Tasks({"restock_report"}) to MCPServer(extensions=[...]), which tells it to answer every call to restock_report with a task. The tool itself calls lib.restock. Serving the shop's server to one client with TasksClient and one without shows both halves of the negotiation; the example reads the first client's declaration off the wire, and the second client also sends one tasks/get.

declare-the-tasks-extension.py Python 3.12.15 · cryptography 50.0.2 · httpx2 2.16.2 · mcp 2.3.0 · mcp-types 2.3.0 · pydantic 2.14.3 · starlette 1.10.0 · uvicorn 0.54.0 通過
"""Declare the Tasks extension on the shop's server, then show what a client gets with it and without it: both declarations, and theMissing Required Client Capability error a client without it gets from the call and from the task method. The prose's point rests on those two errors."""import asyncioimport jsonimport osfrom mcp import Clientfrom mcp.server.mcpserver import MCPServerfrom mcp.shared.exceptions import MCPErrorfrom lib import loopback, restock, shop_api, tasks, wire# only restock_report answers with a task; the server's other tools answer as usualserver = MCPServer("shop-support", version="0.7.0", extensions=[tasks.Tasks({"restock_report"})])@server.tool(title="Restock report")async def restock_report(below: int = 30) -> restock.RestockReport:    """Recount every product's stock and list those with fewer than `below` units. Slow: runs as a task."""    return await restock.run(below)async def main() -> None:    app = wire.record_http(server.streamable_http_app(), log="declare.jsonl")    with loopback.serve(shop_api.create_app()) as api_url, loopback.serve(app) as base_url:        os.environ.update(shop_api.server_env(api_url))        async with Client(base_url + "/mcp", extensions=[tasks.TasksClient()]) as client:            print("protocol revision:", client.protocol_version)            print("server declares:", json.dumps(client.server_capabilities.extensions))            await client.list_tools()        async with Client(base_url + "/mcp") as plain:            try:                await plain.call_tool("restock_report")            except MCPError as error:                print("client without it:", error.error.code, error.error.message)                # the specification's field, which lists the extensions the client lacked                print("required:", json.dumps(error.error.data["requiredCapabilities"]))            try:                await tasks.get(plain.session, "any-task-id")       # the task methods check the declaration too            except MCPError as error:                print("tasks/get without it:", error.error.code)    # the first tools/list the client sent, as the wire trace recorded it    sent = next(e["request"] for e in wire.read_http_trace("declare.jsonl") if e["request"]["method"] == "tools/list")    # at this revision a client declares its capabilities in the _meta of each request it sends    print("client declares:", json.dumps(sent["params"]["_meta"]["io.modelcontextprotocol/clientCapabilities"]))asyncio.run(main())
輸出python declare-the-tasks-extension.py
protocol revision: 2026-07-28
server declares: {"io.modelcontextprotocol/tasks": {}}
client without it: -32021 Client did not declare required extension 'io.modelcontextprotocol/tasks'
required: {"extensions": {"io.modelcontextprotocol/tasks": {}}}
tasks/get without it: -32021
client declares: {"extensions": {"io.modelcontextprotocol/tasks": {}}}

The server declared {"io.modelcontextprotocol/tasks": {}}, and the client with the extension sent {"extensions": {"io.modelcontextprotocol/tasks": {}}} in the _meta of its tools/list request. Both are the identifier with an empty settings object.

The client without the extension called restock_report and got a JSON-RPC error: -32021 Client did not declare required extension 'io.modelcontextprotocol/tasks'. The error's data lists what that client lacked, {"extensions": {"io.modelcontextprotocol/tasks": {}}}. This is the specification's Missing Required Client Capability error, and the SDK's require_client_extension() raises it with the requiredCapabilities field filled in (mcp/server/mcpserver/server.py). The task methods check too. The same client's tasks/get got -32021, because the specification says servers MUST return that error for tasks/get, tasks/update and tasks/cancel from clients that didn't declare the extension (SEP-2663). The SDK doesn't make that check for an extension's own methods, so lib.tasks calls require_client_extension() in each of them.

The shop rejects the call rather than falling back, because the fallback, a plain three-minute call, is the problem this chapter started from. A tool whose work is sometimes short could fall back instead, and answer clients without the extension the ordinary way.

Working rule: Turn an extension on only on a side that implements it, through the SDK's extension classes, never by writing the identifier into capabilities by hand. Decide, for each tool on the server, what a client without the extension gets: an ordinary result when the work can finish within a normal call, and error -32021 when it can't. Check the client's declaration on every request, because at the pinned revision each request declares its own.

此部分尚未翻譯,因此以英文呈現。

Start a task instead of waiting

最近一次變動於第 2026.11.14 版

The client in Negotiate an extension declared that it can handle a task, and declaring is all the client does. The server alone decides, call by call and at the pinned revision, whether to answer with a task. A client that declared the extension "MUST be prepared to handle either CallToolResult or CreateTaskResult" (SEP-2663). The same tool can answer one call at once and the next with a task, and nothing in its definition says which. In the experimental tasks of revision 2025-11-25, the client asked for a task with a task parameter on the request. That design is gone and not wire-compatible with the extension.

Three rules limit the server. It MUST NOT return a task to a client that didn't declare the extension on that request, even if the client declared it on an earlier one. Only tools/call can be answered with a task in this revision. And the server MUST NOT return the handle until the task is durably created, so that a tasks/get for it would already find it (SEP-2663).

A task's handle is a CreateTaskResult: a result whose resultType is "task" instead of "complete". It carries the task's taskId, its status, an optional statusMessage, the timestamps createdAt and lastUpdatedAt, its lifetime in ttlMs, and a suggested pollIntervalMs (Tasks schema). The specification lets extensions add resultType values, and a client MUST treat a value it doesn't recognize as invalid (overview). That rule is why a server never sends a task to a client that hasn't declared the extension.

lib.tasks puts all of this in Tasks.intercept_tool_call, the SDK's one hook around tools/call. For a call to restock_report, it checks the request's declaration, creates a task record with an ID from secrets.token_urlsafe(24), and stores it. Then it starts the tool's ordinary handler in the background and returns the handle. Because the background work runs the same handler as a plain call, the task's result is exactly the CallToolResult a plain call returns. Timestamps come from tasks.Clock, a fake clock that starts on the shop's reference date, 30 June 2026, and moves only when an example moves it, so the output is the same on every run.

This run reuses the server from the previous example and calls restock_report with allow_claimed=True, which returns the handle, not the finished report. It then sends one tasks/get straight after, to check that the server already holds the task.

start-a-restock-report.py Python 3.12.15 · cryptography 50.0.2 · httpx2 2.16.2 · mcp 2.3.0 · mcp-types 2.3.0 · pydantic 2.14.3 · starlette 1.10.0 · uvicorn 0.54.0 通過
"""Call restock_report and keep the handle the server answers with at once, instead of waiting for the report. The tasks/get sent straight after is the line the prose rests on: it finds the task, so the server stored it before the handle left."""import asyncioimport osfrom mcp import Clientfrom lib import http_mcp, loopback, shop_api, tasks, wireserver = http_mcp.load_server("declare-the-tasks-extension.py")     # the shop's server with the Tasks extensionasync def main() -> None:    app = wire.record_http(server.streamable_http_app(), log="start.jsonl")    with loopback.serve(shop_api.create_app()) as api_url, loopback.serve(app) as base_url:        os.environ.update(shop_api.server_env(api_url))        async with Client(base_url + "/mcp", extensions=[tasks.TasksClient()]) as client:            # allow_claimed hands back the handle itself, not the result the client would otherwise wait for            handle = await client.session.call_tool("restock_report", {"below": 30}, allow_claimed=True)            task = await tasks.get(client.session, handle.task_id)    print("result type:", handle.result_type)    print("handle fields:", ", ".join(sorted(handle.model_dump(by_alias=True, exclude_none=True))))    print("status:", handle.status)    print("created at:", handle.created_at)    print("ttl ms:", handle.ttl_ms)    print("poll interval ms:", handle.poll_interval_ms)    print("task id length:", len(handle.task_id))    print("tasks/get straight after:", task["status"])    exchanges = wire.read_http_trace("start.jsonl")    get = next(e for e in exchanges if e["request"]["method"] == "tasks/get")   # the tasks/get the client sent above    # the trace stores header names in lowercase, so the lookup uses mcp-name    assert get["request_headers"].get("mcp-name") == handle.task_idasyncio.run(main())
輸出python start-a-restock-report.py
result type: task
handle fields: _meta, createdAt, lastUpdatedAt, pollIntervalMs, resultType, status, taskId, ttlMs
status: working
created at: 2026-06-30T09:00:00Z
ttl ms: 3600000
poll interval ms: 100
task id length: 32
tasks/get straight after: working

The call came back at once as a task, not the report. Its resultType was task, and its status was working. The handle's fields were _meta, createdAt, lastUpdatedAt, pollIntervalMs, resultType, status, taskId, ttlMs. The _meta field is the SDK's serverInfo stamp, added to every result at the pinned revision (mcp/server/runner.py).

The task was created at 2026-06-30T09:00:00Z on the fake clock. Its ttlMs was 3600000, one hour, and its pollIntervalMs was 100. The tasks/get sent straight after found the task working, which shows the server stored it before the handle left.

The task ID was 32 characters long, which encodes 192 random bits. The specification says task IDs may act as bearer handles, so servers MUST generate them with sufficient entropy that a third party cannot enumerate or guess them (SEP-2663). Over Streamable HTTP, the client MUST also copy the ID into the Mcp-Name header of tasks/get, tasks/update and tasks/cancel, so that a load balancer can route every request for one task the same way. The client's tasks/get carried the task ID in Mcp-Name, because lib.tasks sets name_param = "taskId" on its request classes and the SDK's client fills the header from that field (mcp_types/_types.py).

Working rule: Answer with a task when the work can outlive the connection, and decide per call, not per tool, when some calls are short. Store the task before you return the handle, and generate its ID from a cryptographic random source, with at least 128 bits. Run the same code a plain call runs, so a task's result never differs from a plain result. Never return a task to a request that didn't declare the extension.

此部分尚未翻譯,因此以英文呈現。

Poll a task and fetch its result

最近一次變動於第 2026.11.14 版

The handle from Start a task instead of waiting said the restock report was working. A task has five statuses: working, input_required, completed, failed and cancelled. The completed, failed and cancelled statuses are terminal, and once a task reaches one, its state doesn't change (Tasks overview). failed means a JSON-RPC error. A tool that ran and returned a result with isError: true ends completed, with that result inside, and the specification says failed MUST NOT be used for it (SEP-2663). It is the same split chapter 3 drew between tool execution errors and protocol errors, in Report failures as tool results.

The client finds out where a task stands by polling. It sends tasks/get with the taskId, and it SHOULD wait the server's pollIntervalMs between polls, a value that may change from one reply to the next. Servers MAY rate-limit clients that poll faster. Each reply is the task, with resultType "complete". When the task has completed, the reply carries result, which has the same structure as the result type of the original request (SEP-2663; Tasks schema). For a tool, that is a CallToolResult. Clients SHOULD store task IDs durably, so that polling can resume after a crash or a restart.

A server may also push status changes. The client subscribes with subscriptions/listen for the task IDs it holds, and the server sends notifications/tasks, each carrying the full task. Polling stays the default (Tasks overview), and lib.tasks implements only polling. A task that needs the user's input moves to input_required and carries input requests shaped like a Multi Round-Trip Request's (Return an input request instead of a result), which the client answers with tasks/update. lib.tasks doesn't implement that either, and the restock report never asks.

In the SDK, polling belongs in a client extension. TasksClient claims the result type "task" with a ResultClaim. The claim's resolver gets the handle and a session for follow-up requests, and it must return the call's ordinary CallToolResult (mcp/client/extension.py). The resolver waits pollIntervalMs, sends tasks/get, and repeats until the task is terminal. Client.call_tool then returns the result as if the call had been plain. A client without a claim for "task" can't parse the handle: the SDK validates it as a CallToolResult and raises pydantic's ValidationError. UnexpectedClaimedResult, which carries the handle, is for a client that has the claim but calls session.call_tool without allow_claimed=True (mcp/client/session.py).

A host makes this call when a lead asks for the restock report. Through TasksClient, with on_poll= set to keep every tasks/get reply, a client calls restock_report with a threshold of 30 units.

poll-the-restock-report.py Python 3.12.15 · cryptography 50.0.2 · httpx2 2.16.2 · jsonschema 4.26.0 · mcp 2.3.0 · mcp-types 2.3.0 · pydantic 2.14.3 · starlette 1.10.0 · uvicorn 0.54.0 通過
"""Call restock_report through a client whose extension polls the task until it ends, and get the report back as an ordinary tool result. The asserts check that the report was still working on more than one poll and that its messages only counted up, which the prose relies on."""import asyncioimport osfrom mcp import Clientfrom lib import http_mcp, loopback, shop_api, tasksserver = http_mcp.load_server("declare-the-tasks-extension.py")     # the shop's server with the Tasks extensionasync def main() -> None:    polls = []    with loopback.serve(shop_api.create_app()) as api_url, loopback.serve(server.streamable_http_app()) as base_url:        os.environ.update(shop_api.server_env(api_url))        # on_poll keeps every tasks/get reply, in the order the client received them        async with Client(base_url + "/mcp", extensions=[tasks.TasksClient(on_poll=polls.append)]) as client:            result = await client.call_tool("restock_report", {"below": 30})    statuses = [p["status"] for p in polls]    # dict.fromkeys drops repeated statuses but keeps their order, so each status is listed once    print("statuses:", " then ".join(dict.fromkeys(statuses)))    assert statuses.count("working") > 1, statuses    # the second word of "recounted N of 64 SKUs" is N    counted = [int(p["statusMessage"].split()[1]) for p in polls if "statusMessage" in p]    assert counted == sorted(counted), counted    print("last message:", polls[-1]["statusMessage"])    print("result type:", type(result).__name__)    report = result.structured_content    print("skus recounted:", report["skus"])    print("to reorder:", len(report["reorder"]))    # the first of the products the report lists for reordering    print("first to reorder:", "{sku}, {units} units".format(**report["reorder"][0]))asyncio.run(main())
輸出python poll-the-restock-report.py
statuses: working then completed
last message: recounted 64 of 64 SKUs
result type: CallToolResult
skus recounted: 64
to reorder: 5
first to reorder: KG-1018, 2 units

The polls show the statuses in order: working then completed. It was still working on more than one poll, its status messages only counted up, and the last one read "recounted 64 of 64 SKUs". The number of polls varies with the machine's speed, so the example prints none.

What came back from Client.call_tool was a CallToolResult. The report recounted 64 products and listed 5 to reorder, the first being KG-1018, 2 units. The code that made the call never saw a task, which is the point of the claim: a host written against plain tool calls, such as the one in Build a host that works through tickets, gets tasks by adding one extension to its client.

Working rule: Poll at the server's pollIntervalMs, re-read it on every reply, and stop at the first terminal status. Treat completed as the original call's result, isError and all, and failed as a protocol error. Hide the polling in a client extension so the rest of the host sees plain calls. When a host must survive a restart, store each task ID before the first poll, and resume from it.

此部分尚未翻譯,因此以英文呈現。

Expire and cancel tasks

最近一次變動於第 2026.11.11 版

The restock report in Poll a task and fetch its result finished and was fetched. Not every task is. A client may crash and never come back, or a lead may close a report they no longer need, and a server that keeps every task forever runs out of storage. The extension gives a task two ways to end early: its lifetime runs out, or the client cancels it.

A task's lifetime is its ttlMs, counted from createdAt, or null for no limit, and the server may change it. After the TTL elapses, servers MAY mark a task failed at any point, and later delete it at any time. A server that has purged a task must answer a tasks/get for it with error -32602, Invalid Params, and it may say the task can't be found rather than that it expired (SEP-2663). So a client can't count on a result outliving the TTL, however the task went.

Cancelling uses tasks/cancel with the taskId, and the specification says notifications/cancelled MUST NOT be used for it. The reply is an empty acknowledgement, and it promises nothing more: "A server is not obligated to actually stop the work; it is only obligated to acknowledge the request." The task may stay working for a while, and it may still end completed or failed. Once it has sent the cancel, the client may forget the task (SEP-2663). This is cooperative cancellation, unlike chapter 6's, where closing the stream cancelled the call's work in the server (Cancel a call the client no longer needs).

lib.tasks makes both concrete. On a tasks/get after the TTL, it deletes the task, stops its work, and answers -32602 with the message the specification's example uses. On tasks/cancel, it sets a flag and acknowledges. The tool's work reads the flag through tasks.cancel_requested(), and lib.restock checks it after each product, so the restock report stops at the end of the product it is recounting, and the task becomes cancelled then.

The expiry example sets a one-minute ttlMs, which shows expiry without a long wait. So that its output never depends on the machine's speed, it holds each report before every product, with restock.Steps, a gate in lib.restock that lets one more product start each time allow() is called. It starts one report that is never allowed a product, polls it, moves the fake clock 61 seconds on, and polls again. Then it starts a second report, lets it recount one product, waits for its first status message, and cancels it. It polls at once, lets the report start its next product, and polls until the task is terminal.

expire-a-task.py Python 3.12.15 · cryptography 50.0.2 · httpx2 2.16.2 · mcp 2.3.0 · mcp-types 2.3.0 · pydantic 2.14.3 · starlette 1.10.0 · uvicorn 0.54.0 通過
"""Show the two ways a task ends early: its time to live runs out and the server purges it, or the client cancels it and the report stops at its next check. The -32602 from the purged task and the final status of the cancelled report are the lines the prose rests on."""import asyncioimport osfrom mcp import Clientfrom mcp.server.mcpserver import MCPServerfrom mcp.shared.exceptions import MCPErrorfrom lib import loopback, restock, shop_api, tasksclock = tasks.Clock()                                     # fake time: moves only when the example says sofirst_steps, second_steps = restock.Steps(), restock.Steps()   # a report starts a product only when allowedpending = [first_steps, second_steps]                     # one per call, in call order# a task expires one minute after it was created, counted on the fake clockserver = MCPServer("shop-support", version="0.7.0",                   extensions=[tasks.Tasks({"restock_report"}, ttl_ms=60_000, clock=clock)])@server.tool(title="Restock report")async def restock_report(below: int = 30) -> restock.RestockReport:    """Recount every product's stock and list those with fewer than `below` units. Slow: runs as a task."""    # calls arrive in order, so each report takes the next gate    return await restock.run(below, steps=pending.pop(0))async def main() -> None:    with loopback.serve(shop_api.create_app()) as api_url, loopback.serve(server.streamable_http_app()) as base_url:        os.environ.update(shop_api.server_env(api_url))        async with Client(base_url + "/mcp", extensions=[tasks.TasksClient()]) as client:            first = await client.session.call_tool("restock_report", allow_claimed=True)            print("first, ttl ms:", first.ttl_ms)         # first_steps allows no product, so it stays working            print("first, first poll:", (await tasks.get(client.session, first.task_id))["status"])            clock.advance(61)                             # 61 seconds: past the one-minute time to live            try:                await tasks.get(client.session, first.task_id)            except MCPError as error:                print("first, 61 s later:", error.error.code, error.error.message)            second = await client.session.call_tool("restock_report", allow_claimed=True)            second_steps.allow()                          # product 1 only: the report then waits before product 2            task = await tasks.poll_until(client.session, second.task_id, lambda t: "statusMessage" in t)            print("second, before cancel:", task["status"] + ",", task["statusMessage"])            ack = await tasks.cancel(client.session, second.task_id)            print("cancel acknowledged, besides _meta:", ", ".join(f"{k} {v}" for k, v in ack.items() if k != "_meta"))            print("second, right after:", (await tasks.get(client.session, second.task_id))["status"])            second_steps.allow()                          # product 2 starts; the check after it sees the cancel            task = await tasks.poll_until(client.session, second.task_id, lambda t: t["status"] in tasks.TERMINAL)            print("second, finally:", task["status"] + ",", task["statusMessage"])asyncio.run(main())
輸出python expire-a-task.py
first, ttl ms: 60000
first, first poll: working
first, 61 s later: -32602 Failed to retrieve task: Task has expired
second, before cancel: working, recounted 1 of 64 SKUs
cancel acknowledged, besides _meta: resultType complete
second, right after: working
second, finally: cancelled, stopped after 2 of 64 SKUs

The first task's ttlMs was 60000, and it was working on its first poll. After 61 seconds on the fake clock, tasks/get answered -32602 Failed to retrieve task: Task has expired. On that poll, lib.tasks stopped the first task's work too, and its result would have gone with it had the work finished.

The second task was working, recounted 1 of 64 SKUs when the client cancelled it. Besides the SDK's _meta stamp, the acknowledgement held only resultType complete: an empty result, apart from the field every result carries. A poll straight after found the task still working, because the cancel only set a flag and the report hadn't reached its next check. In the shop, that check comes after the current product's recount; in the example, the report was held before its second product.

The last poll found cancelled, stopped after 2 of 64 SKUs. The report recounted one more product after the cancel, then stopped, as the specification allows.

Working rule: Give every task a TTL that covers the longest wait you expect between the work finishing and the client fetching it, and purge after it; for the shop's restock report, that is an hour. Make long work check for cancellation at each natural step, such as each product, and clean up there. In the client, treat a cancel's acknowledgement as "asked", not "stopped", and treat -32602 from tasks/get as a task that is gone for good.

此部分尚未翻譯,因此以英文呈現。

Know what MCP Apps add

最近一次變動於第 2026.11.14 版

Tasks change when a tool's result arrives, as Start a task instead of waiting showed. MCP Apps is an official extension that changes how a result is shown. Its identifier is io.modelcontextprotocol/ui. A tool names a user interface in _meta.ui.resourceUri: a ui:// resource, served with the MIME type text/html;profile=mcp-app. A host that supports Apps renders that HTML in a sandboxed iframe, and talks to it only through postMessage, in JSON-RPC: MCP's own methods, such as tools/call, plus methods whose names start with ui/. Through the host, the app can call the server's tools (MCP Apps; Apps specification).

A tool's _meta.ui.visibility says who may call it, ["model", "app"] by default. A tool for the app alone is hidden from the model. The Apps specification puts both directions on the host: it MUST NOT include such a tool in the model's tool list, and it MUST reject an app's call to a tool whose visibility leaves out "app" (Apps specification). A UI-enabled tool should still return meaningful text for clients that don't support the extension (Extensions overview).

The Apps specification is dated 2026-01-26 and marked Stable, and its negotiation examples use the 2025 initialize handshake. At the pinned revision, a client declares Apps per request, like any extension (Negotiate an extension). Unlike Tasks, Apps ships in the Python SDK, in mcp.server.apps. Apps() is the extension, @apps.tool(resource_uri=...) declares a UI-enabled tool, apps.add_html_resource() serves the HTML, and client_supports_apps(ctx) says whether this request's client declared Apps with the right MIME type (mcp/server/apps.py).

The restock report is a candidate. As an app, it could show the products to reorder as a table, with a button beside each that adds the product to the supplier order. That button would call a tool such as add_to_supplier_order, with a visibility of ["app"], so that the model never places orders on its own. The report would keep its text and structured content, so a host without Apps would read the same report as in Poll a task and fetch its result. The book doesn't build this view, because its host loop in chapter 10 has no screen, and an Apps view needs one to render it.

MCP Apps and elicitation do different jobs. Elicitation is the server asking the user one question in the middle of a call, through the client's own form (Ask for structured input with elicitation). An app is a view of a tool's result, which the server writes and the host renders.

Working rule: Reach for MCP Apps when a result needs more than text to act on, such as a table to sort or a choice per row, and the hosts your users run support the extension. Keep every UI-enabled tool's text result complete, so a host without Apps loses only the view. Give app-only tools a visibility of ["app"] when the model shouldn't call them, and remember that the host enforces it, not your server.

選擇任務、進度回報或一般呼叫

最近一次變動於第 2026.11.11 版

商店現在以三種方式執行工作:一般呼叫,例如 get_order_status;會串流進度的呼叫,即第 6 章的 recount_stock;以及任務,即〈輪詢任務並取得結果〉中的補貨報表。三者的差異在於連線必須撐過什麼,以及呼叫端在等待期間能看到什麼。

進度回報是決定多數選擇的關鍵差異。就目前這個版本而言,規格並未全面支援在任務上使用 notifications/progress 或 notifications/message(SEP-2663)。任務只能透過 statusMessage 回報進度,由用戶端在輪詢時讀取。補貨報表中的「已盤點 64 個 SKU 中的 12 個」就是這類訊息:它是一個字串,只在用戶端輪詢時才看得到,也沒有進度條可用的數值。記錄訊息也無法繞過這個限制(〈取代 sampling、roots 與 logging〉)。

另一項差異在於雙方各需支援什麼。一般呼叫與進度回報屬於核心協定。任務則需要雙方都實作一項擴充功能,而各主機對擴充功能的支援程度不一(〈擴充功能支援矩陣〉)。〈任務概覽〉列出了任務適用的情況:執行時間超過連線壽命的工作、必須在用戶端重新啟動後存活的工作,以及原本就以工作形式在佇列中執行的工作。

下表以我們的經驗法則(並非實測數據)比較這三種方式。

一般呼叫 進度回報 任務
典型時間長度 數秒 最多數分鐘 數分鐘以上
連線必須保持開啟 是 是 否
呼叫端等待時看到的內容 無 進度與總量 狀態訊息
用戶端重新啟動後仍可存活 否 否 是,前提是用戶端已儲存 ID
需要擴充功能 否 否 是,雙方都需要

get_order_status維持一般呼叫,因為它在數毫秒內就會回應。recount_stock 沿用第 6 章的進度回報,因為啟動它的組長會看著計數增加並等待。補貨報表則成為任務,因為以該 API 的實際速度它要執行數分鐘,組長希望稍後再取得而不是在一旁守候,而且連線中斷不應讓三分鐘的盤點白費。

實用原則: 當結果能在主機與伺服器之間所有逾時限制之內順利回傳時,使用一般呼叫。當工作耗時較長,呼叫端在一條可信任會保持開啟的連線上等待,且想要顯示數值時,使用進度回報。當工作可能比連線活得更久,或呼叫端想先離開稍後再回來時,使用任務。請接受任務只能回報狀態訊息這項限制,並為沒有該擴充功能的用戶端保留一般呼叫的後備做法,或明確回傳 -32021。

正式環境中會出什麼問題

最近一次變動於第 2026.11.11 版

本章的補貨報告只在單一行程中執行,任務存放在記憶體裡,時鐘也是模擬的。一旦分散到多個副本、連續執行數日,並由許多使用者呼叫,就可能以下列方式失敗,每一種都有可以查看的徵兆。

任務只存放在一個副本上。lib.tasks 把任務存在字典中。在第 6 章的兩個副本之後(不使用黏性工作階段來執行多個副本),若 tasks/get 送到另一個副本,就會找不到任務,並回應 -32602。請把任務存放在每個副本都能讀取的地方,例如資料庫或工作佇列自己的儲存區,或是依 Mcp-Name 標頭進行路由,該標頭在每個任務請求中都帶有任務 ID。你會看到任務在幾秒內就「過期」,頻率與負載平衡器切換副本的速度相近。

**任務 ID 洩漏他人的結果。**任務 ID 可能是呼叫者與已儲存結果之間唯一的屏障。規範指出,伺服器必須對每個與任務相關的請求執行驗證與授權檢查,並且已移除 tasks/list,因為範圍設定不當時,它可能讓一位呼叫者看到另一位的任務 ID(SEP-2663)。請把呼叫者與任務一併記錄,待 以 OAuth 授權用戶端 到位後,改用權杖的 subject,並拒絕其他人發出的每個 tasks/get 與 tasks/cancel。經由任務送達的輸入請求,得到的信任程度與直接呼叫中的相同,不會更高:「任務不是較高信任度的通道。」

**SDK 不會替你檢查宣告。**在 mcp 2.3.0 中,伺服器的執行器會不加檢查地傳遞擴充功能的 resultType,原始碼中的註解說明,對未宣告該擴充功能的用戶端拒絕此結果,仍待完成(mcp/server/runner.py)。擴充功能必須自行呼叫 require_client_extension(),在呼叫本身以及它自己的每個方法上都要呼叫,如同 lib.tasks 所做的。未宣告 Tasks 卻收到任務的用戶端,必須將該結果視為無效。SDK 的用戶端就是這樣做的,因為沒有 "task" 的宣告時,它會把該控制代碼當作 CallToolResult 驗證,並引發 ValidationError。

**輪詢的成本比工作本身更高。**數千個用戶端每 100 毫秒輪詢一次,本身就構成負載。任務執行越久,就應調高 pollIntervalMs;如規範所允許,對忽略它的用戶端進行速率限制;伺服器能夠主動推送後,再提供 notifications/tasks。徵兆是在你的追蹤紀錄中,tasks/get 的數量超過其他所有方法。

**任務越堆越多。**TTL 為 null,或比任何用戶端等待的時間都長,就會保留每個被放棄任務的結果。請設定 TTL,除了讀取時清除之外也要定期清除,並針對已儲存的任務數量設定警示。用戶端在重新啟動時遺失任務 ID,會使堆積更快增長,因此請在第一次輪詢之前就把 ID 儲存在用戶端。

**已取消的工作仍在執行。**從不檢查取消狀態的工具,在每次 tasks/cancel 之後仍會執行到結束,商店的 API 也會重新計算沒有人要的產品。請在每個步驟檢查,並記錄任務在取消之後又執行了多久。

**用戶端使用 2025-11-25 的任務。**該版本的實驗性任務使用 tasks/result、tasks/list,以及請求上的 task 參數,與此擴充功能在傳輸格式上並不相容(SEP-2663)。2025 年代的用戶端從不宣告 io.modelcontextprotocol/tasks,因此會遇到伺服器的 -32021。舊協定的其餘部分,請見 遷移 2025 年代的伺服器。

**擴充功能會在你不知情時改變。**Tasks 目前是 Beta,並正朝核心協定邁進,SDK 也可能在之後的版本推出自己的 Tasks 擴充功能。任一情況都是本章需要更新的觸發條件。當 SDK 推出時,請用它取代 lib.tasks,並保持商店的工具不變,因為該工具從不知道自己是以任務的形式執行。

**實用原則:**在上線之前,把任務的儲存移到每個副本都能讀取的地方,記錄每個任務的擁有者並在每個任務請求中檢查,並設定 TTL 與定期執行的清除機制。然後依副本觀察 tasks/get 的 -32602、tasks/get 與 tools/call 的比例、已儲存任務的數量,以及取消之後工作還會執行多久。

此部分尚未翻譯,因此以英文呈現。

Decisions this chapter made

最近一次變動於第 2026.11.11 版
  • The shop's restock report runs as a task, through the Tasks extension, because its work outlives a connection.
  • The shop's server refuses restock_report with error -32021 for clients without the extension, instead of running a three-minute plain call.
  • The book builds its own small Tasks extension, lib.tasks, on the SDK's extension framework, because mcp 2.3.0 ships none. It implements tasks/get and tasks/cancel, and leaves out tasks/update and pushed notifications.
  • A task runs the tool's ordinary handler, so its result is the same CallToolResult a plain call returns.
  • Task IDs carry 192 random bits, and every task request carries its ID in the Mcp-Name header.
  • The client polls at the server's pollIntervalMs inside a client extension, so the host sees plain tool calls.
  • Tasks expire one hour after they are created, and cancelling is cooperative: the restock report checks after each product.
  • recount_stock keeps chapter 6's progress, and get_order_status stays a plain call.
  • MCP Apps are described, not built, because the book's host loop renders no HTML. A restock view would keep the report's text, and hide its ordering tool from the model with a visibility of ["app"].
  • In production, tasks move to storage that both of chapter 6's replicas share, and every task request is checked against the caller who started the task.
  • The lesson is where the waiting goes: a task moves it off the connection and onto the server, which keeps the state, sets how long it lasts, and decides who may read it.

本章,於本版次中

版次 2026.11.14範例於 2026年11 月 19 通過測試本章 4 個範例 個範例中有 4 個通過

譯自英文書,版次 2026.11.14。

引用本節

格式

各種格式皆引用英文原書,本譯本即依循該原書。

每種格式都會標示本版。其連結會開啟目前版次,節標題會說明該節內文最後一次變動的時間。存取日期與擷取日期即為你開啟此頁的當日。

本頁內容

第 7 章,共 12 章: Run long work as tasks

  1. Negotiate an extension
  2. Start a task instead of waiting
  3. Poll a task and fetch its result
  4. Expire and cancel tasks
  5. Know what MCP Apps add
  6. 選擇任務、進度回報或一般呼叫
  7. 正式環境中會出什麼問題
  8. Decisions this chapter made

返回頂端所有章節