MicroTools MCP Showcase:一个完整的LangGraph代理系统
具有模型上下文协议(MCP)工具集成、Redis支持的内存和本地LLM支持的4节点LangGraph代理的生产就绪演示。
目录
- 概述
- 建筑
- 特性
- 安装
- 快速开始
- 配置
- 使用指南
- api参考
- 发展
- 测试
- 部署
- 故障排除
- 贡献
概述
该项目展示了一个使用LangGraph构建的完整AI代理系统,该系统展示了基于工具的AI交互的现代模式。该系统由两个主要部分组成:
- MCP服务器:一个基于FastAPI的安全服务器,提供工具功能
- LangGraph代理:智能选择和执行工具的4节点工作流
该项目既是一个工作演示,也是一个参考实现,用于构建具有适当内存管理、错误处理和可观察性的生产就绪AI代理系统。
建筑
系统组件```mermaid
graph TB
User[👤 User] --> Agent[🤖 LangGraph Agent]
Agent --> LLM[🧠 Local LLM Server]
Agent --> MCP[🔧 MCP Tool Server]
Agent --> Redis[💾 Redis Memory]
MCP --> Tools[⚙️ Tool Implementations]
subgraph "Agent Workflow"
P[📋 Planner] --> E[⚡ Executor]
E --> M[💾 Memory]
M --> R[💬 Responder]
R --> P
end
### 4节点LangGraph工作流
代理遵循具有条件循环的线性管道:
1. **计划节点** (`planner_node`)
- 使用本地LLM分析用户请求
- 创建结构化的工具执行计划
- 通过智能回退处理JSON解析失败
- 整合对话记忆,实现情境感知规划
1. **工具执行器节点** (`tool_executor_node`)
- 通过HTTP验证和执行计划的工具调用
- 支持并行工具执行和结果链
- 全面的错误处理和重试逻辑
- 实时进度指标
1. **内存更新程序节点** (`memory_updater_node`)
- 将对话状态持久化到Redis
- 自动提取实体和关键事实
- 维护对话历史和上下文
- 内存存储性能下降
1. **响应程序节点** (`responder_node`)
- 使用LLM生成自然语言响应
- 无缝集成工具结果
- 检测会话流的后续意图
- 提供用户友好的错误消息
### 项目结构```
tiny-tools-mcp-showcase/
├── app/ # MCP Server (FastAPI)
│ ├── main.py # FastAPI app with security & rate limiting
│ ├── manifest.py # Tool capability discovery
│ ├── tools/
│ │ ├── schemas.py # Pydantic validation models
│ │ └── impl.py # Tool implementation engine
│ └── tests/
│ └── test_tools.py # Comprehensive MCP server tests
├── agent/ # LangGraph Agent
│ ├── workflow.py # Main orchestrator & CLI interface
│ ├── nodes.py # 4-node implementation
│ ├── edges.py # Conditional routing logic
│ ├── memory.py # Redis-backed conversation memory
│ ├── prompt_fragments.py # LLM prompt templates
│ └── tests/
│ └── test_agent.py # Agent workflow tests
├── logs/ # Execution traces & debugging
├── docker-compose.yml # Multi-service orchestration
├── Dockerfile # MCP server containerization
├── Makefile # Development automation
└── pyproject.toml # Project configuration & dependencies
特性
🚀 核心能力
- 智能刀具选择:LLM驱动的效率优化规划
- 对话记忆:Redis支持具有自动回退功能的持久状态
- 本地LLM集成:与LM Studio、Ollama和OpenAI兼容的服务器兼容
- 安全MCP服务器:速率限制、CORS、身份验证和输入验证
- 丰富的终端用户界面:清洁进度指标和错误处理
- 综合录井:用于调试和监控的JSON执行跟踪
🛠️ 可用工具
| 工具 | 说明 | 使用示例 |
|---|---|---|
clock.now |
获取当前时间 | “现在几点了?” |
clock.shift |
用偏移量计算时间 | “2小时后会是什么时间?” |
🔧 技术特性
- 类型安全:在整个堆栈中进行完整的Pydantic验证
- 异步/等待:无阻塞操作,实现最佳性能
- 错误恢复:妥善处理LLM、工具和网络故障
- 会话管理:具有重置功能的孤立对话
- 可扩展设计:轻松添加新工具和功能
- 生产就绪:Docker支持、健康检查和监控
安装
先决条件
- Python 3.10+ 使用pip
- 本地LLM服务器 (LM Studio、Ollama或OpenAI兼容)
- 码头工人 (可选,用于Redis和容器化部署)
- 雷迪斯 (可选,用于持久内存)
方法1:地方发展(推荐)
- 克隆存储库:```bash
git clone
cd tiny-tools-mcp-showcase
1. **安装依赖项**:```bash
pip install -e .
- 启动Redis(可选但推荐):```bash
Using Docker
docker run -d --name redis -p 6379:6379 redis:alpine
Or using Docker Compose
docker-compose up -d redis
### 方法二:Docker开发
1. **克隆和启动服务**:```bash
git clone
cd tiny-tools-mcp-showcase
docker-compose up -d
快速开始
1.开始你的本地LLM
确保在上运行本地LLM服务器 http://127.0.0.1:1234:
- LM工作室:下载并启动模型服务器
- 没有:
ollama serve使用您喜欢的型号 - 其他:任何与OpenAI兼容的API服务器
2.启动MCP服务器```bash
Local development
python -m uvicorn app.main:app --host 0.0.0.0 --port 7443 --reload
Or using Make
make start-server
Or using Docker
docker-compose up -d mcp
### 3.测试MCP服务器(可选)```bash
# Health check
curl http://localhost:7443/health
# Get tool manifest
curl http://localhost:7443/mcp/manifest
# Execute a tool
curl -X POST http://localhost:7443/mcp/tool.execute \
-H "Content-Type: application/json" \
-d '{"capability": "clock.now", "args": {}}'
4.运行代理```bash
Interactive terminal interface
python agent/workflow.py
Or using Make
make demo
Or programmatically
python -c "
import asyncio
from agent.workflow import run_agent
result = asyncio.run(run_agent('What time is it?'))
print(result)
"
### 5.尝试示例查询```
💬 What time is it?
🧠🔧 ✓ 1 tools
🤖 It's currently 2:30 PM.
💬 What time will it be in 90 minutes?
🧠🔧💾💬 ✓ 2 tools
🤖 In 90 minutes, it will be 4:00 PM.
💬 I have a meeting after 2 hours when will it be
🧠🔧💾💬 ✓ 2 tools
🤖 Your meeting will be at 4:30 PM.
💬 quit
👋 Goodbye!
配置
环境变量
| 变量 | 默认值 | 描述 |
|---|---|---|
LLM_URL |
http://127.0.0.1:1234 |
本地LLM服务器端点 |
REDIS_URL |
redis://localhost:6379 |
Redis连接字符串 |
MCP_API_KEY |
demo-key-change-in-production |
MCP服务器的可选API密钥 |
PYTHONPATH |
/app |
Python模块路径(适用于Docker) |
本地LLM配置
该代理已与多家本地LLM提供商进行了测试:
- LM工作室:使用与OpenAI兼容的API的任何聊天模型
- 没有:模型如
llama2,mistral,codellama - 文本生成WebUI:启用了OpenAI扩展
- vLLM:高性能推理服务器
Redis配置
Redis用于自动回退的会话内存:
- 使用Redis:重启后持续对话
- 没有Redis:内存存储(警告是正常的)
- 生存时间:24小时自动会话清理
使用指南
交互式终端界面
主界面是一个干净的终端对话:```bash
python agent/workflow.py
**命令**:
- 自然地键入您的问题
- `!reset` -清除对话记忆
- `quit`, `exit`, `bye` -结束对话
### 程序化使用```python
import asyncio
from agent.workflow import TinyToolsAgent, run_agent
# Single interaction
async def example():
result = await run_agent("What time is it?", session_id="user123")
print(result["bot_response"])
# Agent instance
async def conversation():
agent = TinyToolsAgent()
# Single message
result = await agent.run_single("What time is it?", "session123")
# Interactive conversation
await agent.run_conversation("session123")
asyncio.run(example())
工具使用模式
时间查询```
"What time is it?" → Uses clock.now (1 tool)
"What time will it be in 2 hours?" → Uses clock.now + clock.shift (2 tools)
"I have a meeting in 45 minutes when will it be" → Uses both tools
#### 对话流程```
User: What time is it?
🧠🔧 ✓ 1 tools
Bot: It's 2:30 PM.
User: What about in 30 minutes?
🧠🔧💾💬 ✓ 2 tools
Bot: In 30 minutes, it will be 3:00 PM.
api参考
MCP服务器端点
| 端点 | 方法 | 描述 |
|---|---|---|
/ |
GET | 服务器信息和端点列表 |
/health |
GET | 用于监控的健康检查 |
/mcp/manifest |
GET | 完整的工具能力清单 |
/mcp/capabilities/summary |
GET | 提示的简要能力总结 |
/mcp/tool.execute |
POST | 执行带有验证的工具 |
代理API```python
Main classes
from agent.workflow import TinyToolsAgent
from agent.nodes import AgentState
from agent.memory import ConversationMemory
Convenience functions
from agent.workflow import run_agent, start_conversation
### 工具执行响应格式```json
{
"success": true,
"result": {
"current_time": "2:30 PM",
"timestamp": "2024-01-15T14:30:00"
},
"error": null,
"execution_time_ms": 5.2
}
发展
设置开发环境```bash
Install in development mode
make dev
Or manually
pip install -e ".[dev]"
### 运行测试```bash
# Run all tests
make test
# Run with coverage
make test-coverage
# Run specific test files
pytest app/tests/test_tools.py -v
pytest agent/tests/test_agent.py -v
代码质量```bash
Format code
make format
Lint code
make lint
Type checking
mypy app/ agent/
### 添加新工具
1. **定义架构** 在……里面 `app/tools/schemas.py`:```python
class NewToolArgs(BaseModel):
param: str = Field(description="Tool parameter")
class NewToolResult(BaseModel):
result: str = Field(description="Tool result")
- 机具功能 在……里面
app/tools/impl.py:```python
def execute_new_tool(args: NewToolArgs) -> NewToolResult:
return NewToolResult(result=f"Processed: {args.param}")
1. **注册工具** 在架构注册表中:```python
TOOL_SCHEMAS["new.tool"] = {
"args": NewToolArgs,
"result": NewToolResult,
"description": "Description of new tool",
"cost_estimate": 0.1,
"avg_latency_ms": 10.0
}
- 添加实现 注册:```python
TOOL_IMPLEMENTATIONS["new.tool"] = execute_new_tool
1. **编写测试** 在……里面 `app/tests/test_tools.py`
### 开发命令```bash
# Start MCP server in development mode
make start-mcp
# Start agent in development mode
make start-agent
# Clean build artifacts
make clean
# Build Docker images
make docker-build
# Start full stack with Docker
make docker-up
测试
测试结构```
tests/
├── app/tests/
│ └── test_tools.py # MCP server tests
└── agent/tests/
└── test_agent.py # Agent workflow tests
### 运行测试```bash
# All tests
pytest
# Specific test file
pytest app/tests/test_tools.py::TestToolImplementations::test_clock_now_tool
# With coverage
pytest --cov=app --cov=agent --cov-report=html
# Async tests
pytest -v -s agent/tests/test_agent.py
测试类别
- 单元测试:单个组件测试
- 集成测试:组件交互测试
- API测试:HTTP端点测试
- 工作流测试:端到端代理测试
部署
Docker部署```bash
Build and start all services
docker-compose up -d
Scale services
docker-compose up -d --scale mcp=2
View logs
docker-compose logs -f mcp
### 生产注意事项
1. **安全**:
- 更改默认API密钥
- 配置正确的CORS源
- 在生产环境中使用HTTPS
- 设置正确的身份验证
1. **监控**:
- 健康检查端点
- 执行跟踪日志记录
- 绩效指标收集
- 错误率监控
1. **扩展**:
- Redis集群实现高可用性
- MCP服务器的负载平衡
- 代理实例的横向扩展
### 环境特定配置```bash
# Development
export LLM_URL="http://localhost:1234"
export REDIS_URL="redis://localhost:6379"
# Production
export LLM_URL="https://your-llm-server.com"
export REDIS_URL="redis://your-redis-cluster:6379"
export MCP_API_KEY="your-secure-api-key"
故障排除
常见问题
1.LLM连接问题```
Error: Error calling local LLM: Connection refused
**解决方案**:确保您的本地LLM服务器在正确的端口上运行。
#### 2.MCP服务器没有响应```
Warning: Could not fetch tool manifest
解决方案:启动MCP服务器,检查端口7443是否可用。
3.Redis连接警告```
Warning: Redis not available, using in-memory storage
**解决方案**:启动Redis或忽略(内存回退工作正常)。
#### 4.工具执行失败```
⚠ 0/1 tools
解决方案:检查MCP服务器日志,确保工具已正确注册。
5.JSON解析错误```
Planning failed: Invalid JSON response
**解决方案**:代理对此有内置的回退逻辑。检查LLM配置。
### 调试模式
启用详细日志记录:```python
import logging
logging.basicConfig(level=logging.DEBUG)
日志分析
执行跟踪保存在 logs/trace-{session}-{timestamp}.json:json
{
"session_id": "abc123",
"timestamp": "2024-01-15T14:30:00",
"user_message": "What time is it?",
"bot_response": "It's 2:30 PM",
"execution_summary": {
"planning_success": true,
"execution_success": true,
"tools_executed": 1
},
"plan": [...],
"tool_results": [...]
}
性能调整
- LLM设置:
- 调整温度(0.1以获得一致的结果)
- 为您的用例优化max_tokens
- 考虑模型尺寸与速度的权衡
- Redis优化:
- 根据对话模式调整TTL
- 监控内存使用情况
- 考虑Redis集群的规模
- 工具执行:
- 实现独立工具的并行执行
- 为昂贵的操作添加缓存
- 监控执行时间并优化慢速工具
贡献
我们欢迎捐款!请参阅我们的投稿指南:
- 分叉存储库
- 创建要素分支:
git checkout -b feature/amazing-feature - 进行更改 进行适当的测试和记录
- 运行测试套件:
make test - 提交拉取请求
开发工作流程
- 问题:通过GitHub问题报告错误或请求功能
- 拉取请求:遵循PR模板并确保测试通过
- 代码审查:所有更改在合并前都需要审查
- 文档:更新任何新功能的文档
代码的风格
- Python代码遵循PEP 8
- 全程使用类型提示
- 编写全面的文档字符串
- 添加新功能的测试
- 保持功能集中和小型化
许可证
此项目根据MIT许可证获得许可-请参阅 许可证 文件以获取详细信息。
致谢
- LangGraph 对于工作流框架
- 快速 API 对于web框架
- 派丹蒂克 用于数据验证
- 雷迪斯 用于内存持久性
- 富有的 用于终端UI
内置于❤️ 面向AI代理社区
