Run long work as tasks

Cerca de 34 minutos min de leitura, com 4 exemplos em 8 seções.

Edição 2026.11.14 Exemplos aprovados em 19 de nov de 2026 70 de 70 exemplos passam O que mudou

Traduzido com IA. Verificado por pessoas em inglês. Como fazemos os livros

Traduzido do livro em inglês, edição 2026.11.14. Leia o original

Esta parte ainda não foi traduzida, por isso está em 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 ainda não foi traduzida, por isso está em inglês.

Negotiate an extension

Última alteração na edição 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 Aprovado
"""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())
Saídapython 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.

Esta parte ainda não foi traduzida, por isso está em inglês.

Start a task instead of waiting

Última alteração na edição 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 Aprovado
"""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())
Saídapython 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.

Esta parte ainda não foi traduzida, por isso está em inglês.

Poll a task and fetch its result

Última alteração na edição 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 Aprovado
"""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())
Saídapython 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.

Expirar e cancelar tarefas

Última alteração na edição 2026.11.11

O relatório de reposição em Consultar uma tarefa e buscar seu resultado terminou e foi buscado. Nem toda tarefa segue esse caminho. Um cliente pode travar e nunca mais voltar, ou um líder de equipe pode fechar um relatório de que já não precisa, e um servidor que guarda todas as tarefas para sempre acaba sem armazenamento. A extensão oferece duas formas de uma tarefa terminar antes do previsto: seu tempo de vida se esgota, ou o cliente a cancela.

O tempo de vida de uma tarefa é o seu ttlMs, contado a partir de createdAt, ou null para indicar que não há limite, e o servidor pode alterá-lo. Depois que o TTL decorre, os servidores PODEM marcar a tarefa como failed a qualquer momento e, mais tarde, excluí-la a qualquer momento. Um servidor que tenha removido uma tarefa deve responder a um tasks/get para ela com o erro -32602, Invalid Params, e pode dizer que a tarefa não foi encontrada, em vez de dizer que ela expirou (SEP-2663). Portanto, o cliente não pode contar com um resultado que sobreviva ao TTL, seja qual for o destino da tarefa.

Cancelar usa tasks/cancel com o taskId, e a especificação diz que notifications/cancelled NÃO DEVE ser usado para isso. A resposta é uma confirmação vazia, e ela não promete mais nada: "Um servidor não é obrigado a interromper de fato o trabalho; ele é obrigado apenas a confirmar a requisição." A tarefa pode permanecer working por algum tempo, e pode ainda terminar como completed ou failed. Depois de enviar o cancelamento, o cliente pode esquecer a tarefa (SEP-2663). Este é um cancelamento cooperativo, diferente do que vimos no capítulo 6, em que fechar o fluxo cancelava, no servidor, o trabalho da chamada (Cancelar uma chamada que o cliente não precisa mais).

lib.tasks torna ambos concretos. Em uma requisição tasks/get feita após o TTL, ele exclui a tarefa, interrompe o trabalho dela e responde com -32602, com a mensagem que o exemplo da especificação usa. Em tasks/cancel, ele define um sinalizador e confirma. O trabalho da ferramenta lê o sinalizador por meio de tasks.cancel_requested(), e lib.restock o verifica depois de cada produto, de modo que o relatório de reposição para ao fim do produto que está recontando, e a tarefa passa a cancelled nesse momento.

O exemplo de expiração define um ttlMs de um minuto, o que mostra a expiração sem uma longa espera. Para que sua saída nunca dependa da velocidade da máquina, ele retém cada relatório antes de cada produto, com restock.Steps, uma barreira em lib.restock que deixa mais um produto começar cada vez que allow() é chamado. Ele inicia um relatório ao qual nunca se permite um produto, consulta-o, avança o relógio falso em 61 segundos e consulta de novo. Em seguida, inicia um segundo relatório, deixa-o recontar um produto, aguarda a primeira mensagem de status dele e o cancela. Consulta imediatamente, deixa o relatório iniciar o próximo produto e consulta até que a tarefa esteja em estado final.

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 Aprovado
"""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())
Saídapython 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

O ttlMs da primeira tarefa era 60000, e ela estava working na primeira consulta. Após 61 segundos no relógio falso, tasks/get respondeu -32602 Failed to retrieve task: Task has expired. Nessa consulta, lib.tasks também interrompeu o trabalho da primeira tarefa, e o resultado dela se perderia junto, caso o trabalho tivesse terminado.

A segunda tarefa estava working, recounted 1 of 64 SKUs quando o cliente a cancelou. Além do carimbo _meta do SDK, a confirmação continha apenas resultType complete: um resultado vazio, além do campo que todo resultado carrega. Uma consulta logo em seguida encontrou a tarefa ainda working, porque o cancelamento apenas definiu um sinalizador, e o relatório ainda não tinha chegado à sua próxima verificação. Na loja, essa verificação ocorre após a recontagem do produto atual; no exemplo, o relatório foi retido antes do seu segundo produto.

A última consulta encontrou cancelled, stopped after 2 of 64 SKUs. O relatório recontou mais um produto após o cancelamento e então parou, como a especificação permite.

Regra prática: Atribua a cada tarefa um TTL que cubra a maior espera que você prevê entre o término do trabalho e a busca do resultado pelo cliente, e remova a tarefa depois disso; para o relatório de reposição da loja, isso equivale a uma hora. Faça o trabalho longo verificar se há cancelamento em cada etapa natural, como cada produto, e limpe os recursos ali. No cliente, trate a confirmação de um cancelamento como "solicitado", e não como "interrompido", e trate o -32602 vindo de tasks/get como uma tarefa que se foi para sempre.

Esta parte ainda não foi traduzida, por isso está em inglês.

Know what MCP Apps add

Última alteração na edição 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.

Escolha entre tarefa, progresso ou uma chamada simples

Última alteração na edição 2026.11.11

A loja agora executa trabalho de três formas: uma chamada simples, como get_order_status; uma chamada que transmite progresso, o recount_stock do capítulo 6; e uma tarefa, o relatório de reposição de Consultar uma tarefa e obter o seu resultado. Elas diferem quanto ao que a conexão precisa suportar e ao que quem chama vê enquanto espera.

O progresso é a diferença que decide a maioria das escolhas. Nesta revisão, a especificação não oferece suporte geral a notifications/progress ou notifications/message em tarefas (SEP-2663). Uma tarefa informa até onde chegou somente por meio de seu statusMessage, que o cliente lê quando consulta a tarefa. A mensagem "recontados 12 de 64 SKUs" do relatório de reposição é desse tipo: uma string, vista apenas com a frequência com que o cliente consulta, sem um número que uma barra de progresso possa usar. Mensagens de log não contornam essa limitação (Substitua sampling, roots e logging).

A outra diferença está em quem precisa oferecer suporte a quê. Uma chamada simples e o progresso fazem parte do protocolo central. Uma tarefa exige que os dois lados implementem uma extensão, e o suporte a extensões varia entre hosts (Matriz de suporte a extensões). A Visão geral de tarefas lista os casos para os quais uma tarefa serve: trabalho que dura mais que uma conexão, trabalho que precisa sobreviver a uma reinicialização do cliente e trabalho que já roda como job em uma fila.

Nossa regra prática, e não uma medição, compara as três formas em uma tabela.

Chamada simples Progresso Tarefa
Duração típica segundos até alguns minutos minutos ou mais
A conexão precisa permanecer aberta sim sim não
O que quem chama vê enquanto espera nada progresso e total uma mensagem de status
Sobrevive a uma reinicialização do cliente não não sim, se o cliente tiver armazenado o ID
Precisa de uma extensão não não sim, nos dois lados

get_order_status continua sendo uma chamada simples, porque responde em milissegundos. recount_stock mantém o progresso do capítulo 6, porque um responsável que o inicia acompanha a contagem subir e espera. O relatório de reposição passa a ser uma tarefa, porque roda por minutos na velocidade real da API, o responsável quer recebê-lo depois, em vez de acompanhá-lo, e uma conexão interrompida não deve custar três minutos de recontagem.

Regra prática: Use uma chamada simples quando o resultado voltar bem dentro de todos os timeouts entre o host e o servidor. Use o progresso quando o trabalho for longo, quem chama espera por ele em uma conexão em que você confia que permanecerá aberta e quer um número para exibir. Use uma tarefa quando o trabalho puder sobreviver à conexão, ou quando quem chama quiser sair e voltar depois. Aceite que uma tarefa informa apenas uma mensagem de status, e mantenha uma alternativa de chamada simples ou um erro -32021 claro para clientes sem a extensão.

O que dá errado em produção

Última alteração na edição 2026.11.11

O relatório de reposição deste capítulo rodou em um único processo, com tarefas na memória e um relógio falso. Distribuído entre réplicas, executando por dias e chamado por muitos usuários, ele pode falhar das formas a seguir, cada uma com um sinal que você pode procurar.

As tarefas são armazenadas em uma única réplica. lib.tasks guarda as tarefas em um dicionário. Atrás das duas réplicas do capítulo 6 (Execute réplicas sem sessões fixas), um tasks/get que chega à outra réplica não encontra nada e responde -32602. Armazene as tarefas em um local que todas as réplicas possam ler, como um banco de dados ou o próprio armazenamento de uma fila de jobs, ou roteie pelo cabeçalho Mcp-Name, que carrega o ID da tarefa em toda requisição de tarefa. Você vai notar isso como tarefas que "expiram" em segundos, na mesma frequência aproximada com que seu balanceador troca de réplica.

IDs de tarefa vazam o resultado de outro chamador. Um ID de tarefa pode ser a única coisa que separa um chamador de um resultado armazenado. A especificação diz que os servidores DEVEM executar verificações de autenticação e autorização em cada requisição relacionada a tarefas, e ela removeu tasks/list, que, mal delimitada, poderia mostrar a um chamador os IDs de tarefa de outro (SEP-2663). Registre o chamador junto com a tarefa, a partir do subject do token, quando Autorize clientes com OAuth estiver implantado, e recuse todo tasks/get e tasks/cancel de qualquer outro chamador. Uma solicitação de entrada que chega por meio de uma tarefa recebe a mesma confiança que uma em chamada direta, nem mais nem menos: "Uma tarefa não é um canal de confiança mais alta."

O SDK não verifica a declaração por você. Em mcp 2.3.0, o executor do servidor repassa a resultType de uma extensão sem verificação, e uma nota no código-fonte diz que rejeitá-la para clientes que não declararam a extensão ainda está por fazer (mcp/server/runner.py). A extensão deve chamar require_client_extension() por conta própria, na chamada e em cada um dos seus métodos, como lib.tasks faz. Um cliente que não declarou Tasks e recebe uma tarefa mesmo assim deve tratar o resultado como inválido. O cliente do SDK faz isso: sem uma declaração para "task", ele valida o identificador como um CallToolResult e levanta um ValidationError.

A consulta periódica custa mais que o trabalho. Milhares de clientes consultando a cada 100 milissegundos geram uma carga própria. Aumente pollIntervalMs conforme uma tarefa roda por mais tempo, limite a taxa de clientes que o ignorarem, como a especificação permite, e ofereça notifications/tasks assim que seu servidor puder enviar dados por iniciativa própria. O sinal é tasks/get superando todos os outros métodos nos seus rastreamentos.

As tarefas se acumulam. Um TTL de null, ou um maior que qualquer tempo de espera dos clientes, mantém o resultado de cada tarefa abandonada. Defina um TTL, faça limpeza em agenda além de na leitura, e alerte sobre o número de tarefas armazenadas. Clientes que perdem os IDs de tarefa ao reiniciar fazem a pilha crescer mais depressa, então armazene os IDs no cliente antes da primeira consulta.

Trabalho cancelado continua rodando. Uma ferramenta que nunca verifica o cancelamento roda até o fim depois de cada tasks/cancel, e a API da loja recontabiliza produtos que ninguém quer. Verifique a cada etapa e registre por quanto tempo as tarefas continuam rodando após um cancelamento.

Clientes falam as tarefas de 2025-11-25. As tarefas experimentais dessa revisão usavam tasks/result, tasks/list e um parâmetro task na requisição, e não são compatíveis em nível de protocolo com a extensão (SEP-2663). Um cliente da era 2025 nunca declara io.modelcontextprotocol/tasks, então encontra o -32021 do servidor. Migre um servidor da era 2025 cobre o restante do protocolo antigo.

A extensão muda sob seus pés. Tasks está em Beta e a caminho do protocolo principal, e o SDK pode lançar sua própria extensão de Tasks em uma versão futura. Qualquer uma das duas é um gatilho para atualizar este capítulo. Quando o SDK lançar uma, substitua lib.tasks por ela e mantenha a ferramenta da loja como está, já que a ferramenta nunca soube que estava rodando como tarefa.

Regra prática: Mova o armazenamento das tarefas para onde todas as réplicas possam lê-lo antes de irem para produção, registre o dono de cada tarefa e verifique-o em toda requisição de tarefa, e defina um TTL com uma limpeza que roda em agenda. Depois, acompanhe as respostas -32602 de tasks/get por réplica, a proporção entre tasks/get e tools/call, o número de tarefas armazenadas e por quanto tempo o trabalho continua rodando após um cancelamento.

Decisões tomadas neste capítulo

Última alteração na edição 2026.11.11
  • O relatório de reposição da loja roda como uma tarefa, pela extensão Tasks, porque o seu trabalho dura mais do que uma conexão.
  • O servidor da loja recusa restock_report com o erro -32021 para clientes sem a extensão, em vez de executar uma chamada simples de três minutos.
  • O livro constrói a sua própria pequena extensão de Tasks, lib.tasks, sobre o framework de extensões do SDK, porque mcp 2.3.0 não traz nenhuma. Ela implementa tasks/get e tasks/cancel, e deixa de fora tasks/update e as notificações enviadas pelo servidor.
  • Uma tarefa executa o handler comum da ferramenta, então o seu resultado é o mesmo CallToolResult que uma chamada simples devolve.
  • Os IDs de tarefa carregam 192 bits aleatórios, e toda requisição de tarefa leva o seu ID no cabeçalho Mcp-Name.
  • O cliente consulta no pollIntervalMs do servidor, dentro de uma extensão do cliente, então o host vê apenas chamadas de ferramenta simples.
  • As tarefas expiram uma hora após serem criadas, e o cancelamento é cooperativo: o relatório de reposição verifica após cada produto.
  • recount_stock mantém o progresso do capítulo 6, e get_order_status continua sendo uma chamada simples.
  • Os MCP Apps são descritos, não construídos, porque o loop de host do livro não renderiza HTML. Uma visão de reposição manteria o texto do relatório e ocultaria do modelo a sua ferramenta de pedidos, com uma visibilidade de ["app"].
  • Em produção, as tarefas passam para um armazenamento compartilhado pelas duas réplicas do capítulo 6, e toda requisição de tarefa é verificada contra quem iniciou a tarefa.
  • A lição está em para onde vai a espera: a tarefa a tira da conexão e a coloca no servidor, que mantém o estado, define por quanto tempo ele dura e decide quem pode lê-lo.

Este capítulo, nesta edição

Edição 2026.11.14Exemplos aprovados em 19 de nov de 20264 de 4 exemplos exemplos deste capítulo passam

Traduzido do livro em inglês, edição 2026.11.14.

Citar esta seção

Formato

Cada formato cita o livro em inglês, que esta tradução acompanha.

Todos os formatos citam esta edição. Seu link abre a edição atual, em que o título de cada seção indica quando seu texto foi alterado pela última vez. As datas de acesso e de recuperação são o dia em que você abre esta página.

Nesta página

Capítulo 7 de 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. Expirar e cancelar tarefas
  5. Know what MCP Apps add
  6. Escolha entre tarefa, progresso ou uma chamada simples
  7. O que dá errado em produção
  8. Decisões tomadas neste capítulo

Voltar ao topoTodos os capítulos