Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Multiples MCPs: AnyIO cancel scope stack corruption #2201

Open
Assignees
DouweM
Labels
bugSomething isn't working
@GustavoRonconi

Description

@GustavoRonconi

Initial Checks

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

Metadata

Metadata

Assignees

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


    [8]ページ先頭

    ©2009-2025 Movatter.jp