Skip to content

Commit 1ddaae9

Browse files
authored
add mcp_sse example (#416)
2 parents 9b64be7 + 1432ee9 commit 1ddaae9

File tree

4 files changed

+134
-2
lines changed

4 files changed

+134
-2
lines changed

README.md

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -475,7 +475,9 @@ npm install -g @executeautomation/playwright-mcp-server
475475
npx playwright install-deps
476476
```
477477

478-
Try our comprehensive MCP example in `examples/run_mcp.py` to see these capabilities in action!
478+
Try our comprehensive MCP examples:
479+
- `examples/run_mcp.py` - Basic MCP functionality demonstration (local call, requires dependencies)
480+
- `examples/run_mcp_sse.py` - Example using the SSE protocol (Use remote services, no dependencies)
479481

480482
## Available Toolkits
481483

README_zh.md

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -458,7 +458,9 @@ npm install -g @executeautomation/playwright-mcp-server
458458
npx playwright install-deps
459459
```
460460

461-
查看我们的综合示例 `examples/run_mcp.py` 来体验这些功能!
461+
查看我们的MCP示例:
462+
- `examples/run_mcp.py` - 基础MCP功能演示 (本地调用,需要安装依赖)
463+
- `examples/run_mcp_sse.py` - 使用SSE协议的示例 (使用远程服务,无需安装依赖)
462464

463465
## 可用工具包
464466

examples/mcp_sse_config.json

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
{
2+
"mcpServers": {
3+
"@modelcontextprotocol/fetch": {
4+
"url": "https://router.mcp.so/sse/zr9l18m8pudpzg"
5+
}
6+
}
7+
}

examples/run_mcp_sse.py

Lines changed: 121 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,121 @@
1+
# ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========
2+
# Licensed under the Apache License, Version 2.0 (the "License");
3+
# you may not use this file except in compliance with the License.
4+
# You may obtain a copy of the License at
5+
#
6+
# http://www.apache.org/licenses/LICENSE-2.0
7+
#
8+
# Unless required by applicable law or agreed to in writing, software
9+
# distributed under the License is distributed on an "AS IS" BASIS,
10+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11+
# See the License for the specific language governing permissions and
12+
# limitations under the License.
13+
# ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========
14+
import asyncio
15+
import sys
16+
from pathlib import Path
17+
from typing import List
18+
19+
from dotenv import load_dotenv
20+
21+
from camel.models import ModelFactory
22+
from camel.toolkits import FunctionTool
23+
from camel.types import ModelPlatformType, ModelType
24+
from camel.logger import set_log_level
25+
from camel.toolkits import MCPToolkit
26+
27+
from owl.utils.enhanced_role_playing import OwlRolePlaying, arun_society
28+
29+
import pathlib
30+
31+
base_dir = pathlib.Path(__file__).parent.parent
32+
env_path = base_dir / "owl" / ".env"
33+
load_dotenv(dotenv_path=str(env_path))
34+
35+
set_log_level(level="DEBUG")
36+
37+
38+
async def construct_society(
39+
question: str,
40+
tools: List[FunctionTool],
41+
) -> OwlRolePlaying:
42+
r"""Build a multi-agent OwlRolePlaying instance for GitHub information retrieval.
43+
44+
Args:
45+
question (str): The GitHub-related question to ask.
46+
tools (List[FunctionTool]): The MCP tools to use for GitHub interaction.
47+
"""
48+
models = {
49+
"user": ModelFactory.create(
50+
model_platform=ModelPlatformType.OPENAI,
51+
model_type=ModelType.GPT_4O,
52+
model_config_dict={"temperature": 0},
53+
),
54+
"assistant": ModelFactory.create(
55+
model_platform=ModelPlatformType.OPENAI,
56+
model_type=ModelType.GPT_4O,
57+
model_config_dict={"temperature": 0},
58+
),
59+
}
60+
61+
user_agent_kwargs = {"model": models["user"]}
62+
assistant_agent_kwargs = {
63+
"model": models["assistant"],
64+
"tools": tools,
65+
}
66+
67+
task_kwargs = {
68+
"task_prompt": question,
69+
"with_task_specify": False,
70+
}
71+
72+
society = OwlRolePlaying(
73+
**task_kwargs,
74+
user_role_name="user",
75+
user_agent_kwargs=user_agent_kwargs,
76+
assistant_role_name="assistant",
77+
assistant_agent_kwargs=assistant_agent_kwargs,
78+
)
79+
return society
80+
81+
82+
async def main():
83+
# Load SSE server configuration
84+
config_path = Path(__file__).parent / "mcp_sse_config.json"
85+
mcp_toolkit = MCPToolkit(config_path=str(config_path))
86+
87+
try:
88+
# Connect to MCP server
89+
await mcp_toolkit.connect()
90+
print("Successfully connected to SSE server")
91+
92+
# Get available tools
93+
tools = [*mcp_toolkit.get_tools()]
94+
95+
# Set default task - a simple example query
96+
default_task = (
97+
"What are the most recent pull requests in camel-ai/camel repository?"
98+
)
99+
100+
# Use command line argument if provided, otherwise use default task
101+
task = sys.argv[1] if len(sys.argv) > 1 else default_task
102+
103+
# Build and run society
104+
society = await construct_society(task, tools)
105+
answer, chat_history, token_count = await arun_society(society)
106+
print(f"\nResult: {answer}")
107+
108+
except KeyboardInterrupt:
109+
print("\nReceived exit signal, shutting down...")
110+
except Exception as e:
111+
print(f"Error occurred: {e}")
112+
finally:
113+
# Ensure safe disconnection
114+
try:
115+
await mcp_toolkit.disconnect()
116+
except Exception as e:
117+
print(f"Error during disconnect: {e}")
118+
119+
120+
if __name__ == "__main__":
121+
asyncio.run(main())

0 commit comments

Comments
 (0)