内容
# X-Gun 内存
您的 AI 代理会忘记一切。x-gun-memory 解决了这个问题。
代理隔离、可扩展、基于向量的知识共享。
您的 AI 代理终于共享一个大脑 - 安全。
## 兼容的 AI 工具
与任何支持 MCP 的 AI 系统无缝集成:
- **Claude Desktop** - stdio 模式
- **Claude Code** - stdio 模式
- **OpenClaw** - HTTP/SSE 模式
- **Cursor** - stdio 模式
- **Hermes Agent** - stdio 模式
- **任何自定义 AI 代理** 支持 MCP
支持两种模式:
- **stdio 模式**:单客户端连接
- **HTTP/SSE 模式**:多个并发客户端
*请参阅下面的每个平台的设置说明。*
[](#兼容的-ai-工具)
[](#兼容的-ai-工具)
[](#多代理使用)
[](#代理隔离)
[](#并发)
[](https://www.npmjs.com/package/x-gun-memory)
[](https://opensource.org/licenses/MIT)
[](https://nodejs.org/)
[](#切换存储后端)
## 功能
- **代理隔离** - 每个 AI 代理的内存完全隔离。代理之间无数据泄露。
- **半结构化内存** - 自动特征提取(类型、标签、实体、摘要、重要性)
- **多代理支持** - 通过 HTTP-SSE 实现并发代理,操作线程安全
- **全局知识共享** - 可选的共享内存空间(`agentId="global"`)用于跨代理知识
- **可插拔存储** - SQLite(本地)、PostgreSQL(云)或内存存储。只需更改一个配置即可切换。
- **智能重复数据删除** - 自动合并近似重复的记忆(>=0.95),链接相关的记忆(0.75-0.95),为新内容创建新鲜的记忆。维护每次合并前原始内容的版本历史。
- **基于相关性的检索** - 对于高相似度(>=0.85),返回完整内容;对于中等相似度(0.60-0.85),返回智能句子边界摘要;对于低相似度,过滤噪声。
- **快速嵌入** - LRU 缓存 + 批处理(可配置的 `embeddings.batchSize`,默认为 `128`)并具有运行时缓存/非缓存延迟统计
- **原生向量搜索** - 通过 sqlite-vec / pgvector 实现 O(log N)。不是暴力搜索。
- **通用 MCP** - 支持 stdio(Cursor、Claude Code、Claude Desktop、Hermes)和 HTTP/SSE(Claude.ai、OpenClaw)
- **批处理操作** - 一次存储多个记忆
- **令牌高效** - 仅返回需要的內容,而不是完整的节点转储
- **后台处理** - 异步嵌入生成队列
- **混合评分** - 将语义相似性与图关系相结合
- **数据库迁移** - 自动模式版本控制和升级
- **结构化日志** - 具有代理跟踪和性能指标的 JSON 日志
- **速率限制** - 内置的滥用保护(每 15 分钟 100 次请求/代理)
- **冲突安全** - 乐观锁定防止并发写入冲突
## 架构
### 存储层
- **节点**:存储对话、文件、代码、上下文、知识及其嵌入 + 代理元数据
- `agentId`:代理标识符(必填)
- `sessionId`:会话标识符(可选)
- `namespace`:逻辑分组(可选)
- **边**:节点之间的关系(引用、相似等)
- **嵌入**:本地向量生成,带缓存
- **元数据**:配置和统计信息
### 接口
- **MCP 服务器**:支持 stdio 和 HTTP/SSE 的通用 MCP
- **REST API**:存储、检索和管理端点
### 项目结构
```text
x-gun-memory/
|-- src/
| |-- storage/
| | |-- adapters/
| | | |-- base-adapter.js # 抽象适配器接口
| | | |-- sqlite-adapter.js # SQLite + sqlite-vec
| | | |-- postgres-adapter.js # PostgreSQL + pgvector
| | | |-- memory-adapter.js # 内存存储(测试)
| | | `-- README.md # 构建您自己的适配器
| | |-- adapter-factory.js # 自动从配置中选择
| | |-- graph-db.js # 协调层
| | `-- embeddings.js # 本地嵌入 + LRU 缓存
| |-- mcp/
| | `-- server.js # MCP stdio + HTTP/SSE
| |-- api/
| | `-- rest-server.js # REST API
| `-- utils/
| |-- retrieval.js # 智能相关性检索
| |-- deduplication.js # 合并/更新/创建逻辑
| |-- graph-traversal.js # BFS/DFS 遍历
| `-- logger.js # 日志记录
|-- data/
| `-- x-gun-memory.db # SQLite 数据库(默认备用)
|-- config.json # 所有配置
`-- package.json
```
## 安装
```bash
git clone https://github.com/swamy18/x-gun-memory
cd x-gun-memory
npm install
```
注意:`npm install` 可能会报告安全漏洞。运行 `npm audit fix` 以尝试自动修复,或运行 `npm audit` 以获取详细信息。
### Node 兼容性注意
- `better-sqlite3` 在 Node 24 的 Windows 上可能会因缺少预编译二进制文件或构建工具链需求而失败。
- 如果 SQLite 启动因缺少原生绑定而失败,请使用 Node 18/20 LTS,在 Windows 上安装 Visual Studio C++ 工作负载,或切换到 PostgreSQL 模式。
- PostgreSQL 模式避免了 `better-sqlite3` 原生依赖路径。
## 快速入门
```bash
git clone https://github.com/swamy18/x-gun-memory
cd x-gun-memory
npm install
npm run start:mcp
```
## 运行测试
运行测试套件:
```bash
npm test
```
注意:目前尚未实现测试。这是一个占位命令。
## 配置
`config.json` 中的完整配置:
```json
{
"storage": {
"type": "sqlite",
"sqlite": { "path": "./data/x-gun-memory.db" },
"postgres": {
"connectionString": "postgresql://user:pass@localhost:5432/xgunmemory"
}
},
"embeddings": {
"model": "Xenova/all-MiniLM-L6-v2",
"cacheDir": "./data/embeddings-cache",
"batchSize": 128,
"lruCacheSize": 1000
},
"retrieval": {
"defaultMaxNodes": 5,
"defaultTraverseDepth": 2,
"highRelevanceThreshold": 0.85,
"lowRelevanceThreshold": 0.60,
"summaryLength": 400
},
"deduplication": {
"enabled": true,
"similarityThreshold": 0.75,
"mergeThreshold": 0.95,
"updateThreshold": 0.75
},
"mcp": { "port": 3001, "host": "localhost" },
"api": {
"port": 3000,
"host": "localhost",
"rateLimit": {
"windowMs": 900000,
"maxRequests": 100
}
},
"logging": { "level": "info", "file": "./logs/app.log" },
"agents": {
"allowGlobalWrites": ["admin-agent"],
"defaultAgentId": "global"
},
"redis": {
"enabled": true,
"host": "127.0.0.1",
"port": 6379
}
}
```
**切换到 Postgres**:将 `storage.type` 更改为 `"postgres"`。无需更改代码。
**环境变量**:使用环境变量覆盖配置值。
1. 复制 `.env.example` 到 `.env`:
```bash
cp .env.example .env
```
2. 编辑 `.env` 以设置所需的值。
支持的变量:
- `STORAGE_TYPE`: 存储后端(`sqlite`、`postgres`、`memory`)
- `POSTGRES_CONNECTION_STRING`: PostgreSQL 连接字符串
- `REDIS_HOST`、`REDIS_PORT`、`REDIS_ENABLED`: Redis 配置
- `MCP_PORT`、`API_PORT`、`API_HOST`: 服务器配置
- `LOG_LEVEL`: 日志级别(`info`、`debug`等)
- `DEFAULT_AGENT_ID`: 默认代理标识符
- `AUTH_ENABLED`: 启用/禁用身份验证
## 用法
### 启动服务器
```bash
# 启动 MCP 服务器(适用于 Claude、Cursor)
npm run start:mcp
# 启动 REST API 服务器
npm run start:api
# 以 HTTP/SSE 模式启动 MCP
npm run start:mcp:http
```
### 基本用法示例
#### 存储记忆
```bash
curl -X POST http://localhost:3000/store \
-H "Content-Type: application/json" \
-H "X-API-Key: YOUR_AGENT_KEY" \
-d '{
"agentId": "my-agent",
"type": "conversation",
"content": "用户询问:天气怎么样?"
}'
```
#### 检索上下文(快速模式)
```bash
curl -H "X-API-Key: YOUR_AGENT_KEY" \
"http://localhost:3000/retrieve?agentId=my-agent&q=weather&max_nodes=3"
```
#### 检索上下文(高精度模式)
```bash
curl -H "X-API-Key: YOUR_AGENT_KEY" \
"http://localhost:3000/retrieve?agentId=my-agent&q=explain+the+weather+pattern&highAccuracy=true"
```
#### MCP 工具调用
```json
{
"method": "tools/call",
"params": {
"name": "store_context",
"arguments": {
"agentId": "claude-desktop",
"type": "code",
"content": "修复了用户身份验证中的错误"
}
}
}
```
### 连接到任何平台
#### Cursor / Claude Code / Claude Desktop
在 `~/.cursor/mcp.json` 或 `claude_desktop_config.json` 中:
```json
{
"mcpServers": {
"x-gun-memory": {
"command": "node",
"args": ["/absolute/path/to/x-gun-memory/src/mcp/server.js"],
"env": {}
}
}
}
```
#### Claude.ai 自定义连接器
在 HTTP 模式下启动服务器:
```bash
npm run start:mcp:http
```
然后添加连接器 URL:`http://localhost:3001/sse`
#### OpenClaw
在 `openclaw.json` 或配置中:
```json
{
"plugins": {
"x-gun-memory": {
"mcp": "http://localhost:3001/sse"
}
}
}
```
#### Hermes Agent
在 `~/.hermes/config.yaml` 中:
```yaml
mcp_servers:
x-gun-memory:
command: "node"
args: ["/absolute/path/to/x-gun-memory/src/mcp/server.js"]
```
## 多代理使用
### 代理隔离
每个 AI 代理都有自己的内存空间。在所有操作中指定 `agentId`:
```json
{
"agentId": "claude-assistant",
"type": "conversation",
"content": "用户询问天气情况"
}
```
### 全局知识共享
使用 `agentId: "global"` 进行共享知识:
```json
{
"agentId": "global",
"type": "knowledge",
"content": "巴黎是法国的首都"
}
```
所有代理都可以读取全局记忆。
写入控制取决于传输方式:
- REST API 使用 API 密钥权限(`global`)通过身份验证中间件,或在 `agents.allowGlobalWrites` 中列出的 `callerAgentId` / `X-Agent-Id`。
- MCP 写入工具需要 `callerAgentId` 用于 `agentId: "global"` 并将其与 `agents.allowGlobalWrites` 进行验证。
### 会话和命名空间
可选分组以实现更好的组织:
```json
{
"agentId": "my-chatbot",
"sessionId": "session-123",
"namespace": "customer-support",
"type": "conversation",
"content": "今天我能帮您什么?"
}
```
### 并发访问
- HTTP-SSE 模式支持多个并发代理
- 具有写入锁定的线程安全操作
- 每个代理的速率限制防止滥用
## API 参考
### MCP 工具
#### store_context
存储图中的任何数据。
参数: `{agentId, callerAgentId?, sessionId?, namespace?, type, content, relationships?, metadata?}`
必填: `agentId`, `type`, `content`
返回:
- "Context stored successfully with ID: Z"(新建)
- "Memory already exists (ID: X, similarity: 0.97). Updated."(合并)
- "Stored as new memory (ID: Y). Linked to related ID: X (similarity: 0.82)."(更新)
#### retrieve_context
使用语义 + 图搜索获取相关上下文。
参数: `{agentId, sessionId?, namespace?, query, max_nodes?, traverse_depth?, highAccuracy?}`
必填: `agentId`, `query`
返回: `[{id, type, content, contentType: "full"|"summary", similarity, source}]`
#### query_graph
直接图查询,带过滤。
参数: `{agentId, node_type?, relationship?, time_range?: {start?, end?}}`
返回: `{nodes, edges}`
#### batch_store_context
一次存储多个记忆。比重复调用 `store_context` 快得多。
参数: `{agentId, callerAgentId?, sessionId?, namespace?, items: [{type, content, metadata?}]}`
必填: `agentId`, `items`
返回: "Stored X memories. Node IDs: ..."
#### store_memory
存储具有自动特征提取的结构化记忆。
参数: `{agentId, callerAgentId?, sessionId?, namespace?, content, memoryType?, tags?, entities?, summary?, importance?, confidence?, autoExtract?}`
必填: `agentId`, `content`
返回:具有提取的特征的结构化记忆
### REST 端点
所有端点都需要请求体/查询参数中的 `agentId`。
- `POST /store/memory` - 存储具有自动提取的结构化记忆
- 正文: `{agentId, callerAgentId?, content, memoryType?, tags?, entities?, summary?, importance?, confidence?, autoExtract?}`
- `POST /store` - 存储单个记忆(带重复数据删除)
- 正文: `{agentId, callerAgentId?, sessionId?, namespace?, type, content, relationships?, metadata?}`
- `POST /store/batch` - 一次存储多个记忆
- 正文: `{agentId, callerAgentId?, sessionId?, namespace?, items: [{type, content, metadata?}]}`
- `GET /retrieve?agentId=X&sessionId=Y&namespace=Z&q=query&max_nodes=5&traverse_depth=2&highAccuracy=false` - 语义 + 图搜索(可选会话/命名空间范围)
- `POST /query` - 按类型/关系/时间筛选
- 正文: `{agentId, node_type?, relationship?, time_range?}`
- `GET /graph?node_id=123&depth=2` - 从节点 ID 遍历(在代理范围内)
- `GET /health` - 基本健康检查
- `GET /health/detailed` - 存储 + 嵌入统计信息
#### GET /health/detailed 响应
```json
{
"status": "ok",
"storage": { "type": "sqlite", "status": "ok", "latencyMs": 2 },
"embeddings": {
"cacheHits": 142,
"cacheMisses": 23,
"lruCacheSize": 321,
"redisEnabled": true,
"avgLatencyMs": 45,
"avgCachedLatencyMs": 8,
"avgUncachedLatencyMs": 220,
"batchSize": 128
},
"uptime": 3600,
"version": "1.0.0"
}
```
## 切换存储后端
### 本地开发(SQLite - 默认)
无需更改。开箱即用。
### 生产环境(PostgreSQL)
1. 安装 pgvector:`CREATE EXTENSION vector;`
2. 确保规划器统计信息是最新的,以便高效使用向量/文本索引:`ANALYZE nodes; ANALYZE edges;`
3. 更新 `config.json`:
```json
{
"storage": {
"type": "postgres",
"postgres": {
"connectionString": "your connection string"
}
}
}
```
3. 重启服务器。完成。
### 测试/短暂
```json
{
"storage": {
"type": "memory"
}
}
```
数据在重启后丢失。无需依赖。
### 自定义适配器
参见 `src/storage/adapters/README.md`
## 安全
- 所有数据都存储在本地
- 核心功能无需外部 API 调用
- SQLite 数据库文件权限适用
- 嵌入内容本地缓存
- 代理隔离防止数据泄露
- 速率限制保护免受滥用
## 并发
- **线程安全**:使用互斥锁(SQLite)或连接池(PostgreSQL)序列化写入操作
- **乐观锁定**:防止重复数据删除合并中的冲突
- **基于代理的速率限制**:每 15 分钟 100 次请求/代理
- **并发读取**:多个代理可以同时读取
- **冲突解决**:针对瞬时故障的自动重试逻辑
## 高级功能
### Redis 集成
- **耐用队列**:基于 Redis 的嵌入处理队列,具有至少一次传递(RPOPLPUSH 模式)
- **分布式缓存**:多级缓存(Redis + LRU)具有防止踩踏保护
- **作业去重**:Redis 集防止重复嵌入作业
- **安全模式删除**:基于 SCAN 的缓存失效(非阻塞)
- **TTL 策略**:基于数据新鲜度的智能缓存过期
- **高可用性**:系统在无 Redis 时可正常工作(性能降低)
### 后台嵌入处理
嵌入内容异步处理以防止阻塞:
```javascript
// 自动队列处理
await embeddings.generateBatch(texts); // 非阻塞
```
### 混合检索(快速 + 准确)
两阶段检索以获得最佳性能:
1. **快速关键词过滤**:全文搜索(FTS5/PostgreSQL tsvector)
2. **嵌入重新排序**:过滤候选对象的语义相似性
```json
{
"retrieval": {
"useHybrid": true,
"fastLimit": 50,
"finalLimit": 10
}
}
```
**性能**:比纯向量搜索快 5-10 倍,准确率相同或更好。
### 双模式检索(快速 vs 高精度)
**自动模式选择:**
- **快速模式**(默认):用于快速响应的摘要 + 轻量级上下文
- **高精度模式**:用于复杂查询的完整内容 + 图形扩展
**自动检测触发器:**
- 显式 `highAccuracy: true` 标志
- 查询长度 > 80 个字符
- 关键词:`why`, `explain`, `analyze`, `compare`, `reason`, `how`
**配置:**
```json
{
"retrieval": {
"dualMode": true,
"highAccuracyLimit": 100,
"graphDepth": 2
}
}
```
`dualMode: false` 强制使用快速模式,除非请求显式设置 `highAccuracy: true`。
**性能比较:**
- **快速模式**:50-100ms,摘要内容
- **高精度模式**:200-500ms,完整内容 + 上下文
嵌入式吞吐量注意(本地基准示例):
- 在此项目设置中,`embeddings.batchSize=128` 在 256 项未缓存运行中优于 `64`(`3389ms` vs `3851ms` 总时间)。
- 对于更高的写入吞吐量,请优先使用 `POST /store/batch` 而不是重复的 `POST /store`。
### 混合评分
结合语义相似性和图关系:
```json
{
"retrieval": {
"useHybridScoring": true,
"hybridWeights": {
"semantic": 0.7,
"graph": 0.3
}
}
}
```
## 半结构化记忆
存储具有自动特征提取和轻量级结构的记忆:
### 记忆特征
- **类型**:`fact`, `event`, `preference`, `task`, `general`
- **标签**:最多 5 个相关关键词(自动提取)
- **实体**:人员、地点、组织(自动提取)
- **摘要**:一行摘要(第一句话)
- **重要性**:0-1 的分数,基于关键词和紧迫程度
- **置信度**:0-1 的提取置信度分数
### API 用法
```bash
curl -X POST http://localhost:3000/store/memory \
-H "Content-Type: application/json" \
-H "X-API-Key: YOUR_AGENT_KEY" \
-d '{
"agentId": "my-agent",
"content": "Paris is the capital of France",
"memoryType": "fact",
"tags": ["France", "capital"],
"entities": ["Paris", "France"],
"summary": "Paris is the capital.",
"importance": 0.8,
"confidence": 0.9
}'
```
# 存储结构化记忆,自动提取
curl -X POST http://localhost:3000/store/memory \
-H "X-API-Key: YOUR_AGENT_KEY" \
-H "Content-Type: application/json" \
-d '{
"agentId": "my-agent",
"content": "我需要在周五前完成项目报告。这很紧急!"
}'
**响应:**
```json
{
"success": true,
"nodeId": 123,
"features": {
"memory_type": "任务",
"tags": ["紧急", "项目", "截止日期"],
"entities": [],
"summary": "我需要在周五前完成项目报告。",
"importance": 0.8,
"confidence": 0.8
}
}
```
### MCP 工具
```json
{
"method": "tools/call",
"params": {
"name": "store_memory",
"arguments": {
"agentId": "claude-assistant",
"content": "巴黎是法国的首都",
"memoryType": "事实",
"importance": 0.9
}
}
}
```
### 配置
```json
{
"memory": {
"autoExtract": true,
"maxTags": 5,
"maxEntities": 5
}
}
```
## 生产环境考虑
## 最小配置
### 内存(快速本地测试)
```json
{
"storage": { "type": "memory" },
"auth": { "enabled": false },
"redis": { "enabled": false }
}
```
### SQLite(单节点持久化)
```json
{
"storage": {
"type": "sqlite",
"sqlite": { "path": "./data/x-gun-memory.db" }
},
"auth": { "enabled": true },
"redis": { "enabled": false }
}
```
### PostgreSQL(生产基准)
```json
{
"storage": {
"type": "postgres",
"postgres": { "connectionString": "postgresql://user:pass@host:5432/db" }
},
"auth": { "enabled": true },
"redis": { "enabled": true, "host": "127.0.0.1", "port": 6379 }
}
```
## 故障排除
- `Invalid API key` 或 `Permission 'write' required`:检查 `auth.enabled`、`X-API-Key` 和 `config.json` 中的密钥权限。
- `Global access not permitted`:您的密钥需要 `"global"` 权限才能进行 REST 全局写入。
- `SQLite adapter failed to load`:安装 `better-sqlite3` 并确保原生构建支持。
- `PostgreSQL adapter failed to load`:安装 `pg` 并验证连接字符串。
- `Redis disabled: ioredis module not available`:安装 `ioredis` 或设置 `"redis": { "enabled": false }`。
- 请求缓慢:嵌入式模型初始化在首次运行时较慢。
## 性能声明说明
本 README 中的延迟和吞吐量数字取决于环境,并因模型、硬件、存储后端和网络条件而异。请使用您自己的工作负载基准进行生产规模化。
### Redis 最佳实践
- **连接池**:Redis 自动处理连接池。
- **内存管理**:使用 `INFO memory` 监控 Redis 内存使用情况。
- **持久性**:配置 Redis AOF/RDB 以确保数据持久性。
- **监控**:使用 Redis `INFO` 命令和键空间通知。
### 缓存策略
- **基于 TTL 的过期**:减少手动失效的需要。
- **防止雪崩**:防止缓存未命中时的惊人负载。
- **分层缓存**:LRU + Redis 实现最佳性能。
### 队列可靠性
- **至少一次交付**:RPOPLPUSH 确保作业不会丢失。
- **去重**:Redis 集防止重复作业处理。
- **监控**:跟踪队列长度和处理时间。
### 扩展考虑因素
- **读取副本**:使用 Redis 复制进行读密集型工作负载。
- **分片**:考虑使用 Redis 集群进行大规模扩展。
- **备份**:定期进行 Redis 备份以实现灾难恢复。
### 数据库迁移
自动模式升级,带有版本跟踪:
```sql
-- 自动应用于启动时
ALTER TABLE nodes ADD COLUMN agent_id TEXT;
CREATE INDEX idx_nodes_agent_id ON nodes(agent_id);
```
### 身份验证和安全
基于 API 密钥的身份验证,具备粒度权限:
```json
{
"auth": {
"apiKeys": {
"agent-key": ["read", "write", "global"]
}
}
}
```
### 结构化日志记录
用于监控和调试的 JSON 日志记录:
```json
{
"timestamp": "2026-04-29T18:30:50.000Z",
"level": "INFO",
"message": "存储记忆",
"agentId": "claude-assistant",
"action": "store",
"duration": 45
}
```
## 许可证
MIT
MCP 配置
以下是此 MCP Server 的配置信息,可直接复制到 Cursor 或其他 MCP 客户端中使用。
mcp.json
连接信息
猜你喜欢
暂无推荐服务器