MCP Tasks Extension: Durable Work on a Stateless Core
Stateless MCP does not mean every operation must finish in one request. The official Tasks extension gives long-running work an explicit durable handle. A server can return that handle from tools/callany instance can answer tasks/getand client input arrives through tasks/update without reviving protocol sessions.
Learning Objectives
- Distinguish stateless protocol transport from durable application task state.
- Negotiate the
io.modelcontextprotocol/tasksextension in per-request capabilities andserver/discover. - Return a server-directed
CreateTaskResultwithresultType: "task"only after durable creation. - Poll with
tasks/getfulfill task input withtasks/updateand request cooperative cancellation withtasks/cancel. - Remove the older
tasks/statustasks/resultandtasks/listassumptions. - Subscribe to optional task notifications through
subscriptions/listenon a POST response SSE stream. - Model task expiry, restart recovery, input-key deduplication, and execution errors correctly.
Why Tasks Are an Extension
Tasks first appeared as an experimental core feature in 2025-11-25. The July 2026 redesign moves them into the official io.modelcontextprotocol/tasks extension so clients and servers can opt into the extra lifecycle without expanding the core protocol for everyone.
The extension specification remains a draft surface even though it is the current official home for Tasks. Pin the extension version supported by your SDK, run conformance scenarios, and isolate wire adapters from your worker and storage domain.
Use a task when the operation has one or more of these properties:
- It may outlive an ordinary request timeout.
- A worker queue or external job system already owns execution.
- The client needs to recover after its own restart.
- The operation pauses for user or model input during execution.
- Cancellation and durable result retrieval are product requirements.
Do not create a task for a cheap deterministic lookup. A handle, persistence, polling, expiry, and cancellation are real complexity.
Stateless Core, Stateful Application
MCP 2026-07-28 removes initializenotifications/initializedprotocol sessions, and Mcp-Session-Id. That does not prohibit stateful products.
A task id is explicit application state:
- The server persists it before returning it.
- The client can store it and poll again after restart.
- The id can route to any replica backed by the same durable store.
- Authorization is checked on every task method.
- Expiry and deletion are defined by task fields, not a transport lifetime.
This is operationally different from hidden state attached to a connection.
Keep four lifetimes separate:
| State | Lifetime | Where it belongs |
|---|---|---|
| Protocol metadata | One request | params._metavalidated again on every call |
| Transport work | One stdio request or HTTP response | In-flight coordinator with a bounded deadline |
| MRTR continuation | One retry sequence | Integrity-protected requestStateplus replay controls when needed |
| Durable task | Across requests, replicas, restarts, and reconnects | Shared application store keyed by an authorized taskId |
Moving a task record into process memory does not make MCP stateful. It makes the application unreliable. The protocol stays stateless, but a later tasks/get routed to another replica cannot recover the record. Persist before returning the handle, then make every task method resolve the same shared record under tenant and principal checks.
Capability Negotiation
The client advertises support on every eligible request:
{
"_meta": {
"io.modelcontextprotocol/protocolVersion": "2026-07-28",
"io.modelcontextprotocol/clientCapabilities": {
"extensions": {
"io.modelcontextprotocol/tasks": {}
}
},
"io.modelcontextprotocol/clientInfo": {
"name": "lesson-client",
"version": "1.0.0"
}
}
}The server returns exact supportedVersionscapabilities, ttlMsand cacheScope from server/discoverwith the same extension under capabilities. Because it advertises tools, it also implements mandatory tools/list. That result returns a deterministic generate_report descriptor, valid object inputSchemaresultType: "complete"server identity metadata, and public cache hints.
A task method from a client that did not declare the extension returns -32021Missing Required Client Capability, with data.requiredCapabilities set to {"extensions":{"io.modelcontextprotocol/tasks":{}}}. An unsupported protocol string returns -32022 with exact supported and requested data; a missing or non-string version returns -32602.
An envelope without a JSON-RPC id is a notification. The receiver may process it, but it emits no JSON-RPC result or error. A Streamable HTTP adapter returns 202 Accepted with no body for an accepted notification.
At present, only tools/call supports task-augmented execution. Design your internal abstraction so future request types do not require rewriting storage.
Server-Directed Task Creation
The old client flag params._meta.task.required is gone. The client declares extension support, then the server decides whether a particular tools/call becomes a task.
Request:
{
"jsonrpc": "2.0",
"id": 1,
"method": "tools/call",
"params": {
"name": "generate_report",
"arguments": {"size": "large"},
"_meta": {
"io.modelcontextprotocol/protocolVersion": "2026-07-28",
"io.modelcontextprotocol/clientCapabilities": {
"extensions": {
"io.modelcontextprotocol/tasks": {}
}
}
}
}
}Response:
{
"jsonrpc": "2.0",
"id": 1,
"result": {
"resultType": "task",
"taskId": "tsk_786512e29e0d",
"status": "working",
"statusMessage": "Preparing report outline.",
"createdAt": "2026-08-21T10:30:00Z",
"lastUpdatedAt": "2026-08-21T10:30:00Z",
"ttlMs": 900000,
"pollIntervalMs": 1000
}
}The server must not return this handle until a tasks/get for the id can resolve. In an eventually consistent store, wait for read visibility before answering. Otherwise a client can receive a valid-looking id and immediately get "not found."
A task response is unsolicited in the sense that the client does not request task mode. It is not unnegotiated: the current request still must advertise the extension.
The Task Shape
Every task carries:
taskId: stable server-generated identifier;status:workinginput_requiredcompletedcancelledorfailed;createdAtandlastUpdatedAt: ISO 8601 timestamps;ttlMs: expiry duration from creation, ornullfor no advertised limit;- optional
pollIntervalMs: the server's current minimum suggested polling cadence; - optional
statusMessage: user-facing or model-facing context.
Status-specific fields appear only when relevant:
input_requiredincludesinputRequests.completedincludes the original request'sresultshape.failedincludes a JSON-RPCerrorobject.
The client should honor pollIntervalMs. A server may rate-limit more aggressive polling and may change the interval over the task lifetime.
Poll with tasks/get
The client asks for a current snapshot:
POST /mcp HTTP/1.1
Content-Type: application/json
MCP-Protocol-Version: 2026-07-28
Mcp-Method: tasks/get
Mcp-Name: tsk_786512e29e0d{
"jsonrpc": "2.0",
"id": 2,
"method": "tasks/get",
"params": {
"taskId": "tsk_786512e29e0d",
"_meta": {
"io.modelcontextprotocol/protocolVersion": "2026-07-28",
"io.modelcontextprotocol/clientCapabilities": {
"extensions": {
"io.modelcontextprotocol/tasks": {}
}
}
}
}
}tasks/get itself completed, so its result always has resultType: "complete". The nested task can still have status: "working" or status: "input_required".
This distinction prevents a common parser bug:
result.resultType = complete means the tasks/get RPC finished
result.status = working means the represented job is still runningThere is no tasks/result call. When the task completes, the next tasks/get response inlines the original CallToolResult under result:
{
"resultType": "complete",
"taskId": "tsk_786512e29e0d",
"status": "completed",
"createdAt": "2026-08-21T10:30:00Z",
"lastUpdatedAt": "2026-08-21T10:34:12Z",
"ttlMs": 900000,
"result": {
"resultType": "complete",
"content": [
{"type": "text", "text": "Generated large report with approved outline."}
],
"structuredContent": {"size": "large", "approved": true},
"isError": false,
"_meta": {
"io.modelcontextprotocol/serverInfo": {
"name": "tasks-demo",
"version": "1.0.0"
}
}
},
"_meta": {
"io.modelcontextprotocol/serverInfo": {
"name": "tasks-demo",
"version": "1.0.0"
}
}
}The outer resultType says the tasks/get RPC completed. The nested result.resultType says the original tool call completed. That nested discriminator is required. The nested CallToolResult SHOULD also carry its own io.modelcontextprotocol/serverInfo; this lesson includes it instead of storing an untyped payload.
There is no tasks/list. Sessionless servers cannot safely infer which tasks belong in a connection-scoped list. Applications that need history should expose an authorized domain tool with explicit filters and ownership rules.
Input During Task Execution
Task input and core MRTR look similar but use different continuations.
Input needed before task creation
Return core resultType: "input_required" from the original tools/call. The client fulfills it and retries that original call. Only create the task after those synchronous MRTR rounds finish.
Input needed after task creation
Set the task to input_required. tasks/get exposes the outstanding inputRequestsand the client sends responses through tasks/update. The client does not retry the original tools/call.
Snapshot:
{
"resultType": "complete",
"taskId": "tsk_786512e29e0d",
"status": "input_required",
"createdAt": "2026-08-21T10:30:00Z",
"lastUpdatedAt": "2026-08-21T10:31:00Z",
"ttlMs": 900000,
"inputRequests": {
"approve_outline": {
"method": "elicitation/create",
"params": {
"mode": "form",
"message": "Approve the generated report outline?",
"requestedSchema": {
"type": "object",
"properties": {"approved": {"type": "boolean"}},
"required": ["approved"]
}
}
}
}
}Update:
POST /mcp HTTP/1.1
Content-Type: application/json
MCP-Protocol-Version: 2026-07-28
Mcp-Method: tasks/update
Mcp-Name: tsk_786512e29e0d{
"jsonrpc": "2.0",
"id": 4,
"method": "tasks/update",
"params": {
"taskId": "tsk_786512e29e0d",
"inputResponses": {
"approve_outline": {
"action": "accept",
"content": {"approved": true}
}
},
"_meta": {
"io.modelcontextprotocol/protocolVersion": "2026-07-28",
"io.modelcontextprotocol/clientCapabilities": {
"extensions": {
"io.modelcontextprotocol/tasks": {}
}
}
}
}
}The success response is an empty acknowledgement plus resultType: "complete". The state change may be eventually consistent, so the client continues polling or listening.
Each inputRequests key must be unique for the entire task lifetime. Repeated tasks/get snapshots may show the same outstanding key; clients deduplicate the UI and servers ignore responses for unknown, superseded, or already fulfilled keys. A partial update can leave the task in input_required until all required keys are answered.
Cancellation Is Cooperative
tasks/cancel signals intent and returns an empty complete acknowledgement. That acknowledgement does not guarantee the worker stopped. Work may finish first, ignore cancellation, or transition later.
POST /mcp HTTP/1.1
Content-Type: application/json
MCP-Protocol-Version: 2026-07-28
Mcp-Method: tasks/cancel
Mcp-Name: tsk_786512e29e0d{
"jsonrpc": "2.0",
"id": 5,
"method": "tasks/cancel",
"params": {
"taskId": "tsk_786512e29e0d",
"_meta": {
"io.modelcontextprotocol/protocolVersion": "2026-07-28",
"io.modelcontextprotocol/clientCapabilities": {
"extensions": {
"io.modelcontextprotocol/tasks": {}
}
}
}
}
}For all three task methods, Mcp-Name mirrors params.taskId. It does not repeat the JSON-RPC method name. code/main.py centralizes this rule in make_http_request.
The lesson worker honors cancellation immediately, making repeated calls idempotent. A production client must still treat cancellation as cooperative rather than infer a final task status from the acknowledgement.
Do not use notifications/cancelled to cancel a task. That notification belongs to request cancellation, not durable Tasks.
The distinction matters at the routing boundary. Request cancellation targets one in-flight JSON-RPC operation or its request-scoped HTTP response. If tools/call has already returned resultType: "task"that request is complete and closing its transport cannot name or stop the durable job. tasks/cancel is a new authorized RPC. It carries params.taskIdmirrors that id in Mcp-Nameresolves the task's owning backend, records cooperative cancellation intent, and returns an acknowledgement without claiming the worker has stopped.
A gateway must therefore keep request coordinators and task routes in different tables. The request table can disappear when the response finishes. The task route must survive until terminal state and retention expiry. Lesson 29: MCP Reliability, Cancellation, and Flow Control builds the race, timeout, idempotency, backpressure, and retry rules for both paths.
Optional Notifications
Polling is the baseline. A client that wants push updates sends subscriptions/listen with task ids. For Streamable HTTP, this is a POST whose response is a request-scoped SSE stream. There is no standalone GET event stream and no protocol session to keep alive.
The server acknowledges the accepted ids with notifications/subscriptions/acknowledged and can then send full snapshots through notifications/tasks. The acknowledgement and every task notification carry io.modelcontextprotocol/subscriptionId in _metaequal to the subscriptions/listen request id. Each task notification is otherwise equivalent to what tasks/get would return at that moment.
Clients must still declare the Tasks extension. They should reconnect and resume from durable task ids rather than depend on event replay or Last-Event-ID.
Failure Semantics
Use the two error layers correctly.
Protocol error
Invalid method parameters or an unknown task id return a JSON-RPC error, commonly -32602. Missing extension support returns -32021 with the required capability object.
Task execution outcome
- A normal tool result with
isError: trueis still acompletedtask because the tool call produced its defined result. - A JSON-RPC error during deferred execution makes the task
failedand stores that JSON-RPC error undererror. - User refusal can produce
cancelleda completed refusal result, or another domain-specific safe outcome. Document the choice.
Durability, Expiry, and Ownership
Persist at least the task id, status, timestamps, ttl, poll interval, original operation ownership, result or error, outstanding input requests, and all issued input keys.
The storage key must include or resolve an authoritative tenant and principal. Knowing a task id must not grant access. Check ownership on every tasks/gettasks/updatetasks/canceland subscription.
ttlMs is measured from creation and may change. A client can treat it as a backstop when a task has stopped producing observable updates. A server may fail and later delete an expired task. Do not describe it as a promise to retain a completed result for that many milliseconds after completion.
Use atomic writes or transactions. The lesson writes a temporary file and atomically renames it. A multi-replica service should use a shared durable store and a worker lease or equivalent concurrency control.
Build It
code/main.py implements a deterministic task service:
server/discoverreturnssupportedVersionscache hints, and the Tasks extension.tools/listreturns a deterministic, cacheablegenerate_reportdescriptor with a valid input schema.tools/callcreates and persists the task before returningresultType: "task".- A new service instance reloads the same task, demonstrating restart recovery.
tasks/getreturns complete task snapshots.- The worker moves from
workingtoinput_required. tasks/updateaccepts a form response and returns an empty complete acknowledgement.- The worker stores a nested
CallToolResultwith its ownresultTypeand server identity, then transitions tocompleted. tasks/cancelis idempotent in this implementation.- The HTTP builder sets
Mcp-Nametoparams.taskIdfortasks/gettasks/updateandtasks/cancel. - Notification helpers use
notifications/subscriptions/acknowledgedandnotifications/tasksboth tagged with the listen request id. - Id-less notifications produce no JSON-RPC response.
The worker advances explicitly instead of sleeping in a background thread. That makes every state transition deterministic and keeps the protocol example separate from queue mechanics.
Use It
From the repository root:
cd phases/13-tools-and-protocols/13-mcp-async-tasks/code
python3 main.py
python3 -m unittest discover tests -vExpected result sequence:
id=0 resultType=complete status=ack
id=1 resultType=task status=working
id=2 resultType=complete status=working
id=3 resultType=complete status=input_required
id=4 resultType=complete status=ack
id=5 resultType=complete status=completedAlso verify that tasks/statustasks/resultand tasks/list return method-not-found in the modern service.
Verify that tools/list is deterministic and every current HTTP task method mirrors its task id through Mcp-Name.
Ship It
outputs/skill-task-store-designer.md now produces an extension-aware design: capability negotiation, durable-before-return creation, current methods, input update flow, ownership, expiry, cancellation, subscription, and migration from the removed experimental methods.
Exercises
- Add a second outstanding input key. Send a partial
tasks/updateand prove the task remainsinput_requireduntil both keys are answered. - Add tenant ownership to the store and reject a valid task id presented by the wrong authenticated principal.
- Add a worker lease with expiry. Demonstrate that two service instances cannot complete the same task concurrently.
- Implement a POST-response SSE adapter for
subscriptions/listen. Do not add GET,Last-Event-IDor a session header. - Add expiry cleanup. Distinguish an expired task from a malformed task id without leaking cross-tenant existence.
Key Terms
| Term | Meaning in the current extension |
|---|---|
| Tasks extension | Optional io.modelcontextprotocol/tasks capability for durable async work |
CreateTaskResult | Server-directed resultType: "task" response to an eligible request |
tasks/get | Poll a full current task snapshot, including terminal result or pending input |
tasks/update | Submit responses to a task's outstanding inputRequests |
tasks/cancel | Acknowledge cooperative cancellation intent |
input_required | Task status indicating client input is outstanding |
pollIntervalMs | Server-suggested minimum delay before another poll |
ttlMs | Expiry duration measured from task creation |
| Durable-before-return | Rule that the task id must resolve before its handle is sent |
notifications/tasks | Optional full task snapshot delivered on a subscribed SSE response |
Legacy Compatibility
The 2025-11-25 experimental surface used client-requested task augmentation, tasks/statustasks/resultand optional tasks/list. Keep those names only inside a pinned legacy adapter. A current client uses the extension capability, accepts server-directed handles, polls tasks/getsupplies input with tasks/updateand reads the final result from the task snapshot.
Further Reading
Check what you learned
6 questions. Answer each one to see why.
How can a stateless MCP server support work that lasts ten minutes?
The full code
Every file for this lesson. Copy it, run it, then change it.
"""Phase 13 Lesson 13: the stateless MCP Tasks extension.
Lesson: ../docs/en.md
Extension: https://tasks.extensions.modelcontextprotocol.io/specification/draft/tasks
This example uses only Python's standard library.
Run: python3 main.py
"""
from __future__ import annotations
import json
import tempfile
import uuid
from dataclasses import asdict, dataclass, field
from datetime import datetime, timezone
from pathlib import Path
from typing import Any
PROTOCOL_VERSION = "2026-07-28"
PROTOCOL_META = "io.modelcontextprotocol/protocolVersion"
CAPABILITIES_META = "io.modelcontextprotocol/clientCapabilities"
CLIENT_INFO_META = "io.modelcontextprotocol/clientInfo"
SERVER_INFO_META = "io.modelcontextprotocol/serverInfo"
SUBSCRIPTION_ID_META = "io.modelcontextprotocol/subscriptionId"
TASKS_EXTENSION = "io.modelcontextprotocol/tasks"
TERMINAL_STATUSES = {"completed", "cancelled", "failed"}
TOOLS = [
{
"name": "generate_report",
"description": "Generate a durable report that may require outline approval.",
"inputSchema": {
"type": "object",
"properties": {
"size": {
"type": "string",
"enum": ["small", "medium", "large"],
"default": "medium",
}
},
"required": [],
},
}
]
@dataclass
class McpError(Exception):
code: int
message: str
data: dict[str, Any] | None = None
def request_meta(*, tasks: bool = True) -> dict[str, Any]:
extensions = {TASKS_EXTENSION: {}} if tasks else {}
return {
PROTOCOL_META: PROTOCOL_VERSION,
CAPABILITIES_META: {"extensions": extensions},
CLIENT_INFO_META: {"name": "lesson-client", "version": "1.0.0"},
}
def _server_meta() -> dict[str, Any]:
return {SERVER_INFO_META: {"name": "tasks-demo", "version": "1.0.0"}}
def complete(**fields: Any) -> dict[str, Any]:
return {"resultType": "complete", **fields, "_meta": _server_meta()}
def validate_request_meta(params: dict[str, Any]) -> dict[str, Any]:
meta = params.get("_meta")
if not isinstance(meta, dict):
raise McpError(-32602, "missing request _meta")
requested_version = meta.get(PROTOCOL_META)
if not isinstance(requested_version, str):
raise McpError(-32602, "missing protocol version")
if requested_version != PROTOCOL_VERSION:
raise McpError(
-32022,
"unsupported protocol version",
{"supported": [PROTOCOL_VERSION], "requested": requested_version},
)
capabilities = meta.get(CAPABILITIES_META)
if not isinstance(capabilities, dict):
raise McpError(-32602, "missing client capabilities")
return meta
def require_tasks_extension(meta: dict[str, Any]) -> None:
extensions = meta[CAPABILITIES_META].get("extensions")
if not isinstance(extensions, dict) or TASKS_EXTENSION not in extensions:
raise McpError(
-32021,
"missing required client capability",
{"requiredCapabilities": {"extensions": {TASKS_EXTENSION: {}}}},
)
def utc_now() -> str:
return datetime.now(timezone.utc).replace(microsecond=0).isoformat().replace(
"+00:00", "Z"
)
@dataclass
class Task:
task_id: str
owner: str
operation: str
status: str
status_message: str
created_at: str
last_updated_at: str
ttl_ms: int | None
poll_interval_ms: int = 1_000
stage: int = 0
size: str = "medium"
result: dict[str, Any] | None = None
error: dict[str, Any] | None = None
input_requests: dict[str, Any] = field(default_factory=dict)
issued_keys: list[str] = field(default_factory=list)
def to_wire(self) -> dict[str, Any]:
wire: dict[str, Any] = {
"taskId": self.task_id,
"status": self.status,
"statusMessage": self.status_message,
"createdAt": self.created_at,
"lastUpdatedAt": self.last_updated_at,
"ttlMs": self.ttl_ms,
"pollIntervalMs": self.poll_interval_ms,
}
if self.status == "input_required":
wire["inputRequests"] = self.input_requests
elif self.status == "completed":
wire["result"] = self.result
elif self.status == "failed":
wire["error"] = self.error
return wire
class TaskStore:
def __init__(self, directory: Path) -> None:
self.directory = directory
self.directory.mkdir(parents=True, exist_ok=True)
self.tasks: dict[str, Task] = {}
self.reload()
def reload(self) -> None:
self.tasks = {}
for path in sorted(self.directory.glob("*.json")):
data = json.loads(path.read_text(encoding="utf-8"))
task = Task(**data)
self.tasks[task.task_id] = task
def persist(self, task: Task) -> None:
path = self.directory / f"{task.task_id}.json"
temporary = self.directory / f"{task.task_id}.tmp"
temporary.write_text(
json.dumps(asdict(task), indent=2, sort_keys=True),
encoding="utf-8",
)
temporary.replace(path)
self.tasks[task.task_id] = task
def create(self, *, size: str, owner: str) -> Task:
timestamp = utc_now()
task = Task(
task_id=f"tsk_{uuid.uuid4().hex[:12]}",
owner=owner,
operation="tools/call:generate_report",
status="working",
status_message="Preparing report outline.",
created_at=timestamp,
last_updated_at=timestamp,
ttl_ms=900_000,
size=size,
)
self.persist(task)
return task
def get(self, task_id: Any) -> Task:
if not isinstance(task_id, str) or task_id not in self.tasks:
raise McpError(-32602, "task not found")
return self.tasks[task_id]
def save(self, task: Task) -> None:
task.last_updated_at = utc_now()
self.persist(task)
class TaskService:
def __init__(self, directory: Path) -> None:
self.store = TaskStore(directory)
def server_discover(self, params: dict[str, Any]) -> dict[str, Any]:
validate_request_meta(params)
return complete(
supportedVersions=[PROTOCOL_VERSION],
capabilities={
"tools": {},
"extensions": {TASKS_EXTENSION: {}},
},
ttlMs=300_000,
cacheScope="public",
)
def tools_list(self, params: dict[str, Any]) -> dict[str, Any]:
validate_request_meta(params)
return complete(
tools=sorted(TOOLS, key=lambda tool: tool["name"]),
ttlMs=60_000,
cacheScope="public",
)
def _owned_task(self, task_id: Any, *, principal: str) -> Task:
task = self.store.get(task_id)
if task.owner != principal:
raise McpError(-32602, "task not found")
return task
def tools_call(self, params: dict[str, Any], *, principal: str) -> dict[str, Any]:
meta = validate_request_meta(params)
require_tasks_extension(meta)
if params.get("name") != "generate_report":
raise McpError(-32602, "unknown tool")
arguments = params.get("arguments", {})
if not isinstance(arguments, dict):
raise McpError(-32602, "arguments must be an object")
size = arguments.get("size", "medium")
if size not in {"small", "medium", "large"}:
raise McpError(-32602, "size must be small, medium, or large")
task = self.store.create(size=size, owner=principal)
return {"resultType": "task", **task.to_wire(), "_meta": _server_meta()}
def tasks_get(self, params: dict[str, Any], *, principal: str) -> dict[str, Any]:
meta = validate_request_meta(params)
require_tasks_extension(meta)
task = self._owned_task(params.get("taskId"), principal=principal)
return complete(**task.to_wire())
def tasks_update(self, params: dict[str, Any], *, principal: str) -> dict[str, Any]:
meta = validate_request_meta(params)
require_tasks_extension(meta)
task = self._owned_task(params.get("taskId"), principal=principal)
responses = params.get("inputResponses")
if not isinstance(responses, dict):
raise McpError(-32602, "inputResponses must be an object")
if task.status == "input_required":
answer = responses.get("approve_outline")
if isinstance(answer, dict):
action = answer.get("action")
if action in {"decline", "cancel"}:
task.status = "cancelled"
task.status_message = "User did not approve the outline."
task.input_requests = {}
self.store.save(task)
elif action == "accept" and isinstance(answer.get("content"), dict):
if answer["content"].get("approved") is True:
task.status = "working"
task.status_message = "Generating approved report."
task.stage = 2
task.input_requests = {}
self.store.save(task)
return complete()
def tasks_cancel(self, params: dict[str, Any], *, principal: str) -> dict[str, Any]:
meta = validate_request_meta(params)
require_tasks_extension(meta)
task = self._owned_task(params.get("taskId"), principal=principal)
if task.status not in TERMINAL_STATUSES:
task.status = "cancelled"
task.status_message = "Cancellation was acknowledged by the worker."
task.input_requests = {}
self.store.save(task)
return complete()
def advance_worker(self, task_id: str) -> Task:
task = self.store.get(task_id)
if task.status != "working":
return task
if task.stage == 0:
key = "approve_outline"
if key in task.issued_keys:
raise RuntimeError("task input request key cannot be reused")
task.issued_keys.append(key)
task.input_requests = {
key: {
"method": "elicitation/create",
"params": {
"mode": "form",
"message": "Approve the generated report outline?",
"requestedSchema": {
"type": "object",
"properties": {"approved": {"type": "boolean"}},
"required": ["approved"],
},
},
}
}
task.status = "input_required"
task.status_message = "Waiting for outline approval."
task.stage = 1
elif task.stage == 2:
task.status = "completed"
task.status_message = "Report completed."
task.stage = 3
task.result = complete(
content=[
{
"type": "text",
"text": f"Generated {task.size} report with approved outline.",
}
],
structuredContent={"size": task.size, "approved": True},
isError=False,
)
self.store.save(task)
return task
def subscription_acknowledgement(
self,
task_ids: list[str],
*,
subscription_id: int | str,
principal: str = "user-42",
) -> dict[str, Any]:
accepted = [
task_id
for task_id in task_ids
if task_id in self.store.tasks
and self.store.tasks[task_id].owner == principal
]
return {
"jsonrpc": "2.0",
"method": "notifications/subscriptions/acknowledged",
"params": {
"notifications": {"taskIds": accepted},
"_meta": {SUBSCRIPTION_ID_META: subscription_id},
},
}
def task_notification(
self,
task_id: str,
*,
subscription_id: int | str,
principal: str = "user-42",
) -> dict[str, Any]:
task = self._owned_task(task_id, principal=principal)
return {
"jsonrpc": "2.0",
"method": "notifications/tasks",
"params": {
**task.to_wire(),
"_meta": {SUBSCRIPTION_ID_META: subscription_id},
},
}
def dispatch(
self,
request: dict[str, Any],
*,
principal: str = "user-42",
) -> dict[str, Any] | None:
is_notification = "id" not in request
request_id = request.get("id")
try:
params = request.get("params", {})
if not isinstance(params, dict):
raise McpError(-32602, "params must be an object")
method = request.get("method")
if method == "server/discover":
result = self.server_discover(params)
elif method == "tools/list":
result = self.tools_list(params)
elif method == "tools/call":
result = self.tools_call(params, principal=principal)
elif method == "tasks/get":
result = self.tasks_get(params, principal=principal)
elif method == "tasks/update":
result = self.tasks_update(params, principal=principal)
elif method == "tasks/cancel":
result = self.tasks_cancel(params, principal=principal)
else:
raise McpError(-32601, "method not found")
if is_notification:
return None
return {"jsonrpc": "2.0", "id": request_id, "result": result}
except McpError as exc:
if is_notification:
return None
error: dict[str, Any] = {"code": exc.code, "message": exc.message}
if exc.data is not None:
error["data"] = exc.data
return {"jsonrpc": "2.0", "id": request_id, "error": error}
def make_request(
request_id: int,
method: str,
params: dict[str, Any],
*,
tasks: bool = True,
) -> dict[str, Any]:
return {
"jsonrpc": "2.0",
"id": request_id,
"method": method,
"params": {**params, "_meta": request_meta(tasks=tasks)},
}
def make_http_request(
request_id: int,
method: str,
params: dict[str, Any],
*,
tasks: bool = True,
) -> tuple[dict[str, Any], dict[str, str]]:
body = make_request(request_id, method, params, tasks=tasks)
headers = {
"Accept": "application/json, text/event-stream",
"Content-Type": "application/json",
"MCP-Protocol-Version": PROTOCOL_VERSION,
"Mcp-Method": method,
}
name: Any = None
if method == "tools/call":
name = body["params"].get("name")
elif method in {"tasks/get", "tasks/update", "tasks/cancel"}:
name = body["params"].get("taskId")
if method == "tools/call" or method in {"tasks/get", "tasks/update", "tasks/cancel"}:
if not isinstance(name, str) or not name:
raise ValueError(f"{method} requires a name for Mcp-Name")
headers["Mcp-Name"] = name
return body, headers
def run_demo(directory: Path) -> tuple[TaskService, list[dict[str, Any]]]:
service = TaskService(directory)
transcript: list[dict[str, Any]] = []
transcript.append(
service.dispatch(
make_request(0, "server/discover", {})
)
)
created = service.dispatch(
make_request(
1,
"tools/call",
{"name": "generate_report", "arguments": {"size": "large"}},
)
)
transcript.append(created)
task_id = created["result"]["taskId"]
service = TaskService(directory)
transcript.append(
service.dispatch(make_request(2, "tasks/get", {"taskId": task_id}))
)
service.advance_worker(task_id)
needs_input = service.dispatch(
make_request(3, "tasks/get", {"taskId": task_id})
)
transcript.append(needs_input)
transcript.append(
service.dispatch(
make_request(
4,
"tasks/update",
{
"taskId": task_id,
"inputResponses": {
"approve_outline": {
"action": "accept",
"content": {"approved": True},
}
},
},
)
)
)
service.advance_worker(task_id)
transcript.append(
service.dispatch(make_request(5, "tasks/get", {"taskId": task_id}))
)
return service, transcript
def main() -> None:
with tempfile.TemporaryDirectory(prefix="lesson-13-tasks-") as directory:
service, transcript = run_demo(Path(directory))
for response in transcript:
result = response["result"]
print(
f"id={response['id']} resultType={result['resultType']} "
f"status={result.get('status', 'ack')}"
)
task_id = transcript[1]["result"]["taskId"]
print(
"notification:",
json.dumps(
service.task_notification(task_id, subscription_id="listen-demo"),
indent=2,
),
)
if __name__ == "__main__":
main()