MCP使用黑客马拉松演示
使用工具构建AI代理的最简单方法 制造商/mcp使用.
此演示具有 3个文件:
server.py--带有3个简单工具(add、roll_dice、reverse_string)的MCP服务器agent.py--自动调用工具的一次性代理chat.py--一个互动聊天,您可以在其中与代理交谈
快速开始
1.安装依赖项
pip install -r requirements.txt2.设置Groq API密钥
cp .env.example .env
# Edit .env and paste your key from https://console.groq.com/keys3.启动MCP服务器
python server.pyWindows用户: 如果服务器因Unicode错误而崩溃,请使用以下命令运行: set PYTHONIOENCODING=utf-8 && python server.py服务器运行在 http://localhost:8000/mcp.
4.(可选)使用MCP检查器浏览您的工具
在单独的终端中:
npx @modelcontextprotocol/inspector --transport http --server-url http://127.0.0.1:8000/mcp这将打开一个web UI,您可以在其中交互式地查看和测试所有工具。
5.运行代理(在另一个终端中)
单次模式 --代理运行预定义的任务:
python agent.py交互式聊天 --问代理人任何事情:
python chat.py运作原理
You --> Agent (Groq LLM) --> MCP Server (your tools)
| |
Decides which Executes the tool
tool to call and returns resultserver.py将Python函数公开为 MCP工具 通过HTTP- 代理连接到服务器,发现可用工具,并使用Groq LLM根据您的查询决定调用哪些工具
- LLM看到工具描述,选择正确的工具,然后代理执行它
添加您自己的工具
在中添加新工具 server.py:
@server.tool(
name="my_tool",
description="Describe what it does — the LLM reads this!",
)
async def my_tool(
param: Annotated[str, Field(description="What this param is for")],
) -> str:
return f"Result: {param}"重新启动服务器,代理将自动发现并使用您的新工具。
