Skip to content

[FEATURE] Improved MCP DX to prevent common context manager scoping issue #198

@dbschmigelski

Description

@dbschmigelski

Problem Statement

Currently, many users are encountering a common issue with MCP, where the user needs to manage the lifecycle of the connection using a context manager.

The intended syntax is the following

with mcp_client:
   agent = Agent(tools=mcp_client.list_tools_sync())
   agent("do something")

However, in both #96 and #184 we have seen customers encounter MCPClientInitializationError because they do something like the following which fails because the mcp connection is closed when we exit the with statement

with mcp_client:
   agent = Agent(tools=mcp_client.list_tools_sync())
agent("do something")

We have enhanced error messaging #175 and documentation strands-agents/docs#81, but customers will still likely encounter this creating a poor initial experience.

Proposed Solution

I would like to be able to provide an MCP Transport implementation to an Agent class, where the lifecycle of the MCP connection is managed by the Agent, not the user.

From the customer's perspective, this would look something like

agent = Agent(tools=[mcp_client])

or

agent=Agent(mcp_clients=[mcp_client])

The mechanism by which the connections are closed is TBD. We should consider things like atexit and and weakref

Use Case

Customers would use this to be abel to offload the initialization of the mcp server to the agent class. This would obscure the initialization of the client however, for example

mcp_client = ...
agent = Agent(tools=[mcp_client]) # initializes client
mcp_client.get_prompt() # relies on initialization within the Agent class

Alternatives Solutions

No response

Additional Context

No response

Metadata

Metadata

Assignees

Labels

enhancementNew feature or request

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions