Вся онлайн-документация, которую я нашел, предполагает использование асинхронных функций для подключения к таким серверам. Пример на странице github для langchain-mcp-adapters предлагает следующую структуру:
Код: Выделить всё
from mcp import ClientSession
from mcp.client.streamable_http import streamablehttp_client
from langgraph.prebuilt import create_react_agent
from langchain_mcp_adapters.tools import load_mcp_tools
async with streamablehttp_client("http://localhost:3000/mcp") as (read, write, _):
async with ClientSession(read, write) as session:
# Initialize the connection
await session.initialize()
# Get tools
tools = await load_mcp_tools(session)
agent = create_react_agent("openai:gpt-4.1", tools)
math_response = await agent.ainvoke({"messages": "what's (3 + 5) x 12?"})
Код: Выделить всё
# agent definition file
class MyAgent:
def __init__(self):
self.mcp_client = # open an http connection to the server
tools = self.mcp_client.get_tools()
self.agent = create_react_agent(model=...,tools=tools)
def run(query:str) -> AIMessage:
# ... invoke self.agent with the given query
# NOTE: self.mcp_client still connected -> tools are still available here
#---
# main file
agent = MyAgent()
print(agent.run("what is 100 plus 120?")) # this will cause the agent to call the math tool
Подробнее здесь: https://stackoverflow.com/questions/798 ... ous-manner
Мобильная версия