Skip to content

add session-persistent tools context manager #211

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 38 additions & 1 deletion langchain_mcp_adapters/client.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import asyncio
from contextlib import asynccontextmanager
from contextlib import asynccontextmanager, AsyncExitStack
from types import TracebackType
from typing import Any, AsyncIterator

Expand Down Expand Up @@ -78,6 +78,14 @@ def __init__(
async with client.session("math") as session:
tools = await load_mcp_tools(session)
```

Example: get all tools from all servers while keep session
```python
client = MultiServerMCPClient({...})
async with client.tools() as all_tools:
# use all tools here
# sessions are kept alive until exiting the context
```
"""
self.connections: dict[str, Connection] = connections if connections is not None else {}

Expand Down Expand Up @@ -110,6 +118,35 @@ async def session(
await session.initialize()
yield session

@asynccontextmanager
async def tools(self, *, server_name: str | None = None) -> AsyncIterator[list[BaseTool]]:
"""Get tools from MCP server(s) while keeping the session(s) alive.

Args:
server_name: Optional name of the server to get tools from.
If None, tools from all servers will be returned (default).

Yields:
A list of LangChain tools
"""
async with AsyncExitStack() as stack:
all_tools: list[BaseTool] = []
if server_name is not None:
if server_name not in self.connections:
raise ValueError(
f"Couldn't find a server with name '{server_name}', expected one of '{list(self.connections.keys())}'"
)
session = await stack.enter_async_context(self.session(server_name))
tools = await load_mcp_tools(session)
all_tools.extend(tools)
else:
for name in self.connections:
session = await stack.enter_async_context(self.session(name))
tools = await load_mcp_tools(session)
all_tools.extend(tools)

yield all_tools

async def get_tools(self, *, server_name: str | None = None) -> list[BaseTool]:
"""Get a list of all tools from all connected servers.

Expand Down