Repository navigation
Description
Summary
StatefulMCPServerProvider keeps one MCP server connected for a stateful_mcp_server() block in Python, or between connect() and cleanup() of a statefulMcpServer() in TypeScript. A second server with the same name in the same run should start with a new, empty MCP session. Instead, its calls reach the first server until the first server's session Activity notices that it was cancelled:
- Python: up to one heartbeat interval of the old session Activity, 30 seconds. The second block's
getreturns the value the first block stored, and a write lands in the old server and is lost when it closes. Meanwhile the second block's session Activity fails withCannot connect to an already running serverand is retried until the old server closes. - TypeScript: worse. The second server's session Activity fails with the same error but non-retryably, so the second server never gets a session of its own. Without a
heartbeatTimeout, the old session Activity sends no heartbeats, never learns of the cancel, and serves the second server until the run ends. With one, the old session stops after about one heartbeat interval, the second server's next call fails withMCP Stateful Server Worker failed to schedule activity, and itscleanup()throws.
Every server of a run with the same name serves its operations on one task queue, <name>-stateful@<run_id> (Python, TypeScript). cleanup() cancels the session Activity and returns without waiting for it to stop (Python, default TRY_CANCEL; TypeScript). The session Activity learns of the cancel only from a heartbeat response, every 30 seconds in Python and only with a heartbeatTimeout in TypeScript. Until then, its nested Worker keeps polling the shared queue. TypeScript also refuses the second session for good (StatefulMCPServerAlreadyRunning, nonRetryable: true), where Python raises a retryable error (_mcp.py L556).
Versions
- Python:
temporalio-openai-agentsfrommainat61fe33a,temporalio1.34.0,openai-agents0.22.0,mcp2.2.0, Python 3.13.16. - TypeScript:
@temporalio/openai-agentsfrommainat61fe33a,@temporalio/worker1.24.0,@openai/agents-core0.14.3, Node 24.22.0. - Temporal CLI 1.9.1 dev server (Server 1.32.0).
Reproduction
Each factory call returns a new in-memory server that holds its own value, like an MCP session. A Workflow connects a server, stores "A" with put, and closes it. It then connects a second server with the same name, reads get, waits 40 to 45 seconds and reads get again.
Python: repro.py (one file)
"""A second stateful_mcp_server() block with the same name reaches the first block's MCP server.
OPENAI_API_KEY=unused python repro.py <temporal address>
One workflow opens a block, stores "A" with a stateful MCP server's `put`, and
exits the block. It then opens a second block with the same name, reads `get`,
waits 45 seconds and reads `get` again. Each factory call returns a new
in-memory server that holds its own value, like an MCP session, so a new block
should read "EMPTY". Exits 0 when the second block's first `get` returns "A".
"""
import asyncio
import itertools
import sys
import uuid
from datetime import timedelta
from typing import Any
from agents.mcp import MCPServer
from mcp import GetPromptResult, ListPromptsResult, Tool
from mcp.types import CallToolResult, TextContent
from temporalio import workflow
from temporalio.client import Client
from temporalio.openai_agents import OpenAIAgentsPlugin, StatefulMCPServerProvider
from temporalio.worker import Worker
with workflow.unsafe.imports_passed_through():
import temporalio.openai_agents as openai_agents
sessions = itertools.count(1)
class MemoryServer(MCPServer):
def __init__(self) -> None:
super().__init__()
self.session = f"S{next(sessions)}"
self.value = "EMPTY"
@property
def name(self) -> str:
return "state"
async def connect(self) -> None:
pass
async def cleanup(self) -> None:
pass
async def list_tools(self, run_context: Any = None, agent: Any = None) -> list[Tool]:
return []
async def call_tool(self, tool_name: str, arguments: Any, meta: Any = None) -> CallToolResult:
if tool_name == "put":
self.value = arguments["text"]
return CallToolResult(content=[TextContent(type="text", text=f"{self.value} (server {self.session})")])
async def list_prompts(self) -> ListPromptsResult:
return ListPromptsResult(prompts=[])
async def get_prompt(self, name: str, arguments: Any = None) -> GetPromptResult:
raise NotImplementedError
@workflow.defn
class TwoBlocks:
@workflow.run
async def run(self) -> list[str]:
async with openai_agents.workflow.stateful_mcp_server("state") as server:
await server.call_tool("put", {"text": "A"})
async with openai_agents.workflow.stateful_mcp_server("state") as server:
first = await server.call_tool("get", {})
await workflow.sleep(45)
later = await server.call_tool("get", {})
return [first.content[0].text, later.content[0].text] # type: ignore[union-attr]
async def main() -> None:
plugin = OpenAIAgentsPlugin(
mcp_server_providers=[StatefulMCPServerProvider("state", lambda _: MemoryServer())]
)
client = await Client.connect(sys.argv[1], plugins=[plugin])
task_queue = f"same-name-{uuid.uuid4()}"
async with Worker(client, task_queue=task_queue, workflows=[TwoBlocks]):
first, later = await client.execute_workflow(
TwoBlocks.run, id=task_queue, task_queue=task_queue, execution_timeout=timedelta(minutes=3)
)
print(f"second block, first get: {first!r}")
print(f"second block, get 45 s later: {later!r}")
assert first.startswith("A "), "the second block started with its own server"
if __name__ == "__main__":
asyncio.run(main())TypeScript: repro.cjs and workflows.cjs
// A second statefulMcpServer() with the same name in one run reaches the first one's MCP session.
// Usage: NODE_PATH=<node_modules with @temporalio/openai-agents> node repro.cjs <temporal-address>
//
// The Workflow (workflows.cjs) connects a stateful server, stores "A" with `put` and calls
// cleanup(). It then connects a second server with the same name, reads `get`, waits 40 seconds
// and reads `get` again; once without and once with a 10-second session heartbeat timeout. Each
// factory call returns a new in-memory server that holds its own value, like an MCP session, so
// the second server should read "EMPTY". Exits 0 when its first `get` returns "A" in both runs.
const path = require('node:path');
const { randomUUID } = require('node:crypto');
const { Client, Connection } = require('@temporalio/client');
const { NativeConnection, Worker, bundleWorkflowCode, Runtime, DefaultLogger } = require('@temporalio/worker');
const { OpenAIAgentsPlugin, StatefulMCPServerProvider } = require('@temporalio/openai-agents');
Runtime.install({ logger: new DefaultLogger('ERROR') });
let servers = 0;
function factory() {
const server = `S${++servers}`;
let value = 'EMPTY';
return {
name: 'state',
cacheToolsList: false,
async connect() {},
async close() {},
async listTools() { return []; },
async callTool(name, args) {
if (name === 'put') value = args.text;
return [{ type: 'text', text: `${value} (server ${server})` }];
},
async invalidateToolsCache() {},
};
}
async function main(address) {
const nc = await NativeConnection.connect({ address });
const plugin = new OpenAIAgentsPlugin({
modelProvider: { getModel() { throw new Error('no model'); } },
mcpServerProviders: [new StatefulMCPServerProvider('state', factory, nc)],
});
const { code } = await bundleWorkflowCode({
workflowsPath: path.join(__dirname, 'workflows.cjs'),
plugins: [plugin],
logger: new DefaultLogger('WARN'),
// Resolve the Workflow's imports from NODE_PATH, as Node does for this script.
webpackConfigHook: (c) => ({ ...c, resolve: { ...c.resolve, modules: [process.env.NODE_PATH, 'node_modules'] } }),
});
const client = new Client({ connection: await Connection.connect({ address }) });
let reached = true;
for (const heartbeatTimeout of [false, true]) {
servers = 0;
const taskQueue = `same-name-${randomUUID()}`;
const worker = await Worker.create({ connection: nc, taskQueue, workflowBundle: { code }, plugins: [plugin] });
const out = await worker.runUntil(
client.workflow.execute('twoServers', { taskQueue, workflowId: taskQueue, args: [heartbeatTimeout], workflowExecutionTimeout: '2 minutes' })
);
console.log(`heartbeat timeout ${heartbeatTimeout ? '10 s' : 'unset'}:`);
console.log(` second server, first get: ${JSON.stringify(out[0])}`);
for (const line of out.slice(1)) console.log(` then: ${JSON.stringify(line)}`);
reached &&= out[0].startsWith('A ');
}
process.exit(reached ? 0 : 1);
}
main(process.argv[2]).catch((err) => {
console.error(err);
process.exit(2);
});// The Workflow for repro.cjs: two stateful servers with the same name, one after the other.
const wf = require('@temporalio/workflow');
const { statefulMcpServer } = require('@temporalio/openai-agents/workflow');
const text = (content) => content.map((c) => c.text).join('');
async function twoServers(heartbeatTimeout) {
const options = heartbeatTimeout ? { serverSessionConfig: { heartbeatTimeout: '10 seconds' } } : {};
const first = statefulMcpServer('state', options);
await first.connect();
try {
await first.callTool('put', { text: 'A' });
} finally {
await first.cleanup();
}
const second = statefulMcpServer('state', options);
await second.connect();
const out = [];
try {
out.push(text(await second.callTool('get', {})));
await wf.sleep('40 seconds');
out.push(text(await second.callTool('get', {})));
} catch (err) {
out.push(`error: ${err.message}`);
}
try {
await second.cleanup();
} catch (err) {
out.push(`cleanup: ${err.message} <- ${err.cause?.message}`);
}
return out;
}
module.exports = { twoServers };Expected
The second server starts with a new, empty session: its first get returns EMPTY.
Observed
Python:
python 3.13.16 temporalio==1.34.0 openai-agents==0.22.0 mcp==2.2.0
plugin: temporalio-openai-agents from ai-integrations main at 61fe33a, temporal version 1.9.1 (Server 1.32.0, UI 2.54.1)
$ OPENAI_API_KEY=unused python repro.py 127.0.0.1:7297
second block, first get: 'A (server S1)'
second block, get 45 s later: 'EMPTY (server S2)'
exit=0
worker log lines with "Cannot connect to an already running server": 10
TypeScript (NODE_PATH points at the plugin built from main and its dependencies):
node v24.22.0 @temporalio/worker==1.24.0 @openai/agents-core==0.14.3
plugin: @temporalio/openai-agents from ai-integrations main at 61fe33a
$ node repro.cjs 127.0.0.1:7297
heartbeat timeout unset:
second server, first get: "A (server S1)"
then: "A (server S1)"
then: "cleanup: Activity task failed <- Cannot connect to an already running server. Use a distinct name if running multiple servers in one workflow."
heartbeat timeout 10 s:
second server, first get: "A (server S1)"
then: "error: MCP Stateful Server Worker failed to schedule activity. Check that a worker is polling the dedicated task queue for this MCP run."
then: "cleanup: Activity task failed <- Cannot connect to an already running server. Use a distinct name if running multiple servers in one workflow."
exit=0
In Python the second block's first get was served by the first block's server (S1); once that server closed, the second block got its own (S2). In TypeScript the second server was served only by the first server's session (S1), or failed once that session stopped, and its own session Activity was refused for good in both runs.
Impact
Code that opens a new block or server with the same name in one run, for example to recover after a DedicatedWorkerFailure, can read the previous session's state and write into a session that is about to close, with no error. In TypeScript the new server then fails, and without a heartbeatTimeout the old session Activity keeps its MCP connection and nested Worker until the run ends.
Proposed fix
As for Google ADK in #380: make a new server tell the old session that it has been superseded. For example, send a per-block token from the Workflow's random UUID with the session Activity and its operations, so that an older session stops at once and refuses newer-token operations as retryable, and a newer session refuses older-token ones. A smaller alternative is a bounded wait in cleanup() for the session Activity to stop, at the cost of a slower block exit. For TypeScript, also make the "already running" refusal retryable, as in Python, and heartbeat periodically without a heartbeatTimeout, as Python does every 30 seconds, so that the cancel from cleanup() reaches the session Activity.
Found while reviewing #373, which documents this limitation in both READMEs for now.
Activity
campoy commentedon Nov 3, 2026
One more TypeScript case for this issue, found in DABH's review of #373: the other direction happens too. A call to the first server that is still queued when
cleanup()runs can later run with the second server of the same name, and see its state. In that run, the first server had one call running and one queued, thencleanup(), then a second server with the same name connected: the queued call returnedget=B session=S2, the second server's state, onmainand on #373, with the default config.Python refuses this direction: in #373, a block refuses any operation the server first scheduled before the block's own session Activity (
_mcp.pyL863-L872). TypeScript has no such check. WithscheduleToStartTimeout: 0, #373 cancels the queued call when the first session ends, so only operations with a schedule-to-start timeout (the default) are affected.The per-block token proposed above would cover this direction too, if a newer session refuses operations with an older token. #373 documents this case in the TypeScript README for now.
rahulsjha commentedon Nov 17, 2026
Hi @brianstrauch @campoy, I'd like to pick this up. Plan: give each stateful_mcp_server()/statefulMcpServer() block its own session task queue (adding a per-block sequence to -stateful@<run_id>) in python/openai_agents and typescript/openai-agents, so a second same-name server cannot reach the first one's session, and drop queued calls when cleanup() runs. Tests would run two same-name blocks back to back and check the second starts empty, plus the queued-call case from DABH's review. Is changing the task queue name acceptable for replay, or does it need a patch gate? Could you assign it to me?