Skip to content

[BUG] MCP Instrumentation Wrapper Not Idempotent - Hits Python Recursion Limit #869

@mbutler-aws

Description

@mbutler-aws

Checks

  • I have updated to the lastest minor and patch version of Strands
  • I have checked the documentation and this is not expected behavior
  • I have searched ./issues and there are no duplicates of my issue

Strands Version

1.8.0

Python Version

3.11

Operating System

Windows (development), Linux (deployed)

Installation Method

pip

Steps to Reproduce

The mcp_instrumentation() function in strands/tools/mcp/mcp_instrumentation.py is non-idempotent, causing wrapper accumulation on BaseSession.send_request that eventually leads to RecursionError in production environments.

Environment

  • Strands version: 1.8.0
  • Python version: 3.11
  • Use case: WebSocket server creating MCPClient per connection

Steps to Reproduce

from strands.tools.mcp import MCPClient
from mcp.client.streamable_http import streamablehttp_client

# Create ~1000 MCPClient instances
for i in range(1000):
    client = MCPClient(lambda: streamablehttp_client("http://localhost:8080/mcp"))
    client.start()
    # Each instantiation adds another wrapper layer

Expected Behavior

Telemetry instrumentation should be applied once per process, not per client instance.

Actual Behavior

mcp_instrumentation() unconditionally wraps BaseSession.send_request without checking if already wrapped, causing wrapper accumulation.

Observed Behavior

  • Each MCPClient instantiation calls mcp_instrumentation() in __init__
  • Each call adds a new wrap_function_wrapper() layer to BaseSession.send_request
  • After a certain number of client creations, Python hits recursion limit
  • Results in RecursionError and "client session is not running" errors

Additional Context

No response

Possible Solution

Make mcp_instrumentation() idempotent by:

  1. Tracking if patches have been applied via module-level flag
  2. Only applying instrumentation on first call
  3. Skipping subsequent calls

Related Issues

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions