Skip to content

[Bug] strands-agents: MCP connections are shared across StrandsPlugin instances and Workers in one process #370

Closed

Description

@campoy

What happens

Each StrandsPlugin takes its own mcpClients (TypeScript) or mcp_clients (Python) factory map
and registers Activities built from those factories. But the Worker-side MCP connection cache is
one module-level map keyed only by server name. In a process with two Workers whose plugins
register the same server name with different factories, whichever plugin connects first serves
both:

  • Wrong server or credentials. The other Worker's MCP calls go to the first Worker's server,
    with the first Worker's credentials, and succeed with no error.
  • Teardown. When one Worker stops, its plugin closes the shared connection, even while another
    Worker's call is using it. That call fails with MCP error -32000: Connection closed and is
    retried, so the tool runs twice. This also happens with one plugin instance shared by two
    Workers (for example on the NativeConnection), and in Python when a Replayer with the plugin
    finishes.

Expected: each plugin instance uses only its own factories, and a connection stays open while a
Worker that uses it, or a call on it, is still running.

Reproduction (TypeScript)

One file, no Temporal server needed: it runs each plugin's own tools-callTool Activity in a
MockActivityEnvironment, with a fake MCP client that answers with its server's name, and stops
plugin A's Worker (through StrandsPlugin.runWorker) while a call through plugin B is in flight.
It exits 0 when each plugin reaches its own server and B's connection stays open.

// Two StrandsPlugin instances register the MCP server name `tools` with different factories,
// as two Workers in one process with their own plugins do.
// Usage: node issue-repro.cjs   (needs @temporalio/strands-agents, @strands-agents/sdk, @temporalio/testing)
// Runs each plugin's own `tools-callTool` Activity in a MockActivityEnvironment, and stops "Worker A"
// (plugin A's runWorker) while a call through plugin B is in flight. Exits 0 when each plugin's
// Activity reaches its own server and B's connection stays open, 1 otherwise.
const { McpClient } = require('@strands-agents/sdk');
const { MockActivityEnvironment } = require('@temporalio/testing');
const { StrandsPlugin } = require('@temporalio/strands-agents');

const log = [];
let releaseHeld;
const held = new Promise((resolve) => (releaseHeld = resolve));

// Stands in for an MCP server: answers with its own name.
class FakeServer extends McpClient {
  constructor(name) {
    super({ transport: { async start() {}, async send() {}, async close() {} } });
    this.serverName = name;
    this.callsInFlight = 0;
  }
  async connect() {}
  async disconnect() {
    log.push(`${this.serverName} disconnected${this.callsInFlight ? ' during a call' : ''}`);
  }
  async callTool(tool, args) {
    this.callsInFlight++;
    try {
      if (args.hold) await held;
      return { content: [{ type: 'text', text: `server ${this.serverName}` }] };
    } finally {
      this.callsInFlight--;
    }
  }
}

const plugins = {
  A: new StrandsPlugin({ models: {}, mcpClients: { tools: () => new FakeServer('A') } }),
  B: new StrandsPlugin({ models: {}, mcpClients: { tools: () => new FakeServer('B') } }),
};
const activities = Object.fromEntries(
  Object.entries(plugins).map(([k, p]) => [k, p.configureWorker({ taskQueue: k }).activities])
);
const call = (k, args = {}) =>
  new MockActivityEnvironment().run(activities[k]['tools-callTool'], { toolName: 'whoami', args });
// The Worker that StrandsPlugin.runWorker receives; only its registered Activities are read.
const worker = (k) => ({ options: { activities: new Map(Object.entries(activities[k])) } });

(async () => {
  let stopA;
  const workerA = plugins.A.runWorker(worker('A'), () => new Promise((resolve) => (stopA = resolve)));
  const workerB = plugins.B.runWorker(worker('B'), () => held);

  const a = await call('A');
  const b = await call('B');
  console.log(`plugin A's call: ${JSON.stringify(a)}`);
  console.log(`plugin B's call: ${JSON.stringify(b)}`);

  const inFlight = call('B', { hold: true });
  await new Promise((resolve) => setTimeout(resolve, 50));
  stopA();
  await workerA;
  console.log(`after Worker A stopped, while B's call is in flight: ${JSON.stringify(log)}`);
  const closedUnderCall = log.some((entry) => entry.endsWith('during a call'));
  releaseHeld();
  console.log(`B's held call: ${JSON.stringify(await inFlight)}`);
  await workerB;
  console.log(`after both stopped: ${JSON.stringify(log)}`);

  const ok = JSON.stringify(a).includes('server A') && JSON.stringify(b).includes('server B') && !closedUnderCall;
  console.log(ok ? 'OK: each plugin used its own server and connection' : 'DEFECT: plugins shared a connection');
  process.exit(ok ? 0 : 1);
})().catch((err) => {
  console.error(err);
  process.exit(2);
});

Output on main at 88745dc (@strands-agents/sdk 1.19.0, @temporalio/* 1.24.0, Node 24):

plugin A's call: {"content":[{"type":"text","text":"server A"}]}
plugin B's call: {"content":[{"type":"text","text":"server A"}]}
after Worker A stopped, while B's call is in flight: ["A disconnected during a call"]
B's held call: {"content":[{"type":"text","text":"server A"}]}
after both stopped: ["A disconnected during a call"]
DEFECT: plugins shared a connection
exit=1

The same happens with real Workers: two Workers in one process with their own StrandsPlugin
and the same server name, calling one MCP tool through TemporalAgent, send the second Worker's
call to the first Worker's server, or with the first Worker's authorization header, in both
start orders. Stopping one of two Workers (with separate plugins or one shared plugin) while the
other has a call in flight fails that call with MCP error -32000: Connection closed; its retry
runs the tool again. With both Workers shut down together and a 6-second shutdownGraceTime, the
call is cut off at once and runs twice. With one Worker per process, or a distinct server name per
plugin, nothing is shared.

Python

temporalio-strands-agents 0.1.0 and main have the same module-level _CONNECTIONS cache keyed
by server name. With two Workers in one process: Worker B's call reached Worker A's server and
read A's session value, and sent A's dummy authorization header, in both orders; Worker A
stopping, or a Replayer with the plugin finishing, closed the connection under Worker B's
in-flight call, which timed out and ran again on a new server process; and a graceful shutdown of
both Workers cut the call off and ran it twice.

Open PR #190 replaces that cache with temporalio-mcp's pool, which belongs to each
StrandsPlugin and closes only when the last Worker or Replayer using it ends. The same checks
on #190 (head 7a139a1; its later head d7ccd75 only merges main and changes neither package), with servers on the current MCP protocol (pooled connections) and on an
older one (a connection per Activity), all show each Worker using its own server and key, and
Worker B's call finishing on its first attempt, with one tool run. So Python needs nothing beyond
#190; the fix below is for TypeScript.

Versions

TypeScript: @temporalio/strands-agents on main at 88745dc (also @temporalio/strands-agents
1.24.0 from sdk-typescript contrib/strands), @strands-agents/sdk 1.19.0,
@modelcontextprotocol/sdk 1.32.0, @temporalio/worker 1.24.0, Node 24. Python:
temporalio-strands-agents 0.1.0 and main at 88745dc, temporalio 1.34.0,
strands-agents 1.56.0, mcp 1.30.0. Temporal CLI 1.9.1 (Server 1.32.0).

Impact

A tool call can silently act on another tenant's server or with another tenant's credentials.
The teardown delays the run and runs a tool's side effect twice. One Worker per process, or a
distinct server name per plugin, avoids it.

Proposed fix (TypeScript)

Keep the connections in each StrandsPlugin instance instead of a module-level map: the
listTools/callTool Activities use their plugin's connections, the plugin's runContext counts
the Workers using the plugin and closes the connections when the last one stops, and a connection
a call still uses is closed when that call finishes. This matches Python #190's temporalio-mcp
pool. Workers that share one plugin instance still share its connections; two separate instances
that map one name to the same server no longer share a session.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions