Designing MCP Tasks That Survive Disconnects and Worker Restarts
Build reliable long-running MCP operations with durable task acceptance, protocol-version adapters, fenced workers, honest cancellation, resumable observation, and tenant-safe result access.
On this page
A long-running MCP operation has two lifecycles: the work being executed and the client's observation of that work.
A network disconnect can end observation while execution continues. A cancellation request can reach the server while an external operation is already finishing. A task can complete its protocol lifecycle and still return a tool-level error.
Those distinctions belong in the application state model. Without them, the host can report failure too early, retry work that already happened, or describe an acknowledgement as proof that execution stopped.
I would build MCP Tasks around three invariants: an accepted handle resolves to durable state, terminal outcomes remain immutable, and every observer receives only the state it is authorized to inspect.
The example in this article is a hypothetical repository-analysis service. It scans a pinned repository snapshot and produces an inventory of dependencies and findings. No benchmark results or production incidents are claimed.
Pick a protocol generation before implementing the adapter
MCP has more than one Tasks design in its published history. The experimental 2025-11-25 specification uses task-augmented requests and separate result retrieval. The released 2026-07-28 extension is a different contract.
For the latter, the extension identifier is io.modelcontextprotocol/tasks. Clients declare support in per-request capabilities, and servers advertise support through discovery. The server chooses whether a supported tool call returns its ordinary result or an asynchronous handle. A client must handle either shape.
Pin the release supported by both peers. Keep older behavior behind a separate adapter rather than assembling a hybrid from examples written for different generations. Test the actual host and server combination before enabling the asynchronous path.
This article's wire-protocol discussion follows the released 2026-07-28 extension, checked on October 13, 2026. The implementation sketches are application code, not a complete MCP SDK implementation.
Accept work only after its identity is recoverable
For the repository analyzer, acceptance should record:
- authenticated owner and tenant;
- repository identity and immutable revision;
- tool and analysis-policy versions;
- validated arguments and an application operation ID;
- runtime budget and retention policy;
- initial task state and dispatch intent.
Commit the task record and dispatch intent together. An outbox dispatcher can enqueue the job after that transaction. This prevents a crash from leaving an accepted task with no record of the work that must be dispatched.
It does not create exactly-once delivery. A dispatcher or broker can deliver again, so the worker still needs a stable operation identity and replay-safe stages. See the idempotency design.
An MCP JSON-RPC request ID correlates a request and response; it should not silently become your business idempotency key. If retries must return the same task, define a separate tool or application contract for that behavior, scope it to the caller, and reject reuse with different arguments.
Return the handle after the durable record is readable on the path that serves status requests. Do not send a handle first and hope a delayed replica catches up before the client polls.
Preserve the released result shape
The released schema defines a flat creation result: resultType: "task" accompanies fields such as taskId, status, timestamps, ttlMs, and an optional pollIntervalMs. It is not the older nested task response.
The observer calls tasks/get. Its response uses resultType: "complete" and includes the task's current state. Here, “complete” describes the response to the status request; it does not mean the underlying task finished.
The lifecycle states are working, input_required, completed, failed, and cancelled. The last three are terminal. Completed state carries the original operation's result; failed state carries its JSON-RPC error.
There is a further distinction: a completed task may contain a tool result with isError: true. The core tool-result contract distinguishes that result from a protocol error. The application must inspect both layers before deciding what to show or retry.
Even a tool result without an error flag still needs domain validation. A valid response envelope does not establish that every dependency was analyzed or every reported artifact is accessible.
Give the client an explicit observation policy
I would persist the task ID with server identity, protocol version, owner scope, and local observation policy. Persist it before handing control back to the model or UI. Otherwise a host crash can lose the only path to work that is still running.
Status handling should produce a decision, rather than hiding every branch inside an unbounded polling loop.
The TypeScript sketch below consumes a compact projection of an already validated task response:
type TaskView = { taskId: string; pollIntervalMs?: number;} & ( | { status: "working" } | { status: "input_required"; inputRequests: Record<string, unknown> } | { status: "completed"; result: Record<string, unknown> } | { status: "failed"; error: Record<string, unknown> } | { status: "cancelled" });type Observation = | { kind: "result"; result: Record<string, unknown> } | { kind: "tool-error"; result: Record<string, unknown> } | { kind: "protocol-error"; error: Record<string, unknown> } | { kind: "cancelled" } | { kind: "input"; requests: Record<string, unknown> } | { kind: "poll"; afterMs: number } | { kind: "detach"; taskId: string };function observationPlan( task: TaskView, nowMs: number, observeUntilMs: number, jitter: number,): Observation { if ( !Number.isSafeInteger(nowMs) || nowMs < 0 || !Number.isSafeInteger(observeUntilMs) || observeUntilMs < 0 || !Number.isFinite(jitter) || jitter < 0 || jitter > 1 ) { throw new Error("invalid-observation-policy"); } if (task.status === "completed") { return { kind: task.result.isError === true ? "tool-error" : "result", result: task.result, }; } if (task.status === "failed") return { kind: "protocol-error", error: task.error }; if (task.status === "cancelled") return { kind: "cancelled" }; const remaining = observeUntilMs - nowMs; if (remaining <= 0) return { kind: "detach", taskId: task.taskId }; if (task.status === "input_required") { return { kind: "input", requests: task.inputRequests }; } const interval = task.pollIntervalMs ?? 1000; if (!Number.isSafeInteger(interval) || interval < 1) { throw new Error("invalid-poll-interval"); } const delay = Math.ceil(interval * (1 + 0.2 * jitter)); if (!Number.isSafeInteger(delay)) throw new Error("poll-delay-overflow"); return delay >= remaining ? { kind: "detach", taskId: task.taskId } : { kind: "poll", afterMs: delay };}The nonnegative jitter delays the poll slightly; it never accelerates polling below the server's suggested interval. The default interval is application policy.
The host must separately bound each network request, honor rate-limit responses, validate response sizes, and execute sleeps through cancellable scheduling. This function deliberately does not implement those mechanisms.
“Detach” means observation stopped and the handle remains available for later recovery. It is not a remote cancellation result. If product policy requires cancellation when the local budget expires, persist that intent, send tasks/cancel, and observe the outcome through a separate recovery path.
Keep timeouts, deadlines, and retention separate
| Clock | What it bounds | What expiry establishes |
|---|---|---|
| Status-request timeout | One network exchange | The caller stopped waiting for that exchange |
| Observation deadline | This host's active waiting | The host should detach or request cancellation under policy |
| Execution deadline | Worker and downstream work | The runtime must enforce its stop or reconciliation policy |
| Task TTL | Availability of the protocol task record | The handle may no longer be usable |
Task TTL is defined from creation and can change. It is not a substitute for a worker deadline or a promise of indefinite result retention.
For the repository analyzer, a recoverable analysis artifact may outlive the task handle under its own access and retention policy. A lost or expired handle should not automatically cause the host to resubmit an expensive scan. Consult an authorized application operation record first.
The deadline and cancellation article covers enforcement through actual I/O and subprocesses. Tasks add the protocol observation surface; they do not terminate a process by themselves.
Fence workers before they commit terminal state
Shared storage makes status visible across replicas. Worker ownership needs additional coordination.
Use a lease and a monotonically increasing fencing token. A replacement worker receives a newer token. Every state-changing write must verify that token, the applicable lease, and the expected lifecycle state.
The following Python example illustrates the final database write using SQLite. It assumes a table containing the referenced columns and a result artifact already committed and verified:
import sqlite3def commit_result( db: sqlite3.Connection, *, task_id: str, tenant_id: str, fence: int, artifact_ref: str,) -> bool: if type(fence) is not int or fence < 1 or not artifact_ref: raise ValueError("Invalid fencing token or artifact reference") with db: changed = db.execute( """ UPDATE analysis_tasks SET status = 'completed', artifact_ref = ?, version = version + 1 WHERE task_id = ? AND tenant_id = ? AND fence = ? AND status = 'working' AND lease_until_unix > unixepoch() RETURNING task_id """, (artifact_ref, task_id, tenant_id, fence), ).fetchone() return changed is not NoneThis is an application persistence seam, not the wire representation of a task. The service still needs to construct a schema-valid tool result from the artifact reference.
The artifact precondition matters. Commit durable artifact contents before exposing completed state. If the state write then fails, garbage collection can remove an unreferenced artifact later. Exposing completed state before the artifact is readable creates a harder recovery problem.
Database fencing alone cannot stop a stale worker from calling an external API. For consequential effects, the downstream system must enforce an equivalent token, an idempotency contract, or another authorization boundary. Worker leases and fencing explain that distinction.
Cancellation acknowledgement is not teardown evidence
The current extension makes cancellation cooperative. An acknowledgement from tasks/cancel does not prove the worker stopped, a subprocess exited, or an external operation was undone.
Record cancellation intent separately from confirmed terminal state. Let the worker stop at safe boundaries, propagate cancellation where supported, and reconcile external outcomes where necessary.
A race is possible: completion wins just before the cancellation request is processed. Preserve the truthful completed outcome rather than rewriting it to cancelled because that is what the UI expected.
Terminal state should be immutable. If additional reconciliation changes your understanding of a business effect, append evidence to an application operation record rather than changing the protocol task's historical terminal status.
The UI needs distinct language for “cancellation requested,” “cancelled,” and “completed before cancellation.” A reassuring label should not replace execution evidence.
Input requests need their own trust boundary
The released extension can surface outstanding inputRequests and accept corresponding responses through tasks/update. The host must treat these as requests from the server, not instructions that automatically gain the user's authority.
For a repository analyzer, the server might ask which workspace to inspect. For a task involving a consequential action, it might request review. The existence of an input_required state does not define an application's approval policy.
Bind approval to the exact action, authenticated reviewer, tenant, and resource version. Revalidate expiring permissions before execution. The human-approval pattern applies whether the interaction arrives through Tasks or another surface.
Persist outstanding request identities and already-provided responses. After a reconnect, do not repeatedly prompt the user for the same input or apply a response to a different request.
Separate delivery from observation

*A durable task and outbox are committed before returning a handle; worker execution, fencing, terminal results, and client polling remain separate.*
The diagram is an application architecture. It does not prescribe that the transport process itself runs the worker. A deployment can use a broker, durable workflow engine, or an external job service.
Notifications can reduce polling when both peers support them. The extension provides task notifications through subscriptions. Keep reconnect and resynchronization behavior explicit, and validate the identity and scope of every incoming update. Polling remains a useful recovery path.
Authorization continues after task creation
Long-lived work outlasts many short-lived credentials.
A task handle can expose sensitive results or act as a bearer capability, depending on the deployment. Protect it accordingly: generate unpredictable IDs, keep them out of public URLs and analytics, and use additional caller binding when the application requires it.
Every status read, input update, cancellation, and artifact fetch should follow the deployment's authorization policy. Credential refresh must preserve the intended principal and scope; it should not quietly attach another account's identity.
Decide how revocation affects running work. Losing permission to fetch an artifact is different from requiring the worker to stop. For mutations, recheck authority at the action boundary rather than relying only on authorization recorded minutes earlier.
Apply quotas to accepted and outstanding work, input wait time, result size, storage, and polling. Do not let a valid capability turn into unlimited background compute.
Observe the boundaries that can fail independently
Track acceptance latency, queue age, execution duration, input wait duration, and time between execution completion and client observation.
For reliability, watch:
- handles returned before status becomes readable;
- accepted tasks with no recoverable dispatch intent;
- lease recovery and stale-writer rejection;
- tool errors inside completed tasks;
- cancellation requests without observed terminal outcomes;
- expired handles whose operations remain unresolved;
- cross-tenant access denials;
- result artifacts missing after completion;
- repeated submissions for one application operation.
Use task and operation IDs in restricted traces or logs, not high-cardinality metric labels. Redact arguments, error payloads, and status messages. They may contain repository paths, tokens, or private findings.
A dashboard showing only the count of completed tasks hides tool errors and observation failures. Report protocol outcome, tool outcome, and externally verified business effect separately.
Failure-inject the implementation before enabling it
Test a crash before acceptance commits, after acceptance but before dispatch, and after artifact commit but before terminal state.
Disconnect and restart the host after it receives a handle. Poll through a different server replica. Replace a worker after its lease expires and verify that the old worker cannot finalize the task.
Exercise cancellation racing with completion, input responses after reconnection, credential expiry, tenant changes, result-size limits, and unsupported clients.
For compatibility, assert the exact released result shapes. A client using the older request-augmentation model should not accidentally appear compatible because both generations happen to use a method named tasks/get.
These checks extend durable agent execution into the MCP boundary. They test whether the host can recover its relationship with the work, as well as whether the worker can resume.
Tasks are useful when execution must survive the request that started it. The durable handle, worker runtime, observation policy, and authority model all have to agree about what happened before the system can report it accurately.
Primary references
KEEP READING
Related engineering notes
A Failover Route Is Not a Recovery Path: Proving Independence in AI Infrastructure
Two LLM providers can share the same failure domain. Build an evidence-backed recovery graph that checks cloud, networking, identity, control-plane and capacity dependencies before admitting fallback routes, then test correlated outages without weakening safety.
Read articleAn Eval Platform Sunset Can Erase Your Release Evidence: Build an Evidence-Escrow Migration Gate
When a hosted LLM evaluation platform retires, switching runners is not enough. Preserve the historical evidence, reconstruct grader semantics, validate scoring parity, and enforce a fail-closed release gate that survives the service shutdown.
Read articleWhen the Package Runs Before Your App: Quarantining AI Framework Releases
The 2026 agent-framework PyPI compromise exposed a blind spot in AI build pipelines: Python startup hooks execute before application imports. Design an artifact-quarantine gate, inspect wheels without installing them, separate credentials, and recover from suspected exposure.
Read article