Metadata-Version: 2.4
Name: imprint-mcp
Version: 2.0.0
Summary: Local-first persistent long-term memory MCP server
License: MIT
Requires-Python: >=3.11
Description-Content-Type: text/markdown
Requires-Dist: mcp>=1.26.0
Requires-Dist: jsonschema>=4.20.0
Requires-Dist: jieba>=0.42
Provides-Extra: dev
Requires-Dist: pytest>=8.0; extra == "dev"
Requires-Dist: pytest-asyncio>=0.24; extra == "dev"
Requires-Dist: pytest-cov>=5.0; extra == "dev"
Requires-Dist: ruff>=0.8; extra == "dev"
Requires-Dist: mypy>=1.13; extra == "dev"

# Imprint MCP

本地优先的持久化长期记忆 MCP Server。让 AI Agent 跨会话、跨项目记住关键事实。

## 特性

- **本地优先** — 数据存在本地，不依赖云服务
- **极轻量** — 仅 3 个运行时依赖（mcp, jsonschema, jieba）
- **MCP 原生** — 兼容所有 MCP Client（Claude Code、Cursor、Codex 等）
- **JSONL 真相源** — 人类可读、Git 友好、可迁移
- **中文原生支持** — jieba 预分词，中文召回准确率大幅提升
- **Content-hash 去重** — SHA-256 写入时自动去重
- **Token 预算控制** — 可配置输出上限，默认不限制
- **多项目隔离** — project_id 列级隔离，scope=user 跨项目共享

## 记忆如何工作

### 记忆提取 — 三层保障

| 层级 | 机制 | 可靠性 | 说明 |
|------|------|--------|------|
| **Layer 1** | MCP Resource 自动注入 | 最高 | Client 连接时自动拉取 `memory://project-context`，零依赖 Agent 行为 |
| **Layer 2** | Tool description 引导 | 高 | `memory_recall` 描述中标注 "IMPORTANT: Call at START of every task" |
| **Layer 3** | Agent 提示词规则 | 中 | CLAUDE.md / Rules 中的自动触发规则 |

支持 MCP Resources 的 Client（Claude Code、Cursor 等）连接即加载最近高重要度记忆 + 任务状态，
不需要 Agent 主动调用任何工具。

### 记忆写入 — 用户感知

Agent 调用 `memory_save` 时用户可以看到工具调用（MCP 协议限制，无法静默）。
控制策略：

- content-hash 去重避免重复写入
- Tool description 明确标注 "只保存有长期价值的信息"
- Agent 提示词限制写入频率（每会话 1-3 次为合理范围）

### 记忆管理 — CLI 命令

```bash
# 查看最近记忆
imprint-mcp list                           # 最近 20 条
imprint-mcp list --type gotcha             # 按类型过滤
imprint-mcp list --tags nginx,sse          # 按标签过滤
imprint-mcp list -v                        # 详细模式

# 全文搜索
imprint-mcp search "SSE 流延迟"

# 查看单条详情（完整 JSON）
imprint-mcp show mem_20260402_0001

# 归档记忆（软删除）
imprint-mcp delete mem_20260402_0001

# 统计信息
imprint-mcp stats

# 导出所有记忆（备份/迁移）
imprint-mcp export > backup.json

# 启动 MCP Server（默认行为）
imprint-mcp                                # 等价于 imprint-mcp serve
```

## 快速开始

### 1. 安装

```bash
# 方式 A: npm（推荐，自动解析 Python 环境）
npm install -g imprint-mcp

# 方式 B: pip
pip install imprint-mcp

# 方式 C: 源码开发
git clone <repo-url> && cd imprint_mcp
pip install -e .

# 验证
imprint-mcp --help
```

### 2. 配置 MCP Client

**Claude Code** — 在项目根目录创建 `.mcp.json`：

```json
{
  "mcpServers": {
    "imprint-mcp": {
      "command": "npx",
      "args": ["imprint-mcp"]
    }
  }
}
```

或直接指向 Python 入口：

```json
{
  "mcpServers": {
    "imprint-mcp": {
      "command": "/path/to/imprint_mcp/.venv/bin/imprint-mcp"
    }
  }
}
```

> `IMPRINT_MCP_PROJECT_ID` 可选 — 不设则自动从 git repo root 推导，与 Claude Code 行为一致。

**Codex** — 在 `~/.codex/config.toml` 中添加：

```toml
[mcp_servers.imprint-mcp]
command = "npx"
args = ["imprint-mcp"]
```

### 3. 配置 Agent 提示词

将以下规则添加到 Agent 的系统提示词（CLAUDE.md / `.claude/rules/` / System Prompt），
让 Agent 知道何时自动调用记忆工具。

<details>
<summary>完整版（推荐嵌入 CLAUDE.md）— 点击展开</summary>

```markdown
# Imprint MCP 自动记忆管理

## 自动触发规则

### 会话开始（必做）
每次接收新任务时，第一步调用：
memory_recall(query=<任务描述>, max_tokens=2000)
将返回的 memories 和 state_context 作为工作背景。

### 及时写入
| 场景 | type | scope | importance |
|------|------|-------|------------|
| 确认技术事实 | fact | project | 0.5 |
| 踩坑/非直觉行为 | gotcha | project | 0.9 |
| 技术决策 | decision | project | 0.8 |
| 用户偏好 | preference | user | 0.7 |
| 硬约束条件 | constraint | project | 0.8 |
| API 行为/限制 | api_note | project | 0.6 |

写入格式：
memory_save(text: "<完整描述>", type: "<类型>", tags: ["<关键词>"], importance: N)

memory_save 内置 content-hash 去重，无需写入前手动检查。

### 状态同步
任务目标或进展变化时：
memory_upsert_state(namespace: "current_task", value: {
  goal: "<当前目标>", status: "in_progress", next_steps: ["<下一步>"]
})

### 场景化召回
- 调试排错：memory_recall(query=<错误信息>) — 系统自动提升 gotcha 权重
- 架构讨论：memory_recall(query=<设计主题>) — 系统自动提升 decision 权重
- 精确过滤：memory_recall(type="gotcha", tags=["nginx"]) — 无需 query，纯结构化过滤

### 不做
- 不要每句话都写记忆，只记有长期价值的信息
- 不要写模糊内容，要写具体、可操作的事实
- 不要忽略 tags，它们是检索的关键
- 不要把临时信息存为 project scope，用 session scope
```

</details>

<details>
<summary>精简版（适合嵌入 Rules 文件）— 点击展开</summary>

```markdown
# Imprint MCP 自动记忆管理

## 会话开始（必做）
memory_recall(query=<任务描述>, max_tokens=2000)

## 及时写入
| 场景 | type | importance |
|------|------|------------|
| 确认技术事实 | fact | 0.5 |
| 踩坑 | gotcha | 0.9 |
| 技术决策 | decision | 0.8 |
| 用户偏好 | preference (scope=user) | 0.7 |

写入：memory_save(text: "...", type: "...", tags: [...])
内置去重，无需手动检查。

## 状态同步
memory_upsert_state(namespace: "current_task", value: { goal, status, next_steps })

## 场景化召回
- 调试：memory_recall(query=<错误信息>) — gotcha 权重自动提升
- 精确：memory_recall(type="gotcha", tags=["nginx"]) — 纯过滤
```

</details>

### 4. 验证

配置完成后，在 Agent 对话中测试：

```
你: 记住一下，这个项目用的是 FastAPI + SQLite 技术栈
Agent 应调用: memory_save(text="这个项目用的是 FastAPI + SQLite 技术栈", type="fact", ...)

你: 回忆一下这个项目的技术栈
Agent 应调用: memory_recall(query="项目技术栈")
```

检查数据是否写入成功：

```bash
# 用 CLI 查看
imprint-mcp list
imprint-mcp stats

# 或直接看原始文件
cat ~/.memory/events/*.jsonl | python -m json.tool
```

## MCP 工具参考

### memory_save（推荐写入方式）

只需传入文本，服务端自动提取 tags、生成结构化字段，内置 content-hash 去重。

```
memory_save(
    text: "Nginx 默认缓冲 SSE 流，需要关闭 proxy_buffering",
    type: "gotcha",           # 可选 hint
    tags: ["nginx", "sse"],   # 可选 hint，不传则自动提取
    importance: 0.9           # 可选，默认 0.5
)
```

### memory_recall（语义召回 + 结构化过滤）

召回与当前问题最相关的记忆。支持纯文本搜索、纯过滤、或两者组合。

```
# 语义搜索
memory_recall(query: "SSE 流为什么有延迟", max_tokens: 2000)

# 纯结构化过滤（query 可省略）
memory_recall(type: "gotcha", tags: ["nginx"], status: "active")

# 组合：搜索 + 过滤
memory_recall(query: "缓冲问题", type: "gotcha", tags: ["nginx"])
```

全部参数：`query`, `type`, `tags`, `entity_refs`, `status`, `scope`, `project_id`, `max_tokens`, `limit`

### memory_upsert_state

更新状态快照（当前任务、项目摘要等）。

```
memory_upsert_state(
    namespace: "current_task",
    value: { goal: "实现 memory MCP v2", status: "in_progress" }
)
```

### memory_stats

返回记忆库统计信息。

```
memory_stats()
memory_stats(project_id: "my-project")
```

### memory_append（批量结构化写入）

批量写入多条完整结构化记忆事件。每条需提供完整 schema 字段。

```
memory_append(entries=[{
    type: "gotcha", scope: "project",
    title: "Nginx 缓冲 SSE", content: "Nginx 默认缓冲 SSE 流...",
    source: { kind: "agent" }, tags: ["nginx", "sse"]
}])
```

## 环境变量

| 变量 | 默认值 | 说明 |
|------|--------|------|
| `IMPRINT_MCP_DATA_DIR` | `~/.memory` | 数据存储目录 |
| `IMPRINT_MCP_PROJECT_ID` | 自动从 CWD 推导 | 当前项目标识（可选，不设则自动推导） |
| `IMPRINT_MCP_MAX_TOKENS` | `0` | recall 输出 Token 上限，0 = 不限制 |
| `IMPRINT_MCP_STATE_BUDGET` | `500` | state_context Token 预算 |
| `IMPRINT_MCP_FTS_LIMIT` | `50` | FTS5 检索返回上限 |
| `IMPRINT_MCP_STRUCTURED_LIMIT` | `50` | 结构化过滤返回上限 |
| `IMPRINT_MCP_RRF_K` | `60` | RRF 融合常量 |

## 数据存储

```
~/.memory/
├── events/
│   └── 2026-04.jsonl       # 按月分文件，append-only（唯一事实源）
├── state/
│   ├── current_task.json   # 状态快照
│   └── project_summary.json
└── index/
    └── memory_fts.db       # SQLite FTS5 索引（可从 events 重建）
```

- `events/` — JSONL 格式，永不原地修改，`cat` 即可查看
- `index/` — 读模型，删除后重启服务会自动从 events 重建
- `state/` — 命名空间隔离的 JSON 快照
- 多项目通过 `project_id` 列隔离，`scope=user` 的记忆 `project_id` 为 `__global__`（跨项目可见）

## 版本

- **v1.0** — 写入/索引/召回闭环
- **v2.0**（当前）— 轻量写入 + 中文分词 + 多项目隔离 + content-hash 去重 + MCP Resource 自动注入 + CLI 管理工具

## License

MIT
