-
Notifications
You must be signed in to change notification settings - Fork 2.7k
Description
Please read this first
- Have you read the docs?Agents SDK docs
- Have you searched for related issues? Others may have had similar requests
Question
As mentioned in the docs and #446, the non-hosted MCP server (Streamable HTTP / SSE / stdio) needs either async with
to start connection, or manually connect with server.connect()
and server.cleanup()
.
This requires BOTH agent declaration AND Runner.run
to be wrapped inside async with
or connect() & cleanup()
.
from pathlib import Path
from agents import Agent, Runner
from agents.mcp import MCPServerStdio
current_dir = Path(__file__).parent
samples_dir = current_dir / "sample_files"
async with MCPServerStdio(
name="Filesystem Server via npx",
params={
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-filesystem", str(samples_dir)],
},
) as server:
agent = Agent(
name="Assistant",
instructions="Use the files in the sample directory to answer questions.",
mcp_servers=[server],
)
result = await Runner.run(agent, "List the files available to you.")
print(result.final_output)
However, this connection method is not ideal for a multi-agent workflow.
server = MCPServerStdio(...)
agent_fs = Agent(
name="File System Agent",
instructions="Use the files in the sample directory to answer questions.",
mcp_servers=[server],
)
agent_echo = Agent(
name="Echo Agent",
instructions="Just repeat what the user says",
)
orchestrator = Agent(
name="Orchestrator Agent",
instructions=(
"If the user asks for any repository question, then use file system agent to answer."
"Otherwise, forward to echo agent."
),
handoffs=[agent_echo, agent_fs],
)
asyncio.run(Runner.run(orchestrator))
It is fine with a simple multi-agent, because we can simply wrap the whole code with async with server:
.
But what about in a complicated workflow? What if each agent is defined in a single .py
file and imported in an orchestrator file? What if there are multiple MCP servers assigned to multiple agents, which is not a good option to connect to all the MCP servers at the very beginning of the workflow?
It is hard to write a simple structure to achieve the MCP server connection. I wonder if there's any good roundabout to solve this issue. I thought about using on_handoff
, but this cannot close the connection.