Run long work as tasks
Unos 29 minutos de lectura, con 4 ejemplos en 8 secciones.
Traducido con IA. Verificado por personas en inglés. Cómo hacemos los libros
Traducido del libro en inglés, edición 2026.11.14. Lee el original
Esta parte aún no está traducida, así que está en inglés.
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.
Esta parte aún no está traducida, así que está en inglés.
Negotiate an extension
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.
1"""Declare the Tasks extension on the shop's server, then show what a client gets with it and without it: both declarations, and the2Missing 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."""3import asyncio4import json5import os67from mcp import Client8from mcp.server.mcpserver import MCPServer9from mcp.shared.exceptions import MCPError1011from lib import loopback, restock, shop_api, tasks, wire1213# only restock_report answers with a task; the server's other tools answer as usual14server = MCPServer("shop-support", version="0.7.0", extensions=[tasks.Tasks({"restock_report"})])151617@server.tool(title="Restock report")18async def restock_report(below: int = 30) -> restock.RestockReport:19 """Recount every product's stock and list those with fewer than `below` units. Slow: runs as a task."""20 return await restock.run(below)212223async def main() -> None:24 app = wire.record_http(server.streamable_http_app(), log="declare.jsonl")25 with loopback.serve(shop_api.create_app()) as api_url, loopback.serve(app) as base_url:26 os.environ.update(shop_api.server_env(api_url))27 async with Client(base_url + "/mcp", extensions=[tasks.TasksClient()]) as client:28 print("protocol revision:", client.protocol_version)29 print("server declares:", json.dumps(client.server_capabilities.extensions))30 await client.list_tools()31 async with Client(base_url + "/mcp") as plain:32 try:33 await plain.call_tool("restock_report")34 except MCPError as error:35 print("client without it:", error.error.code, error.error.message)36 # the specification's field, which lists the extensions the client lacked37 print("required:", json.dumps(error.error.data["requiredCapabilities"]))38 try:39 await tasks.get(plain.session, "any-task-id") # the task methods check the declaration too40 except MCPError as error:41 print("tasks/get without it:", error.error.code)42 # the first tools/list the client sent, as the wire trace recorded it43 sent = next(e["request"] for e in wire.read_http_trace("declare.jsonl") if e["request"]["method"] == "tools/list")44 # at this revision a client declares its capabilities in the _meta of each request it sends45 print("client declares:", json.dumps(sent["params"]["_meta"]["io.modelcontextprotocol/clientCapabilities"]))464748asyncio.run(main())
python declare-the-tasks-extension.pyprotocol 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.
Esta parte aún no está traducida, así que está en inglés.
Start a task instead of waiting
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.
1"""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."""2import asyncio3import os45from mcp import Client67from lib import http_mcp, loopback, shop_api, tasks, wire89server = http_mcp.load_server("declare-the-tasks-extension.py") # the shop's server with the Tasks extension101112async def main() -> None:13 app = wire.record_http(server.streamable_http_app(), log="start.jsonl")14 with loopback.serve(shop_api.create_app()) as api_url, loopback.serve(app) as base_url:15 os.environ.update(shop_api.server_env(api_url))16 async with Client(base_url + "/mcp", extensions=[tasks.TasksClient()]) as client:17 # allow_claimed hands back the handle itself, not the result the client would otherwise wait for18 handle = await client.session.call_tool("restock_report", {"below": 30}, allow_claimed=True)19 task = await tasks.get(client.session, handle.task_id)20 print("result type:", handle.result_type)21 print("handle fields:", ", ".join(sorted(handle.model_dump(by_alias=True, exclude_none=True))))22 print("status:", handle.status)23 print("created at:", handle.created_at)24 print("ttl ms:", handle.ttl_ms)25 print("poll interval ms:", handle.poll_interval_ms)26 print("task id length:", len(handle.task_id))27 print("tasks/get straight after:", task["status"])28 exchanges = wire.read_http_trace("start.jsonl")29 get = next(e for e in exchanges if e["request"]["method"] == "tasks/get") # the tasks/get the client sent above30 # the trace stores header names in lowercase, so the lookup uses mcp-name31 assert get["request_headers"].get("mcp-name") == handle.task_id323334asyncio.run(main())
python start-a-restock-report.pyresult 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.
Esta parte aún no está traducida, así que está en inglés.
Poll a task and fetch its result
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.
1"""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."""2import asyncio3import os45from mcp import Client67from lib import http_mcp, loopback, shop_api, tasks89server = http_mcp.load_server("declare-the-tasks-extension.py") # the shop's server with the Tasks extension101112async def main() -> None:13 polls = []14 with loopback.serve(shop_api.create_app()) as api_url, loopback.serve(server.streamable_http_app()) as base_url:15 os.environ.update(shop_api.server_env(api_url))16 # on_poll keeps every tasks/get reply, in the order the client received them17 async with Client(base_url + "/mcp", extensions=[tasks.TasksClient(on_poll=polls.append)]) as client:18 result = await client.call_tool("restock_report", {"below": 30})19 statuses = [p["status"] for p in polls]20 # dict.fromkeys drops repeated statuses but keeps their order, so each status is listed once21 print("statuses:", " then ".join(dict.fromkeys(statuses)))22 assert statuses.count("working") > 1, statuses23 # the second word of "recounted N of 64 SKUs" is N24 counted = [int(p["statusMessage"].split()[1]) for p in polls if "statusMessage" in p]25 assert counted == sorted(counted), counted26 print("last message:", polls[-1]["statusMessage"])27 print("result type:", type(result).__name__)28 report = result.structured_content29 print("skus recounted:", report["skus"])30 print("to reorder:", len(report["reorder"]))31 # the first of the products the report lists for reordering32 print("first to reorder:", "{sku}, {units} units".format(**report["reorder"][0]))333435asyncio.run(main())
python poll-the-restock-report.pystatuses: 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.
Vencer y cancelar tareas
El informe de reposición de Consultar una tarea y obtener su resultado terminó y se recuperó. No todas las tareas llegan a ese punto. Un cliente puede fallar y no volver nunca, o un responsable puede cerrar un informe que ya no necesita, y un servidor que conserva todas las tareas para siempre se queda sin almacenamiento. La extensión ofrece a una tarea dos formas de terminar antes: que se agote su vigencia, o que el cliente la cancele.
La vigencia de una tarea es su ttlMs, contado desde el createdAt, o null si no tiene límite, y el servidor puede cambiarla. Una vez transcurrido el TTL, los servidores PUEDEN marcar una tarea como failed en cualquier momento, y eliminarla más adelante en cualquier momento. Un servidor que ya ha purgado una tarea debe responder a un tasks/get sobre ella con el error -32602, Invalid Params, y puede indicar que la tarea no se encuentra en lugar de que ha vencido (SEP-2663). Por tanto, un cliente no puede dar por hecho que un resultado sobreviva al TTL, sea cual sea el camino que haya seguido la tarea.
Para cancelar se usa tasks/cancel con el taskId, y la especificación dice que notifications/cancelled NO DEBE usarse para ello. La respuesta es un acuse de recibo vacío, y no promete nada más: «Un servidor no está obligado a detener realmente el trabajo; solo está obligado a acusar recibo de la solicitud». La tarea puede seguir en working durante un tiempo, y todavía puede terminar en completed o en failed. Una vez enviada la cancelación, el cliente puede olvidar la tarea (SEP-2663). Es una cancelación cooperativa, a diferencia de la del capítulo 6, donde cerrar el flujo cancelaba en el servidor el trabajo de la llamada (Cancelar una llamada que el cliente ya no necesita).
lib.tasks lo muestra de forma concreta. En un tasks/get posterior al TTL, elimina la tarea, detiene su trabajo y responde -32602 con el mensaje que usa el ejemplo de la especificación. Ante un tasks/cancel, activa un indicador y acusa recibo. El trabajo de la herramienta lee ese indicador mediante tasks.cancel_requested(), y lib.restock lo comprueba tras cada producto, de modo que el informe de reposición se detiene al final del producto que está recontando, y la tarea pasa entonces a cancelled.
El ejemplo de vencimiento establece un ttlMs de un minuto, lo que permite mostrar el vencimiento sin una espera larga. Para que su salida no dependa de la velocidad de la máquina, retiene cada informe antes de cada producto, con restock.Steps, una compuerta en lib.restock que deja empezar un producto más cada vez que se llama a allow(). Inicia un informe al que nunca se le permite un producto, lo consulta, avanza 61 segundos el reloj simulado y vuelve a consultarlo. Después inicia un segundo informe, le deja recontar un producto, espera su primer mensaje de estado y lo cancela. Lo consulta de inmediato, deja que el informe comience su siguiente producto y consulta hasta que la tarea llega a un estado terminal.
1"""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."""2import asyncio3import os45from mcp import Client6from mcp.server.mcpserver import MCPServer7from mcp.shared.exceptions import MCPError89from lib import loopback, restock, shop_api, tasks1011clock = tasks.Clock() # fake time: moves only when the example says so12first_steps, second_steps = restock.Steps(), restock.Steps() # a report starts a product only when allowed13pending = [first_steps, second_steps] # one per call, in call order14# a task expires one minute after it was created, counted on the fake clock15server = MCPServer("shop-support", version="0.7.0",16 extensions=[tasks.Tasks({"restock_report"}, ttl_ms=60_000, clock=clock)])171819@server.tool(title="Restock report")20async def restock_report(below: int = 30) -> restock.RestockReport:21 """Recount every product's stock and list those with fewer than `below` units. Slow: runs as a task."""22 # calls arrive in order, so each report takes the next gate23 return await restock.run(below, steps=pending.pop(0))242526async def main() -> None:27 with loopback.serve(shop_api.create_app()) as api_url, loopback.serve(server.streamable_http_app()) as base_url:28 os.environ.update(shop_api.server_env(api_url))29 async with Client(base_url + "/mcp", extensions=[tasks.TasksClient()]) as client:30 first = await client.session.call_tool("restock_report", allow_claimed=True)31 print("first, ttl ms:", first.ttl_ms) # first_steps allows no product, so it stays working32 print("first, first poll:", (await tasks.get(client.session, first.task_id))["status"])33 clock.advance(61) # 61 seconds: past the one-minute time to live34 try:35 await tasks.get(client.session, first.task_id)36 except MCPError as error:37 print("first, 61 s later:", error.error.code, error.error.message)38 second = await client.session.call_tool("restock_report", allow_claimed=True)39 second_steps.allow() # product 1 only: the report then waits before product 240 task = await tasks.poll_until(client.session, second.task_id, lambda t: "statusMessage" in t)41 print("second, before cancel:", task["status"] + ",", task["statusMessage"])42 ack = await tasks.cancel(client.session, second.task_id)43 print("cancel acknowledged, besides _meta:", ", ".join(f"{k} {v}" for k, v in ack.items() if k != "_meta"))44 print("second, right after:", (await tasks.get(client.session, second.task_id))["status"])45 second_steps.allow() # product 2 starts; the check after it sees the cancel46 task = await tasks.poll_until(client.session, second.task_id, lambda t: t["status"] in tasks.TERMINAL)47 print("second, finally:", task["status"] + ",", task["statusMessage"])484950asyncio.run(main())
python expire-a-task.pyfirst, 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
La ttlMs de la primera tarea fue 60000, y en su primera consulta fue working. Tras 61 segundos en el reloj simulado, tasks/get respondió -32602 Failed to retrieve task: Task has expired. En esa consulta, lib.tasks detuvo también el trabajo de la primera tarea, y su resultado se habría perdido con él si el trabajo hubiera terminado.
La segunda tarea estaba working, recounted 1 of 64 SKUs cuando el cliente la canceló. Además del sello _meta del SDK, el acuse de recibo contenía solo resultType complete: un resultado vacío, aparte del campo que todo resultado lleva. Una consulta inmediatamente posterior encontró la tarea todavía working, porque la cancelación solo activó un indicador y el informe aún no había llegado a su siguiente comprobación. En la tienda, esa comprobación llega después del recuento del producto actual; en el ejemplo, el informe quedó retenido antes de su segundo producto.
La última consulta encontró cancelled, stopped after 2 of 64 SKUs. Tras la cancelación, el informe recontó un producto más y luego se detuvo, como permite la especificación.
Regla práctica: Da a cada tarea un TTL que cubra la espera más larga que preveas entre que el trabajo termina y que el cliente obtiene el resultado, y purga después de ese plazo; para el informe de reposición de la tienda, es una hora. Haz que el trabajo largo compruebe si hay cancelación en cada paso natural, como cada producto, y limpie allí. En el cliente, trata el acuse de recibo de una cancelación como «solicitada», no como «detenida», y trata el -32602 recibido de tasks/get como una tarea que ya no existe y no volverá.
Esta parte aún no está traducida, así que está en inglés.
Know what MCP Apps add
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.
Elige una tarea, progreso o una llamada simple
La tienda ahora ejecuta trabajo de tres maneras: una llamada simple, como get_order_status; una llamada que transmite progreso, recount_stock del capítulo 6; y una tarea, el informe de reposición de Sondea una tarea y obtén su resultado. Se diferencian en lo que la conexión debe sobrevivir y en lo que el llamador ve mientras espera.
El progreso es la diferencia que decide la mayoría de las elecciones. En esta revisión, la especificación no admite notifications/progress ni notifications/message en tareas en general (SEP-2663). Una tarea informa hasta dónde ha llegado solo a través de su statusMessage, que el cliente lee al consultarla. El mensaje del informe de reposición, "recontados 12 de 64 SKU", es de ese tipo: una cadena, vista solo tantas veces como el cliente consulta, sin ningún número que una barra de progreso pueda usar. Los mensajes de registro no son un atajo para esto (Reemplaza muestreo, raíces y registro).
La otra diferencia es quién debe admitir qué. Una llamada simple y el progreso forman parte del protocolo básico. Una tarea requiere que ambos lados implementen una extensión, y el soporte de extensiones en los hosts varía (Matriz de soporte de extensiones). La visión general de Tareas enumera los casos para los que sirve una tarea: trabajo que sobrevive a una conexión, trabajo que debe sobrevivir a un reinicio del cliente y trabajo que ya se ejecuta como un trabajo en una cola.
Nuestra regla práctica, no una medición, compara las tres formas en una tabla.
| Llamada simple | Progreso | Tarea | |
|---|---|---|---|
| Duración típica | segundos | hasta unos pocos minutos | minutos o más |
| La conexión debe mantenerse abierta | sí | sí | no |
| Lo que ve el llamador mientras espera | nada | progreso y total | un mensaje de estado |
| Sobrevive a un reinicio del cliente | no | no | sí, si el cliente guardó el ID |
| Necesita una extensión | no | no | sí, en ambos lados |
get_order_status sigue siendo una llamada simple, porque responde en milisegundos. recount_stock conserva el progreso del capítulo 6, porque quien la inicia ve subir un contador y espera. El informe de reposición pasa a ser una tarea, porque tarda minutos a la velocidad real de la API, el responsable lo quiere recibir más tarde en lugar de verlo avanzar, y una conexión caída no debería costar tres minutos de reconteo.
Regla práctica: Usa una llamada simple cuando el resultado llega con holgura dentro de todos los tiempos de espera entre el host y el servidor. Usa progreso cuando el trabajo es largo, el llamador lo espera en una conexión en la que confías que se mantendrá abierta, y quiere un número para mostrar. Usa una tarea cuando el trabajo puede sobrevivir a la conexión, o cuando el llamador quiere irse y volver después. Acepta que una tarea solo informa un mensaje de estado, y mantén una alternativa de llamada simple o un error claro -32021 para los clientes sin la extensión.
Qué sale mal en producción
El informe de reposición de este capítulo se ejecutó en un solo proceso, con tareas en memoria y un reloj simulado. Repartido entre réplicas, ejecutado durante días y llamado por muchos usuarios, puede fallar de las maneras que siguen, cada una con una señal que puedes buscar.
Las tareas se almacenan en una sola réplica. lib.tasks guarda las tareas en un diccionario. Detrás de las dos réplicas del capítulo 6 (Ejecuta réplicas sin sesiones pegajosas), un tasks/get que llega a la otra réplica no encuentra nada y responde -32602. Guarda las tareas donde todas las réplicas puedan leerlas, como una base de datos o el propio almacén de una cola de trabajos, o enruta según la cabecera Mcp-Name, que lleva el ID de la tarea en cada solicitud de tarea. Lo notarás como tareas que "caducan" en segundos, a un ritmo parecido al de los cambios de réplica de tu balanceador de carga.
Los ID de tarea filtran el resultado de otro llamador. Un ID de tarea puede ser lo único que separa a un llamador de un resultado almacenado. La especificación dice que los servidores DEBEN realizar comprobaciones de autenticación y autorización en cada solicitud relacionada con tareas, y eliminó tasks/list, que, mal acotado, podía mostrar a un llamador los ID de tarea de otro (SEP-2663). Registra al llamador junto con la tarea, a partir del sujeto del token una vez que Autoriza clientes con OAuth esté implantado, y rechaza cada tasks/get y tasks/cancel de cualquier otra persona. Una solicitud de entrada que llega a través de una tarea recibe la misma confianza que una en una llamada directa, ni más ni menos: "Una tarea no es un canal de mayor confianza".
El SDK no comprueba la declaración por ti. En mcp 2.3.0, el ejecutor del servidor pasa sin revisar el resultType de una extensión, y una nota en el código fuente dice que rechazarlo para los clientes que no declararon la extensión sigue pendiente (mcp/server/runner.py). La extensión debe llamar ella misma a require_client_extension(), en la llamada y en cada uno de sus propios métodos, como lo hace lib.tasks. Un cliente que no declaró Tasks y recibe una tarea de todos modos debe tratar el resultado como inválido. El cliente del SDK lo hace, porque sin una afirmación para "task" valida el manejador como un CallToolResult y lanza un ValidationError.
Sondear cuesta más que el trabajo. Miles de clientes sondeando cada 100 milisegundos generan una carga propia. Aumenta pollIntervalMs a medida que una tarea tarda más, limita la frecuencia de los clientes que lo ignoran, como permite la especificación, y ofrece notifications/tasks cuando tu servidor pueda enviar datos por iniciativa propia. La señal es tasks/get superando a cualquier otro método en tus trazas.
Las tareas se acumulan. Un TTL de null, o uno más largo que cualquier espera de cliente, conserva el resultado de cada tarea abandonada. Define un TTL, purga según un calendario además de al leer, y lanza una alerta según el número de tareas almacenadas. Los clientes que pierden los ID de tarea al reiniciarse hacen que la acumulación crezca más rápido, así que guarda los ID en el cliente antes del primer sondeo.
El trabajo cancelado sigue ejecutándose. Una herramienta que nunca comprueba la cancelación se ejecuta hasta el final tras cada tasks/cancel, y la API de la tienda vuelve a contar productos que nadie quiere. Comprueba en cada paso y registra cuánto tiempo siguen ejecutándose las tareas después de una cancelación.
Los clientes hablan las tareas de 2025-11-25. Las tareas experimentales de esa revisión usaban tasks/result, tasks/list y un parámetro task en la solicitud, y no son compatibles a nivel de protocolo con la extensión (SEP-2663). Un cliente de la era 2025 nunca declara io.modelcontextprotocol/tasks, así que recibe el -32021 del servidor. Migra un servidor de la era 2025 cubre el resto del protocolo antiguo.
La extensión cambia bajo tus pies. Tasks está en Beta y camino de incorporarse al protocolo principal, y el SDK puede publicar su propia extensión de Tasks en una versión posterior. Cualquiera de las dos cosas es un motivo para actualizar este capítulo. Cuando el SDK publique una, sustituye lib.tasks por ella y mantén la herramienta de la tienda tal como está, ya que la herramienta nunca supo que se ejecutaba como tarea.
Regla práctica: Traslada el almacenamiento de las tareas a un lugar que todas las réplicas puedan leer antes de pasar a producción, registra el propietario de cada tarea y compruébalo en cada solicitud de tarea, y define un TTL con una purga que se ejecute según un calendario. Después vigila el -32602 de tasks/get por réplica, la proporción de tasks/get frente a tools/call, el número de tareas almacenadas y cuánto tiempo siguen ejecutándose las tareas tras una cancelación.
Decisiones que tomó este capítulo
- El informe de reposición de la tienda se ejecuta como una tarea, mediante la extensión Tasks, porque su trabajo sobrevive a una conexión.
- El servidor de la tienda rechaza
restock_reportcon el error -32021 para los clientes sin la extensión, en lugar de ejecutar una llamada simple de tres minutos. - El libro construye su propia y pequeña extensión Tasks,
lib.tasks, sobre el marco de extensiones del SDK, porquemcp2.3.0 no incluye ninguna. Implementatasks/getytasks/cancel, y deja fueratasks/updatey las notificaciones enviadas. - Una tarea ejecuta el manejador ordinario de la herramienta, así que su resultado es el mismo
CallToolResultque devuelve una llamada simple. - Los identificadores de tarea llevan 192 bits aleatorios, y toda solicitud de tarea lleva su identificador en la cabecera
Mcp-Name. - El cliente consulta el estado con el intervalo
pollIntervalMsdel servidor, dentro de una extensión del cliente, de modo que el host ve llamadas simples a herramientas. - Las tareas caducan una hora después de su creación, y la cancelación es cooperativa: el informe de reposición comprueba la cancelación después de cada producto.
recount_stockconserva el progreso del capítulo 6, yget_order_statussigue siendo una llamada simple.- Las MCP Apps se describen, no se construyen, porque el bucle de host del libro no muestra HTML. Una vista de reposición conservaría el texto del informe y ocultaría al modelo su herramienta de pedidos mediante una visibilidad de
["app"]. - En producción, las tareas pasan a un almacenamiento que comparten las dos réplicas del capítulo 6, y cada solicitud de tarea se verifica frente a quien inició la tarea.
- La lección está en dónde va la espera: una tarea traslada la espera de la conexión al servidor, que conserva el estado, fija cuánto dura y decide quién puede leerla.
Este capítulo, en esta edición
Edición 2026.11.14Ejemplos verificados el 19 de nov de 2026Superan la prueba 4 de 4 ejemplos ejemplos de este capítulo
Traducido del libro en inglés, edición 2026.11.14.