Skip to content

Commit 4241a87

Browse files
committed
Add a new MCP example
1 parent a32d83a commit 4241a87

File tree

6 files changed

+179
-1
lines changed

6 files changed

+179
-1
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -444,6 +444,7 @@ triage = AgentSpec(
444444

445445
- [patterns](examples/patterns)
446446
- [mcp](examples/mcp)
447+
- [mcp-new](examples/mcp-new)
447448
- [structured-outputs](examples/structured-outputs)
448449
- [deepseek-r1](examples/deepseek-r1)
449450
- [translator](examples/translator)

examples/mcp-new/README.md

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
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+
Set the environment variables for your model:
15+
16+
```bash
17+
export MODEL_ID="your-model-id"
18+
export MODEL_BASE_URL="your-base-url"
19+
export MODEL_API_KEY="your-api-key"
20+
```
21+
22+
### Run the local agent
23+
24+
Run the agent as a script:
25+
26+
```bash
27+
python examples/mcp-new/local_agent.py
28+
```
29+
30+
### Run the daemon agent
31+
32+
First start the MCP server using SSE in one terminal:
33+
34+
```bash
35+
python examples/mcp-new/server.py -t sse
36+
```
37+
38+
Then run the agent as a daemon in another terminal:
39+
40+
```bash
41+
python examples/mcp-new/daemon_agent.py
42+
```
43+
44+
Next, connect to the MCP server in the third terminal:
45+
46+
```bash
47+
coagent mcp_server:server1 -H type:Connect -d '{"transport": "sse", "params": {"url": "http://localhost:8080/sse"}}'
48+
```
49+
50+
Finally, communicate with the MCP agent using the `coagent` CLI:
51+
52+
```bash
53+
coagent mcp -H type:ChatMessage --chat -d '{"role": "user", "content": "What is the weather like in Beijing"}'
54+
```
55+
56+
57+
[1]: https://modelcontextprotocol.io/

examples/mcp-new/daemon_agent.py

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
import asyncio
2+
3+
from coagent.agents import ChatAgent
4+
from coagent.agents.mcp_server import MCPServer
5+
from coagent.core import AgentSpec, idle_loop, new, set_stderr_logger
6+
from coagent.runtimes import NATSRuntime
7+
8+
9+
server = AgentSpec("mcp_server", new(MCPServer))
10+
11+
agent = AgentSpec(
12+
"mcp",
13+
new(
14+
ChatAgent,
15+
mcp_servers=["server1"],
16+
system="You are a helpful Weather Reporter",
17+
),
18+
)
19+
20+
21+
async def main():
22+
async with NATSRuntime.from_servers() as runtime:
23+
await runtime.register(server)
24+
await runtime.register(agent)
25+
await idle_loop()
26+
27+
28+
if __name__ == "__main__":
29+
set_stderr_logger("TRACE")
30+
asyncio.run(main())

examples/mcp-new/local_agent.py

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
import asyncio
2+
3+
from coagent.agents import ChatAgent, ChatMessage
4+
from coagent.agents.mcp_server import MCPServer, MCPServerStdioParams, Connect, Close
5+
from coagent.core import AgentSpec, new, set_stderr_logger, logger
6+
from coagent.runtimes import LocalRuntime
7+
8+
9+
server = AgentSpec("mcp_server", new(MCPServer))
10+
11+
agent = AgentSpec(
12+
"mcp",
13+
new(
14+
ChatAgent,
15+
mcp_servers=["server1"],
16+
system="You are a helpful Weather Reporter",
17+
),
18+
)
19+
20+
21+
async def main():
22+
async with LocalRuntime() as runtime:
23+
await runtime.register(server)
24+
await runtime.register(agent)
25+
26+
logger.info("Connecting to the server")
27+
await server.run(
28+
Connect(
29+
transport="stdio",
30+
params=MCPServerStdioParams(
31+
command="python",
32+
args=["examples/mcp-new/server.py"],
33+
),
34+
).encode(),
35+
session_id="server1",
36+
)
37+
38+
logger.info("Chatting with the agent")
39+
result = await agent.run(
40+
ChatMessage(
41+
role="user",
42+
content="What is the weather like in Beijing",
43+
).encode(),
44+
stream=True,
45+
)
46+
async for chunk in result:
47+
msg = ChatMessage.decode(chunk)
48+
print(msg.content, end="", flush=True)
49+
50+
logger.info("Close the server")
51+
await server.run(
52+
Close().encode(),
53+
session_id="server1",
54+
request=False,
55+
)
56+
57+
58+
if __name__ == "__main__":
59+
set_stderr_logger()
60+
asyncio.run(main())

examples/mcp-new/server.py

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
import argparse
2+
from mcp.server.fastmcp import FastMCP
3+
4+
mcp = FastMCP("Weather", port=8080)
5+
6+
7+
@mcp.prompt()
8+
def system_prompt(role: str) -> str:
9+
"""Create a system prompt."""
10+
return f"You are a helpful {role}."
11+
12+
13+
@mcp.tool()
14+
def query_weather(city: str) -> str:
15+
"""Query the weather in the given city."""
16+
return f"The weather in {city} is sunny."
17+
18+
19+
if __name__ == "__main__":
20+
parser = argparse.ArgumentParser()
21+
parser.add_argument(
22+
"-t",
23+
"--transport",
24+
default="stdio",
25+
choices=["stdio", "sse"],
26+
help="Transport protocol to use",
27+
)
28+
args = parser.parse_args()
29+
30+
mcp.run(transport=args.transport)

examples/notification/README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@ Then create a subscription via a proxy agent in another terminal:
2525
coagent proxy -H type:Subscribe --stream --filter .content -d '{"user_id": "1"}'
2626
```
2727

28-
Finally, send a notification to the center agent in a third terminal, and then observe the output in the second terminal:
28+
Finally, send a notification to the center agent in the third terminal, and then observe the output in the second terminal:
2929

3030
```bash
3131
coagent center:singleton -H type:Notify -d '{"user_id": "1", "notification": {"type": "created", "content": "Hello, world!"}}'

0 commit comments

Comments
 (0)