Skip to main content
Glama
keshrath

agent-knowledge

by keshrath

agent-knowledge

License: MIT Node >= 20 Tests: 563 passing MCP Tools: 6 LongMemEval R@5: 98.8%

面向 AI 编码助手的跨会话记忆与召回 —— 开箱即用地支持 Claude Code、Cursor、OpenCode、Cline、Continue.dev 和 Aider。Git 同步的知识库、混合语义 + TF-IDF 搜索、自动蒸馏并清洗机密信息。

基准测试: 在 longmemeval_s 上 R@5 = 97.2%(稀疏)/ 98.8%(混合),在更难的 longmemeval_m 分割上 86.0%(稀疏)/ 88.4%(混合) —— 这是公开的 LongMemEval 学术基准(Wu 等人,2024,ICLR 2025),每个分割 500 个完整问题,无需 LLM、无需 API 密钥,完全离线运行。在与论文的苹果对苹果复现中,R@5 比论文官方 flat-bm25 基线高出 +8.6 到 +13.2 个百分点。完整的按类别表格、复现说明和论文对比细节见 bench/README.md。

为什么

AI 编码会话是短暂的。当会话结束时,它学到的一切——架构决策、调试见解、项目上下文——都消失了。下一个会话从零开始。

agent-knowledge 通过两个互补系统解决这个问题:

  1. 知识库 —— 一个 Git 同步的 Markdown 仓库,包含结构化条目(决策、工作流、项目上下文),跨会话和跨机器持久化。

  2. 会话搜索 —— 对所有编码工具的会话记录进行 TF-IDF 排序的全文搜索,让代理能够回忆之前发生的事情——无论使用哪个工具。

Related MCP server: Memory-MCP

支持的工具

所有主流 AI 编码助手的会话都会被自动发现——如果安装了某个工具,它的会话会自动出现。

工具

格式

自动检测路径

Claude Code

JSONL

~/.claude/projects/

Cursor

JSONL

~/.cursor/projects/*/agent-transcripts/

Codex CLI

JSONL

~/.codex/projects/

Aider

Markdown/JSONL

.aider.chat.history.md / .aider.llm.history 在项目目录中

Continue.dev

JSON

~/.continue/projects/

Cline

JSON

VS Code globalStorage saoudrizwan.claude-dev/tasks/

OpenCode

SQLite

~/.local/share/opencode/opencode.db(或 $OPENCODE_DATA_DIR)

无需配置。可以通过 AGENT_KNOWLEDGE_EXTRA_SESSION_ROOTS 环境变量(逗号分隔的路径)添加额外的会话根目录。

功能

  • 与宿主无关的会话搜索 —— 统一搜索所有主流 AI 编码助手(Claude Code、Cursor、Codex CLI、Aider、Continue.dev、Cline、OpenCode)。配置中不硬编码任何宿主名称——适配器注册表在启动时探测已安装的宿主根目录。

  • 混合搜索 —— 语义向量相似度与 TF-IDF 关键词排名混合

  • Git 同步的知识库 —— 带 YAML frontmatter 的 Markdown 仓库,写入时自动提交并推送

  • 自动过时检测 —— knowledge_analyze(action: "stale_by_code_activity") 将每个条目正文中提到的文件路径与最近会话摘要中的 filesModified 进行交叉引用。配合符号存在性精确层:检查条目引用的标识符(内联反引号 + 围栏代码块)是否在受影响的文件中;如果仍然存在,置信度下调 ×0.3。带有 evergreen: true 的条目豁免。

  • 搜索缺口跟踪 —— knowledge_analyze(action: "search_gaps") 显示过去 since_days 内的零结果查询,按 token-Jaccard 相似度分组。这是“接下来应该写什么条目?”的最清晰信号。

  • 分区优先级上下文打包器 —— knowledge(action: "wakeup") 在 token 预算内(默认 800,可通过 token_budget 或 AGENT_KNOWLEDGE_WAKEUP_BUDGET 覆盖)组装多分区捆绑包(identity → active_tasks → recent_decisions → known_gotchas → last_session_summary → top_weighted → semantic_fallback)。未使用的分区预算会重新分配给后面的分区。

  • 评分 + 门控提升器 —— 通过 6 信号加权评分器提升会话洞察,带有三个独立门控(minScore、minRecallCount、minUniqueQueries)。自动在后台运行,可通过 knowledge_admin(action: "promote") 按需运行,或通过 npm run bench:promote 离线基准测试。每次运行都会生成可审计的 .dreams/YYYY-MM-DD.md 日记。

  • 可插拔适配器系统 —— 通过实现 SessionAdapter 接口来添加对新工具的支持

  • 嵌入 —— 本地(Hugging Face)、OpenAI、Claude/Voyage 或 Gemini 提供商

  • 模糊匹配 —— 使用 Levenshtein 距离的容错搜索

  • 6 种搜索范围 —— 错误、计划、配置、工具、文件、决策

  • 6 个 MCP 工具 —— 统一的基于操作的接口(knowledge、knowledge_search、knowledge_session、knowledge_graph、knowledge_analyze、knowledge_admin)

  • 常青条目 —— frontmatter 中的 evergreen: true 使条目在排名中免于衰减,并在提升时仅允许追加。仪表板在这些卡片上显示图钉徽章。

  • 作者归属 —— 可选的 author: <string> frontmatter 在每张卡片上显示为弱化的标签。

  • 代码图解析 —— 用于代码结构的 calls、imports、inherits 边类型;有向 BFS 遍历(outbound/inbound/both);bulk_link 用于高效摄取;unlink_by_origin 用于在重新摄取前清除过时的代码边;code: 前缀的节点 ID 区分代码与知识

  • 时间知识图 —— 边支持 valid_from / valid_to 有效性窗口;as_of 查询返回时间点快照;invalidate 操作将事实标记为已结束而不删除它们

  • 混合评分提升 —— 在 TF-IDF + 语义混合之上增加专有名词和时间邻近性提升,上限为 +66.7%,无信号时短路

  • 类别作为提升(而非过滤) —— 选择 category_mode: "boost",这样错误的类别猜测会降低排名,而不是丢弃正确答案

  • 逐字会话索引 —— 将每条消息的块(≥30 字符)嵌入向量存储,使原始对话可检索;通过 AGENT_KNOWLEDGE_INDEX_VERBATIM=false 切换

  • 可配置的 Git URL —— knowledge_admin(action: "config") 用于运行时设置,持久化在 XDG/AppData 位置

  • 跨机器持久化 —— 知识通过 git 同步,会话从每个工具的本地存储读取

  • 实时仪表板 —— 在 localhost:3423 浏览、搜索和管理

  • 机密清洗 —— API 密钥、令牌、密码、私钥在 git push 前自动编辑

  • 知识图 —— 条目之间的关系边(related_to、supersedes、depends_on、contradicts、specializes、part_of、alternative_to、builds_on)及 BFS 遍历

  • 置信度/衰减评分 —— 根据访问频率和最近性对条目评分;从候选自动提升到已建立再到已验证

  • 记忆整合 —— 写入时进行 TF-IDF 重复检测(警告相似条目),加上 knowledge_analyze(action: "consolidate") 进行批量去重扫描

  • 反思循环 —— knowledge_analyze(action: "reflect") 显示未连接的条目,并生成结构化提示,让代理识别新的图连接

  • 写入时自动链接 —— 当余弦相似度 > 0.7 时,新条目自动链接到前 3 个相似现有条目

  • 置信度元数据 —— 条目标记为 extracted(用户编写)或 inferred(自动蒸馏,0.85× 搜索排名乘数);confidence_score 字段携带模型的确定性 0-1

  • 知识分析 —— knowledge_analyze 操作 god_nodes(连接最多的条目)、bridges(跨类别连接器)、gaps(孤立条目)

  • 知识简报 —— knowledge_analyze(action: "brief") 返回缓存的约 200 token 摘要(核心概念、活跃项目、最近决策、过时和缺口计数),用于会话开始时的定向

  • 边来源 —— 图边跟踪 origin(manual、auto-link、distill、reflect),以便分析区分用户判断与自动化启发式

  • 蒸馏中的确定性预提取 —— 会话摘要现在包括通过正则表达式从 bash/工具输出中提取的 git 提交、错误模式、访问的 URL 和更改的包(无 LLM 成本)

  • 每次搜索命中的新鲜度元数据 —— 每个知识结果都携带 freshness: { body_age_days, last_accessed, access_count, verified_at, verification_age_days, evergreen }。代理读取信任信号并自行决定;我们不施加任何策略降级。

  • 按类别衰减窗口 —— “未使用”过滤器和按类型图表遵循按类别阈值(项目 180 天、人员 365 天、决策 90 天、工作流 60 天、笔记 30 天),这样身份类内容不会仅仅因为不是每周重读而显得过时。

  • 生命周期钩子 —— SessionStart 自动唤醒 + 摄取新鲜度检查,UserPromptSubmit 首次提示定向注入,PreCompact 内存刷新提示 + 蒸馏,SessionEnd 蒸馏。共六个钩子脚本,全部故障开放,每个可通过 AGENT_KNOWLEDGE_* 环境变量切换。参见 docs/HOOKS.md。

  • 取代宿主自动记忆 —— 在具有每会话记忆系统的宿主上(Claude Code 的 ~/.claude/projects/*/memory/,其他 IDE 类似),将持久的用户事实和反馈路由到 agent-knowledge 而不是自动记忆。自动记忆是机器本地的,对其他机器不可见;agent-knowledge 是 git 同步的、跨机器的、可搜索的,并在唤醒时显示。参见 docs/USER-MANUAL.md 中的 Claude Code 集成说明。

代码库摄取

knowledge-ingest 技能从代码库目录填充或更新知识库。它使用 tree-sitter 进行零 token 的结构提取(类、函数、导入、调用图、原理注释),然后将文件聚类为子系统,并通过现有的 MCP 工具创建知识条目 + 图边。后续运行是增量的——只重新处理更改的文件。

/knowledge-ingest ./my-project

使用 Agent Skills 标准 —— 适用于 Claude Code、OpenCode、Cursor、Codex CLI 和 Gemini CLI。详见 摄取指南。

支持的语言: TypeScript、JavaScript、Python、Go、Rust、Java、C、C++。

快速开始

从 npm 安装

npm install -g agent-knowledge

或从源码克隆

git clone https://github.com/keshrath/agent-knowledge.git
cd agent-knowledge
npm install && npm run build

选项 1:MCP 服务器(用于 AI 代理)

添加到你的 MCP 客户端配置(Claude Code、Cline 等):

{
  "mcpServers": {
    "agent-knowledge": {
      "command": "npx",
      "args": ["agent-knowledge"]
    }
  }
}

仪表板在首次 MCP 连接时自动启动于 http://localhost:3423。

参见 设置指南 获取特定客户端的说明(Claude Code、Cursor、Windsurf、OpenCode)。

选项 2:独立服务器(用于 REST/WebSocket 客户端)

node dist/server.js --port 3423

MCP 工具(6)

知识库

工具

操作

描述

参数

knowledge

list

按分类和/或标签列出条目

category?, tag?

read

读取特定条目

path(必填)

write

创建/更新条目(自动 git 同步)

category, filename, content(均必填)

delete

删除条目(自动 git 同步)

path(必填)

sync

手动 git pull + push

--

wakeup

返回 L0 身份 + L1 权重最高的条目(受 token 预算限制)

token_budget?, category?

搜索

工具

描述

参数

knowledge_search

通用混合 TF-IDF + 语义搜索(无 scope)

query, project?, role?, max_results?, ranked?, semantic?, category?, category_mode?, mmr?, mmr_lambda?, explain?

限定会话范围的召回(当设置 scope 时)

query, scope, project?, max_results?

响应格式:{mode: "general" | "scoped", sessions, knowledge}。限定范围模式按设计返回 knowledge: []。

范围:errors, plans, configs, tools, files, decisions, all。

搜索调节选项:

  • mmr: true 应用最大边际相关性(Maximal Marginal Relevance)重排序(消除 top-K 中的近似重复簇)。mmr_lambda 取值范围 0-1,默认 0.7。

  • category_mode: "boost"(默认)为匹配分类的条目提供 1.25× 的分数乘数,而不是丢弃不匹配的条目。传入 "filter" 可进行硬过滤。

  • explain: true 为每条知识命中附加 score_components: {bm25, decay, maturity, confidence, category_boost, mmr_penalty}。

会话

工具

操作

描述

参数

knowledge_session

list

列出带元数据的会话

project?

get

检索完整会话对话

session_id, project?, include_tools?, tail?

summary

会话摘要(主题、工具、文件)

session_id, project?

知识图谱

工具

操作

描述

参数

knowledge_graph

link

创建/更新条目之间的边

source, target, rel_type, strength?

unlink

移除条目之间的边

source, target, rel_type?

invalidate

将边标记为过期(设置 valid_to)

source, target, rel_type?, valid_to?

list

列出边

entry?, rel_type?, as_of?

traverse

从条目进行有向 BFS 遍历

entry, depth?, direction?, rel_type?, as_of?

bulk_link

批量创建边(代码图谱摄取)

edges({source, target, rel_type, strength?, origin?} 数组)

unlink_by_origin

按来源删除所有边

origin

知识类型:related_to, supersedes, depends_on, contradicts, specializes, part_of, alternative_to, builds_on 代码结构类型:calls, imports, inherits

遍历方向:outbound(source→target)、inbound(target→source)、both(默认,无向)

分析

工具

操作

描述

参数

knowledge_analyze

consolidate

查找近似重复条目

category?, threshold?

reflect

查找未连接的条目以进行链接

category?, max_entries?

god_nodes

连接最多的条目(度中心性)

top_n?

bridges

跨分类连接器(介数中心性)

top_n?

gaps

按成熟度查找孤立条目(0-1 条边)

max_entries?

brief

缓存的约 200 token 知识库摘要

--

管理

工具

操作

描述

参数

knowledge_admin

status

向量存储统计

--

config

查看或更新配置

git_url?, memory_dir?, auto_distill?

rebuild_embeddings

重新嵌入所有知识条目(在切换提供商时有用)

--

prune_orphans

删除磁盘上已不存在会话的嵌入

vacuum?, force_vacuum?

vacuum

回收向量存储中的空闲页

--

promote

带评分和门控的提升器

promote_mode?(apply|explain)、min_score?、min_recall_count?、min_unique_queries?

评分提升器

每个项目级候选条目基于六个信号进行评分(相关性 0.30、频率 0.24、查询多样性 0.15、时效性 0.15、整合度 0.10、概念丰富度 0.06),并通过 minScore ≥ 0.5、minRecallCount ≥ 2、minUniqueQueries ≥ 2 进行门控。三个门控必须全部通过。后台自动提升由相同的 auto_distill 配置标志控制;可通过 knowledge_admin(action: "promote") 按需调用。

  • promote_mode: "explain"(默认)— 对候选条目进行评分 + 门控,写入日志,不修改知识库。

  • promote_mode: "apply" — 提升通过的候选条目,写入日志,git 提交。

  • 每次运行都会在 ~/agent-knowledge/.dreams/YYYY-MM-DD.md 中写入每个候选条目的信号分解和门控结果。以 . 开头的目录由 git 跟踪,但被排除在列表/搜索之外。

  • 基于来源的再水合:如果候选条目的源会话文件在磁盘上不再存在,则跳过该候选条目(防止提升已删除的内容)。

  • 带有 evergreen: true frontmatter 的条目永远不会被提升覆盖 — 活动会被追加。

写入基准测试工具:npm run bench:promote — 离线回放,通过"在后续会话中被引用"自动标注。将门控提升器与朴素的"全部发布"基线进行比较,报告精确率 / 召回率 / F1。在推出信号权重或阈值更改之前,使用它进行门控。

REST API

方法

端点

描述

GET

/api/knowledge

列出知识条目

GET

/api/knowledge/search?q=

搜索知识库

GET

/api/knowledge/:path

读取特定条目

GET

/api/knowledge/god-nodes?top_n=

连接最多的条目

GET

/api/knowledge/bridges?top_n=

跨分类连接器

GET

/api/knowledge/gaps?max_entries=

孤立条目

GET

/api/knowledge/brief

知识库摘要

GET

/api/sessions

列出会话

GET

/api/sessions/search?q=&role=&ranked=

搜索会话(TF-IDF)

GET

/api/sessions/recall?scope=&q=

限定范围召回

GET

/api/sessions/:id

读取会话

GET

/api/sessions/:id/summary

会话摘要

POST

/api/knowledge

写入条目(HTTP 客户端)

GET

/health

健康检查

架构

graph LR
    subgraph Storage
        KB[(Knowledge Base<br/>~/agent-knowledge<br/>Git Repository)]
    end

    subgraph Session Sources
        CC[(Claude Code<br/>JSONL)]
        CU[(Cursor<br/>JSONL)]
        OC[(OpenCode<br/>SQLite)]
        CL[(Cline<br/>JSON)]
        CD[(Continue.dev<br/>JSON)]
        AI[(Aider<br/>MD / JSONL)]
    end

    subgraph agent-knowledge
        KM[Knowledge Module<br/>store / search / git]
        AD[Session Adapters<br/>auto-discovery]
        SE[Search Engine<br/>TF-IDF + Fuzzy]
        DS[Dashboard<br/>:3423]
        MCP[MCP Server<br/>stdio]
    end

    subgraph Clients
        AG[Agent Sessions]
        WB[Web Browser]
    end

    KB <-->|git pull/push| KM
    CC --> AD
    CU --> AD
    OC --> AD
    CL --> AD
    CD --> AD
    AI --> AD
    AD --> SE
    KM --> MCP
    SE --> MCP
    KM --> DS
    SE --> DS
    MCP --> AG
    DS --> WB

知识图谱

条目和代码符号可以通过存储在专用 edges SQLite 表中的类型化、加权边进行连接。支持十一种关系类型 — 8 种用于知识边,3 种用于代码结构:

知识:related_to, supersedes, depends_on, contradicts, specializes, part_of, alternative_to, builds_on 代码结构:calls, imports, inherits

  • knowledge_graph(action: "link") 创建或更新边(可带 0-1 的强度值)

  • knowledge_graph(action: "unlink") 移除边(可选按类型过滤)

  • knowledge_graph(action: "list") 列出条目或关系类型的边

  • knowledge_graph(action: "traverse") 从起始条目执行有向 BFS 遍历。支持 direction(outbound、inbound、both)和 rel_type 过滤器

  • knowledge_graph(action: "bulk_link") 在单个事务中批量创建边(用于代码图谱摄取)

  • knowledge_graph(action: "unlink_by_origin") 删除具有特定来源的所有边(用于在重新摄取前清除过期的代码边)

代码图谱

代码结构边由 knowledge-ingest 技能在代码库摄取期间创建。它们使用 code: 前缀的节点 ID:

code:src/auth/middleware.ts                    # file node
code:src/auth/middleware.ts::validateToken      # symbol node

查询示例:

# Who calls validateToken?
knowledge_graph({ action: "traverse", entry: "code:src/auth.ts::validateToken", direction: "inbound", rel_type: "calls", depth: 3 })

# What breaks if I change this function?
knowledge_graph({ action: "traverse", entry: "code:src/auth.ts::validateToken", direction: "inbound", rel_type: "calls", depth: 5 })

# Combined: callers + knowledge context (decisions, design rationale)
knowledge_graph({ action: "traverse", entry: "code:src/auth.ts::validateToken", depth: 2 })

自动链接

当 knowledge 以 action: "write" 创建或更新条目时,它会自动通过余弦相似度找到最相似的 3 个现有条目,并为任何得分高于 0.7 的配对创建 related_to 边。

置信度与衰减评分

每个知识条目都有一个置信度分数,跟踪在 entry_scores SQLite 表中。搜索结果使用以下公式排名:

finalScore = baseRelevance * 0.5^(daysSinceLastAccess / 90) * maturityMultiplier

条目根据访问次数自动成熟:

阶段

访问次数

倍数

candidate

< 5

0.5x

established

5-19

1.0x

proven

20+

1.5x

频繁访问的条目在搜索排名中会上升;过时的条目会随时间衰减。

搜索能力

TF-IDF 排名 —— 结果按词频-逆文档频率(term frequency-inverse document frequency)评分。稀有词会提升相关性。全局索引缓存 60 秒。

模糊匹配 —— 基于 Levenshtein 编辑距离的滑动窗口匹配。阈值可配置(默认 0.7)。

作用域召回 —— 通过 knowledge_search 的 scope 参数实现:

作用域

匹配内容

errors

堆栈跟踪、异常、失败的命令

plans

架构、待办事项、实现步骤

configs

设置、环境变量、配置文件

tools

MCP 工具调用、CLI 命令

files

文件路径、修改

decisions

权衡、理由、选择

集成

REST 写入端点

POST /api/knowledge 接受 { category, filename, content } 并运行完整的写入流水线:git pull → 文件写入 → 嵌入索引 → 自动链接 → git push → 重复检查。返回 { path, autoLinks?, duplicateWarnings?, git },状态码为 201。

这使得其他服务无需 MCP 连接即可通过 HTTP 进行写入。

agent-tasks KnowledgeBridge

agent-tasks 内置了 KnowledgeBridge,会在任务完成时自动将 learning 和 decision 工件推送到 agent-knowledge。条目会落入 decisions/ 目录并带有 frontmatter 标签(agent-tasks、项目名称、工件类型),自动进行嵌入索引,并自动链接到相似条目。无需配置——只要 agent-knowledge 运行在 localhost:3423,即可正常工作。

测试

npm test              # 563 tests across 35 files
npm run test:watch    # Watch mode
npm run lint          # ESLint on src/ and tests/
npm run typecheck     # tsc --noEmit
npm run check         # typecheck + lint + format + test

环境变量

所有环境变量均以 AGENT_KNOWLEDGE_* 前缀命名。没有硬编码的主机名——适配器注册表会自动检测已安装的 AI 编码主机(.claude、.cursor、.codex、.aider、.continue、OpenCode),无需配置。

核心

变量

默认值

描述

AGENT_KNOWLEDGE_MEMORY_DIR

~/agent-knowledge

Git 同步的知识库目录

AGENT_KNOWLEDGE_GIT_URL

--

Git 远程仓库 URL(若目录不存在则自动克隆)

AGENT_KNOWLEDGE_AUTO_DISTILL

true

自动将会话洞察提炼到知识库中

AGENT_KNOWLEDGE_INDEX_VERBATIM

true

将原始会话消息块索引到向量存储中,以便后续可检索会话内容。在规模较大时设为 false 可节省磁盘空间。

AGENT_KNOWLEDGE_DATA_DIR

(平台配置)

覆盖主主机数据根目录。常规情况下保持未设置——适配器会自动检测 ~/ 下所有已知的主机根目录。

AGENT_KNOWLEDGE_EXTRA_SESSION_ROOTS

--

额外的会话目录,以逗号分隔。会添加到自动检测到的结果之上。

AGENT_KNOWLEDGE_PORT

3423

仪表板 HTTP/WebSocket 端口

嵌入

变量

默认值

描述

AGENT_KNOWLEDGE_EMBEDDING_PROVIDER

local

local | openai | claude | gemini

AGENT_KNOWLEDGE_EMBEDDING_ALPHA

0.3

TF-IDF 与语义混合权重(0 = 纯语义,1 = 纯 TF-IDF)

AGENT_KNOWLEDGE_EMBEDDING_MODEL

--

覆盖提供商的默认模型

AGENT_KNOWLEDGE_EMBEDDING_IDLE_TIMEOUT

60

卸载本地模型前的空闲秒数(0 = 保持加载)

AGENT_KNOWLEDGE_EMBEDDING_THREADS

(自动)

本地提供商的 ONNX / OMP 线程数

API 密钥

项目级覆盖优先于标准密钥。设置任一即可;项目级形式允许你使用与环境中其他部分不同的密钥来运行 agent-knowledge。

变量

回退

描述

AGENT_KNOWLEDGE_OPENAI_API_KEY

OPENAI_API_KEY

OpenAI 嵌入

AGENT_KNOWLEDGE_ANTHROPIC_API_KEY

ANTHROPIC_API_KEY

Claude / Voyage 嵌入

AGENT_KNOWLEDGE_GEMINI_API_KEY

GEMINI_API_KEY

Gemini 嵌入

钩子

变量

默认值

描述

AGENT_KNOWLEDGE_AUTOWAKE

1

自动将 knowledge(action: wakeup) 包注入 SessionStart。设为 0 可禁用。

AGENT_KNOWLEDGE_WAKEUP_BUDGET

800

唤醒包的令牌数

AGENT_KNOWLEDGE_FIRSTPROMPT_INJECT

1

在首个用户提示上执行定向 knowledge_search 并注入最佳命中结果。设为 0 / false / off 可禁用。

AGENT_KNOWLEDGE_FIRSTPROMPT_BUDGET

600

首提示注入的令牌数(限制在 [100, 8000] 范围内)

AGENT_KNOWLEDGE_FIRSTPROMPT_MAX_HITS

4

附加到首提示的最大知识命中数(限制在 [1, 20] 范围内)

AGENT_KNOWLEDGE_PRECOMPACT_NUDGE

1

在预压缩之前,提示代理通过 knowledge(action: write) 保存上下文。0 禁用提示;off 同时抑制提示和磁盘转储。

外部工具覆盖

变量

默认值

描述

OPENCODE_DATA_DIR

~/.local/share/opencode

覆盖 OpenCode 会话数据库的存储位置(OpenCode 自身的环境变量,我们的适配器会予以识别)

文档

  • 设置指南 —— 安装、客户端设置(Claude Code、OpenCode、Cursor、Windsurf)、钩子、技能

  • 摄取指南 —— 代码库摄取技能、tree-sitter 提取、增量更新

  • 架构 —— 源码结构、设计原则、数据库模式

  • 仪表板 —— Web UI 视图与功能

  • 更新日志

许可证

MIT

Available Tools

6 tools
knowledgeA

Knowledge base CRUD, sync, and session-start hydration. Actions: "list" (browse entries), "read" (get entry content), "write" (create/update entry, auto git sync), "delete" (remove entry, auto git sync), "sync" (manual git pull + push), "wakeup" (return token-budgeted section-priority context bundle — identity, active_tasks, recent_decisions, known_gotchas, last_session_summary, top_weighted, semantic_fallback — call once at session start).

ParametersJSON Schema
NameRequiredDescriptionDefault
tagNoFilter by tag (action=list)
pathNoRelative path to the entry, e.g. 'projects/my-project.md' (action=read, delete)
actionYesAction to perform
contentNoFull markdown content for the entry (action=write)
categoryNoCategory (action=list: filter; action=write: target directory). One of: projects, people, decisions, workflows, notes
filenameNoFilename with or without .md extension (action=write), e.g. 'my-project.md'
sectionsNo[wakeup] Comma-separated, ordered section list. Valid: identity, active_tasks, recent_decisions, known_gotchas, last_session_summary, top_weighted, semantic_fallback. Default: all seven in that order. Omit to preserve v1.8.0 behaviour.
token_budgetNo[wakeup] Max tokens to render (chars/4 estimate, default 800)
section_budgetsNo[wakeup] Per-section token-budget overrides, e.g. {"identity": 200, "top_weighted": 400}. Unspecified sections split the remainder evenly. Unused budget redistributes to later sections.

TDQS

A3.5/5.0
Behavior4/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

No annotations are provided, so the description carries the full burden — and it does disclose meaningful side effects: write/delete trigger auto git sync, sync is a manual git pull+push, and wakeup returns a token-budgeted section-priority bundle. This is solid disclosure for a mutation-capable tool; it only omits reversibility (e.g., whether delete is recoverable from git history) and confirmation behavior.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness3/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The purpose is front-loaded and the content is dense and informative, but it is presented as one long run-on sentence without line breaks or structural separation, making the six actions and their caveats harder to parse at a glance. Fewer words could be used; the parentheticals are useful but poorly delimited.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness3/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

For a high-complexity tool (9 params, 6 actions, enums, nested objects) with no output schema, the description explains wakeup's return bundle but not the return values for the other five actions (e.g., what list returns, what read returns on success/failure). The schema covers parameter semantics well, but the absence of output descriptions for the remaining actions leaves gaps.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters3/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema coverage is 100%, so the input schema already documents all nine parameters with action-scoped descriptions. The description adds value on top by explaining wakeup semantics — section ordering, defaults, budget behavior — but does not substantially enrich the other parameters beyond what the schema states. A baseline of 3 is appropriate given the high schema coverage.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose4/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description states a clear purpose ('Knowledge base CRUD, sync, and session-start hydration') and enumerates six concrete actions with brief one-line definitions. It implicitly distinguishes from siblings (search, graph, analyze) by being the CRUD/sync/wakeup orchestrator, though it never names the siblings or their differing responsibilities explicitly.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines3/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

Usage context is conveyed per-action ('call once at session start' for wakeup, 'auto git sync' for write/delete) and the verb definitions imply when each is appropriate. However, with five siblings present, there is no explicit when-to-use-versus-alternative guidance (e.g., when to prefer knowledge_search over this tool's list action), and no exclusions are stated.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

knowledge_adminB

Admin operations: view vector store stats, view/update configuration, rebuild embeddings, prune orphan session embeddings, or VACUUM the database. Use action "status" for index stats, "config" to view or update settings, "rebuild_embeddings" to re-embed all knowledge entries (useful when switching providers), "prune_orphans" to delete embeddings for sessions no longer present on disk, "vacuum" to reclaim free pages.

ParametersJSON Schema
NameRequiredDescriptionDefault
actionYesAction: status (vector store stats), config (view/update settings), rebuild_embeddings (re-embed all entries), prune_orphans (delete embeddings for missing sessions), vacuum (reclaim free pages), promote (run the scored promoter — see promote_mode)
vacuumNoRun VACUUM after pruning (action=prune_orphans, default true)
git_urlNoGit remote URL (action=config). Set to empty string to remove.
min_scoreNo[promote] Minimum composite score to promote (default: 0.5).
memory_dirNoLocal knowledge base directory (action=config). Empty to reset.
auto_distillNoEnable/disable scheduled promotion (action=config)
force_vacuumNoRun VACUUM even if no orphans were pruned (action=prune_orphans)
promote_modeNoaction=promote mode (default: explain). "explain" returns score breakdowns without writing; "apply" promotes candidates that pass all gates.
min_recall_countNo[promote] Minimum recall count gate (default: 2).
min_unique_queriesNo[promote] Minimum unique-query gate (default: 2).

TDQS

B3.3/5.0
Behavior3/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

With no annotations provided, the description carries the full burden of behavioral disclosure, and it does disclose destructive effects for prune_orphans ('delete embeddings') and vacuum ('reclaim free pages'). However, it understates rebuild_embeddings' destructive rewriting of existing embeddings, and it completely omits the 'promote' action's behavior (apply vs explain modes, write behavior vs read-only). For a tool with several destructive operations, the disclosure is partial.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness4/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The core operations are front-loaded in the opening sentence, with each action's purpose expanded in a single subsequent sentence. The structure is efficient and scannable. Minor deduction for the slightly run-on single-sentence expansion and for leaving out promote, which makes the list feel incomplete rather than intentionally concise.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness2/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

For a complex admin tool with 10 parameters, 6 actions, no output schema, and no annotations, the description should be comprehensive — but it covers only 5 of 6 actions and omits the entire promote workflow with its 4 dedicated parameters (promote_mode, min_score, min_recall_count, min_unique_queries). An agent reading only the description would never learn a whole callable mode exists, which is a significant completeness gap.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters3/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema coverage is 100%, so the schema already documents all 10 parameters, giving a baseline of 3. The description adds marginal value by linking rebuild_embeddings to the provider-switching use case, but it adds no semantics beyond the schema for the config params (git_url, memory_dir, auto_distill) and leaves the promote-related parameters entirely unexplained in prose despite them being a substantial cluster of the schema.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose4/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description states a clear purpose — administrative operations on the knowledge/vector store — and enumerates five concrete actions (status, config, rebuild_embeddings, prune_orphans, vacuum) with their effects. It clearly distinguishes itself from the read/search siblings. However, it silently omits the 'promote' action that exists in the schema enum, and the umbrella phrase 'Admin operations' is vague until the action list clarifies it.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines3/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description gives actionable when-to-use context for rebuild_embeddings ('useful when switching providers') and explains what each action accomplishes, which implicitly routes the agent to the right action. But it provides no guidance for the 'promote' action (its dedicated params min_score, min_recall_count, min_unique_queries, promote_mode are never narrated), and it never states when NOT to use the tool or how it differs from siblings beyond 'admin' framing.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

knowledge_analyzeA

Analysis tools: find duplicates, unconnected entries, most-connected concepts (god nodes), bridge entries, knowledge gaps, zero-result search queries, stale-by-code-activity entries, or generate a compact knowledge brief. Actions: consolidate, reflect, god_nodes, bridges, gaps, brief, search_gaps, stale_by_code_activity.

ParametersJSON Schema
NameRequiredDescriptionDefault
top_nNoNumber of results (action=god_nodes default: 10, action=bridges default: 5)
actionYesAction: consolidate (find duplicates), reflect (find unconnected entries), god_nodes (most-connected entries), bridges (cross-cluster connectors), gaps (entries with 0-1 edges), brief (compact knowledge base summary), search_gaps (zero-result knowledge_search queries grouped by similarity — the single best signal for "what entries should I write next?"), stale_by_code_activity (entries whose referenced file paths were modified in recent sessions after the entry body was last edited — automatic staleness signal, v1.8.1).
categoryNoScan only this category (omit for all)
min_countNo[search_gaps] Minimum occurrence count per merged group (default: 1). Raise to surface only repeated misses.
thresholdNoSimilarity threshold 0-1 (action=consolidate, default: 0.5)
since_daysNo[search_gaps] Lookback window in days (default: 30). Only queries logged within this window are considered.
max_entriesNoMax unconnected entries to include (action=reflect, default: 20)
group_similarityNo[search_gaps] Jaccard token similarity threshold for merging near-duplicate queries (default: 0.35, range 0-1). Low because short queries yield low Jaccard even when topically related.
min_touching_sessionsNo[stale_by_code_activity] Minimum distinct sessions that must have modified one of the entry's referenced files for it to be flagged (default: 1).

TDQS

A3.6/5.0
Behavior2/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

With no annotations provided, the description bears the full disclosure burden, yet it is internally contradictory on the consolidate action: the verb implies merging/mutation while the gloss '(find duplicates)' implies read-only discovery. There is no statement about whether any action mutates entries, what output shape results, or performance implications — a real gap for a multi-action analysis tool.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness4/5

Is the description appropriately sized, front-loaded, and free of redundancy?

Purpose is front-loaded in the first sentence and the whole description runs roughly 60 words with no filler. The trailing 'Actions:' enumeration is partially redundant with the schema enum but serves as a useful name→semantic mapping, earning its place.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness3/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

This is a complex tool — 9 parameters, 8 actions, no output schema, no annotations. All action semantics are enumerated, but the description is silent on per-action return formats and on whether any action (notably consolidate) has side effects, both material for an analysis surface of this breadth.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters3/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema coverage is 100% and the schema's parameter descriptions are unusually rich (per-action defaults, the Jaccard rationale for group_similarity, min_count semantics). The tool description adds little beyond re-listing action names, so the schema-carrying baseline of 3 is correct.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description enumerates eight distinct analyses with denotative glosses (duplicates, unconnected entries, god nodes, bridges, gaps, zero-result queries, stale-by-code-activity, brief), clearly binding the tool to knowledge-base entry analysis. This differentiates it from siblings like knowledge_search (querying) and knowledge_admin (admin actions) without needing to open a schema.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines4/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

Each action carries clear context, e.g., 'gaps (entries with 0-1 edges)', 'bridges (cross-cluster connectors)', and search_gaps is explicitly framed as 'the single best signal for what entries should I write next?'. Missing, however, are explicit when-not or alternative statements that route selection against sibling tools at the tool level.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

knowledge_graphB

Knowledge graph operations with temporal validity and code structure support. Create/remove edges, traverse via directed BFS, bulk-import code graph edges. Relationship types: related_to, supersedes, depends_on, contradicts, specializes, part_of, alternative_to, builds_on, calls, imports, inherits. Code structure types (calls/imports/inherits) are created by knowledge-ingest and use "code:" prefixed node IDs.

ParametersJSON Schema
NameRequiredDescriptionDefault
as_ofNoISO date — only return edges valid at this date (action=list/traverse, optional)
depthNoMax traversal depth in hops (action=traverse, default: 2)
edgesNoArray of edges to create (action=bulk_link). Each: { source, target, rel_type, strength?, origin? }
entryNoEntry path for filtering (action=list) or BFS start (action=traverse)
actionYesAction: link (create edge), unlink (remove edge), invalidate (set valid_to), list (list edges), traverse (directed BFS), bulk_link (batch-create edges), unlink_by_origin (delete all edges from a specific origin)
originNoEdge origin to delete (action=unlink_by_origin). E.g. "tree-sitter" to clear code graph before re-ingest.
sourceNoSource entry path (action=link/unlink/invalidate), e.g. 'projects/my-project.md'
targetNoTarget entry path (action=link/unlink/invalidate), e.g. 'decisions/architecture.md'
rel_typeNoRelationship type (required for link, optional filter for unlink/invalidate/list)
strengthNoEdge strength 0-1 (action=link, default: 0.5)
valid_toNoISO date the fact stopped being true (action=link/invalidate). For invalidate, defaults to today.
directionNoTraversal direction (action=traverse, default: both). outbound: follow source→target (what does X call?). inbound: follow target→source (who calls X?). both: undirected (default, preserves legacy behavior).
valid_fromNoISO date the fact became true (action=link, optional). Null/omitted = unbounded.

TDQS

B3.1/5.0
Behavior3/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

With no annotations, the description carries the burden. It discloses temporal validity and that code structure edges are created by knowledge-ingest, which is useful. However, it does not warn about destructive side effects of unlink/invalidate or the scope of bulk operations, leaving behavioral uncertainty.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness4/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is reasonably concise, using three sentences to cover operations, relationship types, and code structure nuance. It could tighten by omitting the redundant relationship list from the enum, but it remains front-loaded and readable.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness2/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

No output schema is present, and the description does not describe return values for actions like list or traverse. It also omits details about state mutations (e.g., irreversibility of unlink). Given the tool's complexity and no annotations, this is a significant gap.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters3/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema description coverage is 100%, so baseline is 3. The description adds minimal value: it re-lists relationship types (already in the enum) and notes the 'code:' prefix for node IDs. It does not explain parameter interactions beyond what the schema already states.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose4/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the tool performs knowledge graph operations: create/remove edges, traverse via BFS, bulk-import code edges. It also lists relationship types and code structure specifics. However, it does not explicitly contrast with sibling tools like knowledge_search or knowledge_analyze, so differentiation relies on the implicit 'graph' focus.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines2/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

No explicit guidance on when to use this tool versus siblings. It does not mention when not to use it, nor does it reference alternative tools. The code structure note implies a use case, but there is no clear routing or exclusion.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

knowledge_sessionA

Session operations: list sessions, get a full conversation, or get a summary. Use action "list" to browse sessions, "get" to retrieve messages, "summary" for a quick overview.

ParametersJSON Schema
NameRequiredDescriptionDefault
tailNoOnly return the last N messages (action=get)
limitNoMax sessions to return (action=list, default: 20, max: 500)
actionYesAction to perform
offsetNoSkip first N sessions (action=list, default: 0)
projectNoFilter by project name (substring match)
session_idNoSession UUID (required for get, summary)
include_toolsNoInclude tool_use and tool_result messages (action=get, default: false)

TDQS

A3.5/5.0
Behavior2/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

With no annotations provided, the description carries full responsibility for behavioral disclosure. It states the actions but does not mention whether operations are read-only, side effects, required permissions, error behavior (e.g., invalid session_id), or any rate limits. For a tool with three read-like actions, this is a notable gap; the agent is left to infer safety and failure modes.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is two short sentences with zero waste. It front-loads the core concept 'Session operations' and immediately explains the three actions. Every sentence contributes to understanding the tool, making it highly efficient.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness3/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

The description provides enough to invoke the tool correctly for the three actions, but it omits the response format entirely. Since there is no output schema, the agent is unaware of what each action returns (e.g., list returns an array, get returns messages). For a multi-action tool, this is a moderate gap, though the actions are simple enough that an agent might infer typical behavior.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters3/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

All seven parameters are fully described in the schema (100% coverage), so the schema carries the heavy lifting. The description adds context for how the action parameter drives behavior (list vs get vs summary) and clarifies the purpose of some parameters indirectly (e.g., tail for get, limit for list), but it does not add new semantic detail beyond the schema. This aligns with the coverage baseline of 3.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the tool's purpose: 'Session operations: list sessions, get a full conversation, or get a summary.' It identifies three distinct actions (list, get, summary) and explicitly differentiates from sibling tools by focusing on session operations, which none of the sibling names (knowledge, knowledge_search, knowledge_admin, knowledge_graph, knowledge_analyze) cover.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines3/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description provides per-action guidance: 'Use action list to browse sessions, get to retrieve messages, summary for a quick overview.' This clarifies when to use each action, but it does not mention when to favor this tool over siblings such as knowledge_search or knowledge_analyze. There is no explicit exclusion or alternative routing at the tool level, though the action-level guidance is useful.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Tool Schema Changelog

Recent tool additions, removals, and schema changes observed during successful MCP inspections.

  1. 6 tool updatesv1.9.7
    • First observedknowledge
    • First observedknowledge_admin
    • First observedknowledge_analyze
    • First observedknowledge_graph
    • First observedknowledge_search
    • First observedknowledge_session

TDQS

A3.9/5.0

Scored across 6 tools

Disambiguation5/5

Each tool targets a distinct functional domain: CRUD operations, cross-source search, session management, admin/maintenance, graph relationships, and analysis/insights. The action-based sub-operations are clearly scoped, and there is no meaningful overlap between tools.

Naming Consistency5/5

All tool names follow the consistent pattern `knowledge_<verb_noun>` using snake_case throughout. The naming convention is uniform, with descriptive suffixes (search, session, admin, graph, analyze) that clearly differentiate purposes.

Tool Count5/5

Six tools is an ideal count for a knowledge-management server. Each tool encapsulates a distinct set of related operations (CRUD, search, sessions, admin, graph, analysis), providing comprehensive functionality without overwhelming the agent.

Completeness5/5

The toolset covers the full lifecycle of a knowledge base: creating/reading/updating/deleting entries, searching across sessions and entries, managing session history, performing administrative tasks (embeddings, vacuum), maintaining knowledge graph relationships, and deriving analytical insights. No obvious gaps exist; even advanced features like bulk graph import and orphan pruning are included.

Maintenance

ActivityMaintained
ResponsivenessNo issues

Related MCP Connectors

Related MCP Servers

  • A
    license
    Not graded
    quality
    C
    maintenance
    Provides persistent memory for AI coding assistants, storing and retrieving architectural decisions, patterns, and solutions across sessions using semantic search, while also offering git integration for commit messages and code expertise mapping.
    MIT
  • A
    license
    A
    quality
    D
    maintenance
    Provides persistent memory for AI agents using hybrid search (vector embeddings + BM25) with neural reranking, enabling storage and retrieval of insights, debugging solutions, and patterns across coding sessions.
    8
    MIT
  • A
    license
    Not graded
    quality
    D
    maintenance
    Provides AI coding assistants with persistent, context-rich memory of a codebase, including documentation and git history, enabling recall across sessions.
    105
    Apache 2.0
  • A
    license
    Not graded
    quality
    B
    maintenance
    Provides persistent, searchable memory and knowledge capture for AI-assisted development, enabling agents to retain decisions, bugs, and patterns across sessions and projects.
    MIT