Skip to content

Build and run agents you can see, understand and trust.

Add MCP using demo with structured output (#672)

Leo Yangece8114a054a
diff --git a/examples/agent_with_mcp/README.md b/examples/agent_with_mcp/README.md
new file mode 100644
index 000000000..bb8029064
--- /dev/null
+++ b/examples/agent_with_mcp/README.md
@@ -0,0 +1,61 @@
+# 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 file
diff --git a/examples/agent_with_mcp/main.py b/examples/agent_with_mcp/main.py
new file mode 100644
index 000000000..5ed1f499a
--- /dev/null
+++ b/examples/agent_with_mcp/main.py
@@ -0,0 +1,112 @@
+# -*- coding: utf-8 -*-
+"""
+Demo showcasing ReAct agent with MCP tools using different transports.
+
+This example demonstrates:
+- Registering MCP tools with different transports (sse and streamable_http)
+- Using a ReAct agent with registered MCP tools
+- Getting structured output from the agent
+
+Before running this demo, please execute:
+ python mcp_servers.py
+"""
+
+import asyncio
+import json
+import os
+
+from pydantic import BaseModel, Field
+
+from agentscope.agent import ReActAgent
+from agentscope.formatter import DashScopeChatFormatter
+from agentscope.mcp import HttpStatelessClient
+from agentscope.memory import InMemoryMemory
+from agentscope.message import Msg
+from agentscope.model import DashScopeChatModel
+from agentscope.tool import Toolkit
+
+
+class NumberResult(BaseModel):
+ """A simple number result model for structured output."""
+
+ 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 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)
+
+ print(
+ "Total number of MCP tools registered:",
+ len(toolkit.get_json_schemas()),
+ )
+
+
+async def run_calculation_agent() -> None:
+ """Run the calculation agent with a math problem."""
+ # Initialize the agent
+ agent = ReActAgent(
+ name="Jarvis",
+ sys_prompt="You're a helpful assistant named Jarvis.",
+ model=DashScopeChatModel(
+ 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
+ res = await agent(
+ Msg(
+ "user",
+ "Calculate 2345 multiplied by 3456, then add 4567 to the result,"
+ " what is the final outcome?",
+ "user",
+ ),
+ structured_model=NumberResult,
+ )
+
+ print(
+ "Structured Output:\n"
+ "```\n"
+ f"{json.dumps(res.metadata, indent=4)}\n"
+ "```",
+ )
+
+
+async def main() -> None:
+ """Main function to run the demo."""
+ # Register MCP tools
+ await register_mcp_tools()
+
+ # Run the calculation agent
+ await run_calculation_agent()
+
+
+if __name__ == "__main__":
+ # Run the main async function
+ asyncio.run(main())
diff --git a/examples/agent_with_mcp/mcp_servers.py b/examples/agent_with_mcp/mcp_servers.py
new file mode 100644
index 000000000..14de75275
--- /dev/null
+++ b/examples/agent_with_mcp/mcp_servers.py
@@ -0,0 +1,58 @@
+# -*- 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)