Token导航 LogoToken导航TokenDH.com
Devops AI First Phase logo
AI代理stdio官方级别未说明来源级核验

Devops AI First Phase

MCP Server

一个基于Python和Ollama实现的Model Context Protocol (MCP)代理系统,支持代理间通信(A2A),适用于AI代理架构的学习和教学。

工具数

3

提示词数

0

GitHub Stars

0

资源数

0
AI代理Python本地部署

安装说明

本站只整理中文说明和来源信息,不托管安装包,也不代用户安装。

作者 / 组织

BaruchiHalamish20

提供方

BaruchiHalamish20

最后核验

2026/5/17 20:20

运行时

Python

快速接入

先看主来源和安装命令,再打开仓库或文档;下面只保留这个条目的关键接入事实。

命令预览

python3 -m venv venv

详细介绍

🤖 MCP代理系统-Python实现

实际执行 模型上下文协议(MCP) 随着 代理人对代理人(A2A) 使用Python和Ollama进行通信。非常适合学习和教授AI代理架构。

![Python 3.10+](https://www.python.org/downloads/) ![MCP](https://modelcontextprotocol.io) ![Ollama](https://ollama.ai)

📖 概述

该项目展示了:

  • MCP服务器:提供可重复使用的工具(天气、时间、计算器)
  • 代理程序:计划和委派任务
  • 工人代理人:使用MCP工具执行任务
  • A2A通信:代理商合作解决问题

建筑

┌─────────────────┐
│  User Request   │
└────────┬────────┘
         │
         ▼
┌─────────────────────┐
│ Coordinator Agent   │  ◄── Plans & Decides
│   (Ollama LLM)      │
└─────────┬───────────┘
          │ A2A Communication
          ▼
┌─────────────────────┐
│   Worker Agent      │  ◄── Executes Tasks
│   (Ollama LLM)      │
└─────────┬───────────┘
          │
          ▼
┌─────────────────────┐
│    MCP Server       │  ◄── Tool Execution
│  (weather, time,    │
│   calculator)       │
└─────────────────────┘

🚀 快速开始

先决条件

  • Python 3.10或更高版本
  • Ollama已安装并正在运行
  • 对异步Python的基本理解

安装

  1. 克隆或创建项目:
mkdir mcp-agents-demo
cd mcp-agents-demo
  1. 设置Python环境:
python3 -m venv venv
source venv/bin/activate  # On Windows: venv/Scripts/activate
  1. 安装依赖项:
pip install mcp httpx
  1. 创建文件:
  • 复制 mcp_server.py (MCP服务器实现)
  • 复制 agents.py (代理系统)
  • 复制 requirements.txt
  1. 安装并运行Ollama:
# Install Ollama (if not already installed)
# curl -fsSL https://ollama.com/install.sh | sh

# Start Ollama server
ollama serve

# In another terminal, pull a model
# ollama pull llama2  # or llama3, mistral, etc.

运行演示

python3 agents.py

您将看到:

  • ✅ 协调员分析请求
  • ✅ 代理间通信
  • ✅ MCP工具执行
  • ✅ 完整结果

📂 项目结构

mcp-agents-demo/
├── mcp_server.py       # MCP server with tools
├── agents.py           # Two-agent system
├── requirements.txt    # Python dependencies
└── README.md          # This file

🎯 运作原理

1.MCP服务器(mcp_server.py)

提供三种可通过MCP协议访问的工具:

工具描述参数
get_weather获取城市天气city: string
get_time获取当前时间timezone: string
calculate数学运算operation, a, b

2.协调代理

角色:高级别任务规划和授权

Responsibilities:
- Analyze user requests
- Understand available tools
- Create execution plans
- Delegate to Worker Agent

示例流程:

User: "What's the weather in Tokyo?"
↓
Coordinator: Analyzes → Identifies "get_weather" tool needed
↓
Delegates to Worker with plan

3.工人代理人

角色:使用MCP工具执行任务

Responsibilities:
- Receive tasks from Coordinator
- Select appropriate MCP tools
- Execute tool calls
- Return results

示例流程:

Receives: "Get weather for Tokyo"
↓
Calls: get_weather(city="Tokyo")
↓
Returns: Weather data

4.A2A通信

代理通过共享进行通信:

  • 任务上下文
  • 执行计划
  • 对话历史
  • 工具结果
# Example A2A flow
coordinator_result = await coordinator.process(request)
↓
worker_result = await worker.execute_task(
    coordinator_result["task"],
    coordinator_result["decision"]  # A2A context sharing
)

🔧 配置

更改Olama模型

编辑 agents.py:

OLLAMA_MODEL = "llama3"  # Options: llama2, llama3, mistral, codellama

自定义测试用例

编辑 test_requests 在中列出 agents.py:

test_requests = [
    "What is the weather in Tokyo?",
    "Calculate 15 divided by 3",
    "What time is it in Paris?",
    "Your custom request here"
]

添加新的MCP工具

mcp_server.py,添加到 handle_list_tools():

types.Tool(
    name="your_tool",
    description="Tool description",
    inputSchema={
        "type": "object",
        "properties": {
            "param": {"type": "string"}
        },
        "required": ["param"]
    }
)

然后执行 handle_call_tool():

elif name == "your_tool":
    result = your_implementation(arguments)
    return [types.TextContent(type="text", text=json.dumps(result))]

📊 输出示例

======================================================================
🚀 Starting MCP Agent System (A2A Demo)
======================================================================

✅ Connected to MCP server

======================================================================
📝 TEST CASE 1: What is the weather in Tokyo?
======================================================================

🎯 COORDINATOR AGENT: Analyzing request...
   Request: What is the weather in Tokyo?

🤖 Calling Ollama...

📋 Coordinator Analysis:
   This request requires the get_weather tool...

----------------------------------------------------------------------

🔄 AGENT-TO-AGENT COMMUNICATION
   Coordinator → Worker: Delegating task

⚙️  WORKER AGENT: Executing task...
   Task: What is the weather in Tokyo?

📡 Calling MCP tool: get_weather(city='Tokyo')
✅ Tool Result: {
  "city": "Tokyo",
  "temperature": 23,
  "condition": "Sunny",
  "humidity": 65
}

======================================================================
✅ FINAL RESULT:
{
  "success": true,
  "result": "...",
  "tool": "get_weather"
}
======================================================================

🧪 测试

运行默认测试

python3 agents.py

添加交互模式

添加到 agents.py:

async def interactive_mode():
    mcp_client = MCPClientWrapper()
    await mcp_client.connect()
    
    coordinator = CoordinatorAgent(mcp_client)
    worker = WorkerAgent(mcp_client)
    
    print("Interactive mode. Type 'quit' to exit.\n")
    
    while True:
        user_input = input("Your request: ")
        if user_input.lower() in ['quit', 'exit']:
            break
        
        coord_result = await coordinator.process(user_input)
        worker_result = await worker.execute_task(
            coord_result["task"],
            coord_result["decision"]
        )
        
        print("\n✅ Result:")
        print(json.dumps(worker_result, indent=2))
        print()
    
    await mcp_client.close()

if __name__ == "__main__":
    asyncio.run(interactive_mode())

🐛 故障排除

Ollama连接问题

问题: Warning: Ollama not running

解决方案:

# Start Ollama in a separate terminal
ollama serve

# Verify it's running
curl http://localhost:11434/api/tags

MCP服务器连接失败

问题:无法连接到MCP服务器

解决方案:

  • 确保 mcp_server.py 位于同一目录中
  • 检查Python路径权限
  • 验证 mcp 软件包已安装: pip install mcp

模块导入错误

问题: ModuleNotFoundError: No module named 'mcp'

解决方案:

# Activate virtual environment
source venv/bin/activate

# Install/reinstall dependencies
pip install --upgrade mcp httpx

未找到型号

问题:Olama型号不可用

解决方案:

# List available models
ollama list

# Pull the model you need
ollama pull llama2
# or
ollama pull llama3

🎓 学习练习

  1. 添加数据库工具

- 创建 query_database MCP服务器中的工具 - 添加SQL查询执行功能 - 使用示例查询进行测试

  1. 创建验证器代理

- 添加第三个代理以验证结果 - 执行结果检查逻辑 - 链:协调员→ 工人→ 验证器

  1. 实施错误恢复

- 向Worker代理添加重试逻辑 - 妥善处理MCP工具故障 - 记录调试错误

  1. 添加持久内存

- 存储对话历史记录 - 跨会话启用上下文 - 实现内存检索

  1. 构建Web界面

- 创建FastAPI/Flask端点 - 为代理系统添加REST API - 构建简单的web UI

🔬 高级功能

启用调试日志记录

export MCP_DEBUG=1
python3 agents.py

使用不同型号跑步

# Edit agents.py to change OLLAMA_MODEL
# Then run specific tests
python3 agents.py

基准代理性能

添加计时 agents.py:

import time

start = time.time()
result = await coordinator.process(request)
end = time.time()

print(f"Coordinator took {end - start:.2f}s")

📚 关键概念

模型上下文协议(MCP)

  • AI工具集成的标准化协议
  • 实现跨不同代理的工具可重用性
  • 将工具实现与代理逻辑分离

代理间通信

  • 代理共享上下文和决策
  • 启用复杂的多代理工作流
  • 维护对话历史记录

工具调用模式

  1. 代理识别所需工具
  2. 代理准备工具参数
  3. 工具通过MCP执行
  4. 结果返回给代理
  5. 代理处理和响应

🤝 贡献

贡献想法:

  • 添加更多MCP工具(文件操作、API调用等)
  • 改进LLM快速工程
  • 添加单元测试
  • 创建可视化仪表板
  • 改进错误处理

📖 资源

📝 许可证

本项目按原样提供,用于教育目的。请随意使用、修改和分发。

💬 支持

如有疑问或问题:

  • 检查故障排除部分
  • 审查MCP文件
  • 用简化示例进行测试
  • 确认Ollama运行正常

🎯 后续步骤

  1. ✅ 运行基本演示
  2. ✅ 了解代理通信流程
  3. ✅ 修改测试用例
  4. ✅ 添加自定义工具
  5. ✅ 尝试不同的模型
  6. ✅ 建立自己的代理系统!

______________________________________________________________________

快乐学习! 🚀

专为与AI代理和MCP合作的DevOps工程师而设计。

目录标签

目录标签

AI代理Python本地部署多代理系统工具调用任务规划Python实现

接入字段

传输方式(transport,传输协议)

stdio

鉴权方式(authType,认证方式)

none

运行时(runtime,运行环境)

Python

工具数量(toolCount,工具数)

3

资源数量(resourceCount,资源数)

0

提示词数量(promptCount,提示词数)

0

权限和风险

stdionone部署方式未说明

接入前请确认传输方式、认证方式和部署位置,并根据实际工具能力限制访问范围。

安装前确认

不要直接授予不必要的文件、网络或账号权限;先核对安装命令和配置内容。

来源信息

继续浏览同类 MCP