Build and run agents you can see, understand and trust.
Python agentchatbotlarge-language-modelsllmllm-agentmcpmulti-agentmulti-modalreact-agentrealtime-agentvoice-agentvoice-assistant
[HOTFIX] Fix the bug and simplify the MCP example (#754)
DavdGao62a8f2b04b95
diff --git a/README.md b/README.mdindex 972699c5e..f852b50a6 100644--- a/README.md+++ b/README.md@@ -353,7 +353,7 @@ as_studio- [ACEBench](https://github.com/agentscope-ai/agentscope/tree/main/examples/evaluation/ace_bench)- Functional- [ReAct Agent](https://github.com/agentscope-ai/agentscope/tree/main/examples/react_agent)- - [MCP](https://github.com/agentscope-ai/agentscope/tree/main/examples/functionality/agent_with_mcp)+ - [MCP](https://github.com/agentscope-ai/agentscope/tree/main/examples/functionality/mcp)- [Structured Output](https://github.com/agentscope-ai/agentscope/tree/main/examples/functionality/structured_output)- [Long-Term Memory](https://github.com/agentscope-ai/agentscope/tree/main/examples/functionality/long_term_memory)- [Session with SQLite](https://github.com/agentscope-ai/agentscope/tree/main/examples/functionality/session_with_sqlite)diff --git a/README_zh.md b/README_zh.mdindex 3aca570a0..5ea5e1065 100644--- a/README_zh.md+++ b/README_zh.md@@ -355,7 +355,7 @@ as_studio- [ACEBench](https://github.com/agentscope-ai/agentscope/tree/main/examples/evaluation/ace_bench)- 功能演示- [ReAct Agent](https://github.com/agentscope-ai/agentscope/tree/main/examples/react_agent)- - [MCP](https://github.com/agentscope-ai/agentscope/tree/main/examples/functionality/agent_with_mcp)+ - [MCP](https://github.com/agentscope-ai/agentscope/tree/main/examples/functionality/mcp)- [结构化输出](https://github.com/agentscope-ai/agentscope/tree/main/examples/functionality/structured_output)- [长期记忆](https://github.com/agentscope-ai/agentscope/tree/main/examples/functionality/long_term_memory)- [基于DB的会话管理](https://github.com/agentscope-ai/agentscope/tree/main/examples/functionality/session_with_sqlite)diff --git a/examples/functionality/agent_with_mcp/README.md b/examples/functionality/agent_with_mcp/README.mddeleted file mode 100644index bb8029064..000000000--- a/examples/functionality/agent_with_mcp/README.md+++ /dev/null@@ -1,61 +0,0 @@-# Agent with MCP Tools Example--This example demonstrates how to use AgentScope's ReAct agent with Model Context Protocol (MCP) tools using different transports. It showcases:--- Registering MCP tools with different transports (SSE and Streamable HTTP)-- Using a ReAct agent with registered MCP tools-- Getting structured output from the agent--## Prerequisites--- Python 3.10 or higher-- DashScope API key from Alibaba Cloud--## Installation--### Install AgentScope--```bash-# Install from source-cd {PATH_TO_AGENTSCOPE}-pip install -e .-```--## Setup--### 1. Environment Configuration--Set up your DashScope API key:--```bash-export DASHSCOPE_API_KEY="your_dashscope_api_key_here"-```--You can obtain a DashScope API key from [Alibaba Cloud DashScope Console](https://dashscope.console.aliyun.com/).--### 2. Start MCP Servers--Before running the agent, you need to start the MCP servers that provide the tools:--```bash-cd examples/agent_with_mcp-python mcp_servers.py-```--This will start a server on `http://127.0.0.1:8001` with two MCP tools:-- An addition tool available via SSE transport at `/sse_app/sse`-- A multiplication tool available via Streamable HTTP transport at `/streamable_http_app/mcp/`--## Usage--After starting the MCP servers, you can run the agent example:--```bash-cd examples/agent_with_mcp-python main.py-```--The agent will:-1. Register the MCP tools from the servers-2. Use a ReAct agent to solve a calculation problem (multiplying two numbers and then adding another number)-3. Return structured output with the final result\ No newline at end of filediff --git a/examples/functionality/agent_with_mcp/mcp_servers.py b/examples/functionality/agent_with_mcp/mcp_servers.pydeleted file mode 100644index 14de75275..000000000--- a/examples/functionality/agent_with_mcp/mcp_servers.py+++ /dev/null@@ -1,58 +0,0 @@-# -*- coding: utf-8 -*---"""This module contains the server setup for FastMCP applications."""--from contextlib import asynccontextmanager, AsyncExitStack-from typing import AsyncGenerator, Any--import uvicorn-from mcp.server.fastmcp import FastMCP-from starlette.applications import Starlette-from starlette.routing import Mount-from starlette.types import Lifespan--# Define the addition tool-mcp_add = FastMCP("Add")---@mcp_add.tool()-def add(a: int, b: int) -> int:- """Add two numbers."""- return a + b---# Define the multiplication tool-mcp_multiply = FastMCP("Multiply")---@mcp_multiply.tool()-def multiply(a: int, b: int) -> int:- """Multiply two numbers."""- return a * b---def combine_lifespans(*lifespans: Any) -> Lifespan[Any]:- """Combine multiple lifespans into one asynchronous context manager."""-- @asynccontextmanager- async def combined_lifespan(app: Any) -> AsyncGenerator[None, Any]:- async with AsyncExitStack() as stack:- for lifespan in lifespans:- ctx = lifespan(app)- await stack.enter_async_context(ctx)- yield-- return combined_lifespan---# Create the main application-main_app = Starlette(- routes=[- Mount("/sse_app/", app=mcp_add.sse_app()),- Mount("/streamable_http_app/", app=mcp_multiply.streamable_http_app()),- ],- lifespan=combine_lifespans(lambda app: mcp_multiply.session_manager.run()),-)--if __name__ == "__main__":- uvicorn.run(main_app, host="0.0.0.0", port=8001)diff --git a/examples/functionality/mcp/README.md b/examples/functionality/mcp/README.mdnew file mode 100644index 000000000..33f9eb02e--- /dev/null+++ b/examples/functionality/mcp/README.md@@ -0,0 +1,59 @@+# MCP in AgentScope++This example demonstrates how to++- create MCP client with different transports (SSE and Streamable HTTP) and type (Stateless and Stateful),+- register MCP tool functions and use them in a ReAct agent, and+- get MCP tool function as a local callable object from the MCP client.+++## Prerequisites++- Python 3.10 or higher+- DashScope API key from Alibaba Cloud++## Installation++### Install AgentScope++```bash+# Install from source+cd {PATH_TO_AGENTSCOPE}+pip install -e .+```++## QuickStart++Install agentscope and ensure you have a valid DashScope API key in your environment variables.++> Note: The example is built with DashScope chat model. If you want to change the model in this example, don't forget+> to change the formatter at the same time! The corresponding relationship between built-in models and formatters are+> list in [our tutorial](https://doc.agentscope.io/tutorial/task_prompt.html#id1)++```bash+pip install agentscope+```++Start the MCP servers by the following commands in two separate terminals:++```bash+# In one terminal, run:+python mcp_add.py++# In another terminal, run:+python mcp_multiply.py+```++Two MCP servers will be started on `http://127.0.0.1:8001` (SSE server) and `http://127.0.0.1:8002` (streamable+HTTP server).++After starting the MCP servers, you can run the agent example:++```bash+python main.py+```++The agent will:+1. Register the MCP tools from the servers+2. Use a ReAct agent to solve a calculation problem (multiplying two numbers and then adding another number)+3. Return structured output with the final resultdiff --git a/examples/functionality/agent_with_mcp/main.py b/examples/functionality/mcp/main.pysimilarity index 50%rename from examples/functionality/agent_with_mcp/main.pyrename to examples/functionality/mcp/main.pyindex 5ed1f499a..5516c1ecc 100644--- a/examples/functionality/agent_with_mcp/main.py+++ b/examples/functionality/mcp/main.py@@ -19,8 +19,7 @@ from pydantic import BaseModel, Fieldfrom agentscope.agent import ReActAgentfrom agentscope.formatter import DashScopeChatFormatter-from agentscope.mcp import HttpStatelessClient-from agentscope.memory import InMemoryMemory+from agentscope.mcp import HttpStatelessClient, HttpStatefulClientfrom agentscope.message import Msgfrom agentscope.model import DashScopeChatModelfrom agentscope.tool import Toolkit@@ -32,39 +31,34 @@ class NumberResult(BaseModel):result: int = Field(description="The result of the calculation")-# Initialize MCP clients-add_tool_stateless_client = HttpStatelessClient(- # The name to identify the MCP- name="add_tool",- transport="sse",- url="http://127.0.0.1:8001/sse_app/sse",-)--multiply_tool_stateless_client = HttpStatelessClient(- # The name to identify the MCP- name="multiply_tool",- transport="streamable_http",- url="http://127.0.0.1:8001/streamable_http_app/mcp/",-)--# Initialize toolkit-toolkit = Toolkit()+async def main() -> None:+ """The main entry of the MCP example."""+ toolkit = Toolkit()-async def register_mcp_tools() -> None:- """Register all MCP tools from the clients."""- # Register all tools from the MCP servers- await toolkit.register_mcp_client(add_tool_stateless_client)- await toolkit.register_mcp_client(multiply_tool_stateless_client)+ # Create a stateful MCP client to connect to the SSE MCP server+ # note you can also use the stateless client+ add_mcp_client = HttpStatefulClient(+ name="add_mcp",+ transport="sse",+ url="http://127.0.0.1:8001/sse",+ )- print(- "Total number of MCP tools registered:",- len(toolkit.get_json_schemas()),+ # Create a stateless MCP client to connect to the StreamableHTTP MCP server+ # note you can also use the stateful client+ multiply_mcp_client = HttpStatelessClient(+ name="multiply_mcp",+ transport="streamable_http",+ url="http://127.0.0.1:8002/mcp",)+ # The stateful client must be connected before using+ await add_mcp_client.connect()++ # Register the MCP clients to the toolkit+ await toolkit.register_mcp_client(add_mcp_client)+ await toolkit.register_mcp_client(multiply_mcp_client)-async def run_calculation_agent() -> None:- """Run the calculation agent with a math problem."""# Initialize the agentagent = ReActAgent(name="Jarvis",@@ -73,10 +67,8 @@ async def run_calculation_agent() -> None:model_name="qwen-max",api_key=os.environ["DASHSCOPE_API_KEY"],),- memory=InMemoryMemory(),formatter=DashScopeChatFormatter(),toolkit=toolkit,- parallel_tool_calls=True,)# Run the agent with a calculation task@@ -93,20 +85,26 @@ async def run_calculation_agent() -> None:print("Structured Output:\n""```\n"- f"{json.dumps(res.metadata, indent=4)}\n"+ f"{json.dumps(res.metadata, indent=4, ensure_ascii=False)}\n""```",)+ # AgentScope also allows developers to obtain the MCP tool as a local+ # callable object, and use it directly.+ add_tool_function = await add_mcp_client.get_callable_function(+ "add",+ # If wrap the MCP tool result into the ToolResponse object in+ # AgentScope+ wrap_tool_result=True,+ )-async def main() -> None:- """Main function to run the demo."""- # Register MCP tools- await register_mcp_tools()+ # Call it manually+ manual_res = await add_tool_function(a=5, b=10)+ print("When manually calling the MCP tool function:")+ print(manual_res)- # Run the calculation agent- await run_calculation_agent()+ # The stateful client should be disconnected manually!+ await add_mcp_client.close()-if __name__ == "__main__":- # Run the main async function- asyncio.run(main())+asyncio.run(main())diff --git a/examples/functionality/mcp/mcp_add.py b/examples/functionality/mcp/mcp_add.pynew file mode 100644index 000000000..8fcc71c15--- /dev/null+++ b/examples/functionality/mcp/mcp_add.py@@ -0,0 +1,16 @@+# -*- coding: utf-8 -*-+"""An SSE MCP server with a simple add tool function."""++from mcp.server import FastMCP+++mcp = FastMCP("Add", port=8001)+++def add(a: int, b: int) -> int:+ """Add two numbers."""+ return a + b+++mcp.run(transport="sse")diff --git a/examples/functionality/mcp/mcp_multiply.py b/examples/functionality/mcp/mcp_multiply.pynew file mode 100644index 000000000..776f5db19--- /dev/null+++ b/examples/functionality/mcp/mcp_multiply.py@@ -0,0 +1,16 @@+# -*- coding: utf-8 -*-+"""An SSE MCP server with a simple multiply tool function."""++from mcp.server import FastMCP+++mcp = FastMCP("Multiply", port=8002)+++def multiply(c: int, d: int) -> int:+ """Multiply two numbers."""+ return c * d+++mcp.run(transport="streamable-http")