Skip to content

Commit 2ffb75f

Browse files
committed
Add an example of MCP
1 parent 4c62ce3 commit 2ffb75f

File tree

3 files changed

+77
-0
lines changed

3 files changed

+77
-0
lines changed

examples/mcp/README.md

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
# Model Context Protocol
2+
3+
This example demonstrates how to implement an agent that can use tools provided by MCP ([Model Context Protocol][1]) servers.
4+
5+
6+
## Prerequisites
7+
8+
- Install `coagent` (see [Installation](../../README.md#installation)).
9+
- Start a NATS server (see [Distributed](../../README.md#distributed)).
10+
11+
12+
## Quick Start
13+
14+
First start the MCP server in one terminal:
15+
16+
```bash
17+
python examples/mcp/server.py
18+
```
19+
20+
Then start the MCP agent in another terminal:
21+
22+
```bash
23+
export AZURE_MODEL=csg-gpt4
24+
export AZURE_API_BASE=https://opencsg-us.openai.azure.com
25+
export AZURE_API_VERSION=2024-02-15-preview
26+
export AZURE_API_KEY=<YOUR API KEY>
27+
28+
python examples/mcp/agent.py
29+
```
30+
31+
Finally, communicate with the agent using the `coagent` CLI:
32+
33+
```bash
34+
coagent mcp -H type:ChatMessage -F .content.content -d '{"role":"user","content":"What is the weather like in Beijing"}'
35+
```
36+
37+
38+
[1]: https://modelcontextprotocol.io/

examples/mcp/agent.py

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
import asyncio
2+
3+
from coagent.agents import MCPAgent
4+
from coagent.core import AgentSpec, idle_loop, new, set_stderr_logger
5+
from coagent.runtimes import NATSRuntime
6+
7+
8+
mcp = AgentSpec(
9+
"mcp",
10+
new(
11+
MCPAgent,
12+
system="""You are an agent who can use tools.""",
13+
mcp_server_base_url="http://localhost:8080",
14+
),
15+
)
16+
17+
18+
async def main():
19+
async with NATSRuntime.from_servers() as runtime:
20+
await runtime.register(mcp)
21+
await idle_loop()
22+
23+
24+
if __name__ == "__main__":
25+
set_stderr_logger("TRACE")
26+
asyncio.run(main())

examples/mcp/server.py

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
from mcp.server.fastmcp import FastMCP
2+
3+
mcp = FastMCP("Weather", port=8080)
4+
5+
6+
@mcp.tool()
7+
def query_weather(city: str) -> str:
8+
"""Query the weather in the given city."""
9+
return f"The weather in {city} is sunny."
10+
11+
12+
if __name__ == "__main__":
13+
mcp.run(transport="sse")

0 commit comments

Comments
 (0)