Skip to content

[Bug] strands_agents: the plugin ignores an MCPClient's startup_timeout #187

Closed

Description

@campoy

Summary

StrandsPlugin(mcp_clients=...) takes fully configured MCPClient factories. Strands documents
startup_timeout (default 30 seconds) as the deadline after which MCP server initialization is
cancelled, and MCPClient.start() applies it. The plugin opens the transport and runs
ClientSession.initialize() itself and never reads the setting, so a server slower than the
deadline still connects, and a server that never answers initialize keeps the Activity waiting
until its own timeout.

Versions

temporalio-strands-agents 0.1.0 and main at 495e507; also
temporalio.contrib.strands in temporalio 1.33.0. strands-agents 1.56.0 (1.51.0 at 1.33.0),
mcp 1.30.0, Python 3.13.16.

Reproduction

One file, no Temporal server: it calls the plugin's registered {server}-list-tools Activity
function directly. The factory sets startup_timeout=1 against a stdio MCP server that answers
initialize after about 2 seconds. It exits 0 when the plugin raises as natively.

startup_check.py
"""Does the plugin apply an MCPClient's startup_timeout, as Strands does natively?

  python startup_check.py            run the check
  python startup_check.py server     (internal) an MCP stdio server that waits 2 s before serving

The factory sets startup_timeout=1 against a server that answers initialize after about 2 s.
  native  Strands' MCPClient.list_tools_sync(): raises MCPClientInitializationError
  plugin  the plugin's registered "delayed-list-tools" Activity function, called directly
Exits 0 when the plugin also raises MCPClientInitializationError (the native behavior) and 1 when
it lists the tools after the deadline (the defect).
"""

import asyncio
import importlib
import importlib.metadata as md
import os
import sys
import time
from pathlib import Path

from mcp import StdioServerParameters, stdio_client
from strands.tools.mcp import MCPClient


def factory() -> MCPClient:
    params = StdioServerParameters(command=sys.executable, args=[str(Path(__file__).resolve()), "server"])
    return MCPClient(lambda: stdio_client(params), startup_timeout=1)


def serve() -> None:
    time.sleep(2)
    try:
        from mcp.server.fastmcp import FastMCP
    except ImportError:
        from mcp.server.mcpserver import MCPServer as FastMCP
    server = FastMCP("delayed")

    @server.tool()
    def echo(message: str) -> str:
        return message

    server.run()


async def plugin_list() -> list[str]:
    # PLUGIN_MODULE=temporalio.contrib.strands._temporal_mcp_client for the copy bundled in temporalio.
    plugin = importlib.import_module(os.environ.get("PLUGIN_MODULE", "temporalio.strands_agents._temporal_mcp_client"))
    list_tools = plugin.build_list_tools_activity("delayed", factory)
    try:
        return [info.name for info in await list_tools()]
    finally:
        await plugin._evict_connection("delayed")


def outcome(fn) -> str:
    start = time.monotonic()
    try:
        result = fn()
        return f"returned {result} after {time.monotonic() - start:.1f} s"
    except Exception as err:  # noqa: BLE001
        cause = type(err.__cause__).__name__ if err.__cause__ else None
        return f"raised {type(err).__name__} (cause {cause}) after {time.monotonic() - start:.1f} s: {err}"


def main() -> int:
    names = {d.metadata["Name"] for d in md.distributions()}
    print({p: md.version(p) for p in ("temporalio", "temporalio-strands-agents", "strands-agents", "mcp") if p in names})

    def native() -> list[str]:
        with factory() as client:
            return [t.tool_name for t in client.list_tools_sync()]

    native_result = outcome(native)
    plugin_result = outcome(lambda: asyncio.run(plugin_list()))
    print("native:", native_result)
    print("plugin:", plugin_result)
    fixed = plugin_result.startswith("raised MCPClientInitializationError")
    print("plugin applies startup_timeout" if fixed else "plugin ignores startup_timeout (defect)")
    return 0 if fixed else 1


if __name__ == "__main__":
    if len(sys.argv) > 1 and sys.argv[1] == "server":
        serve()
    else:
        sys.exit(main())

Output on 0.1.0 (exit 1; main gives the same):

{'temporalio': '1.34.0', 'temporalio-strands-agents': '0.1.0', 'strands-agents': '1.56.0', 'mcp': '1.30.0'}
native: raised MCPClientInitializationError (cause TimeoutError) after 6.9 s: background thread did not start in 1 seconds
plugin: returned ['echo'] after 5.7 s
plugin ignores startup_timeout (defect)
exit=1

Expected

The plugin raises MCPClientInitializationError once startup_timeout passes, as native
MCPClient does.

Proposed fix

In the connection owner, start a timer for the client's startup_timeout when it begins opening
the transport. If initialize() has not finished when it fires, fail the waiting callers with
MCPClientInitializationError (cause TimeoutError) and cancel the owner task, which closes the
transport. Callers wait on the shared handshake through asyncio.shield, so one cancelled
Activity, for example at Worker shutdown, cannot end the handshake for the others or turn off the
deadline. A record's idle eviction removes only that record, so a timer armed by a cancelled caller
before the deadline retired it cannot close the connection that replaced it. The {server}-list-tools Activity then fails and its retry policy applies; a
{server}-call-tool Activity returns the error as a tool error, as for other connection failures.

This is a breaking change: an initialization that took longer than startup_timeout (30 seconds
unless set) and completed before now fails. Such applications must raise startup_timeout or make
the server start faster.

A pull request with this change, tests in tests/test_mcp.py (a delayed echo server with a short
startup_timeout, with and without a cancelled caller, with a replacement busy when the cancelled
caller's idle timer fires, and at Worker shutdown) and a README note
follows.
The change runs only in Activities, so no Workflow history changes.

Activity

  1. campoy commented on Nov 2, 2026

    @campoy
    ContributorAuthor

    Resolved by #190 (merged as ddf63a8, not released yet). StrandsPlugin(mcp_clients=...) factories now return mcp.Client. A factory that returns Strands' MCPClient fails each activity with an error that says so, so its startup_timeout can no longer be silently ignored.

    mcp.Client has no startup deadline of its own, and the plugin now behaves like mcp.Client used directly. Against a server that answers initialize 3 s late, both list the tools after 3.4 s, even with read_timeout_seconds=1.

    The fix in #188 is closed, since #190 removed the code it changed.

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