- Notifications
You must be signed in to change notification settings - Fork1k
Open
Description
Initial Checks
- I confirm that I'm using the latest version of Pydantic AI
- I confirm that I searched for my issue inhttps://github.com/pydantic/pydantic-ai/issues before opening this issue
Description
ERROR Case:
When I have two MCPs to link to an agent and one of them fails during initialization with an error (404, 401), thefinally
of therun_mcp_servers
context manager executesexit_stack.aclose()
, which causes the anyio scope cancellation stack to corrupt due to not following LIFO order.
agents.py
@asynccontextmanagerasyncdefrun_mcp_servers(self,model:models.Model|models.KnownModelName|str|None=None)->AsyncIterator[None]:"""Run [`MCPServerStdio`s][pydantic_ai.mcp.MCPServerStdio] so they can be used by the agent.Returns: a context manager to start and shutdown the servers."""try:sampling_model:models.Model|None=self._get_model(model)exceptexceptions.UserError:# pragma: no coversampling_model=Noneexit_stack=AsyncExitStack()try:formcp_serverinself._mcp_servers:ifsampling_modelisnotNone:# pragma: no branchmcp_server.sampling_model=sampling_modelawaitexit_stack.enter_async_context(mcp_server)yieldfinally:awaitexit_stack.aclose()
This leads to abusy-wait loop
that consumes high CPU resources. To fix something like how it worked for me:
@asynccontextmanagerasyncdefrun_mcp_servers(self,model:models.Model|models.KnownModelName|str|None=None )->AsyncIterator[None]:"""Run [`MCPServerStdio`s][pydantic_ai.mcp.MCPServerStdio] so they can be used by the agent.Returns: a context manager to start and shutdown the servers."""try:sampling_model:models.Model|None=self._get_model(model)exceptexceptions.UserError:# pragma: no coversampling_model=Noneservers= []try:formcp_serverinself._mcp_servers:servers.append(mcp_server)ifsampling_modelisnotNone:# pragma: no branchmcp_server.sampling_model=sampling_modelawaitmcp_server.__aenter__()yieldfinally:forsinreversed(servers):awaits.__aexit__(None,None,None
Can you continue with the adjustment or help me correct it in another way?
Example Code
Python, Pydantic AI & LLM client version
pydantic_ai==0.3.4openai==1.93.0