-
Notifications
You must be signed in to change notification settings - Fork 285
test simple middleware / no statefulness changes #317
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
Draft
eyurtsev
wants to merge
2
commits into
main
Choose a base branch
from
eugene/mcp_middleware_no_statefulness
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Draft
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,47 @@ | ||
"""Agent middleware for LangChain.""" | ||
|
||
import asyncio | ||
from concurrent.futures import ThreadPoolExecutor | ||
from typing import TYPE_CHECKING | ||
|
||
from langchain.agents.middleware import AgentMiddleware | ||
|
||
from langchain_mcp_adapters.client import MultiServerMCPClient | ||
from langchain_mcp_adapters.sessions import ( | ||
StreamableHttpConnection, | ||
) | ||
from langchain_core.tools import BaseTool | ||
|
||
|
||
def _sync_await(coro): | ||
"""Run an async coroutine from sync code, even if a loop is already running.""" | ||
try: | ||
asyncio.get_running_loop() | ||
except RuntimeError: | ||
# No running loop in this thread: just run it. | ||
return asyncio.run(coro) | ||
with ThreadPoolExecutor(max_workers=1) as ex: | ||
return ex.submit(lambda: asyncio.run(coro)).result() | ||
|
||
|
||
class MCPMiddleware(AgentMiddleware): | ||
"""MCP Middleware to register tools for use in an agent.""" | ||
|
||
def __init__(self, connections: dict[str, StreamableHttpConnection]) -> None: | ||
"""Initialize the middleware.""" | ||
self.server_to_connection = connections | ||
for connection in connections.values(): | ||
assert connection["transport"] == "streamable_http" | ||
# Check how it looks if we only support stateless connections | ||
# assert connection["is_stateful"] == False | ||
self._client = MultiServerMCPClient(connections) | ||
self._tools = None | ||
|
||
# Do we want to make tools a property? Or support an async method? | ||
@property | ||
def tools(self) -> list[BaseTool]: | ||
"""No additional tools""" | ||
if self._tools is not None: | ||
return self._tools | ||
self._tools = _sync_await(self._client.get_tools()) | ||
return self._tools |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Life cycle management is bad
Would want to be able to do some async initialization to get a list of tools from the server.
tools
into a property