長時間の処理をタスクとして実行する

読了まで約74 分分、8 節 節の 4 例 例。

第2026.11.14版 2026年11月19日時点で例が通過 70 例中 70 例が合格 変更点

AIによる翻訳。英語版は人による検証済みである。 当社の書籍の作り方

英語版の書籍(版2026.11.14)から翻訳した。 原文を読む

この章を終えると、Model Context Protocol の拡張をネゴシエートし、時間のかかる補充レポートをクライアントがポーリングするタスクとして実行し、タスクを期限切れにしたりキャンセルしたりし、MCP Apps がツールに何を加えるかを説明できるようになる。この章の記述は、リビジョン 2026-07-28 の仕様と、Python SDK である mcp 2.3.0 について成り立つ。

ショップが台所用品と園芸用品の週次発注を仕入先に出す前に、サポートチームのリーダーがホストに補充レポートを求める。これは全商品を再集計し、両方の倉庫を合わせた在庫が 30 個未満の商品を再発注の対象として一覧にするものである。これは単なる集計にとどまらない。ショップの API には動作の遅いエンドポイント POST /stock/{sku}/recount があり、1 つの商品を両方の倉庫で再集計し、既定では 3 秒かかる。Streamable HTTP で提供するでは、ショップの recount_stock ツールが 64 個の商品すべてをこのエンドポイントに通して順に処理し、1 つ終えるたびに進捗レポートをストリームで返し、その間クライアントは HTTP レスポンスを開いたままにしている。

API の既定の速度では、64 個の商品の処理に 3 分以上かかる。これほど長い呼び出しは、ホストのタイムアウト、ホストとサーバーの間にあるすべてのプロキシ、そしてノートパソコンを閉じてしまうリーダーのいずれにも耐えなければならない。6 章ではクライアントがもう必要としない呼び出しをキャンセルするで、Streamable HTTP のクライアントがストリームを閉じることで呼び出しをキャンセルすることを示した。したがって、接続が切れた呼び出しは、その作業ごと失われる。

このような処理には、Model Context Protocol(MCP)が提供する別の形が適している。Tasks 拡張を使うと、サーバーは呼び出しに対して、タスクへのハンドルを即座に返す。タスクとは呼び出しの作業そのものであり、クライアントはサーバーが示す頻度で状態を問い合わせ、結果はクライアントが取得するまでサーバー上で待機する。Tasks は拡張、すなわち双方が使用に合意しなければならない、プロトコルへの任意の追加機能である。この章では拡張をネゴシエートし、補充レポートをタスクとして実行し、最後にタスクを使うべきでない場合を述べる。

すべての例は、6 章と同様に、ショップの MCP サーバーをループバックの Streamable HTTP で提供し、その隣にショップの API を置く。共通のセットアップは examples/lib/ にあり、そこの 2 つのモジュールは新しいものである。lib.tasks は本書独自の小さな Tasks 拡張であり、拡張をネゴシエートするで紹介する。lib.restock は補充レポートの作業を収めている。6 章の lib.recount を通じて全商品を再集計し、1 つ終えるたびにタスクのステータスメッセージを設定し、再発注する商品を一覧にする。

この部分はまだ翻訳されていないため、英語で表示している。

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.

MCP Apps が加えるものを把握する

最終変更:版2026.11.14

タスクは、ツールの結果がいつ届くかを変える。これは タスクを開始して待たずに進める で示したとおりである。MCP Apps は、結果の見せ方を変える公式の拡張である。識別子は io.modelcontextprotocol/ui である。ツールは _meta.ui.resourceUri でユーザーインターフェースを指定する。これは ui:// リソースであり、MIME タイプ text/html;profile=mcp-app で提供される。Apps に対応するホストは、その HTML をサンドボックス化された iframe 内に描画し、postMessage だけを通じて、JSON-RPC で通信する。使われるのは、tools/call などの MCP 自身のメソッドと、名前が ui/ で始まるメソッドである。アプリはホストを介して、サーバーのツールを呼び出せる (MCP Apps; Apps 仕様)。

ツールの _meta.ui.visibility は、そのツールを誰が呼び出せるかを示し、既定値は ["model", "app"] である。アプリ専用のツールは、モデルからは見えない。Apps 仕様は、この両方向の制御をホストに課している。ホストは、そのようなツールをモデルのツール一覧に含めてはならず (MUST NOT)、可視性に "app" を含まないツールへのアプリからの呼び出しを拒否しなければならない (MUST) (Apps 仕様)。それでも、UI を持つツールは、拡張に対応しないクライアントのために、意味のあるテキストを返すべきである (拡張の概要)。

Apps 仕様の日付は 2026-01-26 で、Stable と記されている。ただし、ネゴシエーションの例には 2025 年版の initialize ハンドシェイクが使われている。固定したリビジョンでは、クライアントは他の拡張と同様に、リクエストごとに Apps を宣言する (拡張をネゴシエーションする)。Tasks と異なり、Apps は Python SDK の mcp.server.apps に含まれている。Apps() が拡張そのものであり、@apps.tool(resource_uri=...) が UI を持つツールを宣言し、apps.add_html_resource() が HTML を提供し、client_supports_apps(ctx) は、このリクエストのクライアントが正しい MIME タイプで Apps を宣言したかどうかを返す (mcp/server/apps.py)。

再発注レポートは、アプリ化の候補である。アプリとして実装すれば、発注すべき商品を表で表示し、各行の横に、その商品を仕入先への発注に追加するボタンを置ける。このボタンは add_to_supplier_order のようなツールを呼び出し、その可視性は ["app"] とする。これにより、モデルが自分で発注することはない。レポートはテキストと構造化コンテンツを保つので、Apps に対応しないホストでも、タスクをポーリングして結果を取得する と同じレポートを読める。本書はこのビューを構築しない。10 章のホストループには画面がなく、Apps のビューを描画するには画面が必要だからである。

MCP Apps とエリシテーションは、役割が異なる。エリシテーションは、呼び出しの途中でサーバーがユーザーに 1 つの質問をする仕組みであり、クライアント自身のフォームを通じて行う (エリシテーションで構造化された入力を求める)。アプリは、ツールの結果を見せるビューであり、サーバーが書き、ホストが描画する。

実践ルール: 結果に対して操作するのにテキスト以上のものが必要な場合 (並べ替える表や、行ごとの選択など) で、ユーザーが使うホストが拡張に対応しているときは、MCP Apps を使う。UI を持つすべてのツールのテキスト結果は完全な形に保ち、Apps に対応しないホストが失うのがビューだけになるようにする。モデルに呼び出させたくないアプリ専用ツールには ["app"] の可視性を与える。そして、それを強制するのはサーバーではなくホストであることを忘れてはならない。

タスク、進捗通知、通常の呼び出しから選ぶ

最終変更:版2026.11.11

ショップは現在、三つの方法で処理を実行している。get_order_status のような通常の呼び出し、6章の recount_stock のように進捗をストリーミングする呼び出し、そして タスクをポーリングして結果を取得する で扱った補充レポートのようなタスクである。これらは、接続がどこまで持ちこたえる必要があるか、また待機中に呼び出し側に何が見えるかという点で異なる。

選択の大半を決めるのは進捗の違いである。この版の時点では、仕様はタスク全般で notifications/progress や notifications/message をサポートしていない(SEP-2663)。タスクが進行状況を報告する手段は statusMessage だけであり、クライアントはポーリングのときにそれを読む。補充レポートの「64 SKU のうち 12 を再集計済み」は、この種のメッセージである。これは文字列であり、クライアントがポーリングした頻度でしか見えず、進捗バーに使える数値も含まない。ログメッセージでこれを回避することはできない(サンプリング、ルート、ログの置き換え)。

もう一つの違いは、どちらが何をサポートしなければならないかである。通常の呼び出しと進捗通知はコアプロトコルに含まれる。タスクは双方が拡張を実装する必要があり、ホストによる拡張のサポート状況は一様ではない(拡張サポート対応表)。タスクの概要は、タスクが対象とするケースとして、接続より長く続く処理、クライアントの再起動をまたいで残る必要がある処理、すでにキュー内のジョブとして実行されている処理を挙げている。

三つの方法を一つの表で比較する。これは測定ではなく、私たちの経験則である。

通常の呼び出し 進捗通知 タスク
一般的な長さ 数秒 数分まで 数分以上
接続を開いたままにする必要 あり あり なし
待機中に呼び出し側に見えるもの なし 進捗と合計 ステータスメッセージ
クライアントの再起動後も残る いいえ いいえ はい(クライアントが ID を保存している場合)
拡張が必要 いいえ いいえ はい(双方)

get_order_status は、ミリ秒で応答するため通常の呼び出しのままとする。recount_stock は、実行したリードが件数の増えるのを見ながら待つため、6章の進捗通知を維持する。補充レポートはタスクにする。API の実際の速度では数分かかり、リードは見守るよりも後で結果を受け取りたく、接続が切れても 3 分間の再集計が無駄になるべきではないからである。

実践ルール: 結果がホストとサーバーの間のどのタイムアウトよりも十分早く返る場合は、通常の呼び出しを使う。処理が長く、呼び出し側が開いたままと信頼できる接続上で待ち、表示する数値を求める場合は、進捗通知を使う。処理が接続より長く続きうる場合、または呼び出し側がいったん離れて戻ってくる場合は、タスクを使う。タスクが報告するのはステータスメッセージだけであることを受け入れ、拡張のないクライアント向けには、通常の呼び出しによるフォールバックを用意するか、明確な -32021 を返す。

この部分はまだ翻訳されていないため、英語で表示している。

What goes wrong in production

最終変更:版2026.11.11

The restock report in this chapter ran in one process, with tasks in memory and a fake clock. Spread across replicas, run for days and called by many users, it can fail in the ways that follow, each with a sign you can look for.

Tasks are stored on one replica. lib.tasks keeps tasks in a dictionary. Behind chapter 6's two replicas (Run replicas without sticky sessions), a tasks/get that reaches the other replica finds nothing and answers -32602. Store tasks where every replica can read them, such as a database or a job queue's own store, or route on the Mcp-Name header, which carries the task ID on every task request. You'll notice it as tasks that "expire" within seconds, at about the rate your load balancer switches replicas.

Task IDs leak another caller's result. A task ID can be the only thing between a caller and a stored result. Servers MUST perform authentication and authorization checks on each task-related request, the specification says, and it removed tasks/list, which, scoped badly, could show one caller another's task IDs (SEP-2663). Record the caller with the task, from the token's subject once Authorize clients with OAuth is in place, and refuse every tasks/get and tasks/cancel from anyone else. An input request that arrives through a task gets the same trust as one in a direct call, and no more: "A task is not a higher-trust channel."

The SDK doesn't check the declaration for you. In mcp 2.3.0, the server runner passes an extension's resultType through unchecked, and a note in the source says that rejecting it for clients that didn't declare the extension is still to do (mcp/server/runner.py). The extension must call require_client_extension() itself, on the call and on each of its own methods, as lib.tasks does. A client that didn't declare Tasks and gets a task anyway must treat the result as invalid. The SDK's client does, because without a claim for "task" it validates the handle as a CallToolResult and raises a ValidationError.

Polling costs more than the work. Thousands of clients polling every 100 milliseconds make a load of their own. Raise pollIntervalMs as a task runs longer, rate-limit clients that ignore it, as the specification allows, and offer notifications/tasks once your server can push. The sign is tasks/get outnumbering every other method in your traces.

Tasks pile up. A TTL of null, or one longer than any client waits, keeps every abandoned task's result. Set a TTL, purge on a schedule as well as on read, and alert on the number of stored tasks. Clients that lose task IDs on restart make the pile grow faster, so store IDs on the client before the first poll.

Cancelled work keeps running. A tool that never checks for cancellation runs to the end after every tasks/cancel, and the shop's API recounts products nobody wants. Check at each step, and log how long tasks run after a cancel.

Clients speak the 2025-11-25 tasks. That revision's experimental tasks used tasks/result, tasks/list and a task parameter on the request, and they aren't wire-compatible with the extension (SEP-2663). A 2025-era client never declares io.modelcontextprotocol/tasks, so it meets the server's -32021. Migrate a 2025-era server covers the rest of the old protocol.

The extension changes under you. Tasks is Beta and on its way into the core protocol, and the SDK may ship its own Tasks extension in a later release. Either is an update trigger for this chapter. When the SDK ships one, replace lib.tasks with it and keep the shop's tool as it is, since the tool never knew it ran as a task.

Working rule: Move tasks' storage to where every replica can read it before they go to production, record each task's owner and check it on every task request, and set a TTL with a purge that runs on a schedule. Then watch -32602 from tasks/get by replica, the ratio of tasks/get to tools/call, the number of stored tasks, and how long work runs after a cancel.

この部分はまだ翻訳されていないため、英語で表示している。

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)から翻訳した。

この節を引用する

形式

いずれの形式も、本訳書が従う英語版の書籍を出典として示す。

いずれの形式もこの版を明示している。そのリンクは現行版を開き、節の見出しには本文が最後に変更された日付が示される。アクセス日と取得日は、これを開いた日である。

このページの内容

全12章中の第7章: 長時間の処理をタスクとして実行する

  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. MCP Apps が加えるものを把握する
  6. タスク、進捗通知、通常の呼び出しから選ぶ
  7. What goes wrong in production
  8. Decisions this chapter made

ページの先頭に戻るすべての章