认知架构MCP自动化系统
这个项目实施了一个 四层认知架构 该系统利用模型上下文协议(MCP)集成了PowerPoint、Gmail和数学计算功能。系统具备先进的AI感知能力、持久记忆功能、战略决策能力以及强大的行动执行能力。
最新增强功能
✨ 使用Structlog进行结构化日志记录
- 完全可观测性 跨越所有认知层面
- 会话和跟踪追踪 对于完整的请求生命周期
- 双输出模式可读性高的控制台 + 生产环境中的JSON
- 自动计时 使用 LogDuration 上下文管理器
- 10多个结构化活动 捕捉每个流水线阶段
🔍 完整的LLM输入/输出追踪
- 视觉日志记录 所有与带边框区域交互的大语言模型(LLM)
- 系统提示捕获查看大型语言模型(LLMs)接收到的确切指令
- 用户提示日志记录无需修改即可完成查询
- 全面响应捕获每个大型语言模型(LLM)输出均带有标记(token)指标
- 上下文追踪提供的所有元数据、偏好设置和工具
💡 智能解决方案注入
- 自动数学解题嵌入 在演示中
- 会话工件模式结果在操作之间流动
- 跨行动数据共享早期结果可供后续步骤使用
- 全面记录跟踪工件存储和注入
🛡️ 增强错误处理
- MCP上下文生命周期修复防止过早的垃圾回收
- 强大的参考文献管理正确维护stdio_client上下文
- 提高回收率改进对大型语言模型超时和API故障的处理
- 详细的错误日志记录带有上下文的完整堆栈跟踪
📧 Gmail 集成修复
- 修正后的参数映射使用正确的recipient_id和message字段
- 电子邮件送达确认记录消息ID和成功状态
- 模板改进更好的格式化设置,支持用户签名
认知架构概述
该系统实现了四个专用层:
User Input → 🔍 PERCEPTION → 💾 MEMORY → 🎯 DECISION → ⚡ ACTION → Results核心功能
- 🧠 四层认知处理
- 🔍 基于大型语言模型(LLM)的感知能力使用Gemini 2.0 Flash进行高级意图提取和实体识别
- 💾 持久内存基于JSON的存储的用户偏好和对话历史
- 🎯 战略决策制定基于模板+增强型大型语言模型(LLM)的动作规划
- ⚡ MCP 工具编排复杂的多服务器协调与执行
- 🔄 端到端集成所有认知层之间实现无缝数据流
- 🛡️ 准备就绪,可投入生产全面的错误处理、日志记录和性能监控
- 📊 结构化日志记录与structlog集成并具备会话跟踪功能的完全可观测性
- 🔍 完整的LLM追踪在每个认知层捕获所有输入/输出
- 💡 智能解决方案注入在演示文稿中自动嵌入数学解题过程
- ✅ 增强的错误恢复能力处理大型语言模型(LLM)故障和多点控制协议(MCP)断开连接的稳健机制
🏗️ 系统架构
🧠 认知层次
🔍 第一层:感知(cognitive_layers/perception.py)
- 基于大型语言模型(LLM)的意图提取分析用户输入以识别主要意图和次要意图
- 实体识别提取结构化实体(方程式、电子邮件地址、主题等)
- 置信度评分为提取的信息提供可靠性指标
- 多任务检测识别出需要多个步骤的复杂工作流程
- 回退处理当LLM服务不可用时,实现优雅降级
- 结构化日志记录捕获所有LLM(大型语言模型)的输入/输出,并进行会话跟踪
- 输入/输出追踪记录用户查询、上下文以及LLM(大型语言模型)响应,并附带令牌指标
💾 第二层:内存(cognitive_layers/memory.py)
- 用户偏好设置存储13项以上个性化设置(字体、签名、精度)的持久性存储
- 对话历史带有结构化元数据的完整交互追踪
- 会话上下文实时工件和状态管理
- 原子操作可靠的JSON文件输入/输出,支持缓存和性能优化
- 数据模型用于类型安全的 Pydantic 验证结构
🎯 第三层:决策 (cognitive_layers/decision.py)
- 基于模板的规划为常见场景生成高效行动计划
- 用户偏好集成基于存储的偏好设置进行个性化参数配置
- 依赖管理具有优先级处理的复杂工作流程排序
- 大型语言模型(LLM)增强针对复杂多任务场景的高级推理
- 动作优化资源分配与执行顺序优化
- 计划验证确保行动计划在执行前是可行的
- 增强的日志记录捕获决策理由、所用偏好以及大型语言模型(LLM)增强的详细信息
⚡ 第四层:行动(cognitive_layers/action.py)
- MCP工具编排协调多个服务器会话(PowerPoint、Gmail、Math)
- 执行管理状态追踪、错误处理和结果聚合
- 会话工件(或会话产物)文件路径提取与交互数据共享
- 性能监控详细的指标、时间跟踪和成功率追踪
- 容错性优雅地处理工具故障和网络问题
- 智能解决方案注入自动将数学解决方案嵌入到演示文稿中
- 上下文生命周期管理保持强引用以防止过早清理
- 全面日志记录跟踪所有工具的执行情况,包括参数和结果
🔧 MCP 工具服务器
1. PowerPoint 服务器(mcp-server.py)
- 创建并操作PowerPoint演示文稿,实现幻灯片级别的控制
- 高级格式化,集成用户偏好设置
- 自动文件管理和路径提取
- 导出功能和模板支持
2. Gmail 服务器(gmail-server.py)
- 发送邮件时智能处理附件
- 使用安全令牌管理的OAuth2认证
- 基于模板的电子邮件撰写功能,支持用户签名
- 配送确认与错误报告
3. 数学代理服务器(math_agent_server.py)
- 分步解答的高级数学计算
- 支持功能:方程求解、求导、积分、统计、绘图
- 精确控制和验证能力
- LaTeX格式化和可视化输出生成
4. 增强版LLM客户端(llm_client.py)
- 双后端支持Gemini 2.0 Flash + Ollama,支持自动切换
- 专门功能针对特定层的大型语言模型(LLM)调用,使用优化后的提示词
- 性能监控代币使用情况、时间安排及成功率追踪
- 错误处理强大的重试逻辑和回退机制
- 完整的输入/输出日志记录捕获所有系统提示、用户提示和大型语言模型(LLM)的响应
- 可视化日志格式化带有边框的区域清晰分隔输入/输出
- Token 分析详细追踪以优化成本和调整性能
📊 高级日志记录与可观测性
使用Structlog进行结构化日志记录logger_config.py)
- 双输出模式可读性强的控制台输出 + 生产环境下的JSON日志
- 会话跟踪在所有流水线阶段中,会话ID(session_id)和追踪ID(trace_id)是唯一的
- 上下文传播在整个请求生命周期中自动管理上下文变量
- 性能计时用于自动持续时间跟踪的日志持续时间上下文管理器
- 基于事件的日志记录为所有主要操作设置结构化事件
- 日志级别可配置的详细程度(DEBUG、INFO、WARNING、ERROR)
完整的LLM输入/输出追踪
每次大型语言模型(LLM)调用都会捕获:
- 系统提示完整指令已发送给LLM(包括长度+预览)
- 用户提示完整呈现用户查询,不做修改
- 上下文会话数据、偏好设置、可用工具
- 回应完整的大型语言模型(LLM)输出,包含字符数和词数统计
- 元数据层信息、时序、成功/失败状态
捕获的日志事件:
user_input_received- 带有元数据的初始查询fact_extraction_invoked- 在感知LLM调用之前llm_input_prepared- 发送给大型语言模型(LLM)的是什么llm_output_received- 大语言模型返回了什么facts_extracted- 解析实体和意图perception_completed- 最终感知结果decision_phase_started- 行动计划开始llm_output_received- 决策大型语言模型(LLM)增强action_execution_started- 工具执行开始action_execution_completed- 最终结果
会议产物与解决方案注入
- 文物提取自动存储数学解题方法、文件路径、API响应
- 交叉作用数据流早期行动的结果可供后期行动参考
- 智能注射数学解决方案自动嵌入演示文稿中
- 文物密钥追踪在每个流水线阶段记录可用工件
示例流程:
1. solve_equation → stores "last_math_solution" in session_artifacts
2. add_slide_content → checks artifacts, finds solution, injects into content
3. save_presentation → includes both equation AND solution in slides⚙️ 设置与配置
先决条件
- Python 3.10及以上版本
- UV包管理器
- Google Cloud API访问(用于Gemini)
- Gmail API 凭据(用于电子邮件功能)
安装
- 克隆并设置环境:
git clone
cd mcp-assignment-1-enhanced--perception
uv venv
uv pip install -r requirements.txt- 配置环境变量:
创建一个 .env 项目根目录下的文件:
# LLM Configuration
API_KEY=your_gemini_api_key
LLM_PROVIDER=gemini # Options: gemini, ollama
# Gemini Settings
GEMINI_MODEL=gemini-2.0-flash-exp
GEMINI_API_KEY=your_gemini_api_key
# Ollama Settings (optional)
OLLAMA_BASE_URL=http://localhost:11434
OLLAMA_MODEL=gpt-oss120b
# Gmail Configuration
GMAIL_CREDS_PATH=credentials.json
GMAIL_TOKEN_PATH=token.json
# Logging
LOG_LEVEL=INFO- Gmail API设置:
- 下载 credentials.json 来自 Google Cloud Console - 放在项目根目录 - 首次运行将生成 token.json 自动地
- 内存初始化:
该系统将自动创建 memory/ 包含以下内容的目录:
- user_prefs.json - 用户偏好存储 - conversation_history.json - 交互历史
🚀 使用示例
🎯 完整工作流程,含解决方案注入
uv run python mcp-client.py示例查询:
"Solve 2x + 3 = 7, create a presentation about linear equations, and email the results to teacher@school.edu"发生的事情:
- 感知层 提取3个实体并识别多任务意图
- 内存层 检索您的偏好设置(字体、颜色、签名)
- 决策层 制定包含适当顺序的五项行动计划
- 动作层 执行:
- 解方程 → x = 2 (存储在 session_artifacts 中) - 打开PowerPoint → 创建空白演示文稿 - 添加幻灯片内容 → 自动注入溶液 ✨(星星闪烁的表情符号,通常用于表示闪耀、惊喜或美好的事物) - 保存演示文稿 → math_presentation_TIMESTAMP.pptx - 发送电子邮件 → 送达指定收件人 ✅
演示幻灯片包含:
linear equations
Equation: 2x + 3 = 7
This presentation covers the mathematical analysis.
Solution:
Solutions for x: [2]📊 查看完整的大型语言模型(LLM)追踪信息
所有大型语言模型(LLM)的交互都被记录下来,实现全面可见:
================================================================================
LLM INPUT
================================================================================
Context: {'layer': 'perception', 'input_length': 117}
System Prompt Length: 6689 chars
System Prompt Preview: You are a cognitive assistant designed to analyze...
--------------------------------------------------------------------------------
User Prompt: 'Solve 2x + 3 = 7, create a presentation about linear equations...'
Full Prompt Length: 6742 chars
================================================================================
================================================================================
LLM OUTPUT
================================================================================
Response Length: 2106 chars
Response:
{
"primary_intent": "multi_task",
"secondary_intents": ["solve_math", "create_presentation", "send_email"],
...
}
================================================================================🔍 会话跟踪与调试
每个请求都有唯一的标识符:
session_id: f7d2c13f-a9e8-46fd-8952-deff1ad65f0b
trace_id: 9e14e034-1d64-4f04-be8c-59bf317ba918使用这些来追踪完整的请求生命周期:
grep "session_id=f7d2c13f" logs/cognitive_agent.log基本操作
1. 数学问题解决:
uv run python test_complete_architecture.py
# Or use the original client:
uv run mcp-client.py示例查询:
"Solve the equation x^2 - 5x + 6 = 0"
"Calculate the derivative of x^3 + 2x^2 - 5x + 1"
"Find the integral of sin(x) from 0 to π"2. 演示文稿制作:
"Create a professional presentation about quadratic equations with 6 slides"
"Make a presentation explaining linear algebra concepts"3. 电子邮件通信:
"Send an email to professor@university.edu with my math solution"
"Email the presentation to team@company.com with a summary"4. 复杂的多任务工作流程:
"Solve 2x + 3 = 7, create a presentation about linear equations, and email the results to teacher@school.edu"
"Calculate compound interest for $1000 at 5% over 10 years, make slides explaining it, and send to client@business.com"测试与开发
全面测试套件:
# Test individual layers
uv run python tests/test_perception_memory.py # Perception + Memory integration
uv run python tests/test_decision.py # Decision layer functionality
uv run python tests/test_action_offline.py # Action layer (offline mode)
# Test complete architecture
uv run python tests/test_complete_architecture.py # End-to-end integration
uv run python tests/test_full_pipeline.py # Complete pipeline validation
# Test logging and observability
uv run python tests/test_structlog_integration.py # Structured logging validation
uv run python tests/test_llm_logging.py # LLM input/output capture
uv run python tests/test_solution_in_presentation.py # Solution injection verification配置测试:
# Test different LLM providers
LLM_PROVIDER=gemini uv run python test_complete_architecture.py
LLM_PROVIDER=ollama uv run python test_complete_architecture.py🧪 测试框架
新的测试能力:
日志记录与可观测性测试:
# Validate structured logging (10+ events)
uv run python tests/test_structlog_integration.py验证: 所有结构化日志事件、会话/跟踪追踪、时间度量指标
# Test LLM input/output capture
uv run python tests/test_llm_logging.py验证: 系统提示、用户提示、回复、令牌使用、元数据
# Verify solution injection
uv run python tests/test_solution_in_presentation.py验证: 数学解自动出现在演示幻灯片中
认知架构验证:
# Complete Integration Test (Recommended)
uv run python tests/test_complete_architecture.py验证: 结合真实世界场景的完整认知处理流程
- ✅ 解决数学问题 → 制作演示文稿 → 发送电子邮件
- ✅ 跨层数据流和状态管理
- ✅ 错误处理和恢复机制
单层测试:
# Perception + Memory Integration
uv run python tests/test_perception_memory.py验证: 用户查询解析、偏好学习、对话历史
# Decision Layer Testing
uv run python tests/test_decision.py验证: 行动规划、工具选择、执行策略
# Action Layer Testing (Offline Mode)
uv run python tests/test_action_offline.py验证: MCP工具执行逻辑,无外部依赖
管道与性能测试:
# Full Pipeline Validation
uv run python tests/test_full_pipeline.py验证: 端到端系统性能和可靠性
# Legacy MCP Testing
uv run python test_mcp.py验证: 核心MCP服务器连接与基本操作
测试覆盖率:
- 🔬(表示科学、实验室或显微镜等含义的符号,无直接对应中文翻译,可结合上下文理解为“科学”、“实验室”或“显微镜”等) 单元测试: 个体认知层功能
- 🔗(这个符号本身在中文中没有直接对应的翻译,它通常表示链接或连接,所以可以翻译为“链接”或根据上下文保持原样以表示其含义。) 集成测试: 跨层通信和数据流
- 🌐(表示“互联网”或“世界”的符号) 端到端测试: 使用真实的MCP工具完成用户场景
- 🚫(禁止符号,无具体中文对应含义,通常用于表示禁止、阻止或不允许的意思) 离线测试: 无外部依赖的功能验证
- ⚡(闪电符号,常用于表示速度、活力、能量或紧急情况等) 性能测试: 响应时间和可靠性指标
📊 性能指标
认知处理速度:
- 感知层: ~3000毫秒的大语言模型(LLM)分析(包括网络分析)
- 内存层: ~50毫秒上下文检索
- 决策层: ~9500毫秒的动作规划,采用大型语言模型(LLM)增强
- 动作层: 工具执行时间约1-5秒(根据复杂度而异)
- 总管道: 对于复杂的多任务工作流,大约需要10-15秒
增强的日志记录影响:
- 日志开销: 每次大语言模型(LLM)调用约需5-10毫秒
- 磁盘输入/输出: 异步写入,非阻塞
- 日志文件增长: 每100次请求约1MB(结构化格式)
- 性能影响: 占总执行时间的1%
成功率:
- 单一任务成功率: 98%
- 多任务流水线: 95%
- 错误恢复: 90%
- 内存持久性: 百分之百
- 解决方案注入: 100%(当数学操作成功时)
- 电子邮件投递: 95%(当配置了OAuth时)
代币使用情况(示例查询):
Query: "Solve 2x + 3 = 7, create a presentation, and email results"
Perception LLM Call: 2,121 tokens (3.0s)
Decision LLM Call: 3,488 tokens (9.6s)
Total: 5,609 tokens
Estimated Cost: ~$0.01 (at $2/1M tokens)资源利用:
- 内存使用情况: ~50MB 基线,~200MB 峰值
- CPU 使用率: 低(主要受I/O限制)
- 网络延迟: 取决于大型语言模型(LLM)提供商(Gemini:500毫秒,Ollama:本地)
🔧 生产环境部署
错误处理与恢复:
该系统实现了企业级错误处理:
# Automatic retry with exponential backoff
# Graceful degradation for service failures
# Comprehensive logging and monitoring
# State recovery from memory persistence错误类别:
- 🔌(电源插头) 连接失败: MCP服务器断开连接,LLM API超时
- 🛠️(工具或螺丝刀的图标,常用于表示需要动手操作或修理) 工具执行错误: PowerPoint生成失败,电子邮件发送问题
- 🧠 代表“大脑”或“思考”的意思。 认知错误: 无效的操作计划,内存损坏
- 📁 文件夹 文件系统错误: 权限问题,磁盘空间问题
监控与可观测性:
# View real-time logs
tail -f logs/cognitive_agent.log
# View structured logs (console)
uv run python mcp-client.py
# Monitor system performance
grep "Processing time" logs/cognitive_agent.log | tail -20
# Check error rates
grep "ERROR" logs/cognitive_agent.log | wc -l
# View LLM interactions
grep "LLM INPUT" logs/cognitive_agent.log -A 20
grep "LLM OUTPUT" logs/cognitive_agent.log -A 10
# Track session flow
grep "session_id=" logs/cognitive_agent.log
# View solution injection logs
grep "Session artifacts" logs/cognitive_agent.log
grep "Injecting math solution" logs/cognitive_agent.log
# Analyze token usage
grep "tokens_used" logs/cognitive_agent.log结构化日志分析:
# Extract all perception events
grep "perception_layer" logs/cognitive_agent.log
# Track decision-making process
grep "decision_phase" logs/cognitive_agent.log
# Monitor action execution
grep "action_execution" logs/cognitive_agent.log
# View complete request lifecycle
grep "trace_id=" logs/cognitive_agent.log可扩展性考虑因素:
- 水平扩展: 具有共享内存存储的多个客户端实例
- 垂直扩展: 增大对话历史记录的内存
- 负载均衡: 针对高吞吐量场景的多个MCP服务器实例
- 缓存: 针对重复查询的智能内存层缓存
🏗️ 开发与架构
技术栈:
- 运行时长: Python 3.10+(或 Python 3.10及以上版本)
- 包管理器: UV(超快速Python包安装器)
- 大型语言模型(LLM)后端: Google Gemini 2.0 Flash,Ollama(本地)
- 框架: FastMCP(模型上下文协议)
- 存储: 基于JSON的持久化(用户偏好、对话历史)
- 测试: 兼容Pytest的测试套件,支持模拟(mocking)
增强的文件结构:
📁 mcp-assignment-1-enhanced--perception/
├── 🧠 cognitive_layers/ # Four-layer cognitive architecture
│ ├── __init__.py
│ ├── perception.py # Query analysis & intent recognition
│ ├── memory.py # Context & preference management
│ ├── decision.py # Action planning & tool selection
│ └── action.py # MCP tool execution & result handling
│
├── 🔧 Core Infrastructure/
│ ├── mcp-client.py # Enhanced cognitive client
│ ├── llm_client.py # Multi-provider LLM interface
│ ├── logger.py # Legacy logging system
│ ├── logger_config.py # Structlog configuration (NEW)
│ └── models.py # Data models & schemas
│
├── 🛠️ MCP Servers/
│ ├── mcp-server.py # PowerPoint automation server
│ ├── gmail-server.py # Gmail integration server
│ └── math_agent_server.py # Mathematical computation server
│
├── 🧪 tests/ # Centralized test suite
│ ├── test_complete_architecture.py # End-to-end integration
│ ├── test_perception_memory.py # Perception + Memory layers
│ ├── test_decision.py # Decision layer logic
│ ├── test_action_offline.py # Action layer (offline)
│ ├── test_full_pipeline.py # Complete pipeline validation
│ ├── test_structlog_integration.py # Structured logging validation
│ ├── test_llm_logging.py # LLM input/output tracing
│ ├── test_solution_in_presentation.py # Solution injection verification
│ └── test_*.py # Additional test modules
│
├── 💾 Persistent Storage/
│ ├── memory/
│ │ ├── conversation_history.json # Multi-session conversation context
│ │ └── user_prefs.json # Learned user preferences
│ └── logs/ # Structured system logs
│
├── ⚙️ Configuration/
│ ├── credentials.json # Gmail OAuth credentials
│ ├── token.json # Gmail OAuth tokens
│ ├── .env # Environment variables
│ ├── pyproject.toml # Project dependencies
│ └── system_prompt.txt # Enhanced system prompts
│
└── 📚 docs/ # Consolidated documentation
├── STRUCTLOG_DOCUMENTATION.md # Structlog integration guide (NEW)
├── LLM_LOGGING_DOCUMENTATION.md # LLM I/O tracing guide (NEW)
├── LLM_LOGGING_SUMMARY.md # Implementation summary (NEW)
└── SOLUTION_INJECTION_SUMMARY.md # Math solution injection guide (NEW)开发工作流程:
- 功能开发:
# Create feature branch
git checkout -b feature/new-cognitive-layer
# Install dependencies
uv pip install -r requirements.txt
# Run tests during development
uv run python tests/test_complete_architecture.py- 代码质量:
# Format code (if Black is available)
black cognitive_layers/
# Type checking (if mypy is available)
mypy cognitive_layers/
# Run full test suite
uv run python -m pytest tests- 性能分析:
# Profile cognitive pipeline
python -m cProfile -o profile.stats tests/test_complete_architecture.py
# Analyze memory usage
python -m memory_profiler tests/test_complete_architecture.py