Building Fault-Tolerant MCP Servers With Temporal for Durable AI Agent Execution
Temporal enables fault-tolerant MCP servers with durable AI agent execution, automatic failure recovery, idempotent retries, and resilience to network disconnections.
AI agents are increasingly invoking tools that take longer than a single network request and depend on systems that can fail independently of the agent runtime. A Model Context Protocol (MCP) tool may trigger document generation, code analysis, data synchronization, or infrastructure automation. It may also trigger another operation that runs for minutes rather than milliseconds. Treating such work as an ordinary request-response handler creates a fragile coupling between the lifetime of the MCP connection and the lifetime of the underlying operation.
Temporal provides a different execution model: the MCP server can accept a tool request, start a durable Workflow, return a stable execution identifier, and allow later requests to retrieve the result. The operation can then survive MCP client restarts, HTTP disconnects, Worker crashes, transient dependency failures, and process redeployments without restarting completed steps. Temporal calls this model Durable Execution because Workflow progress is reconstructed from persisted Event History when execution moves between Workers.
The following examples use the Temporal Java SDK (current published version:1.40.0), together with the MCP Java SDK 2.2.0, which added support for the stateless MCP 2026-07-28 specification. The snippets are documentation-aligned illustrative code and were not executed as part of this article.
String workflowId = "agent-job-" + request.executionKey();
WorkflowOptions options = WorkflowOptions.newBuilder()
.setWorkflowId(workflowId)
.setTaskQueue("agent-execution")
.build();
AgentWorkflow workflow =
workflowClient.newWorkflowStub(AgentWorkflow.class, options);
WorkflowClient.start(workflow::run, request);
return new StartResult(workflowId, "RUNNING");
Temporal requires a Task Queue when creating a new Workflow stub, and a business-derived Workflow ID is preferable when the same logical request must not create duplicate executions. A Workflow ID identifies the logical Workflow across client interactions and can be used to reconnect to an existing execution instead of tying identity to an MCP socket, HTTP request, or process-local object.
This pattern also handles duplicate MCP submissions more cleanly. Retries can occur at proxies, clients, agent frameworks, or application layers. If every retry invents a new Workflow ID, one logical agent instruction can start several independent executions. Deriving the ID from a stable request key moves deduplication into the orchestration boundary. Temporal documents the same principle for durable operations that may be started more than once: stable IDs should be derived from request identity or operation input so retries reuse the intended execution rather than duplicating side effects.
Durable Progress Belongs Inside the Workflow
A Temporal Workflow should contain orchestration state, branching decisions, timers, and durable coordination, while external calls belong in Activities. Workflow code is replayed from history, so nondeterministic side effects such as HTTP requests, database mutations, or LLM calls should not execute directly inside Workflow logic. Activities are explicitly designed for these operations and can be retried when Workers crash, dependencies time out, or temporary failures occur.
A durable agent Workflow might coordinate an LLM planning step, a remote tool invocation, and persistence of the final result:
public AgentResult run(AgentRequest request) {
Plan plan = activities.createPlan(request);
ToolResult toolResult = activities.executeTool(plan);
return activities.storeResult(request.executionKey(), toolResult);
}
The relevant Activity options should make failure behavior explicit rather than inheriting assumptions from the MCP request timeout.
ActivityOptions options = ActivityOptions.newBuilder()
.setStartToCloseTimeout(Duration.ofMinutes(2))
.setRetryOptions(RetryOptions.newBuilder()
.setInitialInterval(Duration.ofSeconds(1))
.setBackoffCoefficient(2.0)
.setMaximumInterval(Duration.ofSeconds(30))
.setMaximumAttempts(8)
.build())
.build();
Temporal requires at least one Activity timeout and strongly recommends Start-To-Close for detecting Worker loss or stalled attempts. Retry backoff remains durable even when the Worker process disappears, because retry state is maintained by the Temporal Service rather than an application thread.
Retries do not create exactly-once side effects. Temporal guarantees that a completed Activity is observed as completed once by the Workflow, but an Activity may execute more than once before that successful completion is recorded. A remote service could therefore receive the same write twice if the first call succeeds, but the Activity Worker crashes before reporting completion. Temporal recommends idempotent Activity implementations and specifically notes that Workflow Run ID combined with Activity ID can form an idempotency key that remains stable across retry attempts.
String idempotencyKey =
Activity.getExecutionContext().getInfo().getWorkflowRunId()
+ ":"
+ Activity.getExecutionContext().getInfo().getActivityId();
return remoteExecutor.execute(command, idempotencyKey);
The receiving system should persist that key and return the original outcome when the same operation arrives again. Durable orchestration without idempotent side effects can preserve Workflow progress while still duplicating external mutations.
Disconnect, Cancellation, and Result Retrieval Are Different Operations
Transport cancellation requires deliberate semantics. Under modern MCP Streamable HTTP, cancellation is represented by closing the in-flight request stream. Earlier MCP revisions use notifications/cancelled for request cancellation, while the current protocol removes session coupling for normal HTTP requests. The Java SDK documentation also distinguishes request timeout from remote cancellation in older client behavior: a caller timing out does not automatically prove that server-side work has stopped.
For durable agent execution, an MCP disconnect should normally mean only that the client stopped waiting. It should not automatically cancel the Temporal Workflow. Otherwise a transient Wi-Fi failure, proxy timeout, browser closure, or application restart becomes a business cancellation signal.
Cancellation should instead be exposed as an explicit tool such as cancel_agent_job. That handler can target the Temporal Workflow by ID and request cancellation intentionally.
WorkflowStub workflow =
workflowClient.newUntypedWorkflowStub(workflowId);
workflow.cancel();
Temporal cancellation is cooperative. A Workflow can observe cancellation and perform cleanup, while Activity cancellation requires additional care because cancellation does not forcibly interrupt arbitrary Activity code. Long-running Activities generally need heartbeats so cancellation can be delivered and progress can be checkpointed. Temporal documents that an Activity without heartbeats may continue until its timeout even after cancellation has been requested.
Result retrieval should similarly be independent of the original MCP connection. A later get_agent_job call can reconstruct a Temporal stub from the Workflow ID and wait for or inspect the durable execution.
WorkflowStub workflow =
workflowClient.newUntypedWorkflowStub(workflowId);
AgentResult result =
workflow.getResult(AgentResult.class);
WorkflowStub.getResult waits on the Temporal Service for Workflow completion, and a stub can be recreated from a known Workflow ID after the original application process or connection has disappeared. This makes the execution handle the durable rendezvous point between the MCP layer and the agent job.
Security and Failure Testing Still Matter
Durability does not replace authorization. A server that exposes get_agent_job or cancel_agent_job must verify that the authenticated principal is permitted to access the referenced Workflow ID. Modern MCP places authentication and authorization outside the core protocol transport and expects server implementations to enforce them at the HTTP or application boundary. The Java SDK explicitly delegates authentication and authorization to application infrastructure such as servlet filters or Spring Security.
Workflow IDs therefore should not function as bearer credentials. A stored execution record should bind the Workflow ID to the authenticated tenant, account, or principal, and every retrieval or cancellation request should validate that relationship before contacting Temporal. Legacy MCP session deployments require an additional precaution because session identifiers must also be bound to authenticated identity; the Java SDK warns that session IDs alone do not provide user isolation.
Fault testing should exercise failures at the boundaries that durability is expected to survive. A Worker can be terminated after an Activity completes, a dependency can return transient failures until the Retry Policy succeeds, the MCP connection can be closed immediately after Workflow start, and the result can then be retrieved through a fresh client process using the same Workflow ID. Temporal’s replay model is specifically designed so another Worker can reconstruct Workflow state from Event History and continue without re-running already recorded completed steps. Worker shutdown behavior should also be tested under realistic Activity load because abrupt termination can cause running Activity attempts to time out and retry.
A fault-tolerant MCP server therefore requires more than retrying HTTP requests. Durable execution emerges when MCP request lifetime, business execution lifetime, and cancellation semantics are modeled separately. MCP provides the interoperable tool boundary; Temporal supplies persisted Workflow state, replay, Activity retries, stable execution identity, and post-disconnect result retrieval. With explicit Workflow IDs, idempotent Activities, intentional cancellation, authorization on every execution handle, and fault tests that include real process and network failures, long-running AI agent operations can continue correctly even after the connection that started them no longer exists.
Opinions expressed by DZone contributors are their own.