## mcp server code
async def add(a: int, b: int) -> list[types.TextContent]:
"""
Add two integers
"""
print("add", a, b)
return [types.TextContent(type="text", text=str(a + b))]
## mcp client code fastapi
### langgraph-->agent-->astream--> toolcall --> Error: ClosedResourceError()\n Please fix your mistakes.
@mcp_client_router.get("/mcp_client2")
async def mcp_client2():
"""
测试mcp客户端2
"""
print("mcp_client2")
async with MultiServerMCPClient(
{
# "math": {
# "command": "python",
# # Make sure to update to the full absolute path to your math_server.py file
# "args": ["/path/to/math_server.py"],
# "transport": "stdio",
# },
"math": {
# make sure you start your weather server on port 8000
"url": "http://127.0.0.1:8000/sse",
"transport": "sse",
}
}
) as client:
# 直接使用列表
tools = client.get_tools()
for tool in tools:
print(type(tool))
agent = create_react_agent(model, tools)
config = {"configurable": {"thread_id": "abc123"}} #指定 thread_id 的名称,针对性地管理 memory
# Implementation 1 success
# math_response = await agent.ainvoke({"messages": "1加5是多少?"})
# print("math_response: ", math_response)
# return math_response
# Implementation 2 Error: ClosedResourceError()\n Please fix your mistakes.
async def kb_center_agent_content():
async for event in agent.astream(
{"messages": "1加5是多少?"}, config, stream_mode="values"
):
for k, v in event.items():
print(k, v)
yield json.dumps(Resp.ok(v).dict(), ensure_ascii=False) + "\n"
return StreamingResponse(kb_center_agent_content(),media_type="text/event-stream")
encurrent the same error