计算器服务

一个基于MCP协议和CrewAI的AI计算器服务,通过SSE传输实现实时数学计算功能。

  • by Khan07fahad
  • Python
  • 本地部署
  • 1 星标
  • 更新于
在 GitHub 查看 Khan07fahad/crewai-mcp

使用说明

🧮 带CrewAI的MCP计算器服务器-完整指南

📋 目录

  1. 概述
  2. 建筑
  3. 先决条件
  4. 安装说明
  5. 了解组件
  6. 运行应用程序
  7. 运作原理
  8. 故障排除
  9. 高级用法

🎯 概述

该项目演示了如何集成 模型上下文协议(MCP) 随着 船员AI 创建可以通过远程服务器执行数学计算的AI代理。该系统由以下部分组成:

  • MCP计算器服务器:通过SSE(服务器发送事件)传输提供计算器工具
  • CrewAI代理:使用MCP工具进行计算
  • SSE协议:实现实时双向通信

你将建造什么

一个基于人工智能的计算器系统,CrewAI代理可以自动发现和使用MCP服务器提供的计算器工具(加、减、乘、除)。


🏗️ 建筑

系统概述

┌─────────────────────────────────────────────────────────────────┐
│                         User Input                              │
│              "Calculate 15 + 27 and multiply by 3"              │
└────────────────────────┬────────────────────────────────────────┘
                         │
                         ▼
┌─────────────────────────────────────────────────────────────────┐
│                      CrewAI System                              │
│  ┌──────────────────────────────────────────────────────────┐  │
│  │  Calculator Agent (crew.py)                              │  │
│  │  • Receives user requests                                │  │
│  │  • Plans calculation steps                               │  │
│  │  • Uses MCPServerAdapter to access tools                 │  │
│  └────────────────────┬─────────────────────────────────────┘  │
│                       │                                          │
│  ┌────────────────────▼─────────────────────────────────────┐  │
│  │  MCPServerAdapter (crewai_tools)                         │  │
│  │  • Connects to MCP server via SSE                        │  │
│  │  • Discovers available tools                             │  │
│  │  • Translates tool calls to MCP protocol                 │  │
│  └────────────────────┬─────────────────────────────────────┘  │
└────────────────────────┼─────────────────────────────────────────┘
                         │
                         │ SSE Connection
                         │ (HTTP/SSE Transport)
                         │
┌────────────────────────▼─────────────────────────────────────────┐
│               MCP Calculator Server                              │
│               (mcp_calculator_server.py)                         │
│                                                                   │
│  ┌──────────────────────────────────────────────────────────┐  │
│  │  FastMCP Server                                          │  │
│  │  • Exposes calculator tools via MCP protocol             │  │
│  │  • Handles SSE connections                               │  │
│  │  • Processes tool execution requests                     │  │
│  └──────────────────────────────────────────────────────────┘  │
│                                                                   │
│  🔧 Available Tools:                                             │
│     ├─ add_numbers(a, b)                                        │
│     ├─ subtract_numbers(a, b)                                   │
│     ├─ multiply_numbers(a, b)                                   │
│     └─ divide_numbers(a, b)                                     │
│                                                                   │
│  📡 Endpoints:                                                   │
│     ├─ GET  /sse              → SSE stream (responses)          │
│     └─ POST /messages → Tool calls (requests) │
└───────────────────────────────────────────────────────────────────┘

🔧 先决条件

系统要求

  • python:3.12或更高
  • 操作系统:macOS、Linux或Windows
  • 终端:访问命令行

必需的API密钥

  • OpenAI API密钥:CrewAI代理需要(使用GPT模型)
    • 从以下网址获取:https://platform.openai.com/api-keys
    • 或使用其他LLM提供程序(请参阅高级用法)

📦 安装说明

第一步:项目结构

创建项目目录:

mkdir -p ~/Desktop/crewai-mcp
cd ~/Desktop/crewai-mcp

你的项目应该有这样的结构:

calculater/
├── mcp_calculator_server.py    # MCP server with calculator tools
├── crew.py                      # CrewAI agent that uses MCP tools
├── interactive_calculator.py    # Interactive CLI version
├── requirements.txt             # Python dependencies

第二步:创建虚拟环境

cd ~/Desktop/crewai-mcp

# Create virtual environment named 'vecal'
python3 -m venv vecal

# Activate it
source vecal/bin/activate

# Verify activation (you should see (vecal) in your prompt)
which python
# Should output: /Users/[username]/Desktop/crewai-mcp/vecal/bin/python

步骤3:安装依赖项

pip安装-r要求.txt

步骤4:设置环境变量

创建 .env 文件:

cat > .env << 'EOF'
# OpenAI API Key (required for CrewAI)
OPENAI_API_KEY=your-api-key-here

# Optional: Model configuration
OPENAI_MODEL_NAME=gpt-4o-mini

EOF

重要:替换 your-api-key-here 使用您的实际OpenAI API密钥!

加载环境变量:

# Option 1: Export manually
export OPENAI_API_KEY="your-actual-api-key"

# Option 2: Use dotenv (automatically loaded by crew.py)
# Just make sure .env file exists with correct values

🎓 了解组件

组件1:MCP计算器服务器

文件: mcp_calculator_server.py

关键要素:

  1. FastMCP服务器初始化
mcp = FastMCP("calculator-server")

创建MCP服务器实例。

  1. 工具定义
@mcp.tool()
def add_numbers(a: int, b: int) -> int:
    """Add two numbers together."""
    return a + b

每个功能都装饰着 @mcp.tool() 成为MCP工具。

  1. SSE传输设置
sse = SseServerTransport("/messages/")

创建处理双向通信的SSE传输。

  1. 路由配置
routes=[
    Route("/sse", endpoint=handle_sse, methods=["GET"]),
    Mount("/messages/", app=sse.handle_post_message),
]
  • /sse:客户端在此处连接以接收响应
  • /messages/:客户端在此处发布工具执行请求

成分2:CrewAI试剂

文件: crew.py

关键要素:

  1. MCP服务器适配器
with MCPServerAdapter(server_params) as tools:

自动:

  • 通过SSE连接到MCP服务器
  • 发现可用工具
  • 将它们转换为CrewAI兼容工具
  1. 代理定义
calculator_agent = Agent(
    role="Mathematical Calculator",
    goal="Perform calculations...",
    tools=tools,  # MCP tools injected here
    ...
)
  1. 任务定义
calculator_task = Task(
    description="Calculate X + Y...",
    agent=calculator_agent,
    ...
)
  1. 船员执行
calculator_crew.kickoff()

启动代理程序,根据需要自动使用MCP工具。

🚀 运行应用程序

终端设置

你需要 两个终端:

终端1:MCP服务器

# Navigate to project directory
cd ~/Desktop/crewai-mcp

# Activate virtual environment
source vecal/bin/activate

# Start MCP server
python mcp_calculator_server.py

预期输出:

======================================================================
🧮 MCP Calculator Server (SSE Transport)
======================================================================

✅ Using FastMCP with SSE over HTTP
📡 Server running on: http://localhost:8000

🔧 Available Tools:
  • add_numbers(a, b)
  • subtract_numbers(a, b)
  • multiply_numbers(a, b)
  • divide_numbers(a, b)

💡 This is a proper MCP server with SSE transport!
   Can be used with CrewAI MCPServerAdapter

Press Ctrl+C to stop
======================================================================

INFO:     Started server process [12345]
INFO:     Waiting for application startup.
INFO:     Application startup complete.
INFO:     Uvicorn running on http://0.0.0.0:8000 (Press CTRL+C to quit)

✅ 当您看到“Uvicorn正在运行…”时,服务器已准备就绪

2号航站楼:CrewAI代理

# Open NEW terminal tab/window
cd ~/Desktop/crewai-mcp

# Activate virtual environment
source vecal/bin/activate

# Set API key (if not in .env)
export OPENAI_API_KEY="your-api-key-here"

# Run CrewAI agent
python crew.py

预期输出:

Available tools from MCP server: ['add_numbers', 'subtract_numbers', 'multiply_numbers', 'divide_numbers']

🚀 Starting calculation tasks...

[Agent: Mathematical Calculator]
[Task: Perform calculations...]

Working on: Add 15 and 27...
Using tool: add_numbers
Tool result: 42

Working on: Subtract 10 from 50...
Using tool: subtract_numbers
Tool result: 40

Working on: Multiply 8 by 6...
Using tool: multiply_numbers
Tool result: 48

Working on: Divide 100 by 4...
Using tool: divide_numbers
Tool result: 25.0

======================================================================
✨ FINAL RESULT
======================================================================
# Calculation Results

1. **Addition**: 15 + 27 = 42
2. **Subtraction**: 50 - 10 = 40
3. **Multiplication**: 8 × 6 = 48
4. **Division**: 100 ÷ 4 = 25.0

All calculations completed successfully!
======================================================================

交互模式

from crewai import Agent, Task, Crew, Process
from crewai_tools import MCPServerAdapter

def run_interactive_calculator():
    server_params = {
        "url": "http://localhost:8000/sse",
        "transport": "sse" 
    }

    print("\n" + "="*70)
    print("🧮 Interactive Calculator Agent")
    print("="*70 + "\n")
    
    try:
        with MCPServerAdapter(server_params) as tools:
            calculator_agent = Agent(
                role="Mathematical Calculator Assistant",
                goal="Help users perform calculations using MCP calculator tools.",
                backstory="A friendly calculator AI with arithmetic capabilities.",
                tools=tools,
                reasoning=True,
                verbose=True,
            )

            while True:
                print("\n📝 Enter your calculation (or 'quit' to exit):")
                user_input = input("> ").strip()
                
                if user_input.lower() in ['quit', 'exit', 'q']:
                    print("\n👋 Goodbye!\n")
                    break
                
                if not user_input:
                    continue
                
                task = Task(
                    description=f"Calculate: {user_input}",
                    expected_output="The calculation result with explanation.",
                    agent=calculator_agent,
                )
                
                crew = Crew(
                    agents=[calculator_agent],
                    tasks=[task],
                    verbose=False,
                    process=Process.sequential
                )
                
                result = crew.kickoff()
                print(f"\n✨ Result: {result}\n")

    except Exception as e:
        print(f"\n❌ Error: {e}\n")

if __name__ == "__main__":
    run_interactive_calculator()

运行它:

python interactive_calculator.py

🔍 运作原理

完成请求流

让我们追踪代理计算时发生了什么 15 + 27:

1.初始化阶段

# crew.py starts
with MCPServerAdapter(server_params) as tools:

发生了什么:

  1. MCPServerAdapter连接到 http://localhost:8000/sse
  2. 服务器创建会话: session_id=xxxxxxx
  3. 服务器发送: data: /messages/?session_id=xxxxxxx
  4. 适配器提取会话ID并保持SSE连接打开
  5. 适配器请求工具列表: {"method": "tools/list"}
  6. 服务器返回: ["add_numbers", "subtract_numbers", ...]
  7. 适配器从MCP工具模式创建CrewAI工具

2.代理执行阶段

calculator_crew.kickoff()

发生了什么:

  1. CrewAI读取任务描述:“添加15和27”
  2. 代理(由GPT提供支持)决定使用 add_numbers 工具
  3. 代理生成工具调用: add_numbers(a=15, b=27)

3.工具执行阶段

在MCPServerAdapter中:

# Adapter intercepts tool call
tool_call = {
    "name": "add_numbers",
    "arguments": {"a": 15, "b": 27}
}

# Converts to MCP protocol
mcp_request = {
    "jsonrpc": "2.0",
    "id": 1,
    "method": "tools/call",
    "params": {
        "name": "add_numbers",
        "arguments": {"a": 15, "b": 27}
    }
}

# POSTs to /messages/?session_id=xxxxxxx
response = requests.post(url, json=mcp_request)

在服务器端:

# Server receives request at /messages/?session_id=xxxxxxx
# Looks up session by ID
# Routes message through SSE transport streams
# Calls the actual Python function:
result = add_numbers(15, 27)  # Returns 42

# Sends result back via SSE stream
sse_response = {
    "jsonrpc": "2.0",
    "id": 1,
    "result": {
        "content": [{"type": "text", "text": "42"}]
    }
}

回到MCPServerAdapter:

# Listens on SSE stream
# Receives result: "42"
# Converts to CrewAI format
# Returns to agent

4.响应阶段

# Agent receives: 42
# Agent uses result to formulate answer
# Agent continues with next calculation

数据流图

User Input: "Add 15 and 27"
     ↓
CrewAI Agent (decides to use tool)
     ↓
MCPServerAdapter.add_numbers(15, 27)
     ↓
[Converts to JSON-RPC]
     ↓
POST /messages/?session_id=xxxxxxx
{
  "jsonrpc": "2.0",
  "method": "tools/call",
  "params": {"name": "add_numbers", "arguments": {"a": 15, "b": 27}}
}
     ↓
MCP Server receives & processes
     ↓
Python function: add_numbers(15, 27) → 42
     ↓
[Formats as MCP response]
     ↓
SSE Stream ══════════════════════════>
event: message
data: {"result": {"content": [{"text": "42"}]}}
     ↓
MCPServerAdapter receives via SSE
     ↓
[Extracts result: 42]
     ↓
Returns 42 to Agent
     ↓
Agent: "The sum of 15 and 27 is 42"

🐛 故障排除

问题1:服务器无法启动

错误: Address already in use

解决方案:

# Find process using port 8000
lsof -ti:8000

# Kill it
kill -9 $(lsof -ti:8000)

# Or use different port
# In mcp_calculator_server.py, change:
uvicorn.run(app, host="0.0.0.0", port=8001)
# And in crew.py:
"url": "http://localhost:8001/sse"

问题2:CrewAI无法连接

错误: Error connecting to Calculator MCP server

清单:

# 1. Is server running?
curl http://localhost:8000/sse
# Should connect and stream data

# 2. Check server logs in Terminal 1
# Look for errors or connection attempts

# 3. Verify URL in crew.py
server_params = {
    "url": "http://localhost:8000/sse",  # Must match server port
    "transport": "sse"
}

# 4. Test server manually
curl -N http://localhost:8000/sse
# Should see: event: endpoint, data: /messages/?session_id=...

问题3:缺少OpenAI API密钥

错误: OPENAI_API_KEY is required

解决方案:

# Option 1: Set in terminal
export OPENAI_API_KEY="sk-..."

# Option 2: Create .env file
echo 'OPENAI_API_KEY=sk-...' > .env

# Option 3: Use alternative LLM (see Advanced Usage)

问题4:工具调用失败

错误: Invalid request parameters

调试步骤:

# 1. Check server logs for detailed error
# 2. Verify tool exists
curl http://localhost:8000/sse
# Wait for initialization, then check available tools

# 3. Test tool manually
# Get session ID from SSE connection, then:
curl -X POST "http://localhost:8000/messages/?session_id=YOUR_SESSION_ID" \
  -H "Content-Type: application/json" \
  -d '{
    "jsonrpc": "2.0",
    "id": 1,
    "method": "tools/call",
    "params": {
      "name": "add_numbers",
      "arguments": {"a": 5, "b": 3}
    }
  }'

问题5:未找到依赖项

错误: ModuleNotFoundError: No module named 'mcp'

解决方案:

# Ensure virtual environment is activated
source vecal/bin/activate

# Verify activation
which python
# Must show path to vecal/bin/python

# Reinstall dependencies
pip install -r requirements.txt

# Verify installation
python -c "import mcp; import crewai; print('All good!')"

📚 总结

你建造了什么

  1. MCP计算器服务器:通过标准化协议公开数学运算
  2. CrewAI集成:AI代理自动发现和使用远程工具
  3. 苏格兰和南方能源公司运输:组件之间的高效实时通信

关键要点

✅ MCP实现工具标准化 -任何客户都可以使用您的计算器
✅ SSE提供实时通信 -低延迟、持久连接
✅ CrewAI让AI代理变得简单 -自动工具发现和使用
✅ 模块化架构 -服务器和代理是独立的


📖 其他资源

  • MCP规范: https://spec.modelcontextprotocol.io/
  • FastMCP文档: https://gofastmcp.com/
  • CrewAI文档: https://docs.crewai.com/
  • SSE规范: https://html.spec.whatwg.org/multipage/server-sent-events.html