Repository navigation
Description
Summary
StatefulMCPServerProvider keeps one MCP server connected for a Workflow run, in a -server-session Activity that runs a dedicated Worker on the per-run Task Queue <name>-stateful@<run_id>. When Temporal retries that Activity, the retry calls the server factory again, connects a new server and serves the same queue. Later calls in the run go to the new, empty MCP session and succeed. The Workflow gets wrong results and no error.
The docs promise an error instead:
- Python: the
StatefulMCPServerProviderdocstring says "the caller will have to handle cases where the dedicated worker fails, as Temporal is unable to seamlessly recreate any lost state in that case", by "catching ApplicationError with typeDedicatedWorkerFailure" (_mcp.py). - TypeScript: the provider says "Callers must handle
ApplicationFailurewith type"DedicatedWorkerFailure"if the dedicated Worker fails to start or misses a heartbeat" (stateful-mcp-provider.ts), andstatefulMcpServer()says operations then throw that failure (stateful-mcp-client.ts).
The session Activity runs with Temporal's default retry policy: Python's default server_session_config sets only a one-hour start-to-close timeout (_mcp.py), and TypeScript's serverSessionConfig has no retry option (stateful-mcp-client.ts). The Activity refuses to start only while this process still holds the same run's server (Python, TypeScript). Nothing tells a retry apart from the first attempt.
Ways to trigger the retry:
- Python, with the default config: a graceful shutdown of the Worker hosting the session, as in a deploy (the Activity is cancelled with
worker_shutdownand retried on another Worker), or a session that outlives the one-hour start-to-close timeout. - Both languages: a heartbeat timeout in the session config and a lost host; or the start-to-close timeout when the retry runs on a Worker process that does not hold the run's server (TypeScript needs another Worker process for this; on one Worker the retry fails with
StatefulMCPServerAlreadyRunning).
Versions
- Python:
temporalio-openai-agents1.1.0 (latest release, withtemporalio1.35.0) andmainat88745dc(with its lockedtemporalio1.34.0),openai-agents0.22.0,mcp1.30.0 (the script's server usesFastMCP, whichmcp2 renamed, andmcp2's protocol has no MCP session to keep), Python 3.13.16. - TypeScript:
@temporalio/openai-agentsbuilt frommainat88745dc(the latest npm release, 1.24.0, comes fromtemporalio/sdk-typescriptand has the same session Activity),@temporalio/worker1.24.0,@openai/agents-core0.14.3, Node 24.22.0. temporal server start-devfrom Temporal CLI 1.9.1.
Reproduction (Python)
One file, against a local temporal server start-dev. In one process it runs a stateful MCP server over streamable HTTP (put stores a value per MCP session, get returns it or EMPTY), a Worker with OpenAIAgentsPlugin and StatefulMCPServerProvider, and a Workflow that stores kept, sleeps 30 seconds and reads it back. The session config sets a 15-second start-to-close timeout (the default is one hour), so Temporal retries the session Activity during the sleep. No model is called.
pip install 'temporalio-openai-agents==1.1.0' 'openai-agents==0.22.0' 'mcp==1.30.0' uvicorn
OPENAI_API_KEY=unused python repro.py 127.0.0.1:7233repro.py:
"""A retried stateful MCP session Activity silently opens a new, empty session.
Run: OPENAI_API_KEY=unused python repro.py <temporal-address>
(The plugin builds an OpenAI client at Worker start; no model is called.)
One process runs a stateful MCP server, a Worker with the plugin, and a
Workflow that stores a value through `stateful_mcp_server()`, waits longer
than the session Activity's start-to-close timeout (15 s here; the default is
one hour), then reads the value back. It prints what the second call got.
"""
import asyncio
import sys
import threading
import uuid
from datetime import timedelta
from temporalio import workflow
from temporalio.client import Client
from temporalio.worker import Worker
with workflow.unsafe.imports_passed_through():
import uvicorn
from mcp.server.fastmcp import Context, FastMCP
from agents.mcp import MCPServerStreamableHttp
from temporalio.openai_agents import OpenAIAgentsPlugin, StatefulMCPServerProvider
from temporalio.openai_agents.workflow import stateful_mcp_server
from temporalio.workflow import ActivityConfig
PORT = 7491
server = FastMCP("state", json_response=True, session_idle_timeout=None, log_level="WARNING")
store: dict[str, str] = {}
sessions: list[str] = []
def session_of(ctx: Context) -> str:
sid = ctx.request_context.request.headers["mcp-session-id"]
sessions.append(sid)
return sid
@server.tool()
def put(value: str, ctx: Context) -> str:
store[session_of(ctx)] = value
return "stored"
@server.tool()
def get(ctx: Context) -> str:
return store.get(session_of(ctx), "EMPTY")
@workflow.defn
class Repro:
@workflow.run
async def run(self) -> list[str]:
session = ActivityConfig(start_to_close_timeout=timedelta(seconds=15))
async with stateful_mcp_server("state", server_session_config=session) as mcp:
first = await mcp.call_tool("put", {"value": "kept"})
await workflow.sleep(30)
second = await mcp.call_tool("get", {})
return [first.content[0].text, second.content[0].text]
def factory(_):
return MCPServerStreamableHttp(params={"url": f"http://127.0.0.1:{PORT}/mcp"}, name="state")
async def main() -> None:
app = server.streamable_http_app()
kwargs = {"host": "127.0.0.1", "port": PORT, "log_level": "warning"}
threading.Thread(target=uvicorn.run, args=(app,), kwargs=kwargs, daemon=True).start()
plugin = OpenAIAgentsPlugin(mcp_server_providers=[StatefulMCPServerProvider("state", factory)])
client = await Client.connect(sys.argv[1], plugins=[plugin])
queue = f"repro-{uuid.uuid4().hex[:6]}"
async with Worker(client, task_queue=queue, workflows=[Repro]):
result = await client.execute_workflow(Repro.run, id=queue, task_queue=queue)
print("put ->", result[0])
print("get ->", result[1])
print("put session:", sessions[0])
print("get session:", sessions[-1])
if __name__ == "__main__":
asyncio.run(main())Output on main (log lines omitted; 1.1.0 gives the same with other session IDs):
put -> stored
get -> EMPTY
put session: eba10e7ee538434493c970306939c990
get session: 52de01e9184b43dcbc9fbe19f3a3cc5a
The second call ran in a different MCP session and the run completed. Attempts 2 and 3 of the session Activity failed with Cannot connect to an already running server until the timed-out attempt cleaned up; the next attempt connected a new server.
Control: the same Workflow with retry_policy=RetryPolicy(maximum_attempts=1) in the session config gets the documented failure: get raises DedicatedWorkerFailure: MCP Stateful Server Worker failed to schedule activity. after its 30-second schedule-to-start timeout, and no second session opens.
Reproduction (TypeScript)
Two Worker processes on one Task Queue, each with its own plugin and StatefulMCPServerProvider('mem', factory, connection). Each factory call returns an in-memory MCPServer whose stored value belongs to that instance, as an MCP session would. Worker A has one Activity slot and starts first; once its session is connected, Worker B starts. The session's start-to-close timeout is 10 seconds, so the retry runs on B.
NODE_PATH=<node_modules with @temporalio/openai-agents> OPENAI_AGENTS_DISABLE_TRACING=1 node repro.cjs 127.0.0.1:7233repro.cjs:
// Does a retried session Activity reach the run's original MCP session?
// Usage: NODE_PATH=<node_modules> node repro.cjs <temporal-address>
//
// Two Worker processes poll one Task Queue, each with its own plugin and
// StatefulMCPServerProvider('mem', ...). Each factory call returns an
// in-memory server whose state belongs to that instance, like an MCP session.
// Worker A has one Activity slot, so after the session Activity's 10 s
// start-to-close the retry runs on Worker B.
const fs = require('node:fs');
const os = require('node:os');
const path = require('node:path');
const { spawn } = require('node:child_process');
const { randomUUID } = require('node:crypto');
const { Client, Connection } = require('@temporalio/client');
const { NativeConnection, Worker, bundleWorkflowCode, Runtime, DefaultLogger } = require('@temporalio/worker');
const { activityInfo } = require('@temporalio/activity');
const { OpenAIAgentsPlugin, StatefulMCPServerProvider } = require('@temporalio/openai-agents');
Runtime.install({ logger: new DefaultLogger('ERROR') });
const [address = '127.0.0.1:7259', role, worker, taskQueue, bundle, slots] = process.argv.slice(2);
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
function factory() {
const session = `${worker}#${activityInfo().attempt}`;
let value = 'EMPTY';
return {
name: 'mem',
cacheToolsList: false,
async connect() { console.log(`connect ${session}`); },
async close() {},
async listTools() { return []; },
async callTool(name, args) {
if (name === 'put') value = args.value;
return [{ type: 'text', text: `${name}=${value} session=${session}` }];
},
async invalidateToolsCache() {},
};
}
const plugin = (nc) =>
new OpenAIAgentsPlugin({
modelProvider: { getModel() { throw new Error('no model'); } },
mcpServerProviders: [new StatefulMCPServerProvider('mem', factory, nc)],
});
async function runWorker() {
const nc = await NativeConnection.connect({ address });
const w = await Worker.create({
connection: nc,
taskQueue,
workflowBundle: { codePath: bundle },
plugins: [plugin(nc)],
...(slots ? { maxConcurrentActivityTaskExecutions: Number(slots) } : {}),
});
console.log(`ready ${worker}`);
await w.run();
}
function startWorker(name, queue, codePath, slotCount) {
const child = spawn(process.execPath, [__filename, address, 'worker', name, queue, codePath, ...(slotCount ? [slotCount] : [])], { stdio: ['ignore', 'pipe', 'inherit'] });
child.lines = [];
child.stdout.on('data', (d) => child.lines.push(...String(d).trim().split('\n')));
return child;
}
async function main() {
const queue = `f23-oai-ts-retry-${randomUUID().slice(0, 6)}`;
const { code } = await bundleWorkflowCode({
workflowsPath: path.join(__dirname, 'workflows.cjs'),
plugins: [plugin(undefined)],
logger: { info() {}, warn() {}, error: console.error, debug() {}, trace() {}, log() {} },
webpackConfigHook: (c) => ({ ...c, resolve: { ...c.resolve, modules: [process.env.NODE_PATH, 'node_modules'] } }),
});
const codePath = path.join(fs.mkdtempSync(path.join(os.tmpdir(), 'f23-retry-')), 'bundle.js');
fs.writeFileSync(codePath, code);
const a = startWorker('A', queue, codePath, '1');
while (!a.lines.includes('ready A')) await sleep(100);
const client = new Client({ connection: await Connection.connect({ address }), plugins: [plugin(undefined)] });
const handle = await client.workflow.start('sessionTimeoutRetry', { taskQueue: queue, workflowId: queue });
while (!a.lines.includes('connect A#1')) await sleep(100);
const b = startWorker('B', queue, codePath);
let outcome;
try {
outcome = (await handle.result()).join('\n');
} catch (e) {
outcome = `${e.name}: ${e.message} <- ${e.cause?.name}: ${e.cause?.message}`;
}
console.log(`worker A: ${a.lines.filter((l) => l.startsWith('connect')).join(', ')}`);
console.log(`worker B: ${b.lines.filter((l) => l.startsWith('connect')).join(', ')}`);
console.log(`workflow: ${(await handle.describe()).status.name}`);
console.log(outcome);
a.kill('SIGKILL');
b.kill('SIGKILL');
}
(role === 'worker' ? runWorker() : main()).then(
() => process.exit(0),
(e) => { console.error(e); process.exit(1); }
);workflows.cjs:
// Store a value, outlive the session Activity's 10 s start-to-close, then read it six times.
const wf = require('@temporalio/workflow');
const { statefulMcpServer } = require('@temporalio/openai-agents/workflow');
const text = (content) => content.map((c) => c.text).join('');
async function sessionTimeoutRetry() {
const server = statefulMcpServer('mem', {
serverSessionConfig: { startToCloseTimeout: '10 seconds' },
config: { scheduleToStartTimeout: '60 seconds' },
});
await server.connect();
try {
const out = [text(await server.callTool('put', { value: 'V' }))];
await wf.sleep('20 seconds');
for (let i = 0; i < 6; i++) out.push(text(await server.callTool('get', {})));
return out;
} finally {
await server.cleanup();
}
}
module.exports = { sessionTimeoutRetry };Output on main:
worker A: connect A#1
worker B: connect B#2
workflow: COMPLETED
put=V session=A#1
get=EMPTY session=B#2
get=EMPTY session=B#2
get=EMPTY session=B#2
get=EMPTY session=B#2
get=EMPTY session=B#2
get=EMPTY session=B#2
Expected and observed
Expected: once the session is lost, later calls fail with DedicatedWorkerFailure, as the docs say, or keep the original session.
Observed: later calls succeed against a new, empty MCP session, and the run completes.
Impact
Any stateful MCP server whose state matters (an open file, a transaction, a browser page, a login) silently loses it mid-run. In Python this needs no configuration: every graceful deploy of a Worker that hosts a session, and every session older than an hour, triggers it.
Proposed fix
Plugin only, in both languages, without a version gate, in two parts (the same design as the Google ADK fix in #311):
- Activity side. Each attempt of the session Activity sends its first heartbeat at once with
mcp-session-may-be-open, readsDescribeWorkflowExecutionuntil the server shows that heartbeat for this attempt, connects the server, and then sendsmcp-session-opened. Heartbeat details carry over to the next attempt, so an attempt that inherits either marker fails with a non-retryableDedicatedWorkerFailurebefore it calls the factory. An attempt that ends without connecting clears the marker, so a failed factory call or first connect is still retried. The read-back is needed because the Worker sends heartbeats later and the plugin cannot wait for one. - Workflow side. A refused retry alone does not reach operations that have neither a schedule-to-start nor a schedule-to-close timeout (a Python
configthat sets neither, or TypeScriptscheduleToStartTimeout: 0): they wait on the abandoned queue forever. Such operations fail withDedicatedWorkerFailureonce the session Activity has ended, and a caller's cancellation still reaches the operation.
This is a breaking change for a factory whose state survives being rebuilt (for example, it reloads it from storage): today such a run recovers when the session Activity is retried, and after the fix it gets DedicatedWorkerFailure. The Workflow-side part also changes commands for operations with neither timeout once the session has ended, so such runs do not replay across the change, including runs whose own deadline or cancellation ended that operation and that moved on.
Activity