简单MCP结构化日志服务器
一个最小的模型上下文协议(MCP)服务器,允许像Claude这样的AI代理将结构化事件记录到文件中并查询最近的日志。非常适合调试AI工作流程、创建审计跟踪和跟踪AI决策过程。
🎬 实施演示:该项目是人工智能辅助开发的完整演示。通过与Claude的对话,整个MCP服务器在大约35分钟内从头开始构建。看 docs/cursor_simple_mcp_structured_logging_se.md 为了 全面发展对话 通过测试和文档显示从初始概念到工作实现的每一步。✨ 特性
- 🔄 结构化日志记录 JSON Lines格式,便于解析
- 📅 每日日志文件 自动创建(
logs/YYYY-MM-DD.jsonl) - 🛠️ 三个简单的MCP工具 为AI代理做好准备
- 🔍 查询最近的条目 可选择按级别/计数进行过滤
- ⚡ 最小依赖性 单文件实现(约270行)
- 🧪 全面的测试套件 包含19个测试用例
🎬 AI开发演示
此存储库演示 完整的人工智能辅助软件开发 从概念到生产:
- 📝 完整对话记录:
docs/cursor_simple_mcp_structured_logging_se.md(3468行) - ⏱️ 开发时间表:从创意到GitHub仓库需要35分钟
- 🔧 包含的所有内容:规划、编码、测试、文档编制、部署
- 📊 真实日志:实际开发会话登录
logs/development-session-example.jsonl - 🎯 功能完备的:全面的测试、多平台文档、适当的包装
非常适合学习:
- 人工智能助手如何进行软件开发
- MCP服务器架构与实现
- 人工智能辅助下的快速原型制作
- 人工智能辅助编码工作流程的最佳实践
🚀 快速开始
1.克隆和设置虚拟环境
git clone mcp-structured-logging
cd mcp-structured-logging
# Create and activate virtual environment (recommended)
python -m venv venv
source venv/bin/activate # On Windows: venv\Scripts\activate
# Install dependencies
pip install -r requirements.txt2.测试服务器
# Ensure virtual environment is activated
source venv/bin/activate # On Windows: venv\Scripts\activate
# Run tests to verify everything works
python test_server.py
# Start the server (for testing)
python server.py📦 AI助手的安装
🎯 游标IDE集成
- 安装带有虚拟环境的服务器:
cd ~/Documents/mcp-servers # or your preferred location
git clone structured-logging
cd structured-logging
# Setup virtual environment
python -m venv venv
source venv/bin/activate # On Windows: venv\Scripts\activate
pip install -r requirements.txt- 通过JSON文件配置游标MCP:
全局配置 (适用于所有项目): 创建或编辑 ~/.cursor/mcp.json:
macOS/Linux:
{
"mcpServers": {
"structured-logging": {
"command": "/full/path/to/structured-logging/venv/bin/python",
"args": ["/full/path/to/structured-logging/server.py"],
"cwd": "/full/path/to/structured-logging"
}
}
}窗户:
{
"mcpServers": {
"structured-logging": {
"command": "C:\\full\\path\\to\\structured-logging\\venv\\Scripts\\python.exe",
"args": ["C:\\full\\path\\to\\structured-logging\\server.py"],
"cwd": "C:\\full\\path\\to\\structured-logging"
}
}
}项目特定配置 (仅适用于当前项目): 创建 .cursor/mcp.json 在项目根目录中使用相同的格式。
- 重新启动游标 克劳德将可以使用日志工具!
🤖 Claude AI Web界面(远程MCP)- 新
截至2025年5月,Claude AI web界面直接支持远程MCP服务器。这对大多数用户来说是最简单的方法。
- 使您的服务器可以通过HTTP访问 (用于远程访问):
# Install additional dependency for HTTP server
pip install fastapi uvicorn
# Create a simple HTTP wrapper (optional - for remote access)
# For local testing, you can skip this and use stdio transport- 通过Claude AI Web界面连接:
- 首选 克劳德·艾 并登录(需要Max、Team或Enterprise计划) - 单击您的个人资料图标→ 设置 → 集成 - 点击 “添加更多” 添加新的MCP服务器 - 对于本地测试,您可以直接使用stdio传输
- 用于本地stdio传输 (建议开发):
- 在Claude web界面中,添加您的本地服务器 - 使用与桌面相同的JSON配置格式 - Claude将自动处理stdio通信
- 测试连接:
- 开始新的聊天 - 点击 “搜索和工具” 底部的按钮 - 在可用工具中查找“结构化日志记录” - 尝试: *“记录我正在测试MCP集成的信息事件”*
🖥️ Claude桌面应用程序集成
对于喜欢桌面应用程序的用户:
- 使用虚拟环境设置服务器:
# If not already done
python -m venv venv
source venv/bin/activate # On Windows: venv\Scripts\activate
pip install -r requirements.txt- 找到Claude配置文件:
- macOS: ~/Library/Application Support/Claude/claude_desktop_config.json - 视窗: %APPDATA%\Claude\claude_desktop_config.json - Linux: ~/.config/Claude/claude_desktop_config.json
- 使用虚拟环境Python添加服务器配置:
macOS/Linux:
{
"mcpServers": {
"structured-logging": {
"command": "/full/path/to/mcp-structured-logging/venv/bin/python",
"args": ["/full/path/to/mcp-structured-logging/server.py"],
"cwd": "/full/path/to/mcp-structured-logging"
}
}
}视窗:
{
"mcpServers": {
"structured-logging": {
"command": "C:\\full\\path\\to\\mcp-structured-logging\\venv\\Scripts\\python.exe",
"args": ["C:\\full\\path\\to\\mcp-structured-logging\\server.py"],
"cwd": "C:\\full\\path\\to\\mcp-structured-logging"
}
}
}- 重新启动克劳德桌面 -工具将自动显示!
🚀 JetBrains集成开发环境(IntelliJ、PyCharm等)
对于配备AI助手的JetBrains IDE:
- 设置MCP服务器 (与上述虚拟环境设置相同)
- 在IDE中配置:
- 打开 设置 → 工具 → AI助手 → 模型上下文协议(MCP) - 或者在AI聊天中,键入 / 并选择 “添加命令”
- 添加服务器配置:
- 服务器名称: structured-logging - 命令: /full/path/to/venv/bin/python - 参数: /full/path/to/server.py - 工作目录: /full/path/to/project
- 测试集成:
- 启用 代码库模式 AI助手 - 在AI聊天中,键入 / 查看可用的MCP命令 - 尝试: /log_event 使用日志工具
🐍 Python MCP客户端
对于自定义集成或测试:
import asyncio
from mcp import ClientSession, StdioServerParameters
from mcp.client.stdio import stdio_client
async def test_logging():
server_params = StdioServerParameters(
command="python",
args=["server.py"],
cwd="/path/to/mcp-structured-logging"
)
async with stdio_client(server_params) as (read, write):
async with ClientSession(read, write) as session:
await session.initialize()
# Use the logging tools
result = await session.call_tool("log_event", {
"level": "info",
"message": "Test from Python client",
"context": {"client": "python"}
})
print(result)
asyncio.run(test_logging())🛠️ MCP工具参考
1. log_event -通用日志记录
将结构化日志条目写入每日日志文件。
参数:
level(必填):"debug","info","warn",或"error"message(必填):主日志消息context(可选):作为JSON对象的其他结构化数据
Claude中的示例用法:
“请记录用户启动了一个新的聊天会话,并提供了有关其时区的上下文”
结果:
{
"timestamp": "2025-05-24T10:30:00Z",
"level": "info",
"message": "User started new chat session",
"context": {
"timezone": "UTC-8",
"session_id": "abc123",
"user_agent": "Claude Desktop"
}
}2. log_error -错误跟踪
用详细信息和堆栈跟踪记录错误。
参数:
message(必填):错误描述error_details(必填):详细的错误信息或堆栈跟踪context(可选):关于错误发生时间/地点的其他上下文
Claude中的示例用法:
“记录错误-对天气服务的API调用失败,超时”
结果:
{
"timestamp": "2025-05-24T10:30:00Z",
"level": "error",
"message": "Weather API call failed",
"context": {
"error_details": "requests.exceptions.Timeout: HTTPSConnectionPool timeout",
"api_endpoint": "https://api.weather.com/v1/current",
"timeout_duration": "30s"
}
}3. query_logs -日志分析
从所有日志文件中查询最近的日志条目。
参数:
count(可选):要返回的条目数(默认值:50,最大值:1000)level_filter(可选):筛选条件"debug","info","warn",或"error"
Claude中的示例用法:
“显示日志中的最后10个错误条目”
退货:
{
"total_entries": 3,
"entries": [
{
"timestamp": "2025-05-24T10:30:00Z",
"level": "error",
"message": "API timeout occurred",
"context": {...}
}
]
}📊 日志条目格式
每个日志条目都以JSON对象的形式存储在一行中(JSON Lines格式):
{
"timestamp": "2025-05-24T10:30:00Z", // ISO format with timezone
"level": "info", // debug|info|warn|error
"message": "User completed checkout", // Human-readable message
"context": { // Structured metadata
"user_id": "123",
"session_id": "abc",
"amount": 29.99,
"payment_method": "stripe"
}
}📝 实际开发会话示例
此存储库包含创建此MCP服务器的开发会话的真实日志文件!看 logs/development-session-example.jsonl 对于显示以下内容的真实日志条目:
- 文档更新 随着新平台集成指南的添加
- 问题解决过程 调查日志文件位置时
- GitHub存储库设置 具有提交详细信息和进度跟踪
- 实时开发工作流程 带有时间戳和上下文
开发会议的示例条目:
{"timestamp": "2025-05-24T10:36:08.642660Z", "level": "info", "message": "Starting README update for Claude AI web interface MCP setup", "context": {"task": "documentation_update", "target": "Claude Code/AI web interface", "status": "researching_current_methods", "web_search_completed": true}}
{"timestamp": "2025-05-24T10:41:34.011941Z", "level": "info", "message": "Starting GitHub repository setup for MCP structured logging project", "context": {"task": "github_setup", "status": "initializing", "steps": ["git_init", "create_repo", "push_code"], "project_ready": true}}
{"timestamp": "2025-05-24T10:42:09.037844Z", "level": "info", "message": "Git repository initialized and first commit created", "context": {"commit_hash": "9c509c9", "files_committed": 6, "lines_added": 1273, "branch": "main", "next_step": "create_github_repo"}}这展示了MCP服务器如何实时捕获AI开发工作流程,创建有价值的审计跟踪和调试信息。 总开发时间:~35分钟 一个完整的、可工作的MCP服务器,具有全面的测试和文档!
📖 想了解完整的开发过程吗? 结账 docs/cursor_simple_mcp_structured_logging_se.md 为了 完整对话记录 (3468行)显示了开发过程的每一步,包括研究、编码、测试、文档和GitHub设置。🗂️ 文件结构
mcp-structured-logging/
├── server.py # Main MCP server (266 lines)
├── test_server.py # Comprehensive test suite (406 lines)
├── requirements.txt # Dependencies (mcp, pydantic)
├── docs/ # Implementation demo documentation
│ └── cursor_simple_mcp_structured_logging_se.md # Full development conversation (3,468 lines)
├── venv/ # Virtual environment (created by you)
│ ├── bin/python # Python interpreter for MCP config
│ └── ... # Virtual environment files
├── logs/ # Log files directory
│ ├── 2025-05-24.jsonl # Today's logs
│ ├── development-session-example.jsonl # Real development session logs
│ ├── sample.jsonl # Sample format example
│ └── ... # Historical daily files
└── README.md # This documentation🎯 实际使用示例
AI工作流调试
Claude: I'll help you debug this API issue. Let me log each step...
[Uses log_event to track each API call attempt]
[Uses log_error when calls fail]
[Uses query_logs to analyze patterns]
"I can see from the logs that all failures happen around 2pm - this suggests a rate limiting issue during peak hours."审计跟踪创建
Claude: I'll document all the changes I make to your codebase...
[Logs each file modification with context]
[Logs reasoning for each change]
[Creates searchable audit trail]
Later: "What did Claude change in the authentication module last week?"
[query_logs with appropriate filters shows all auth-related changes]性能监控
Claude: I'll track how long each operation takes...
[Logs start/end times for operations]
[Includes performance metrics in context]
[Enables analysis of slow operations]🧪 测试
运行综合测试套件:
# Run all tests (19 test cases)
python test_server.py
# Run specific test categories
python -m unittest test_server.TestCoreLoggingFunctions -v
python -m unittest test_server.TestMCPTools -v
python -m unittest test_server.TestEdgeCases -v
# Test MCP integration
python -c "
import asyncio
from server import call_tool
async def test():
result = await call_tool('log_event', {'level': 'info', 'message': 'Test'})
print('✅ MCP integration working:', result[0].text)
asyncio.run(test())
"测试覆盖范围:
- ✅ 岩心测井功能(3次测试)
- ✅ 日志读取和查询(4个测试)
- ✅ Pydantic模型验证(5次测试)
- ✅ MCP工具集成(5次测试)
- ✅ 边缘情况和错误处理(2次测试)
🔧 故障排除
虚拟环境问题
# Activate virtual environment first
source venv/bin/activate # On Windows: venv\Scripts\activate
# Verify you're in the virtual environment
which python # Should show path to venv/bin/python
pip list # Should show mcp and pydantic
# If packages missing, reinstall
pip install -r requirements.txt服务器无法启动
# Always use virtual environment Python
source venv/bin/activate # On Windows: venv\Scripts\activate
# Check Python/dependencies
python --version # Should be 3.8+
pip list | grep mcp
pip install -r requirements.txt
# Test server syntax
python -m py_compile server.py克劳德看不见工具
- 检查配置文件位置:
- 光标: ~/.cursor/mcp.json (全球)或 .cursor/mcp.json (项目) - 克劳德桌面: claude_desktop_config.json (见上文路径) - 克劳德·韦伯:设置→ 集成(web界面) - 捷脑:设置→ 工具→ AI助手→ MCP
- 验证帐户要求:
- 克劳德·韦伯:需要Max、团队或企业计划进行集成 - 其他平台:检查订阅要求
- 验证JSON语法 -使用JSON验证器检查语法错误
- 验证绝对路径 在配置中-包括venv Python路径
- 重新启动应用程序 配置更改后
- 检查日志目录权限
- 确保虚拟环境路径正确:
# Find your venv Python path
cd /path/to/mcp-structured-logging
source venv/bin/activate
which python # Copy this path to your config- 直接测试MCP服务器:
# Test that your server starts correctly
source venv/bin/activate
python server.py
# Should start without errors- 检查UI中的工具:
- 克劳德网络/桌面:查找“搜索和工具”按钮 - 光标:在聊天中查看工具可用性 - 捷脑:类型 / 在AI聊天中查看可用命令
权限问题
# Ensure logs directory is writable
chmod 755 logs/
ls -la logs/ # Should show write permissions调试模式
# Run server with verbose output for debugging
python server.py --debug # (if you add debug flag)
# Or check the logs manually
tail -f logs/$(date +%Y-%m-%d).jsonl🚧 局限性
这是一个 示范实施 专为学习、发展和POC而设计:
- ❌ 无身份验证或安全性
- ❌ 无需复杂的查询(文本搜索、日期范围)
- ❌ 无自动日志轮换或清理
- ❌ 无分布式日志记录或远程存储
- ❌ 无实时日志流
- ❌ 无日志压缩或归档
- ❌ 未针对大容量日志记录进行优化
- ❌ 基本错误处理和恢复
非常适合: 学习MCP、开发工作流程、小规模日志记录、人工智能开发演示 不适合: 企业生产系统、大容量应用程序、关键日志基础设施
对于生产使用,可以考虑强大的日志记录解决方案,如ELK堆栈、Splunk或云日志记录服务。
🏗️ 发展
建筑
- 单文件服务器 (
server.py)-易于理解和修改 - JSON行格式 -简单、可解析、仅可追加
- 每日文件轮换 -按日期自动组织
- Pydantic验证 -类型安全和输入验证
- 异步MCP协议 -与现代人工智能助手兼容
依赖项
mcp>=1.0.0-模型上下文协议框架pydantic>=2.0.0-数据验证和类型提示
扩展服务器
服务器设计为易于扩展:
# Add new log levels
VALID_LEVELS = ["debug", "info", "warn", "error", "critical"]
# Add new MCP tools
@server.call_tool()
async def call_tool(name: str, arguments: Dict[str, Any]):
if name == "your_new_tool":
# Implementation here
pass📄 许可证
MIT许可证-您可以出于任何目的自由使用、修改和分发。
______________________________________________________________________
🎯 非常适合: 人工智能开发、调试工作流程、审计跟踪和理解人工智能决策过程。
🚀 开始: 使用您的AI助手进行配置,并在5分钟内开始记录结构化事件!
