﻿# chat-audit-mcp

[![M8ven Score](https://m8ven.ai/badge/mcp/nickyangsx-chat-audit-mcp-48mtsj)](https://m8ven.ai/mcp/nickyangsx-chat-audit-mcp-48mtsj?s=readme)

**面向通用 Agent 的可审计聊天检索 MCP。**给 Agent 查询聊天记录时，同时提供消息来源、请求边界和完整性证据。当前支持用户导出的 QQ CSV/JSON/JSONL，以及 Telegram Desktop JSON；一个 Telegram 全量导出文件可包含多个可独立查询的会话。

> **当前状态：实验性脚手架。**当前版本没有 QQ、微信、钉钉或企业微信官方 API 连接器。插件只解析配置的本地文件；不解密、不读取客户端数据库或内存，也不处理 `.bak` 文件。
>
> 当前版本：`0.2.0`。更新内容见 [CHANGELOG](CHANGELOG.md)。

[English version](#english-version) · [快速开始](#5-分钟开始) · [隐私政策](PRIVACY.md) · [变更记录](CHANGELOG.md) · [MIT License](LICENSE)

## 核心竞争力

### 完整性诚实

工具分别报告文件是否读到 EOF、请求时间窗是否有覆盖证明、是否发生解析错误、分页是否读完、是否触及结果上限。EOF 只说明扫描结束，不会被当成请求时间窗已完整覆盖的证明。

### 结论可追溯

标准化消息保留消息 ID、时间、发言人和来源记录信息。缺少原生 ID 时使用来源 ID 加记录序号生成派生 ID，不使用正文或正文哈希。MCP Prompt 指导 Agent 区分事实与推断，并要求结论附上消息 ID、时间和发言人。

### 完整性协议可复用

`evidence-mcp` 将完整性判定提取成独立 Python 包。聊天、邮件、会议记录、发票、日志等数据源可以映射到同一组完整性门槛。

### 本地处理边界清晰

插件只读取配置文件，代码路径不发起网络请求；审计日志记录元数据而不记录消息正文。导出文件的本地附件路径会从返回内容中剔除。Agent 主机仍可能把返回文本发送给它配置的模型，用户可以按自己的模型和客户端策略选择使用方式。

## 使用场景

### 取证与对证

群聊是事实最多的地方，也是说法最多的地方。用它把关键对话连同证据锚点一起拉出来：

- **交易与拼团纠纷**：把价格承诺、交付节点、售后表态连同时间点导出，核对「谁在什么时候说了什么」。
- **业主群与物业沟通**：车位、维修、公共设施承诺往往是群里的口头表态，出问题时要能翻出原话。
- **网暴与骚扰取证**：聊天记录可能作为证据提交，需要一份记录完整性的书面说明。

### 复盘与追责

出问题之后，群聊是唯一不会被记忆美化的时间线：

- **项目事故复盘**：定位需求变更是谁提出的、什么时候提出的、当时的决策依据是什么。
- **家庭照护与医疗沟通**：医嘱、复诊安排、用药调整散落在多个群里，需要可靠的留痕备查。

### 高保真信息提取

AI 总结容易「顺手润色」。用它把事实原样提出来：

- **家长群通知**：时间、地点、要带的东西，一字不差。
- **技术群答疑**：给出处、给上下文，而不是 AI 转述后的二手答案。
- **群聊会议纪要**：谁说了什么、谁接了什么活，每一条都能指回原消息。

### 隐私敏感场景

**聊天解析路径不出本机、零网络请求**，适合不能上传到云端的内容：

- **医疗、法律、商业机密讨论**：本地解析，正文不落盘，报告只含元数据。

唯一的可选出站是 `trust_gate`：只有调用方显式传 `allow_network=true`（仅本次调用有效）才会连接白名单端点，而且只发送目标标识符（`owner/repo` 或包名），**从不发送消息正文、发言人、时间戳或文件路径**。细节与无法避免的元数据（IP、时间、频率）见 [PRIVACY.md](PRIVACY.md)。

## 5 分钟开始

### 1. 准备导出文件

使用你信任的外部工具导出所需群聊记录，再放到本机目录，例如：

```text
chat-audit-mcp/
└── imports/
    └── qq-group.csv
```

仓库不会附带真实聊天数据；`imports/` 下的文件已加入 Git 忽略规则。

### 2. 安装插件

需要 Python 3.11 或更新版本：

```bash
python -m venv .venv
```

macOS/Linux：

```bash
.venv/bin/python -m pip install -e .
```

Windows PowerShell：

```powershell
./.venv/Scripts/python.exe -m pip install -e .
```

Windows 上使用 `Asia/Shanghai` 等 IANA 时区时，项目会安装 `tzdata` 依赖。

### 3. 选择解析器并配置 MCP 客户端

默认使用 `auto` 自动识别 QQ CSV/JSON/JSONL 和 Telegram Desktop JSON。Telegram 的全量导出会由 `list_allowed_chats` 列出文件中的各个会话；发现 JSON 同时匹配多个格式时，工具会返回 `FORMAT_AMBIGUOUS`，要求明确设置解析器。

将下面配置加入支持 MCP stdio 的客户端。将命令路径、导入目录和会话信息替换成实际值：

```json
{
  "mcpServers": {
    "chat-audit-mcp": {
      "command": "/absolute/path/to/chat-audit-mcp/.venv/bin/chat-audit-mcp",
      "args": [],
      "env": {
        "CHAT_IMPORT_ROOT": "/absolute/path/to/chat-audit-mcp/imports",
        "CHAT_FILE_NAME": "qq-group.csv",
        "CHAT_PARSER": "auto",
        "CHAT_SOURCE_ID": "qq-export-2026-11",
        "CHAT_PLATFORM": "qq-export",
        "CHAT_ID": "local:qq-group-01",
        "CHAT_NAME": "项目讨论群",
        "CHAT_SOURCE_TIMEZONE": "Asia/Shanghai",
        "SOURCE_COVERAGE_START": "2026-11-27T00:00:00Z",
        "SOURCE_COVERAGE_END": "2026-11-28T00:00:00Z"
      }
    }
  }
}
```

Windows 上将 `command` 改为虚拟环境中的 `Scripts/chat-audit-mcp.exe` 完整路径。MCP 客户端会启动该命令并通过 stdio 通信；手动在终端启动时，进程会等待 MCP 客户端连接。

| 环境变量 | 示例 | 用途 |
| --- | --- | --- |
| `CHAT_IMPORT_ROOT` | `/absolute/path/to/imports` | 导出文件目录 |
| `CHAT_FILE_NAME` | `qq-group.csv` | 相对于目录的文件名 |
| `CHAT_PARSER` | `auto` | `auto`、`mock_csv`、`qq_csv`、`qq_json` 或 `telegram_json` |
| `CHAT_SOURCE_ID` | `qq-export-2026-11` | 导入快照的稳定标识；更换文件时建议换新值 |
| `CHAT_PLATFORM` | `qq-export` | 来源标签，不代表官方 API 接入 |
| `CHAT_ID` | `local:qq-group-01` | 这个导出会话的本地标识 |
| `CHAT_NAME` | `项目讨论群` | Agent 展示用名称 |
| `CHAT_SOURCE_TIMEZONE` | `Asia/Shanghai` | QQ 无时区时间文本的时区；Telegram 优先用 Unix 时间戳，无时区 `date` 按 UTC |

Telegram 全量 JSON 导出无需预设 `CHAT_ID` / `CHAT_NAME`：先调用 `list_allowed_chats`，再使用返回的 `telegram:<type>:<id>` 查询对应会话。若导出没有原生会话 ID，解析器会用会话名称和文件内序号形成标识。

### 4. 让 Agent 查询和总结

连接成功后，向 Agent 提出类似请求：

> 请总结 `local:qq-group-01` 在 2026-11-27 09:00 到 10:00 UTC 的讨论。区分事实和推断，每条结论附消息 ID、时间和发言人；如果数据不完整，请先在摘要顶部警告。

Agent 可以先调用 `list_allowed_chats` 确认会话，再调用 `get_messages_by_range` 查询。若返回 `next_page_token`，续读时沿用同一个 `query_id` 和查询边界。支持 MCP Prompt 的客户端也可以使用 `summarize_chat_range` 获取摘要指引。

### 5. 声明导出覆盖范围

`SOURCE_COVERAGE_START` 和 `SOURCE_COVERAGE_END` 应描述导出文件实际覆盖的时间范围，使用带时区的 RFC 3339 时间。查询范围采用半开区间 `[start_time, end_time)`：包含起点，不包含终点。

例如，请求 09:00–10:00 UTC 时，导出文件可声明已知覆盖范围为 00:00–24:00 UTC。文件内观测到的首末消息时间也必须覆盖请求边界。没有可靠的覆盖说明时不要猜测；工具会将完整性标为未能证明。

## 命令行报告（拓展）

除了 MCP 工具，还提供一个独立命令行入口，把审计结果渲染成一份**人眼可读、可打印、可转发的 HTML 审计报告**——给 Agent 的 JSON 收据之外，给「人」的凭证。

```bash
# 安装后（或直接运行模块）
chat-audit-report imports/qq-group.csv
python -m chat_audit_mcp.report_cli imports/qq-group.csv
```

报告包含：完整性判定徽章与六项检查逐项结果、请求/声明/观测三层时间覆盖对照、源文件 SHA-256 与独立验证命令、`network = 0` 处理声明，以及完整性的诚实边界说明。默认输出到源文件旁的 `<文件名>.audit.html`，用浏览器打开即可，也可以直接打印成 PDF。

常用参数：

| 参数 | 说明 |
| --- | --- |
| `--start / --end` | 指定审计时间区间（UTC RFC 3339，半开区间） |
| `--coverage-start / --coverage-end` | 声明导出文件的覆盖范围 |
| `--parser` | 指定解析器：`auto`、`mock_csv`、`qq_csv`、`qq_json`、`telegram_json` |
| `--chat-id` | 只审计文件中的某个会话（Telegram 全量导出时有用） |
| `--out` | 输出路径，默认 `<文件名>.audit.html` |

CLI 与 MCP 共用同一套查询、解析和完整性判定逻辑，只是换了呈现方式——判定结果不会因为走 CLI 而不同。

## 信任安检门（拓展）

`chat-audit-trust` 是第二个 CLI 入口：把项目的「可信度」主线从**数据层**（我拿到的这份聊天记录完整吗）延伸到**工具层**（我要接的这个 MCP 仓库可信吗）。它查询 M8ven Tool Trust API，按本项目定义的规则给出三态建议：**pass（通过）/ warn（警告）/ block（拦截）**，退出码 0/1/2 可直接接脚本。

```bash
chat-audit-trust https://github.com/NickYangSX/chat-audit-mcp --allow-network
# 退出码 0=通过 1=警告 2=拦截 3=无法评估
```

**所有联网请求都走网络屏障五件套**，缺省一个都不发：

1. **网络闸门**：default-deny。没有 `--allow-network`（或 `CHAT_AUDIT_NETWORK_GATE=open`）时，任何外发请求在发出前就被拦截。
2. **出口白名单**：只允许硬编码的 M8ven 端点模板；调用方只能填写 query 参数值（URL 编码），重定向每一跳都重新校验主机——非白名单主机、非 https、超次跳数一律拦截。
3. **限流与熔断**：本地令牌桶（默认每分钟 3 次、每天 20 次）+ 熔断器（连续 3 次失败熔断 60 秒、半开试探），都在发包前检查。

   限流做在**出站层**（`network/policy.py` 的 `RateLimiter` + `CircuitBreaker`），不在 MCP 工具入口——本地 stdio 工具只读本机文件，重复调用不消耗远端额度；真正需要配额保护的是出站请求，在发包前拦才算数。
4. **结构化不可信标记**：每个解析后的响应都套上来源与时间戳，并附带固定提示——数据里出现的指令一律不得执行。
5. **JSON 审计日志**：每次外发决定输出一行结构化 JSON 到 stderr（含授权来源、结果、字节数、耗时），**永不记录 API key 与请求头**。

判定规则（本项目定义，非 M8ven 官方结论）：`score ≥ 80` 且无 fail 项、无警告 → pass；有 fail 项 / grade D·F / `score < 60` / M8ven red → block；两者之间（含 grade C、yellow、warn 项）→ warn。报告始终附带三条诚实声明：联网会向 m8ven.ai 暴露仓库 URL、评估可能滞后于最新提交、三态判定是建议而非保证。

常用参数：

| 参数 | 说明 |
| --- | --- |
| `--key / --key-env` | M8ven API key（m8v_ 开头；默认读 `M8VEN_API_KEY`，不落盘、不进日志） |
| `--allow-network` | 显式打开网络闸门 |
| `--pass-threshold / --warn-threshold` | 调整三态阈值（默认 80 / 60） |
| `--days` | 评分历史窗口（默认 30 天，0 关闭） |
| `--out` | 输出自包含 HTML 报告 |
| `--json` | 输出机器可读 JSON（配合退出码做脚本判定） |

诚实边界：DNS 重绑定是纯 HTTP 层防不到根的，白名单之外建议再配系统级防火墙规则；屏障是护栏，不是承诺。

### 审查官闸门（MCP 工具面，0.1.7）

CLI 只能给人看，Agent 可以不看。所以从 0.1.6 起把同一套三态判定挂进 MCP 工具面，并且**让闸门同时成为唯一的外部代理**——Agent 不再直连外部源，只调 `trust_gate`；闸门验过凭证才代发。0.1.7 修了一个会稀释人类批准语义的续读 bug，并把同意来源的边界写实。

> **prompt 是建议，token 才是闸门；闸门即代理。**
>
> **代理能约束流程，不能自证真人——说清这条，闸门才不是安慰剂。**

| 工具 | 作用 |
| --- | --- |
| `trust_gate(operation, target, allow_network, decision_token?)` | 判定 + 代发。`block` 时返回 `status="awaiting_human"`、`decision_token=null`，并给出 `confirmation_request`（人类要批准的那份载荷），不返回触发拦截的外部数据 |
| `resolve_decision(decision_id, action, proof?)` | 批准/拒绝；**唯一**签发 `decision_token` 的路径。配置审批公钥后，`approve` 必须携带人类签名的 `proof` |

- `decision_token` 用进程内密钥 HMAC 签名，绑定 `(decision_id, operation, params_hash)`，一次性、有 TTL、**fail-closed**：缺失/过期/签名不符/参数不匹配/重放/决策不存在，一律拒绝，绝不降级放行。
- `allow_network=true` 是**仅本次调用**的显式同意（call-scoped grant：代理调用结束或出错即撤销，不会"传染"给后续调用）；不传则网络闸门保持 default-deny，一个包都不发。它**不等价于** CLI 的 `--allow-network`——后者是启动时的人工同意，覆盖整个进程。
- 两种执行模式：客户端支持 elicitation 时，表单由客户端渲染，`human_brief` 不经过 LLM（`verbatim_present=true`，硬保证）；不支持时降级为 Agent 转述，`human_brief` 必带 `verbatim_present=false` 与 `relay_disclaimer`（软约束，不假装锁住了）。
- **续读复用批准快照**：`block` 时闸门已取回数据但不交付；批准后的 resume 只解锁交付，**不重新查询来源**（`verdict_source="decision_snapshot"`）。否则源评分从 F 变 A 时，一个更宽松的新判定会悄悄替换人类批准过的严格判定。
- **同意来源必须标注**：不配置审批公钥时，`resolve_decision` 仍只是 Agent 可调的工具，`decision_token` 证明的是"批准流程未跳步且留下审计痕"，**不证明真人按了按钮**；结果带 `consent_provenance: agent_callable_tool` 与 `consent_verifiable_by_gate: false`。**降级路径下，硬闸退化为"Agent 自证自批"——这是本设计的默认状态，不是已解决的问题。**
- 静默降级不再静默：`mode=auto` 但宿主未注入 handler 时，审计里落一条 `elicitation_degraded`（`ELICITATION_UNSUPPORTED` / `handler_not_injected`）。
- 非 pass 来源的结果带 `trust_label.require_warning_prefix=true`，`summarize_chat_range` prompt 强制以此为警告前缀——声明做在数据层，不走 prompt 自觉。
- `CHAT_AUDIT_TRUST_WARN=block` 可把 warn 也升级为停机；默认 warn 放行（warn 频繁停机会让人关掉闸门，等于废弃它）。

#### 带外人工确认（把上面那条默认状态关掉）

配置 `CHAT_AUDIT_APPROVAL_PUBKEY` 后，批准必须由**人类在另一个终端用私钥签名**，Agent 只能转交签名、无法生成：

```bash
chat-audit-keygen --out-dir ~/.chat-audit          # 生成 Ed25519 密钥对，私钥口令加密（600）
export CHAT_AUDIT_APPROVAL_PUBKEY=~/.chat-audit/approval_ed25519.pub
# block 后，人类在独立终端：
chat-audit-confirm --request req.json > proof.json  # 渲染语义 → 人类确认 → 签名，stdout 只有 proof
# Agent 把 proof 原样交给 resolve_decision(decision_id, "approve", proof)
```

- **不盲签**：CLI 把载荷渲染成「操作 / 目标 / 当前判定 / 每一条风险项 / 语义摘要」，人签的是看懂的东西；签名覆盖的正是这一份规范化载荷。
- **三验缺一不可**：验签 + 验 `params_hash`/`verdict_hash` 与闸门存储的决策一致 + 验可读摘要与闸门将执行的语义逐字一致。任一不符即 `PROOF_MISMATCH`，决策保持 `pending`。
- **nonce 进 `_used_nonces`**：Ed25519 是确定性签名，防重放不能靠"签名不同"，只能靠登记已用。
- **配了公钥就 fail-closed**：缺 proof 返回 `PROOF_REQUIRED`，绝不静默退回 Agent 自批；公钥读不到也一律拒绝。
- 验签通过才 `consent_verifiable_by_gate: true`，且必带 `consent_verification_scope: "key_holder_signature"`——证明的是「**持钥人签了这段语义**」，不是「核实了某个真人的自由意志」。密钥被盗、被胁迫、私钥落在 Agent 可读路径，这套都会失效；passphrase 加密与文件权限是它生效的前提，不是可选的部署建议。

完整字段、状态机、不变量（I1–I11）与已知代价见 [docs/trust-gate-contract.md](docs/trust-gate-contract.md)。

## 专业设计说明

### 完整性判定

一个结果只有在以下条件同时成立时，才会标记为完整：

1. 解析器读到文件结尾（`eof_reached = true`）。
2. 请求会话内以及无法确认所属会话/时间范围的记录，没有因解析错误被跳过（`in_scope_parse_errors = 0` 且 `scope_unknown_parse_errors = 0`）。其他会话的已定位坏行不会阻断本次查询。
3. 导出声明的覆盖范围包含请求时间窗。
4. 文件中观测到的首条消息不晚于请求起点，末条消息不早于请求终点。
5. 所有匹配消息页均已返回。
6. `max_messages` 上限没有阻断仍存在的匹配消息。

核心字段：

- `fetch_status`：读取状态，取值为 `complete`、`partial`、`failed`、`denied`。
- `is_truncated`：结果是否已知或可能因读取、解析、分页或上限而缺少记录。
- `complete_for_requested_scope`：当前响应是否有足够证据覆盖请求范围。
- `completeness_category`：来源无关的完整性原因分类。
- `completeness_basis`：本地文件适配器的具体原因，例如 `file_time_coverage_partial`。
- `source_history_completeness`：保持为 `unknown_export_coverage`。文件级检查不能证明平台导出的历史记录没有缺失。

### 大型 JSONL / NDJSON 文件

QQ JSONL/NDJSON 使用逐行解析和纯 Python 内存字节偏移索引。构建索引时只保留
会话、时间、记录序号、消息 ID 和文件偏移，不缓存消息正文，也不创建索引文件；
查询分页时只重新读取所选消息行。CSV、JSON 数组和 Telegram JSON 当前仍走完整
解析快照路径。为检测文件变更并安全复用索引，每次工具调用仍会顺序计算一次整份
文件的 SHA-256，因此缓存命中可省去重新解析，但不会省去这次 O(文件大小) 的校验读取。

`source_scan.cache_mode`、`records_scanned_this_call`、
`indexed_records_read_this_call` 和 `file_hash_passes_this_call` 会显示本次调用采用的
路径与读取量。更完整的适配器要求见 [`docs/adapter-spec.md`](docs/adapter-spec.md)。
注意：首次 `records_scanned_this_call` 是建索引时的全文件扫描行数，不是当前查询页返回数；
页回读量由 `indexed_records_read_this_call` 表示。
观测到首末时间只能作为必要边界检查，不能证明两者之间没有缺行。EOF 说明文件扫描结束，不说明请求时间窗已被覆盖。详细枚举和返回结构见 [docs/contract.md](docs/contract.md) 与 [docs/tool-schemas.json](docs/tool-schemas.json)。

合成基准（100,000 行 / 13.7 MB JSONL，Windows，Python 3.15）：

| 指标 | 结果 |
| --- | ---: |
| 构建索引 + 首个 25 条页 | 4.16 s |
| 缓存命中（换时间窗，含全文件 SHA-256） | 0.0126 s |
| 每页重读的源记录 | 25 条（而非全量） |
| 索引是否含消息正文列 | 否 |

基准命令见 `benchmarks/benchmark_jsonl_index.py`；完整记录见 [docs/test-records/adapter-and-jsonl-index.md](docs/test-records/adapter-and-jsonl-index.md)。

### 消息映射与来源标记

- `qq_csv` 支持 `时间,发送人,内容` 简表头，以及包含 `timestamp`、`time`、`sender`、`msg_id`、`text`、`attachments` 等字段的导出表头。
- `qq_json` 支持消息数组、含 `messages` / `records` / `items` / `data` 列表的对象，以及单条消息对象。
- `telegram_json` 支持 Telegram Desktop 的单聊导出和 `chats.list[]` 多会话导出；每个会话以导出文件里的会话类型与 ID 单独列出。
- `auto` 根据本地文件头部和结构识别格式。无法唯一识别时返回明确错误，不会静默猜格式；可将 `CHAT_PARSER` 设为相应解析器。
- JSONL/NDJSON 每行解析一条消息；损坏行会跳过并计入解析错误。
- Unix 秒、毫秒或微秒时间戳转换为 UTC。无时区文本按 `CHAT_SOURCE_TIMEZONE` 解释。
- 缺少或重复的原生消息 ID 使用来源 ID 与 1-based 记录序号生成派生 ID；不使用消息正文或正文哈希。
- 导出中没有的编辑、删除和线程状态保持为 `null`。附件元数据中的本地路径会被剔除。

字段映射参考公开的 [qq-bak-chat-history-export README](https://github.com/zywstudy123/qq-bak-chat-history-export) 和[导出脚本](https://github.com/zywstudy123/qq-bak-chat-history-export/blob/main/skills/qq-bak-chat-history-export/scripts/export_ntqq_chat.py)。本项目只读取导出结果，不会运行该工具。

新增解析器需声明支持的扩展名和能力，遵循统一消息与扫描报告契约，并通过无第三方依赖的一致性校验。详见[适配器规范](docs/adapter-spec.md)和 `tests/test_parser_conformance.py`。

### 游标、缓存与审计

分页游标绑定来源指纹、解析器 ID/版本、会话、时间边界、页大小和结果上限；游标签名用于发现被修改的续读参数。标准化来源缓存最多保留 120 秒：JSONL/NDJSON 仅缓存纯 Python 内存元数据索引，其他格式缓存完整解析快照。JSONL 时间筛选通过内存字节偏移索引（二分查找）定位，返回时按偏移重读当前页；其他格式使用会话 UTC 时间索引定位。每次调用仍会重新计算本地文件哈希以检测文件变化，因此缓存命中仍有 O(文件大小) 的哈希读取成本。插件不将正文写入磁盘。

审计日志输出到 stderr，记录查询边界、结果数量、状态和处理模式，不记录聊天正文或绝对源文件路径。哈希仅在本机用于文件变化检测，不会写入日志或返回给 Agent。

### 通用完整性库

`evidence-mcp` 把完整性判定提取为可独立安装的 Python 包：

```bash
python -m pip install ./packages/evidence-mcp
```

邮件、会议记录、发票、日志等 MCP 适配器可以将来源信息映射到同一组完整性门槛。协议和 JSON Schema 位于 [docs/evidence-mcp-protocol.md](docs/evidence-mcp-protocol.md) 与 [docs/evidence-mcp.schema.json](docs/evidence-mcp.schema.json)。发布到 PyPI 前需确认包名可用。

### 当前范围

- 当前服务进程使用一个配置文件；Telegram Desktop 全量导出可以发现并查询其中多个会话。QQ 导出仍按配置的单个本地会话 ID 处理。
- 当前没有平台 API、实时消息推送或后台同步功能。
- Prompt 提供 Agent 使用工具和标注证据的明确指引；MCP 服务端不能强制模型遵循 Prompt。
- **聊天解析路径**不发起网络请求，也不包含解密、客户端进程注入或内存读取逻辑。唯一可选出站是 `trust_gate`：需显式 `allow_network=true`（仅本次调用），只连白名单端点，只发目标标识符。
- 缓存索引或解析快照只在内存中暂存，最多 120 秒；插件不把解析结果写入磁盘。JSONL/NDJSON 缓存不保存正文；CSV、JSON 数组和 Telegram JSON 仍缓存完整的标准化消息。
- MCP 主机可能将工具返回的消息文本发送给其配置的模型；这取决于 Agent 和客户端设置。
- 若要独立验证无网络出口，可在系统防火墙或沙箱中运行。

## 开发与测试

标准库测试，无需安装 pytest（先装运行时依赖）：

```bash
python -m pip install "mcp>=2.0,<3.0" "tzdata>=2024.1"
python -m unittest discover tests
```

**当前状态：253 passed**（2026-12-04，v0.2.0；其中 49 个是信任闸门的负向/诚实回归测试，覆盖契约不变量 I1–I10；24 个是带外确认的证明链测试，覆盖 I11；另有 3 个真子进程 stdio 握手测试与 2 个软启动测试，守护"目录能拉起"）。测试记录、覆盖矩阵与未经编辑的原始输出见[测试记录索引](docs/test-records/README.md)。

跑测试用 `python -m unittest discover tests`（标准库入口）。仓库里若残留 `__pycache__/*.pyc` 不必理会，它们是历史 pytest 运行产物，不是另一套测试口径。

合成测试夹具覆盖 QQ CSV/JSON/JSONL、Telegram JSON 自动识别与多会话、歧义格式、截断文件、坏行、重复 ID、按会话的时间覆盖不足、分页续读和结果截断。

## License

MIT. See [LICENSE](LICENSE).

## English version

**An auditable chat retrieval MCP for general-purpose agents.** It turns user-exported chat files into normalized, time-bounded messages with source metadata and explicit completeness evidence. It currently supports QQ CSV/JSON/JSONL exports and Telegram Desktop JSON exports, including multiple conversations in one Telegram export.

> **Status: experimental scaffold.** This project does not provide official QQ, WeChat, DingTalk, or WeCom API connectors. It only parses a configured local export. It does not decrypt data, read client databases or process memory, or handle `.bak` files.

[Quick start](#5-minute-quick-start) · [Core strengths](#core-strengths) · [Completeness model](#completeness-model) · [Development](#development-and-tests) · [Changelog](CHANGELOG.md)

### Core strengths

#### Honest completeness

The tools distinguish whether the file reached EOF, whether the requested time window has coverage evidence, whether records failed to parse, whether more pages remain, and whether a result limit stopped retrieval. EOF means the file scan ended; it does not prove that the file covers the requested interval.

#### Traceable conclusions

Normalized messages retain their message ID, timestamp, sender, and source record. When an export lacks a native message ID, the parser derives one from the source ID and 1-based record ordinal. It never hashes the message body to generate an ID. The MCP Prompt tells agents to separate facts from inferences and cite each conclusion with a message ID, timestamp, and speaker.

#### A reusable evidence protocol

`evidence-mcp` packages the completeness checks as a standalone Python library. Chat, email, meeting, invoice, log, and other data adapters can map their source-specific evidence to the same checks.

#### A clear local-processing boundary

The plugin reads only its configured local file and its code path makes no network requests. Audit logs contain metadata, not message bodies. Local attachment paths are removed from returned data. The MCP host or agent may still send returned text to its configured model; that depends on the host and model settings.

### Use cases

#### Evidence and verification

Group chats are where facts and claims collide. Pull the key conversations out with their evidence anchors:

- **Transaction and group-buy disputes**: export price promises, delivery milestones, and after-sale commitments with their exact timestamps to check "who said what, when".
- **Owner groups vs. property management**: parking, repairs, and amenity promises are usually verbal statements in the group — produce the original words when they matter.
- **Harassment and online-abuse evidence**: chat records may be submitted as evidence and need a written statement about record completeness.

#### Review and accountability

After something goes wrong, the chat is the one timeline memory cannot rewrite:

- **Incident post-mortems**: locate when a requirement changed, who proposed it, and what the decision rationale was at the time.
- **Family care and medical coordination**: prescriptions, follow-up schedules, and medication changes are scattered across groups and need reliable, searchable records.

#### High-fidelity extraction

AI summaries tend to "polish" things. Extract the facts as written:

- **Parent-group announcements**: time, place, what to bring — verbatim.
- **Tech-group answers**: with sources and context, not an AI paraphrase.
- **Group-chat meeting notes**: who said what and who took which task, each traceable to the original message.

#### Privacy-sensitive scenarios

**The chat-parsing path never leaves the machine and makes zero network requests.** Suitable for content that cannot be uploaded:

- **Medical, legal, and commercial-confidential discussions**: parsed locally, message bodies never written to disk, and the report contains metadata only.

The only opt-in outbound path is `trust_gate`: it connects to allowlisted endpoints only when the caller passes `allow_network=true` (one call only), and sends a target identifier (`owner/repo` or a package name) — never message bodies, speakers, timestamps, or file paths. See [PRIVACY.md](PRIVACY.md) for details and for the metadata (IP, timing, frequency) that no networked design can hide.

### 5-minute quick start

#### 1. Prepare an export

Use an export tool you trust, then place the exported file in a local directory:

```text
chat-audit-mcp/
└── imports/
    └── qq-group.csv
```

The repository contains no real chat data. Files under `imports/` are ignored by Git.

#### 2. Install

Python 3.11 or newer is required:

```bash
python -m venv .venv
```

macOS/Linux:

```bash
.venv/bin/python -m pip install -e .
```

Windows PowerShell:

```powershell
./.venv/Scripts/python.exe -m pip install -e .
```

The project installs `tzdata` for IANA time zones such as `Asia/Shanghai` on Windows.

#### 3. Configure an MCP client

The default parser setting, `auto`, detects supported QQ CSV/JSON/JSONL and Telegram Desktop JSON exports. For a Telegram full export, call `list_allowed_chats` to discover its conversations. If a JSON file is ambiguous, the tool returns `FORMAT_AMBIGUOUS`; set `CHAT_PARSER` explicitly instead of guessing.

Add a server entry to an MCP client that supports stdio. Replace paths and conversation details with your own:

```json
{
  "mcpServers": {
    "chat-audit-mcp": {
      "command": "/absolute/path/to/chat-audit-mcp/.venv/bin/chat-audit-mcp",
      "args": [],
      "env": {
        "CHAT_IMPORT_ROOT": "/absolute/path/to/chat-audit-mcp/imports",
        "CHAT_FILE_NAME": "qq-group.csv",
        "CHAT_PARSER": "auto",
        "CHAT_SOURCE_ID": "qq-export-2026-11",
        "CHAT_PLATFORM": "qq-export",
        "CHAT_ID": "local:qq-group-01",
        "CHAT_NAME": "Project Discussion",
        "CHAT_SOURCE_TIMEZONE": "Asia/Shanghai",
        "SOURCE_COVERAGE_START": "2026-11-27T00:00:00Z",
        "SOURCE_COVERAGE_END": "2026-11-28T00:00:00Z"
      }
    }
  }
}
```

On Windows, set `command` to the full path of `Scripts/chat-audit-mcp.exe` in the virtual environment. The MCP client starts the process and communicates over stdio. If started manually in a terminal, the process waits for an MCP client.

| Environment variable | Example | Purpose |
| --- | --- | --- |
| `CHAT_IMPORT_ROOT` | `/absolute/path/to/imports` | Directory containing the export |
| `CHAT_FILE_NAME` | `qq-group.csv` | File name relative to the import directory |
| `CHAT_PARSER` | `auto` | `auto`, `mock_csv`, `qq_csv`, `qq_json`, or `telegram_json` |
| `CHAT_SOURCE_ID` | `qq-export-2026-11` | Stable ID for this imported snapshot; use a new value when replacing the file |
| `CHAT_PLATFORM` | `qq-export` | Source label; it does not imply official API access |
| `CHAT_ID` | `local:qq-group-01` | Local ID for the configured conversation |
| `CHAT_NAME` | `Project Discussion` | Display name for the agent |
| `CHAT_SOURCE_TIMEZONE` | `Asia/Shanghai` | Time zone for QQ timestamps without an offset; Telegram Unix timestamps take precedence and naive `date` values use UTC |
| `SOURCE_COVERAGE_START` | `2026-11-27T00:00:00Z` | Declared start of the export's known coverage |
| `SOURCE_COVERAGE_END` | `2026-11-28T00:00:00Z` | Declared end of the export's known coverage |

For Telegram full exports, `CHAT_ID` and `CHAT_NAME` can be omitted. Call `list_allowed_chats`, then query a returned ID such as `telegram:private_group:101`. If the export has no native conversation ID, the parser derives one from the conversation name and its position in the file.

#### 4. Ask the agent to retrieve and summarize

For example:

> Summarize the discussion in `local:qq-group-01` from 09:00 to 10:00 UTC on 2026-11-27. Separate facts from inferences, cite each conclusion with message ID, timestamp, and speaker, and put an explicit warning at the top if the data is incomplete.

The agent can call `list_allowed_chats` to confirm the conversation and then call `get_messages_by_range`. If the result contains `next_page_token`, continue with the same `query_id` and query boundaries. MCP clients that support Prompts can also use `summarize_chat_range` for the evidence and completeness instructions.

#### 5. Declare the export's coverage

`SOURCE_COVERAGE_START` and `SOURCE_COVERAGE_END` must describe the export's actual known coverage and use timezone-aware RFC 3339 timestamps. Query intervals are half-open: `[start_time, end_time)` includes the start and excludes the end.

For a 09:00–10:00 UTC query, the export may declare a wider known range, such as 00:00–24:00 UTC. The first and last observed message times must also cover the requested boundaries. Do not guess when the export coverage is unknown; the tool will report that completeness could not be proven. EOF alone is not evidence that the requested time window was covered.

### Command-line report (extension)

Besides the MCP tools, a standalone CLI renders the audit result into a **human-readable, printable, shareable HTML audit report** — a credential for people, alongside the JSON receipts for agents.

```bash
# after installation (or run the module directly)
chat-audit-report imports/qq-group.csv
python -m chat_audit_mcp.report_cli imports/qq-group.csv
```

The report includes: the completeness verdict badge with all six gate results, the three-layer time-coverage comparison (requested / declared / observed), the source file's SHA-256 with independent verification commands, the `network = 0` processing declaration, and an honest completeness-boundary note. By default it writes `<file-name>.audit.html` next to the source; open it in a browser or print it to PDF.

Common options:

| Option | Meaning |
| --- | --- |
| `--start / --end` | audit interval (UTC RFC 3339, half-open) |
| `--coverage-start / --coverage-end` | declare the export's coverage range |
| `--parser` | parser: `auto`, `mock_csv`, `qq_csv`, `qq_json`, `telegram_json` |
| `--chat-id` | audit a single conversation in the file (useful for Telegram full exports) |
| `--out` | output path, default `<file-name>.audit.html` |

The CLI shares the same query, parsing, and completeness logic as the MCP tools — it only changes the presentation. A verdict never differs just because it was produced through the CLI.

### Trust gate (extension)

`chat-audit-trust` is the second CLI entry: it extends the project's trust theme from the **data layer** (is this chat export complete?) to the **tool layer** (is this MCP repo trustworthy?). It queries the M8ven Tool Trust API and applies project-defined rules to give a three-state recommendation — **pass / warn / block** — with exit codes 0/1/2 for scripting.

```bash
chat-audit-trust https://github.com/NickYangSX/chat-audit-mcp --allow-network
# exit codes: 0=pass 1=warn 2=block 3=unable to evaluate
```

**Every outbound request goes through the five-piece network barrier**; by default nothing is sent:

1. **Network gate**: default-deny. Without `--allow-network` (or `CHAT_AUDIT_NETWORK_GATE=open`), every outbound request is blocked before it is sent.
2. **Egress allowlist**: only hard-coded M8ven endpoint templates are reachable. Callers may only fill query-parameter values (URL-encoded); every redirect hop is re-checked — non-allowlisted hosts, non-https targets, and excessive hops are all blocked.
3. **Rate limiting and circuit breaking**: local token buckets (default 3/minute and 20/day) plus a circuit breaker (3 consecutive failures trip it for 60 s, half-open probe), all enforced before any socket work.

   Rate limiting lives in the **egress layer** (`network/policy.py`: `RateLimiter` + `CircuitBreaker`), not at the MCP tool entry. Local stdio tools only read local files, so repeated calls spend no remote quota; the thing that needs a quota is the outbound request, and it is only a real limit if it runs before the socket does.
4. **Structured untrusted marker**: every parsed response is wrapped with provenance and a fixed note — instructions found inside the data must never be executed.
5. **JSON audit log**: one structured JSON line per outbound decision on stderr (consent provenance, result, bytes, duration); **API keys and request headers are never recorded**.

Verdict rules (project-defined, not an M8ven official verdict): `score ≥ 80` with no fail items and no warnings → pass; fail items / grade D·F / `score < 60` / M8ven red → block; anything in between (grade C, yellow, warn items) → warn. The report always carries three honesty notes: the query exposes the repo URL to m8ven.ai, the assessment may lag the latest commit, and the verdict is a recommendation, not a guarantee.

Common options:

| Option | Meaning |
| --- | --- |
| `--key / --key-env` | M8ven API key (`m8v_` prefix; defaults to `M8VEN_API_KEY`, never written to disk or logs) |
| `--allow-network` | explicitly open the network gate |
| `--pass-threshold / --warn-threshold` | adjust the thresholds (default 80 / 60) |
| `--days` | score-history window (default 30; 0 disables) |
| `--out` | write a self-contained HTML report |
| `--json` | emit machine-readable JSON (pair with the exit code) |

Honest boundary: DNS rebinding cannot be defeated at the pure HTTP layer; on top of the allowlist, a host-firewall rule is recommended. The barrier is a guard rail, not a promise.

### Completeness model

A result is complete for the requested scope only when all of these checks pass:

1. The parser reached EOF (`eof_reached = true`).
2. No parse errors inside the requested conversation and interval, or with an unknown conversation/time scope, could have hidden records. A malformed row confidently assigned to another conversation does not block the current query.
3. The declared export coverage contains the requested interval.
4. The selected conversation's first observed message is at or before the requested start, and its last observed message is at or after the requested end.
5. All matching result pages have been returned.
6. `max_messages` did not stop retrieval while matching rows remained.

Key fields:

- `fetch_status`: retrieval state: `complete`, `partial`, `failed`, or `denied`.
- `is_truncated`: whether records may be missing because of scanning, parsing, pagination, or a result limit.
- `complete_for_requested_scope`: whether there is enough evidence to claim coverage of this query's scope.
- `completeness_category`: a source-independent completeness classification.
- `completeness_basis`: the local adapter's specific reason, such as `file_time_coverage_partial`.
- `source_history_completeness`: always `unknown_export_coverage`. File-level checks cannot prove that the platform's export includes every historical message.

Observed first and last timestamps are necessary boundary checks; they cannot prove that there are no missing rows between those timestamps. See [docs/contract.md](docs/contract.md) and [docs/tool-schemas.json](docs/tool-schemas.json) for the complete contract and schemas.

### Large JSONL / NDJSON files

QQ JSONL/NDJSON uses incremental line parsing and a pure-Python in-memory byte-offset index. The index stores conversation, timestamp, record ordinal, message ID, and byte offset only; it does not cache message bodies or create a sidecar file. A page rereads only its selected message lines. CSV, JSON arrays, and Telegram JSON still use a complete parsed-source snapshot.

Before reusing an index, each tool call sequentially recomputes the full source SHA-256 to detect changes. A cache hit avoids reparsing but still performs one O(file size) integrity read. `source_scan.cache_mode`, `records_scanned_this_call`, `indexed_records_read_this_call`, and `file_hash_passes_this_call` report the path and work performed. On a cache miss, `records_scanned_this_call` may be the full source scan used to build the index; it does not mean that many messages were returned. See [docs/adapter-spec.md](docs/adapter-spec.md) for the adapter requirements.

Synthetic benchmark (100,000 rows / 13.7 MB JSONL, Windows, Python 3.15):

| Measurement | Result |
| --- | ---: |
| Index build + first 25-message page | 4.16 s |
| Cached query (different window, incl. full-source SHA-256) | 0.0126 s |
| Source rows reread per page | 25 (not the full file) |
| Message-body column in index | No |

See `benchmarks/benchmark_jsonl_index.py` and [docs/test-records/adapter-and-jsonl-index.md](docs/test-records/adapter-and-jsonl-index.md) for the full record.

### Supported formats and message provenance

- `qq_csv` supports the simple `时间,发送人,内容` header and export headers containing fields such as `timestamp`, `time`, `sender`, `msg_id`, `text`, and `attachments`.
- `qq_json` supports arrays, objects containing a `messages`, `records`, `items`, or `data` array, and a single message object.
- `telegram_json` supports Telegram Desktop single-chat exports and `chats.list[]` multi-chat exports. Each conversation is listed with its exported type and ID.
- `auto` inspects local file content and structure. Ambiguous formats return an explicit error; they are not silently guessed. Set `CHAT_PARSER` to select a parser explicitly.
- JSONL/NDJSON files are read one record per line. Malformed lines are skipped and counted as parse errors.
- Unix timestamps in seconds, milliseconds, or microseconds are converted to UTC. Naive text timestamps use `CHAT_SOURCE_TIMEZONE` (Telegram naive `date` values use UTC).
- Missing or duplicate native message IDs are derived from the source ID and 1-based record ordinal. Message text and text hashes are never used to construct IDs.
- Edit, deletion, and thread fields absent from the export remain `null`. Local attachment paths are removed from returned metadata.

QQ field mapping references the public [`qq-bak-chat-history-export` README](https://github.com/zywstudy123/qq-bak-chat-history-export) and [export script](https://github.com/zywstudy123/qq-bak-chat-history-export/blob/main/skills/qq-bak-chat-history-export/scripts/export_ntqq_chat.py). This project only reads exported files; it does not run that tool.

New adapters declare their file extensions and capabilities, follow the shared message and scan-report contract, and run the dependency-free conformance validators. See the [adapter specification](docs/adapter-spec.md) and `tests/test_parser_conformance.py`.

### Cursors, caching, and audit

Continuation cursors bind the source fingerprint, parser ID/version, conversation, time bounds, page size, and result limit. A process-local HMAC detects modified cursor parameters. Cursors expire after 120 seconds and become invalid when the server process restarts.

Normalized source data is cached in process memory for up to 120 seconds, keyed by the file content hash and parser configuration. JSONL/NDJSON retains a metadata-only in-memory byte-offset index and rereads only the selected page; other supported formats retain a complete normalized snapshot and per-conversation UTC timestamp index. Each call still re-hashes the local file to detect changes, so cache hits retain O(file size) hashing cost. The plugin does not persist source files or parsed messages to disk.

Audit logs go to stderr and record query metadata without message bodies or absolute source paths. The source hash is used locally for change detection and is not logged or returned to the agent. These are declarations about this code path, not proof against a compromised runtime; use an OS firewall or sandbox when independently verifying the no-egress property.

### Reusable `evidence-mcp` library

The completeness rules are available as an independently installable Python package:

```bash
python -m pip install ./packages/evidence-mcp
```

Other MCP adapters for email, meetings, invoices, logs, and similar sources can map their evidence to the same checks. See [docs/evidence-mcp-protocol.md](docs/evidence-mcp-protocol.md) and [docs/evidence-mcp.schema.json](docs/evidence-mcp.schema.json). Confirm package-name availability before publishing to PyPI.

### Current scope

- One configured local file per server process. Telegram Desktop full exports can expose multiple conversations; QQ exports use the configured local conversation ID.
- No platform API connector, real-time message push, or background synchronization.
- The Prompt guides the agent but cannot force a model to follow its instructions.
- **Chat parsing** makes no network requests and does not decrypt data, inject into client processes, or read client memory. The single opt-in exception is `trust_gate`: it needs explicit `allow_network=true` (one call only), reaches allowlisted endpoints only, and sends a target identifier only.
- The MCP host may send returned message text to its configured model, depending on the agent and client settings.

### Development and tests

Tests use the Python standard library; `pytest` is not required:

```bash
python -m unittest discover tests
python -m compileall -q src tests benchmarks
python -m json.tool docs/tool-schemas.json
```

The synthetic fixtures cover QQ CSV/JSON/JSONL, Telegram auto-detection and multi-chat exports, ambiguous and truncated files, malformed rows, duplicate IDs, incomplete time coverage, parser conformance, byte-offset paging, and result limits. To run the synthetic source-cache benchmark:

```bash
python benchmarks/benchmark_source_cache.py --rows 20000
```

To measure JSONL index construction and page reads on generated data:

```bash
python benchmarks/benchmark_jsonl_index.py --rows 100000
```

### License

MIT. See [LICENSE](LICENSE).
