MCP生产事故根本原因分析
基于人工智能的事件分析工具,使用 主控程序 通过关联日志、指标和git历史来自动调查生产事件。
______________________________________________________________________
🎯 这是什么?
当生产事件发生时(如“API结账时出现500个错误”),此工具:
- 自动搜索应用程序日志以查找错误
- 查询指标以检测异常和峰值
- 检查最近的git部署和提交
- 关联所有数据以确定根本原因
- 提供时间表、证据和建议
关键技术:用途 MCP(模型上下文协议) 将AI(Ollama)连接到多个专业数据源。
______________________________________________________________________
🏗️ 建筑
┌─────────────────────────────────────────────────────────┐
│ │
│ MCP Client (mcp_analyze_multi.py) │
│ │
│ ┌──────────────────────────────────────────────────┐ │
│ │ 1. Starts 3 MCP servers as subprocesses │ │
│ │ 2. Connects to each via stdio │ │
│ │ 3. Collects tools from all servers (8 tools) │ │
│ │ 4. Sends tools to Ollama AI │ │
│ │ 5. Routes tool calls to appropriate server │ │
│ └──────────────────────────────────────────────────┘ │
│ │
└────────┬──────────────┬──────────────┬─────────────────┘
│ │ │
▼ ▼ ▼
┌────────┐ ┌────────┐ ┌──────────┐
│ LOGS │ │ GIT │ │ DATADOG │
│ SERVER │ │ SERVER │ │ SERVER │
└────────┘ └────────┘ └──────────┘
(Python) (Python) (Python)
│ │ │
▼ ▼ ▼
┌────────┐ ┌────────┐ ┌──────────┐
│ Tools: │ │ Tools: │ │ Tools: │
│ │ │ │ │ │
│ • read │ │ • get │ │ • get │
│ _logs │ │ _recen│ │ _metric │
│ │ │ t_com│ │ s │
│ • sear │ │ mits │ │ │
│ ch_lo │ │ │ │ • get │
│ gs │ │ • get │ │ _anomal │
│ │ │ _deplo│ │ ies │
│ │ │ yment│ │ │
│ │ │ s │ │ • get │
│ │ │ │ │ _error │
│ │ │ • sear │ │ _rates │
│ │ │ ch_com│ │ │
│ │ │ mits │ │ │
└────────┘ └────────┘ └──────────┘
│ │ │
▼ ▼ ▼
┌────────┐ ┌────────┐ ┌──────────┐
│ Data │ │ Data │ │ Data │
│ app.log│ │ commits│ │ metrics │
│ │ │ .json │ │ .json │
└────────┘ └────────┘ └──────────┘看 建筑.md 查看详细的架构图。
______________________________________________________________________
📁 项目结构
mcp-production-incident-pilot/
│
├── mcp_analyze_multi.py # MCP Client - connects to all 3 servers
│
├── mcp-servers/ # Custom MCP Servers
│ │
│ ├── logs-server/
│ │ ├── server.py # Logs MCP Server
│ │ └── data/
│ │ └── app.log # Application logs
│ │
│ ├── git-server/
│ │ ├── server.py # Git MCP Server
│ │ └── data/
│ │ └── recent_commits.json
│ │
│ └── datadog-server/
│ ├── server.py # Datadog MCP Server
│ └── data/
│ └── metrics.json
│
├── .env # Ollama API configuration
├── .gitignore # Git ignore rules
├── requirements.txt # Python dependencies
│
├── README.md # This file
├── ARCHITECTURE.md # Detailed architecture docs
└── MULTI_SERVER_SETUP.md # Multi-server setup guide______________________________________________________________________
🚀 快速开始
先决条件
- Python 3.8+
- Ollama Cloud API密钥 (一个在https://ollama.com/)
安装
步骤1:安装Python依赖项
pip install -r requirements.txt步骤2:配置环境变量
创建一个 .env 项目根目录中的文件:
OLLAMA_HOST=https://ollama.com
OLLAMA_MODEL=qwen3-coder-next
OLLAMA_API_KEY=your_api_key_here步骤3:运行分析仪
python mcp_analyze_multi.py "500 errors on checkout API"______________________________________________________________________
📖 用法
基本用法
python mcp_analyze_multi.py "500 errors on checkout API"你会看到什么
======================================================================
MULTI-SERVER MCP INCIDENT ANALYZER
======================================================================
Configuration:
Host: https://ollama.com
Model: qwen3-coder-next
API Key: be000b51...
Incident: 500 errors on checkout API
======================================================================
[1/6] Starting 3 MCP servers...
- Logs Server
- Git Server
- Datadog Server
[2/6] Initializing MCP sessions...
[3/6] Getting tools from all servers...
- Logs Server: 2 tools
- Git Server: 3 tools
- Datadog Server: 3 tools
[4/6] Available tools:
- read_logs (Logs Server)
- search_logs (Logs Server)
- get_recent_commits (Git Server)
- get_deployments (Git Server)
- search_commits (Git Server)
- get_metrics (Datadog Server)
- get_anomalies (Datadog Server)
- get_error_rates (Datadog Server)
[5/6] Ollama analyzing with MCP tools...
[Tool #1] search_logs (LOGS server)
Arguments: {'pattern': '500'}
Result: Found 5 matches...
[Tool #2] get_metrics (DATADOG server)
Arguments: {}
Result: Error rate spike detected...
[Tool #3] get_deployments (GIT server)
Arguments: {}
Result: Recent deployment v2.4.1...
======================================================================
[6/6] ANALYSIS COMPLETE
======================================================================
Total MCP tool calls: 8
- Logs Server: 3 calls
- Git Server: 2 calls
- Datadog Server: 3 calls
======================================================================
ROOT CAUSE ANALYSIS
======================================================================
Timeline:
- 14:25: Deployment v2.4.1 deployed
- 14:45: Error rate spike (0.1% → 15.5%)
- 14:46: Connection pool exhausted
Root Cause:
Database connection pool exhaustion after deployment v2.4.1
Evidence:
- Logs: "Connection pool exhausted"
- Metrics: Error spike, response time 180ms → 4500ms
- Git: HOTFIX increased pool 30 → 35 (insufficient)
Recommendations:
1. Increase connection pool to 50+
2. Add connection pool monitoring
3. Implement circuit breakers
======================================================================______________________________________________________________________
🔧 运作原理
1.MCP服务器(定制)
每个MCP服务器都是一个Python进程,提供特定于域的工具:
日志服务器 (mcp-servers/logs-server/server.py)
- 工具:
read_logs(),search_logs() - 数据:中的应用程序日志文件
data/app.log
Git服务器 (mcp-servers/git-server/server.py)
- 工具:
get_recent_commits(),get_deployments(),search_commits() - 数据:Git提交历史记录
data/recent_commits.json
Datadog服务器 (mcp-servers/datadog-server/server.py)
- 工具:
get_metrics(),get_anomalies(),get_error_rates() - 数据:系统指标
data/metrics.json
2.MCP客户端(您构建了此客户端)
客户(mcp_analyze_multi.py):
- 将所有3个MCP服务器作为子进程启动
- 通过stdio(标准输入/输出)连接到每个
- 从每台服务器收集可用工具
- 向Ollama AI发送事件描述+所有工具
- 将Ollama的工具调用路由到正确的服务器
- 将结果返回给Ollama
- 显示最终根本原因分析
3.Olama AI(云服务)
奥拉玛·艾:
- 接收事件描述
- 决定调用哪些MCP工具(自主)
- 分析所有来源的数据
- 关联日志、指标和git历史记录
- 确定根本原因
- 提供建议
______________________________________________________________________
🔍 示例场景
场景1:数据库问题
python mcp_analyze_multi.py "database timeout errors"AI将:
- 在日志中搜索“超时”
- 检查数据库连接池的指标
- 查找最近与数据库相关的提交
场景2:内存泄漏
python mcp_analyze_multi.py "out of memory errors"AI将:
- 搜索OOM错误日志
- 检查内存使用指标
- 查找可能导致泄漏的部署
场景3:API性能
python mcp_analyze_multi.py "slow API response times"AI将:
- 检查响应时间指标
- 查找与性能相关的提交
- 确定减速何时开始
______________________________________________________________________
🎯 主要特点
✅ 多服务器MCP架构
- 3台专用MCP服务器(不是一台通用服务器)
- 用于日志、git和指标的域特定工具
✅ 自主AI分析
- AI决定调用哪些工具
- 关联来自多个来源的数据
- 无需人工调查
✅ 真正的MCP实施
- 使用MCP Python SDK(
pip install mcp) - 正确的stdio通信
- 工具路由和会话管理
✅ 生产就绪设计
- 易于扩展到更多服务器
- 用真实API替换虚拟数据
- 模块化和可维护
______________________________________________________________________
🔄 扩展系统
添加新的MCP服务器
步骤1:创建服务器目录
mkdir -p mcp-servers/kubernetes-server/data步骤2:创建服务器 (mcp-servers/kubernetes-server/server.py)
#!/usr/bin/env python3
import os
import json
import asyncio
from mcp.server import Server
from mcp.types import Tool, TextContent
from mcp.server.stdio import stdio_server
DATA_DIR = os.path.join(os.path.dirname(__file__), "data")
app = Server("kubernetes-server")
@app.list_tools()
async def list_tools() -> list[Tool]:
return [
Tool(
name="get_pods",
description="Get pod status and information",
inputSchema={
"type": "object",
"properties": {
"namespace": {
"type": "string",
"description": "Kubernetes namespace",
"default": "default"
}
}
}
)
]
@app.call_tool()
async def call_tool(name: str, arguments: dict) -> list[TextContent]:
if name == "get_pods":
# Implement your logic here
pods_file = os.path.join(DATA_DIR, "pods.json")
with open(pods_file, 'r') as f:
data = json.load(f)
return [TextContent(type="text", text=str(data))]
async def main():
async with stdio_server() as (read_stream, write_stream):
await app.run(read_stream, write_stream, app.create_initialization_options())
if __name__ == "__main__":
asyncio.run(main())步骤3:更新客户端 (mcp_analyze_multi.py)
添加到服务器配置部分:
k8s_server_params = StdioServerParameters(
command="python",
args=[os.path.join(SERVERS_DIR, "kubernetes-server", "server.py")]
)添加到连接部分:
async with stdio_client(logs_server_params) as (logs_read, logs_write), \
stdio_client(git_server_params) as (git_read, git_write), \
stdio_client(datadog_server_params) as (datadog_read, datadog_write), \
stdio_client(k8s_server_params) as (k8s_read, k8s_write):
async with ClientSession(logs_read, logs_write) as logs_session, \
ClientSession(git_read, git_write) as git_session, \
ClientSession(datadog_read, datadog_write) as datadog_session, \
ClientSession(k8s_read, k8s_write) as k8s_session:
# Get tools from new server
k8s_tools = await k8s_session.list_tools()
# Add to tool mapping
for tool in k8s_tools.tools:
tool_to_session[tool.name] = ("kubernetes", k8s_session)连接到真实API
用真实的API调用替换伪数据文件:
日志服务器 → 连接到:
- 弹性搜索
- 斯普兰克
- CloudWatch日志
- 数据狗日志API
Git服务器 → 连接到:
- GitHub API(
https://api.github.com) - GitLab API
- 比特桶API
Datadog服务器 → 连接到:
- 数据狗API(
https://api.datadoghq.com) - 普罗米修斯
- 格拉法纳
示例:将日志服务器连接到Elasticsearch
from elasticsearch import Elasticsearch
es = Elasticsearch(['http://localhost:9200'])
@app.call_tool()
async def call_tool(name: str, arguments: dict):
if name == "search_logs":
pattern = arguments.get("pattern")
result = es.search(
index="application-logs",
body={"query": {"match": {"message": pattern}}}
)
return [TextContent(type="text", text=str(result))]______________________________________________________________________
🐛 故障排除
错误:“未找到OLLAMA_API_KEY”
解决方案:创建 .env 使用API密钥文件
OLLAMA_HOST=https://ollama.com
OLLAMA_MODEL=qwen3-coder-next
OLLAMA_API_KEY=your_api_key_here错误:“连接超时”
解决方案:
- 检查您的互联网连接
- 验证Ollama API密钥在https://ollama.com/
- 检查防火墙设置
错误:“MCP服务器启动失败”
解决方案:
- 安装依赖项:
pip install -r requirements.txt - 验证Python版本:
python --version(需要3.8+) - 检查服务器文件是否存在于
mcp-servers/目录 - 直接运行服务器以查看错误:
python mcp-servers/logs-server/server.py
错误:“ModuleNotFoundError:没有名为'mcp'的模块”
解决方案:安装MCP SDK
pip install mcp>=1.0.0终端中的Unicode错误(Windows)
问题:无法显示Unicode字符(→) 解决方案:这是已知的Windows终端限制
- 分析仍然成功完成
- 您可以忽略警告
- 或者使用支持UTF-8的Windows终端
无工具调用/分析未完成
解决方案:
- 检查Ollama API密钥是否有效
- 验证模型名称是否正确(默认值:
qwen3-coder-next) - 尝试使用更简单的事件描述
- 检查数据文件是否存在以及是否有内容
______________________________________________________________________
📚 了解更多
- 建筑.md -详细的技术架构
- MULTI_SERVER_SETUP.md -多服务器设置指南
- MCP协议: https://modelcontextprotocol.io/
- MCP Python SDK: https://github.com/modelcontextprotocol/python-sdk
- 奥利玛云: https://ollama.com/
______________________________________________________________________
📝 许可证
MIT许可证-随意使用和修改
______________________________________________________________________
🎉 摘要
- 多服务器架构:3台专用服务器,而不是1台通用服务器
- 自主AI:Ollama决定调用哪些工具以及何时调用
- 数据相关性:自动连接日志、指标和git历史记录
- 根本原因分析:识别事件并提供建议
- 生产就绪:模块化设计,易于扩展,可用于真正的API
