ZeroDB代理内存MCP服务器
AI代理的持久内存
优化的MCP服务器提供14个工具,用于代理内存管理、上下文合成、自动上下文中间件和向外部服务回写操作。
为什么选择MCP?
之前: 使用77个工具的单片服务器,消耗10400多个令牌
之后: 使用14个工具的集中式服务器,消耗约1400个令牌
结果:
减少87% 在上下文足迹方面,更快的代理决策,更好的准确性
主要特点
智能上下文管理
- 自动令牌限制 -永远不要超过LLM上下文窗口
- 智能修剪 -保留重要和最近的记忆
- 记忆衰退 -旧记忆会随着时间的推移而自然消失
- 重要性评分 -自动对内存重要性进行排序
语义记忆
- 矢量嵌入 -BAAI BGE型号(384、768、1024尺寸)
- 语义搜索 -按含义查找,而不仅仅是关键字
- 跨会话内存 -在对话中记住
- 自动嵌入 -无需手动嵌入
通用兼容性
- 零本地 -本地主机:8000(快速、免费、私有)
- ZeroDB云 -api.anative.studio(可扩展、可管理)
- 自动检测 -自动查找可用端点
安装```bash
Clone repository
git clone https://github.com/ainative/zerodb-memory-mcp.git
cd zerodb-memory-mcp
Install dependencies
npm install
Configure environment
cp .env.example .env
Edit .env with your credentials
Test locally
npm start
## 配置
### 凭证```bash
# Recommended: API key auth (no login needed)
ZERODB_API_KEY=sk_xxx
ZERODB_API_URL=https://api.ainative.studio
ZERODB_PROJECT_ID=your-project-id
# OR username/password auth:
ZERODB_USERNAME=your@email.com
ZERODB_PASSWORD=your-password
ZERODB_API_URL=https://api.ainative.studio
ZERODB_PROJECT_ID=your-project-id
> 提示: API密钥验证(ZERODB_API_KEY)比用户名/密码更可取。它避免了令牌到期问题,不受shell环境变量冲突的影响。
选项1:环境变量```bash
export ZERODB_API_URL="http://localhost:8000" # or cloud URL
export ZERODB_API_KEY="sk_your-api-key" # recommended
export ZERODB_PROJECT_ID="your-project-id"
### 选项2:Claude桌面配置```json
{
"mcpServers": {
"zerodb-memory": {
"command": "node",
"args": ["/path/to/zerodb-memory-mcp/index.js"],
"env": {
"ZERODB_API_URL": "http://localhost:8000",
"ZERODB_USERNAME": "your-username",
"ZERODB_PASSWORD": "your-password",
"ZERODB_PROJECT_ID": "your-project-id"
}
}
}
}
选项3:同时使用本地和云```json
{
"mcpServers": {
"zerodb-local": {
"command": "node",
"args": ["/path/to/zerodb-memory-mcp/index.js"],
"env": {
"ZERODB_API_URL": "http://localhost:8000",
"ZERODB_USERNAME": "your-local-username",
"ZERODB_PASSWORD": "your-local-password",
"ZERODB_PROJECT_ID": "your-local-project-id"
}
},
"zerodb-cloud": {
"command": "node",
"args": ["/path/to/zerodb-memory-mcp/index.js"],
"env": {
"ZERODB_API_URL": "https://api.ainative.studio",
"ZERODB_USERNAME": "your-cloud-username",
"ZERODB_PASSWORD": "your-cloud-password",
"ZERODB_PROJECT_ID": "your-cloud-project-id"
}
}
}
}
## 工具
### 1. `zerodb_store_memory`
通过自动重要性评分和嵌入来存储对话上下文。
**输入:**```json
{
"content": "User prefers technical explanations over simplified ones",
"role": "system",
"session_id": "chat-123",
"tags": ["preference", "important"],
"user_id": "user-456"
}
输出:```json
{
"success": true,
"memory_id": "mem_abc123",
"importance": 0.85,
"message": "Memory stored successfully"
}
**特征:**
- 自动计算重要性(0.0到1.0)
- 自动生成嵌入
- 支持分类标签
- 链接到用户以获取跨会话内存
______________________________________________________________________
### 2. `zerodb_search_memory`
使用自然语言在语义上搜索内存。
**输入:**```json
{
"query": "What are the user's dietary restrictions?",
"limit": 10,
"session_id": "chat-123",
"scope": "agent",
"min_importance": 0.5
}
输出:```json
{
"results": [
{
"content": "User is allergic to peanuts",
"role": "user",
"importance": 0.95,
"timestamp": "2026-02-28T10:30:00Z",
"tags": ["health", "critical"],
"similarity": 0.89,
"session_id": "chat-123"
}
],
"count": 1,
"scope": "agent"
}
**特征:**
- 语义搜索(意义,而非关键字)
- 跨会话搜索 `scope: "agent"`
- 按重要性、标签、用户筛选
- 返回相似性得分
______________________________________________________________________
### 3. `zerodb_get_context`
通过智能修剪获得完整的对话上下文。
**输入:**```json
{
"session_id": "chat-123",
"max_tokens": 8192,
"include_stats": true
}
输出:```json
{
"memories": [
{
"content": "Hello, how can I help?",
"role": "assistant",
"importance": 0.6,
"timestamp": "2026-02-28T10:00:00Z",
"tags": []
}
],
"total_tokens": 2048,
"stats": {
"pruned": true,
"original_count": 50,
"returned_count": 25,
"token_limit": 8192
}
}
**特征:**
- 自动修剪以适应令牌限制
- 保留重要和最近的记忆
- 如果启用,则应用内存衰减
- 返回修剪统计信息
______________________________________________________________________
### 4. `zerodb_embed_text`
为文本生成向量嵌入。
**输入:**```json
{
"text": "The quick brown fox jumps over the lazy dog",
"model": "BAAI/bge-small-en-v1.5",
"normalize": true
}
输出:```json
{
"embedding": [0.123, -0.456, 0.789, ...],
"model": "BAAI/bge-small-en-v1.5",
"dimensions": 384,
"normalized": true
}
**特征:**
- 三种型号尺寸(384d、768d、1024d)
- 归一化向量
- 快速本地嵌入(如果使用ZeroLocal)
______________________________________________________________________
### 5. `zerodb_semantic_search`
按语义相似性搜索,无需文本查询。
**输入:**```json
{
"text": "food preferences",
"limit": 10,
"session_id": "chat-123",
"min_similarity": 0.7
}
输出:```json
{
"results": [
{
"content": "User prefers vegetarian meals",
"similarity": 0.85,
"metadata": {
"role": "user",
"tags": ["preference"]
}
}
],
"count": 1,
"search_vector_dims": 384
}
**特征:**
- 直接向量相似性搜索
- 可以提供文本或预先计算的向量
- 按相似性阈值过滤
- 会话范围或全局搜索
______________________________________________________________________
### 6. `zerodb_clear_session`
清除会话的所有记忆。
**输入:**```json
{
"session_id": "chat-123",
"keep_important": true,
"confirm": true
}
输出:```json
{
"success": true,
"deleted_count": 45,
"kept_count": 5,
"message": "Session cleared, important memories preserved"
}
**特征:**
- 需要确认
- 可选择保存重要记忆
- 返回删除统计信息
### 7. `zerodb_synthesize_context`
检索并LLM将相关记忆合成为连贯的上下文字符串。包装 `POST /memory/v2/context`.(第2631期)
**输入:**```json
{
"query": "What did we decide about the pricing model?",
"agent_id": "user-456",
"synthesis_style": "narrative",
"max_tokens": 1000,
"top_k": 10
}
输出:```json
{
"context": "In previous discussions, the team decided to use a usage-based pricing model...",
"synthesis_style": "narrative",
"sources_count": 5,
"confidence": 0.87,
"token_count": 312,
"agent_id": "user-456"
}
**特征:**
- 三种合成风格: `narrative`, `bullet`, `structured`
- 由Claude Haiku提供技术支持,实现快速、连贯的总结
- 如果合成失败,则进行优雅的回退(连接顶部片段)
- 范围由 `agent_id` 用于每个用户的内存隔离
______________________________________________________________________
### 8. `zerodb_configure_auto_context`
启用自动上下文中间件,以便将相关内存自动添加到给定代理的每个工具响应中。(第2678期)
**输入:**```json
{
"agent_id": "user-456",
"enabled": true,
"max_results": 10,
"synthesis_style": "bullet",
"auto_trace": false
}
输出:```json
{
"success": true,
"agent_id": "user-456",
"config": {
"enabled": true,
"max_results": 10,
"synthesis_style": "bullet",
"auto_trace": false
},
"message": "Auto-context enabled for agent user-456"
}
**特征:**
- 启用后,每个后续工具都会调用 `agent_id` 自动预置 `_auto_context` 回应
- `auto_trace: true` 将每个工具反应存储为新的情景记忆,以备将来回忆
- 配置通过以下方式持久化 `/remember` --在MCP服务器重启后幸存
- 跳过列表:配置工具本身从不自动上下文
______________________________________________________________________
### 9. `zerodb_get_auto_context_config`
检索代理的当前自动上下文配置。
**输入:**```json
{
"agent_id": "user-456"
}
输出:```json
{
"agent_id": "user-456",
"config": {
"enabled": true,
"max_results": 10,
"synthesis_style": "bullet",
"auto_trace": false
}
}
______________________________________________________________________
## 回写操作工具
使用存储在ZeroDB同步连接中的OAuth令牌回写外部服务的五个工具。在以下位置连接帐户 `/api/v1/public/memory/v2/connections`.
> **代理工作流程:** `zerodb_recall` → `zerodb_synthesize_context` → 采取行动(发送Slack、回复电子邮件、创建事件等)
### 10. `zerodb_slack_send`
使用用户存储的OAuth令牌发送Slack消息。(第2645期)
**输入:**```json
{
"agent_id": "user-456",
"channel": "C012AB3CD",
"message": "Sprint planning scheduled for Monday 10am",
"thread_ts": "1609459200.000100"
}
输出:```json
{
"ts": "1609459201.000200",
"channel": "C012AB3CD",
"message": "Message sent successfully"
}
**笔记:** `thread_ts` 是可选的——省略以发布新消息,包含以在线程中回复。
______________________________________________________________________
### 11. `zerodb_gmail_reply`
使用用户存储的Google OAuth令牌回复Gmail线程。(第2646期)
**输入:**```json
{
"agent_id": "user-456",
"thread_id": "17abc123def456",
"body": "Thanks for the update. I'll review the PR by EOD.",
"cc": ["manager@example.com"]
}
输出:```json
{
"id": "17abc123def999",
"thread_id": "17abc123def456",
"message": "Reply sent successfully"
}
______________________________________________________________________
### 12. `zerodb_calendar_create`
使用用户存储的Google OAuth令牌创建Google日历事件。(第2647期)
**输入:**```json
{
"agent_id": "user-456",
"title": "Sprint Planning",
"start": "2026-05-10T10:00:00Z",
"end": "2026-05-10T11:00:00Z",
"description": "Q2 sprint kickoff",
"attendees": ["alice@example.com", "bob@example.com"],
"calendar_id": "primary"
}
输出:```json
{
"id": "evt_abc123",
"html_link": "https://calendar.google.com/event?eid=abc123",
"title": "Sprint Planning",
"message": "Event created successfully"
}
**笔记:** 使用与Gmail相同的Google OAuth令牌。 `calendar_id` 默认为 `"primary"`.
______________________________________________________________________
### 13. `zerodb_github_create_issue`
使用用户存储的GitHub OAuth令牌创建GitHub问题。(第2648期)
**输入:**```json
{
"agent_id": "user-456",
"repo": "acme/widget",
"title": "Fix null pointer in payment flow",
"body": "Steps to reproduce:\n1. Add item to cart\n2. Proceed to checkout\n3. Observe crash",
"labels": ["bug", "priority:high"]
}
输出:```json
{
"number": 142,
"html_url": "https://github.com/acme/widget/issues/142",
"title": "Fix null pointer in payment flow",
"message": "Issue created successfully"
}
______________________________________________________________________
### 14. `zerodb_notion_create_page`
使用用户存储的Notion OAuth令牌创建Notion页面。(第2649期)
**输入:**```json
{
"agent_id": "user-456",
"parent_id": "parent-page-uuid",
"title": "Meeting Notes — May 10",
"content": "Attendees: Alice, Bob\n\nDecisions:\n- Ship v2 on Friday\n- Rollback plan: revert to v1.9"
}
输出:```json
{
"id": "page-uuid-xyz",
"url": "https://notion.so/page-uuid-xyz",
"title": "Meeting Notes — May 10",
"message": "Page created successfully"
}
**笔记:** 内容转换为Notion段落块(每非空行一个)。长度超过2000个字符的行将被截断。
______________________________________________________________________
## 高级配置
### 上下文窗口管理```bash
# Set maximum tokens (default: 8192)
CONTEXT_WINDOW=16384
# Choose pruning strategy (default: hybrid)
# - relevance: Keep highest-scored memories
# - recency: Keep most recent memories
# - hybrid: Combine both (70% relevance, 30% recency)
PRUNE_STRATEGY=hybrid
# Always keep N recent messages (default: 5)
KEEP_RECENT=5
# Keep memories tagged as important (default: true)
KEEP_IMPORTANT=true
记忆衰退
随着时间的推移,实现自然记忆衰减:```bash
Enable decay (default: false)
DECAY_ENABLED=true
Half-life in days (default: 30)
After 30 days, importance score is halved
DECAY_HALFLIFE=30
Protect tags from decay
PRESERVE_TAGS=important,permanent,critical
**例子:**
- 第0天:重要性=0.8
- 第30天:重要性=0.4
- 第60天:重要性=0.2
- 回忆与 `important` 标签:永不腐烂
### 自动文摘
自动压缩旧对话:```bash
# Enable summarization (default: true)
SUMMARIZE_ENABLED=true
# Summarize after N messages (default: 20)
SUMMARIZE_AFTER=20
# Model for summarization
SUMMARY_MODEL=claude-3-haiku-20240307
# Keep original messages (default: false)
KEEP_ORIGINALS=false
行为:
- 20条消息后,对最早的15条消息进行总结
- 摘要存储为新内存
summary标签 - 原始邮件已删除(除非
KEEP_ORIGINALS=true) - 始终保留最近5条消息
嵌入模型
根据需要选择嵌入模型:```bash
Small (384 dimensions) - Fast, efficient
EMBEDDING_MODEL=BAAI/bge-small-en-v1.5
Base (768 dimensions) - Balanced
EMBEDDING_MODEL=BAAI/bge-base-en-v1.5
Large (1024 dimensions) - Most accurate
EMBEDDING_MODEL=BAAI/bge-large-en-v1.5
**权衡:**
- **小:** 速度提高3倍,准确率达到70%
- **基地:** 速度提高2倍,准确率达到85%
- **大型:** 1x基线,95%准确率
______________________________________________________________________
## 用例
### 客户支持代理```javascript
// Store user preferences
await zerodb_store_memory({
content: "User prefers email support over phone",
role: "user",
session_id: "support-session-123",
tags: ["preference", "communication"],
user_id: "customer-456"
});
// Later, search across all sessions for this user
const prefs = await zerodb_search_memory({
query: "communication preferences",
scope: "agent",
user_id: "customer-456"
});
个人助理```javascript
// Store important facts
await zerodb_store_memory({
content: "User's birthday is March 15th",
role: "system",
session_id: "assistant-123",
tags: ["important", "permanent", "personal"],
metadata: { category: "birthday" }
});
// Retrieve context before responding
const context = await zerodb_get_context({
session_id: "assistant-123",
max_tokens: 4096
});
### 研究助理```javascript
// Store findings
await zerodb_store_memory({
content: "Study shows 85% efficacy in clinical trials",
role: "assistant",
session_id: "research-789",
tags: ["research", "statistics"],
metadata: { source: "Nature 2026", confidence: 0.9 }
});
// Search semantically
const related = await zerodb_semantic_search({
text: "clinical trial results",
limit: 5,
min_similarity: 0.7
});
端到端代理工作流:召回→ 合成→ Act```javascript
// 1. Recall relevant memories
const memories = await zerodb_recall({
query: "pending items from last standup",
agent_id: "agent-456",
top_k: 10,
rerank: true
});
// 2. Synthesize into a coherent summary
const context = await zerodb_synthesize_context({
query: "pending items from last standup",
agent_id: "agent-456",
synthesis_style: "bullet",
top_k: 5
});
// context.context = "- PR #42 needs review\n- Deploy blocked on staging tests\n- Alice OOO Monday"
// 3. Take action — send Slack update
await zerodb_slack_send({
agent_id: "agent-456",
channel: "C012AB3CD",
message: Standup summary:\n${context.context}
});
// 4. Log the action as a memory for future recall
await zerodb_store_memory({
content: Sent standup summary to #engineering: ${context.context},
role: "assistant",
session_id: "agent-456",
tags: ["action", "slack", "standup"]
});
### 自动上下文中间件
启用自动上下文,以便每次工具调用都会自动预置相关内存:```javascript
// Enable once per agent
await zerodb_configure_auto_context({
agent_id: "agent-456",
enabled: true,
max_results: 10,
synthesis_style: "bullet",
auto_trace: true // also store tool responses as memories
});
// Now every subsequent tool call automatically includes _auto_context
const result = await zerodb_slack_send({
agent_id: "agent-456",
channel: "C123",
message: "Update sent"
});
// result._auto_context = "• User prefers concise updates\n• Last message sent 2h ago"
// result.ts = "..."
演出
上下文足迹比较
| 度量 | 单片服务器 | 代理内存MCP | 改进 |
|---|---|---|---|
| 工具 | 77 | 6 | 减少92% |
| 代币成本 | ~10400 | ~800 | 减少92% |
| 加载时间 | 2.5s | 0.3s | 快8倍 |
| 内存使用量 | 150MB | 20MB | 减少87% |
| 代理准确率 | 60% | 95% | 改善58% |
基准测试
零本地(本地主机:8000):
- 存储内存:~5ms
- 搜索内存:~15ms
- 获取上下文:~20ms
- 嵌入文本:~10ms
ZeroDB Cloud(api.aniative.studio):
- 存储内存:~50ms
- 搜索内存:~75ms
- 获取上下文:~100ms
- 嵌入文本:~60ms
发展
运行测试```bash
npm test
### 使用详细日志记录运行```bash
DEBUG=* npm start
开发模式(自动重新加载)```bash
npm run dev
______________________________________________________________________
## 故障排除
### 错误:store_memory上的“身份验证失败”或401
**常见原因:** Shell环境变量(`~/.zshrc`, `~/.bashrc`)覆盖MCP配置中设置的凭据(例如。, `.claude.json` 或克劳德桌面配置)。MCP服务器继承了所有shell环境变量,并已过时 `ZERODB_USERNAME`/`ZERODB_PASSWORD` shell配置文件中的值将优先。
**修复:**
1. 删除或更新过时 `ZERODB_USERNAME`/`ZERODB_PASSWORD` 出口自 `~/.zshrc` 或 `~/.bashrc`
1. 或者切换到API密钥验证(`ZERODB_API_KEY`)这通常不在外壳轮廓中设置
1. 或者在MCP服务器配置中明确设置凭据 `env` 用于覆盖shell变量的块
**还要检查:**
- `ZERODB_USERNAME` 和 `ZERODB_PASSWORD` 是正确的
- ZeroDB中存在帐户
- 密码未更改
### 错误:“找不到项目”
**检查:**
- `ZERODB_PROJECT_ID` 是正确的
- 项目已存在于您的帐户中
- 您有访问权限
### 错误:“连接被拒绝”
**如果使用ZeroLocal:**```bash
# Check if ZeroLocal is running
curl http://localhost:8000/health
# Start ZeroLocal
cd /path/to/zerodb-local
zerodb local up
如果使用云:```bash
Check internet connection
ping api.ainative.studio
Verify API is online
curl https://api.ainative.studio/health
### 记忆未被修剪
**检查配置:**```bash
# Ensure context window is set
echo $CONTEXT_WINDOW
# Verify prune strategy
echo $PRUNE_STRATEGY
# Check if keep_recent is too high
echo $KEEP_RECENT
建筑```
┌─────────────────────────────────────────────┐
│ Agent Memory MCP Server │
├─────────────────────────────────────────────┤
│ │
│ Main (index.js) │
│ └── MCP Server initialization │
│ │
│ Client (zerodb-client.js) │
│ ├── Auto-detection (local vs cloud) │
│ ├── Authentication & token refresh │
│ └── API request handling │
│ │
│ Memory Manager (memory-manager.js) │
│ ├── Context window management │
│ ├── Memory pruning (relevance/recency) │
│ ├── Importance scoring │
│ ├── Memory decay │
│ └── Automatic summarization │
│ │
│ Tools (memory-tools.js) │
│ ├── zerodb_store_memory │
│ ├── zerodb_search_memory │
│ ├── zerodb_get_context │
│ ├── zerodb_embed_text │
│ ├── zerodb_semantic_search │
│ ├── zerodb_clear_session │
│ └── zerodb_synthesize_context │
│ │
└─────────────────────────────────────────────┘
```
路线图
v1.1(计划中)
- []基于LLM的自动摘要
- []内存聚类和组织
- []导出/导入内存档案
- []内存分析仪表板
v1.2(计划中)
- []多代理内存共享
- []内存权限和访问控制
- []跨实例的联合内存
- []内存复制和备份
v2.0(未来)
- []基于图形的内存关系
- []时间内存查询
- []内存压缩算法
- []实时内存流
贡献
欢迎投稿!请先阅读我们的投稿指南。
许可证
MIT许可证-有关详细信息,请参阅许可证文件
支持
- 文档: https://www.ainative.studio/docs
- 问题: https://github.com/ainative/zerodb-memory-mcp/issues
- 不一致: https://discord.gg/ainative
由AINative Studio构建
让AI代理更聪明,一次一个记忆。
