任意の数のコンテキストマネージャを作る
contextlib.ExitStack / contextlib.AsyncExitStack を使う
code:before.py
with foo() as a:
with bar() as b:
with baz() as c:
...
code:after.py
with ExitStack() as stack:
contexts = [stack.enter_context(f()) for f in foo, bar, baz
...
実際は AsyncExitStack のほうが使う機会があるかな?
async with ... で await enter_async_context(...) する
https://github.com/langchain-ai/langchain-mcp-adapters/issues/189#issuecomment-2968916317
code:langgraph.py
async def make_graph():
async with AsyncExitStack() as st:
sessions = [
await st.enter_async_context(mcp_client.session(server))
for server in server_names
]
tools = sum(await asyncio.gather(*map(load_mcp_tools, sessions)), [])
yield create_react_agent(model=model, tools=tools)
#Python