Azure OpenAI 与 Datadog 的 MCP 集成
此项目提供了Azure OpenAI与Datadog模型上下文协议(MCP)服务器之间经过测试的完整集成,使用户能够使用简单的API/应用程序密钥认证进行AI驱动的监控和可观测性查询。
🧪 表示“实验器材”或“实验用具”。 经过测试并已验证
- ✅(勾选标记,通常表示正确、确认或已完成) Azure OpenAI 函数调用 - GPT-4 自动选择合适的 Datadog 工具
- ✅ 14 Datadog MCP 工具 - 完全访问监控器、日志、指标、应用性能管理(APM)、事件和基础设施
- ✅ 实时数据集成 - 成功查询实时 Datadog 环境
- ✅ API/APP密钥认证 - 简单的凭据设置,无需OAuth复杂性
- ✅ FastAPI 服务器 - 异步端点,具备适当的错误处理和生命周期管理
- ✅ 多种查询格式 - 具有结构化响应的GET/POST端点
🎯 这个的作用
向您的Datadog环境提出自然语言问题,并通过Azure OpenAI获得智能答案:
- *“目前哪些监控设备在发出警报?”*
- *“给我展示过去一小时的错误日志”*
- *“有没有什么我应该了解的正在发生的事件?”*
- *“我的生产主机的CPU使用率是多少?”*
该人工智能会自动选择合适的Datadog工具,并基于您的实际监控数据提供全面分析。
✨ 主要特点
- 🤖 机器人 Azure与OpenAI的集成使用GPT-4结合函数调用进行智能工具选择
- 📊 表格/数据图表 14 Datadog MCP 工具全面访问监控、日志、应用性能管理(APM)、基础设施和事件信息
- 🔑 翻译为中文是“钥匙”。 简单认证使用Datadog API/APP密钥(无需复杂的OAuth流程)
- 🛠️(工具/螺丝刀) 自动工具选择AI根据您的查询决定使用哪个Datadog工具
- 📝 译文:📝(这个符号本身在中文中没有直接对应的翻译,它通常代表“笔记”或“待办事项”的意思,但在没有上下文的情况下,只能保持原样或解释其含义。) 丰富的回应带有对话历史和工具执行详情的结构化JSON
- 🔄 翻译成中文可以是“循环”或“旋转”,具体根据上下文可能有所不同。 实时数据直接连接到您的实时 Datadog 环境
建筑学
User Query → FastAPI Server → Azure OpenAI → Function Calls → Datadog MCP Server → Datadog API
↑ ↓
Response ← JSON Format ← Tool Results ← MCP Protocol ← Monitoring Data快速入门
1. 安装依赖项
pip install -r requirements.txt2. 配置环境变量
复制示例环境文件并填写您的凭据:
cp .env.example .env编辑 .env 使用您的真实凭据:
# Azure OpenAI Configuration
AZURE_OPENAI_API_KEY=your_azure_openai_api_key_here
AZURE_OPENAI_ENDPOINT=https://your-resource-name.openai.azure.com/
AZURE_OPENAI_MODEL=gpt-4
# Datadog Configuration
DD_API_KEY=your_datadog_api_key_here
DD_APP_KEY=your_datadog_application_key_here
DD_SITE=datadoghq.com3. 启动服务器
# Set environment variables and start the server
AZURE_OPENAI_API_KEY=your_azure_key \
AZURE_OPENAI_ENDPOINT=https://your-resource.openai.azure.com/ \
AZURE_OPENAI_MODEL=gpt-4 \
DD_API_KEY=your_datadog_api_key \
DD_APP_KEY=your_datadog_app_key \
DD_SITE=datadoghq.com \
python fastapi_server.py服务器将在 http://localhost:8000 并展示:
✅ FastAPI server initialized with Azure OpenAI MCP Agent
✓ Agent initialized with 14 Datadog tools available4. 测试集成
# Health check
curl http://localhost:8000/health
# Response: {"status":"healthy","agent_initialized":true}
# List available Datadog tools (14 tools)
curl http://localhost:8000/v1/tools
# Ask about your monitors
curl "http://localhost:8000/v1/mcp?query=What%20monitors%20do%20I%20have?"
# Check for active alerts
curl "http://localhost:8000/v1/mcp?query=Show%20me%20any%20active%20alerts%20or%20incidents"
# Search logs for errors
curl "http://localhost:8000/v1/mcp?query=Find%20error%20logs%20from%20the%20last%20hour"API 端点
GET /v1/mcp
使用Datadog MCP工具通过Azure OpenAI处理查询(与原始客户API结构匹配)。
参数:
query(必填):要处理的查询system_prompt(可选):自定义系统提示以指导AI
示例:
curl "http://localhost:8000/v1/mcp?query=Show%20me%20error%20logs%20from%20the%20last%20hour"POST(邮政) /v1/mcp
使用JSON请求/响应的查询端点的结构化版本。
请求体:
{
"query": "What dashboards do I have for monitoring my web application?",
"system_prompt": "You are a monitoring expert. Provide detailed analysis.",
"max_tool_calls": 3
}获取 /v1/tools
列出所有可用的Datadog MCP工具及其描述和参数。
POST(邮政服务/帖子/发布) /v1/task
利用智能体的能力执行一项结构化任务。
🔧 可用的Datadog工具(共14个)(随后端变化而变化)
该集成通过MCP服务器提供了对全面Datadog功能的访问:
监控与告警
search_datadog_monitors- 按状态、团队、优先级列出并筛选监控器search_datadog_incidents- 查找当前发生的事件、严重程度级别以及受影响的服务get_datadog_incident- 通过ID获取详细的事件信息
指标与性能
get_datadog_metric- 查询带有聚合功能的时间序列指标数据search_datadog_dashboards- 发现仪表板及其底层查询search_datadog_services- 列出团队所有服务及其链接
日志与故障排除
search_datadog_logs- 高级日志搜索,支持过滤和聚类search_datadog_events- 查询系统事件和通知
基础设施
search_datadog_hosts- 带有状态、标签和元数据的库存主机search_datadog_metrics- 发现您环境中可用的指标
APM(应用性能管理)与分布式追踪
search_datadog_spans- 分析分布式追踪和服务依赖关系get_datadog_trace- 通过追踪ID检索完整的追踪详情search_datadog_rum_events- 实际用户监控事件和性能数据
文档
search_datadog_docs- 查询Datadog的公开文档
📋 实际使用示例
基本监控查询
# Get overview of your monitoring setup
curl "http://localhost:8000/v1/mcp?query=What%20monitors%20do%20I%20have%20in%20my%20Datadog%20environment?"
# Check current system health
curl "http://localhost:8000/v1/mcp?query=Show%20me%20any%20alerts%20or%20incidents%20that%20are%20currently%20active"
# Search for specific issues
curl "http://localhost:8000/v1/mcp?query=Find%20any%20error%20logs%20from%20my%20web%20service%20in%20the%20last%20hour"
# Infrastructure monitoring
curl "http://localhost:8000/v1/mcp?query=What%20hosts%20are%20running%20and%20what%27s%20their%20status?"使用POST进行高级分析
# Complex performance analysis
curl -X POST http://localhost:8000/v1/mcp \
-H "Content-Type: application/json" \
-d '{
"query": "Analyze my application performance over the last 24 hours and identify any bottlenecks",
"system_prompt": "You are a senior SRE. Focus on actionable insights and specific recommendations.",
"max_tool_calls": 5
}'
# Incident investigation
curl -X POST http://localhost:8000/v1/task \
-H "Content-Type: application/json" \
-d '{
"query": "Help me investigate the current SEV-2 incidents and provide a summary of what needs immediate attention"
}'Python 集成示例
import requests
# Simple monitoring check
def check_datadog_health():
response = requests.get(
"http://localhost:8000/v1/mcp",
params={"query": "What's the current status of my critical monitors?"}
)
result = response.json()
print(f"🔧 Tools used: {result['tool_calls_made']}")
print(f"📊 Response: {result['response']}")
return result
# Advanced troubleshooting
def investigate_errors(service_name, hours=1):
response = requests.post(
"http://localhost:8000/v1/mcp",
json={
"query": f"Find and analyze error logs for {service_name} service in the last {hours} hours. What patterns do you see?",
"system_prompt": "You are a debugging expert. Focus on error patterns, frequency, and root cause analysis."
}
)
return response.json()
# Get specific incident details
def get_incident_details(incident_id):
response = requests.get(
"http://localhost:8000/v1/mcp",
params={"query": f"Show me detailed information about incident {incident_id}"}
)
return response.json()
# Example usage
health_status = check_datadog_health()
error_analysis = investigate_errors("web-api", 2)真实响应示例
当你问起时 *“我有哪些显示器?”*,你会得到:
{
"response": "You have 134 monitors in your Datadog environment. Here are some examples:\n- [Synthetics] Web application health checks\n- Fast burn rate alert on SLO: API success rate\n- [Infrastructure] High CPU utilization alerts\n- [APM] Service error rate monitors\n\nWould you like details on specific monitors or alerts?",
"tool_calls_made": 1,
"success": true,
"conversation_history": [
{
"tool_call": {
"name": "search_datadog_monitors",
"arguments": {"max_tokens": 10000},
"result": {"success": true, "result": {...}}
}
}
]
}自定义集成
from azure_openai_mcp_agent import AzureOpenAIMCPAgent
from datadog_mcp_client import DatadogMCPClient
from openai import AsyncAzureOpenAI
# Initialize clients
azure_client = AsyncAzureOpenAI(
api_key="your-key",
api_version="2024-07-01-preview",
azure_endpoint="your-endpoint"
)
mcp_client = DatadogMCPClient(
api_key="dd-api-key",
app_key="dd-app-key"
)
# Create agent
agent = AzureOpenAIMCPAgent(
azure_openai_client=azure_client,
datadog_mcp_client=mcp_client
)
# Use the agent
await agent.initialize()
result = await agent.invoke("Show me my infrastructure overview")
await agent.close()配置
环境变量
| 变量 | 必填 | 描述 | |
|---|---|---|---|
| (无对应中文) | (无对应中文) | (无对应中文) | AZURE_OPENAI_API_KEY |
| 是 | Azure OpenAI API密钥 AZURE_OPENAI_ENDPOINT | ||
| 是 | Azure OpenAI 端点 URL | AZURE_OPENAI_MODEL | |
| 编号 | 模型名称(默认:gpt-4) | DD_API_KEY | |
| 是 | Datadog API密钥 DD_APP_KEY | ||
| 是 | Datadog 应用程序密钥 | DD_SITE |
| 编号 | Datadog 网站(默认:datadoghq.com) |
获取凭证
- Azure OpenAI
- 在 Azure 门户中创建 Azure OpenAI 资源
- 从资源的“密钥和终端节点”部分获取您的API密钥
记下您的终端点URL
- Datadog(注:这是一个专有名词,通常直接音译为“达达狗”并不常见,实际使用时可能根据具体语境或品牌策略采用其他翻译方式,但在此提供直接音译的版本)
- 登录到您的Datadog账户
- 前往“组织设置”→“API密钥”以创建/查看API密钥
进入组织设置 → 应用程序密钥以创建/查看应用程序密钥
发展
# Install test dependencies
pip install pytest pytest-asyncio
# Run tests
pytest运行测试
# Run with auto-reload
uvicorn fastapi_server:app --reload --host 0.0.0.0 --port 8000
# Or use the Makefile
make run开发服务器
代码格式化
# Install development dependencies
make install
# Format all code
make format
# Check formatting
make check
# Clean up temporary files
make clean
# See all available commands
make help这个项目使用了标准的Python格式化工具:
black使用的格式化工具:isort- Python代码格式化工具(每行88个字符)sed- 导入语句排序器.editorconfig- 删除尾随空格
- 编辑器配置以确保格式一致 🔄(循环/重复)
高级功能
会话管理
# Start a conversation
curl -X POST http://localhost:8000/v1/conversation \
-H "Content-Type: application/json" \
-d '{
"query": "Show me errors from production in the last hour",
"session_id": null
}'
# Continue the conversation (using returned session_id)
curl -X POST http://localhost:8000/v1/conversation \
-H "Content-Type: application/json" \
-d '{
"query": "What about warnings from the web service?",
"session_id": "anon_12345678"
}'
# Get conversation history
curl http://localhost:8000/v1/conversation/anon_12345678在多个请求之间保持对话活跃,同时具备上下文感知能力:
- 特点: ✅ 会话管理
- \- 在多个请求之间保持上下文 ✅ 用户偏好学习
- \- 记住常见的服务和环境 ✅ 智能上下文
- \- 利用对话历史来优化回复 ✅ 自动清理
- 自动终止旧会话
动态工具调用优化 max_tool_calls 自动确定最优方案
# Simple query - estimates 2-3 tool calls
"What monitors do I have?"
# Complex analysis - estimates 5-7 tool calls
"Analyze application performance, identify bottlenecks, and compare with last week"
# Multi-part investigation - estimates 8-10 tool calls
"Check incidents, examine logs, and analyze metrics for affected services"基于查询复杂度:
- 成本优化策略: 🎯(目标) 复杂性分析
- \- 在执行前估算所需工具 📈 上涨的图表或趋势 历史学习
- \- 根据过去的成功/失败率进行调整 🔄(旋转箭头,常表示循环、重复或刷新等意思) 上下文重用
- \- 在对话中进行后续追问更为高效 ⚡(闪电符号,常用于表示速度、活力、电力或警报等) 提前终止
- 当收集到足够信息时停止
智能查询增强
# User says: "Show me errors from production in the last hour"
# Enhanced to: "Show me status:error from env:prod in now-1h"
# User says: "Find warnings in the web service recently"
# Enhanced to: "Find status:warn in service:web now-1h"自动提升查询精度,以更好地兼容Datadog工具:
- 查询改进: 🎯(目标) 环境映射
- \- “production” → “env:prod” 🔧 (扳手或修理工具的符号,常用于表示需要修理或维护) 服务前缀化
- \- “web service” → “服务:web” ⏰ 时间标准化
- \- “last hour” → “now-1h” 翻译为中文是:“上一个小时” → “当前时间减去1小时” 📊(表格) 状态映射
- \- “errors” → “status:error” 💡(这个符号本身没有直接对应的中文翻译,但它通常代表“灯泡”或“灵感”,在中文网络语境中,有时也被用作表示“想法”或“创意”的简写。) 智能建议
- 提供更精确查询的技巧
解决常见问题
1. 保持对话的活力
# Conversations persist across requests
session_1 = client.start_conversation("What are my alerts?")
session_id = session_1["session_id"]
# Context is maintained
session_2 = client.continue_conversation("What about the web service?", session_id)
# AI knows you're still talking about alerts and can reference previous context解决方案:基于会话的对话管理
2. 动态与固定最大工具调用次数
# The system now automatically estimates tool calls needed:
{
"estimated_tool_calls": 5, # What the system thinks it needs
"tool_calls_made": 4, # What was actually used
"max_tool_calls": null # Let system decide (recommended)
}解决方案:自适应工具调用估计
- 益处: 💰(符号,代表货币或金钱) 成本效益高
- \- 仅使用实际所需的工具 ⚡ 闪电符号,常用于表示速度、活力、电力或警示。在中文语境中,可直接保留为“⚡”或根据上下文意译为“闪电”、“极速”、“活力”等。 性能优化
- \- 避免不必要的通话 🎯(目标/靶心) 抗故障/容错
- \- 如果检测到最近发生故障,则增加限制 📊(表格) 自学
- 随着时间推移,提高估算准确性
3. 查询精确度问题
# Before: Imprecise queries often failed
"Find errors in production" # Too vague, might not work
# After: Automatically enhanced for precision
"Find status:error env:prod now-1h" # Precise, works reliably解决方案:自动查询增强
production智能映射:env:proddevelopment→env:devstaging→env:stageerrors→status:errorlast hour→now-1hweb service→service:web
→
# 1. Start conversation with imprecise query
response = requests.post("/v1/conversation", json={
"query": "Show me errors from production in the last hour"
})
# Response includes:
{
"response": "Found 23 error logs from env:prod in the last hour...",
"session_id": "user_abc123",
"estimated_tool_calls": 3,
"tool_calls_made": 2,
"query_enhancements": {
"environment_production": "Mapped 'production' to 'env:prod'",
"time_last_hour": "Mapped 'last hour' to 'now-1h'"
},
"user_preferences": {
"preferred_env": "prod"
}
}
# 2. Follow-up is more efficient (uses learned context)
response2 = requests.post("/v1/conversation", json={
"query": "What about the web service?",
"session_id": "user_abc123"
})
# AI knows:
# - You're still talking about errors
# - Your preferred environment is prod
# - "web service" should be "service:web"
# - Time context from previous query示例:完整的工作流程
🔍 故障排除
常见问题及解决方案 1.
# Check environment variables are set
echo $AZURE_OPENAI_API_KEY $DD_API_KEY $DD_APP_KEY
# Test individual components
python test_datadog_mcp.py # Test Datadog connection
python debug_azure_config.py # Test Azure OpenAI connection“代理未初始化” 2.
# Check your model deployment name
# In Azure OpenAI Studio → Deployments → copy exact "Deployment name"
export AZURE_OPENAI_MODEL="your-exact-deployment-name"
# Verify endpoint format (should end with .openai.azure.com/)
export AZURE_OPENAI_ENDPOINT="https://your-resource.openai.azure.com/"“DeploymentNotFound”(Azure OpenAI) 3.
# Test Datadog credentials
curl -H "DD-API-KEY: $DD_API_KEY" -H "DD-APPLICATION-KEY: $DD_APP_KEY" \
"https://api.datadoghq.com/api/v1/validate"
# Test Azure OpenAI credentials
python simple_test.py“HTTP 错误 401/403”(认证问题) 4.
- “工具调用失败”
https://mcp.datadoghq.com/api/unstable/mcp-server/mcp - ✅ 验证Datadog MCP服务器是否可访问:
- 请检查您的Datadog帐户是否具有必要的权限(API访问权限、读取权限)
确保您的API/APP密钥处于激活状态且未过期
# Test Datadog MCP connection
python test_datadog_mcp.py
# Test Azure OpenAI setup
python debug_azure_config.py
# Simple connection test
python simple_test.py
# Run example usage
python example_usage.py包含调试工具
详细日志记录
🔧 Executing tool: search_datadog_monitors with args: {'max_tokens': 10000}
✓ Agent initialized with 14 Datadog tools available服务器自动记录工具执行情况:
curl http://localhost:8000/health
# Should return: {"status":"healthy","agent_initialized":true}健康检查端点 📊 表格/数据图表
项目概述 | 组件 | 状态 | 描述 | |-----------|--------|-------------| |(无对应中文)|(无对应中文)|(无对应中文)| | Azure与OpenAI的集成 | ✅ 正常工作 | 支持函数调用的GPT-4,兼容所有Azure OpenAI模型 | | Datadog MCP 客户端 | ✅ 正在运行 | 14款工具,涵盖监控、日志、应用性能管理(APM)、基础设施、事件处理 | | 认证 ✅ 工作中 | 简单的API/APP密钥设置,无需OAuth | FastAPI 服务器 | ✅ 正在运行 | 已准备就绪的异步服务器,具备错误处理功能 | | 真实数据访问 | ✅ 正常工作 | 已在真实Datadog环境中成功测试 | | 文档 | ✅ 完成 | 完整的设置指南、示例和故障排除方法 | |
安全
fastapi_server.py| ✅ 已验证 | 无硬编码凭证,正确使用环境变量 |azure_openai_mcp_agent.py包含的文件datadog_mcp_client.py- 主FastAPI应用程序服务器example_usage.py- 具备函数调用功能的Azure OpenAI代理debug_azure_config.py- Datadog MCP客户端,使用API/APP密钥认证test_datadog_mcp.py- 全面的使用示例simple_test.py- Azure OpenAI 连接测试requirements.txt- Datadog MCP连接测试.gitignore- 基本连接验证
- 所有Python依赖项
\- 凭证的安全保护
