关于 smart-context-mcp
smart-context-mcp 是面向编码 Agent 的 MCP 服务,通过压缩代码上下文和保存任务状态,减少重复读取与冗长结果。它提供语义代码导航、预算控制及持久化命令输出等工具。
主要功能
- 01压缩代码读取与搜索结果
- 02符号级定义、引用与影响分析
- 03跨工具共享 tokenBudget
- 04保存并检索命令输出
- 05任务检查点与恢复
适用场景
- 01在调试时检索相关代码和诊断
- 02限制多步骤 Agent 任务的上下文预算
- 03分析重命名影响并预览修改
- 04恢复先前保存的测试或构建输出
MCP 相关
作为 MCP 服务,向客户端提供读取、搜索、代码导航、任务管理等 smart_* 工具。
配置
本地服务的配置在各客户端中通用,复制后粘贴到客户端的 MCP 配置文件即可。
工具
本地服务需要在你的电脑上运行后才能读取工具,维护者暂未提供工具列表。
详细介绍
smart-context-mcp
MCP 服务通过智能上下文压缩,最多可减少 90% 的 AI Agent 令牌用量(根据本项目测得)。
简介
一个 MCP(Model Context Protocol)服务,提供专用于高效读取、搜索和管理代码上下文的工具。它不会加载完整文件或返回海量搜索结果,而是会压缩信息,同时保留与任务相关的关键内容。
生产环境中的实际指标:
- 约 700 万个令牌 → 约 80 万个令牌(减少约 89%)
- 开发过程中跟踪了 1,500 多次操作
- 压缩率:根据工具不同,为 3 倍至 46 倍
- 单独跟踪上下文开销,以便报告显示总节省量和净节省量
工作流级别的节省:
- 调试:令牌减少约 85%–90%
- 代码审查:令牌减少约 85%–90%
- 重构:令牌减少约 85%–90%
- 测试:令牌减少约 85%–90%
- 架构设计:令牌减少约 85%–90%
在非简单任务中的实际采用情况:
- 约 70%–75% 的复杂任务会使用 devctx 工具
- 最常用的工具:
smart_read(使用 850 多次)、smart_search(使用 280 多次)、smart_shell(使用 220 多次) - 不使用的主要原因:任务过于简单、尚未构建索引、优先使用原生工具
最新版本:1.21.0
围绕语义引擎构建的小版本。MCP 工具从 20 个增加到 22 个(smart_code + smart_output)。SQLite 架构从 8 升至 9(新增 outputs 表;首次运行时自动迁移)。未新增任何运行时依赖项——TypeScript LanguageService 来自你已有的 typescript 包;如果没有该包,则会降级使用备用提供程序。
smart_code(新工具)。 通过 TypeScript LanguageService 为 JS/TS 提供语义代码导航,按符号名称(以及可选的filePath)解析,而不必强行要求你知道行号和列号。操作:definition、references、implementations、diagnostics、impact、rename。返回精简的位置(文件 + 从 1 开始的起止位置),绝不返回完整文件内容。includeTests=false会排除测试路径;maxResults会限制结果数量。- 影响分析。
smart_code(action='impact')会将直接命中(语义分析:定义、引用、实现)与传递文件(导入图,maxHops默认为 2)及相关测试分开列出,并提供覆盖标记。risk.level标注为basis: 'heuristic',并在自己的note中说明这一点——它是用于排序的辅助依据,并非语义层面的确定结论。 - 了解作用域的重命名,默认试运行。
smart_code(action='rename')使用findRenameLocations,且默认启用dryRun: true:首次调用会返回按文件划分的计划差异块(每行的before/after),不会写入任何内容。错误冲突(newName无效或为保留名称、名称相同、目标无法解析、路径越界、文件缺失、影响范围超过maxFiles)始终会阻止写入。name-collision是启发式警告,只有在strict: true时才会阻止操作,因为该检查不会验证作用域是否重叠。实际写入后,diagnosticsAfter会报告受影响文件中剩余的 TypeScript 错误。对于非语义的文本替换,请继续使用smart_edit工具。 smart_output(新工具)。 持久化输出/工件存储(shell、test、build、lint、diff),因此二十轮对话前的堆栈跟踪无需重新运行命令即可找回。操作:save、search、excerpt、summary、list、stats、prune。内容会在持久化前清除可能的机密信息;超过DEVCTX_OUTPUT_MAX_BYTES(256KB)时会截取开头和结尾,确保失败相关的末尾内容始终保留。通过DEVCTX_OUTPUT_RETENTION_DAYS(14)和DEVCTX_OUTPUT_MAX_PER_KIND(50)设置保留策略。同一kind+command的相同输出会去重,并计入repeat_count。通过smart_shell/smart_test自动捕获内容需选择启用:设置DEVCTX_OUTPUT_STORE=true(之后smart_shell会返回outputRef);显式调用save/search始终可用。SQLite 不可用或被锁定时,不会抛出错误,而是以degraded: true降级运行。- 在
smart_context中选择启用语义扩展。include: ['semantic']会通过真实的定义、引用和实现扩展上下文,而非依赖文本相似度,并为每个条目添加whyIncluded说明。默认关闭,直到 precision@5 基准测试证明其效果值得启用。 - 更丰富的 ADR/规范识别能力与图路径沿用同一路线图:ADR 章节会以
kind='adr'/'adr-section'编入索引,smart_context还可以返回两个文件或符号之间的图路径。 - 工具间共享
tokenBudget。smart_read、smart_read_batch、smart_context、smart_turn(start+end)和smart_resume现在接受tokenBudget: number | { id?, maxTokens, shared? }。当shared:true(或设置了id)时,同一任务中的多次调用会复用该预算,因此多步骤 Agent 工作流可以在不必逐次调用记账的情况下,保持在严格的 token 上限内。如果预算实际改变了输出,响应会包含taskBudget、remainingBudget和budgetDetails(scope、actions、降级模式)。 smart_search搜索模式。 新增mode: 'needle' | 'balanced' | 'semantic'(默认值为balanced)。needle= 仅字面精确匹配(不使用正则、不扩展词项),可消除调试查询中的噪声。balanced= 精确匹配 + 正则 + 词项扩展。semantic= 优先精确匹配,仅当精确信号较弱时才使用本地语义区块。此前的semantic: true标记仍作为mode: 'semantic'的旧版别名保留。默认maxFiles从 15 收紧至 5。新增maxTokens,用于限制整个响应,并进行智能压缩(优先匹配结果,其次诊断信息,最后语义区块)。现在可以通过matchedBy、boostSource、scoreBreakdown、whyRanked查看每个文件的排名依据。响应还会在查询范围过广或无结果时返回hasMore/totalFiles/nextSuggestedMaxFiles和可执行的suggestions。smart_read持久化缓存 + 感知预算的full降级。 新增 SQLiteread_cache表,以(filePath, mode, selector, content_hash)为键。读取未变更文件的第二次调用几乎不耗费资源。现在full模式是明确的最后手段:如果设置了tokenBudget/maxTokens,会先降级为更轻量的模式(outline → signatures → 截断),并通过fullMode+budgetDetails报告实际使用的模式。新增clearReadCachePersistent+runStorageMaintenance中的 GC 集成。smart_turn简单任务跳过启发式。 当提示词较短(规范化后 ≤ 40 个字符)、被分类为简单任务,且未固定会话/任务时,smart_turn(start)现在会返回skipSmartTurn: true,并将recommendedPath.mode='simple_task_skip',而不是承担完整编排开销。可节省琐碎提示词的连续性解析开销。minimal详细程度还会将 summary/refreshedContext 压缩为 Agent 实际使用的字段。global_memory噪声提示。 按项目统计并清理后的噪声遥测数据会持久化至~/.devctx/global.db(noise_hints表)。新增操作noise_stats和noise_reset(完整重置或通过query重置)。这让smart_search能了解 Agent 已发现某个查询在特定代码仓库中会产生噪声,并据此调整排名,同时绝不泄露内容。- KPI 基线基础设施。 新增脚本
evals/kpi-baseline.js+evals/kpi-utils.js,将harness.js和realworld-eval.js的运行结果汇总为单个 JSON 快照,其中包含前 5 名精确率、召回率、重复读取任务/调用率,以及按任务规模划分的分桶(短 / 长)。保存kpi-baseline-latest.json,用于跨版本回归检测。新增测试套件tests/eval-kpis.test.js。
1.20.0 亮点(当前仍为最新版本)
工具数量与 1.19.0 相同,但有多项工具新增了硬性令牌预算控制、搜索模式约束和二次读取缓存复用。
- 工具间共享的
tokenBudget。smart_read、smart_read_batch、smart_context、smart_turn和smart_resume支持tokenBudget: number | { id?, maxTokens, shared? },可在同一任务的多次调用中重复使用,确保多步流程不超过硬性上限。 smart_search模式。mode: 'needle' | 'balanced' | 'semantic'(默认值为balanced)、用于限制整个响应的maxTokens,以及可检查的排序依据matchedBy/scoreBreakdown/whyRanked。smart_read持久化缓存。 SQLiteread_cache以(filePath, mode, selector, content_hash)为键;未更改文件的二次读取几乎不消耗资源。在预算限制下,full模式会降级为较轻量的模式,并报告实际使用的模式。smart_turn跳过简单任务,适用于简短的琐碎提示词;global_memory噪声提示则让smart_search学习哪些查询在每个仓库中被证明会产生噪声。- KPI 基准基础设施(
evals/kpi-baseline.js),用于记录 precision@5、recall、重复读取率和延迟的快照,以检测回归。
1.19.0 亮点
通过顺序提交并在整个过程中使用自身工具,完成了五步质量提升。MCP 工具从 18 → 20,新增 68 项测试,未新增任何依赖。
- 新增
smart_playbook工具。 声明式组合工作流,可在一次 MCP 调用中运行多个smart_*工具。软件包内置五种剧本:preflight-merge(审查 + 受影响的测试 + 检查点)、debug-flake(最近一次失败 + 精选调试上下文 + 受影响项)、refactor-safe(精选上下文 + 受影响项 + 检查点)、doc-sync(ADR 搜索 + 文档上下文)、ramp-up(状态 + 诊断 + ADR 概览)。可通过.devctx/playbooks/*.{yaml,json}覆盖项目级配置,支持{{args.X}}插值、when/label/stopOnFail/dryRun。工具允许列表仅限smart_*。零依赖:内置精简 YAML 解析器。 - 用于索引的响应式文件系统监视器。
fs.watch(原生、递归监视,防抖 600ms,每 2s 批量刷新一次)可在调用间保持符号索引热更新。过滤.git、node_modules、.devctx、dist、build、锁文件、.min.*、.map、.snap以及不可索引的扩展名。统计信息显示在smart_status中(enabled、flushes、eventsObserved、filesReindexed、filesRemoved、errors、lastFlushAt、pending)。可通过DEVCTX_WATCH_INDEX=false选择关闭。已接入 MCP 关闭流程,可干净地关闭并执行最终刷新。 - 更丰富的 Python / Go 解析器 + 可插拔解析器注册表。 Python 现在可捕获装饰器(
decorators: ["dataclass", ...])、async def(类型为async-function/async-method),将TypeAlias和TypeVar/NewType/ParamSpec/TypeVarTuple记为kind="type",并遵循类缩进以准确确定作用域。Go 现在可捕获将接收者类型作为parent的方法、类型为kind="interface"的接口,以及顶层const/var。src/parsers/registry.js提供registerParser/getParser,便于未来接入 tree-sitter 解析器,无需修改index.js。INDEX_VERSION从 6 升至 7(自动重新索引)。 smart_search的本地语义重排序。 选择启用semantic: true(并设置semanticLimit)后,会返回一个semantic: { embedder, symbols[], files[] }区块,其排序基于哈希 / TF-IDF 嵌入(256 维、FNV-1a 分桶、L2 归一化、余弦相似度,耗时 <5ms)。默认行为不变。可插拔嵌入器接口(id、dimensions、embed、similarity)已就绪,可在不修改调用方的情况下替换为 ONNX/transformers。- 新增
global_memory工具(选择启用)。 跨项目记忆持久化至~/.devctx/global.db(可通过DEVCTX_GLOBAL_DB覆盖,且需启用DEVCTX_GLOBAL_MEMORY=true)。可在不同代码仓库间保存规范化决策、重复出现的模式、剧本草稿和笔记。持久化前会清理疑似 API 密钥 / bearer 令牌 / JWT / PEM 私钥 / AWS / OpenAI / GitHub / Slack / Google API / 数据库 URL / 邮箱 / 主目录路径等内容。项目路径以 FNV-1a 哈希形式存储,而非原始路径。回忆功能使用本地哈希 / TF-IDF 嵌入器进行语义排序。
完整的 v1.21.0 + v1.20.0 条目请参阅 CHANGELOG.md。
完整的版本历史请参阅 CHANGELOG.md。
何时使用(以及何时不使用)
在以下情况下使用 devctx:
- 你正在探索不熟悉的代码库
- 任务跨越多个会话(检查点可保存上下文)
- 你需要了解文件之间的关系(图谱/导入)
- 上下文过大,无法手动管理
- 你正在进行复杂的多文件重构,或跨层调试
在以下情况下跳过 devctx:
- 你已经明确知道要修改哪些文件
- 这是单文件或小范围修改(最多 2-3 处编辑)
- 你最近探索过代码库,脑中已有完整的结构图
- 对于当前任务,原生工具(Grep、Read、StrReplace)更直接
真实用户的坦诚评价:
“对于耗时较长、跨多个会话的任务,或不熟悉代码库时,MCP 的优势很明显。对于范围明确且你已知道要修改哪些内容的重构,原生工具同样快,甚至更快。真正有价值的是初步分析时使用的
smart_read(outline),以及能避免在不同会话间丢失思路的检查点。”
节省 90% 令牌确实可行,但需要适合的任务类型才能实现。
为什么要创建它
AI Agent 会在三方面浪费令牌:
- 读取完整文件,而实际只需要了解结构或特定函数
- 搜索结果过多,包含数百条无关匹配
- 在多轮对话中重复上下文
这个 MCP 通过提供可压缩、排序并缓存上下文的工具,解决了以上所有问题。
🚨 Agent 忽略了 devctx?→ 接下来粘贴此内容
📋 官方提示词(复制并粘贴)
⚡ 超短版本
|
使用时机: Agent 使用 Read 读取了大型文件、反复使用 Grep,或你在复杂任务中看不到任何 devctx 工具。
发生这种情况的原因: 任务看起来很简单、尚未构建索引、原生工具显得更直接,或规则不够明确。
快速入门:我该使用哪个客户端?
🎯 最佳默认选择:Cursor
适用情况: 你使用 Cursor IDE,并希望在引导性和灵活性之间取得最佳平衡。
工作流:
1. Install MCP → rules auto-load
2. Start task → agent reads .cursorrules
3. Agent decides when to use devctx
4. Use /prompt commands to force usage if needed
自动化程度: 默认中等。如果在任务运行器工作流中使用辅助启动器 ./.devctx/bin/cursor-devctx,则为中高。
🔄 连续性最佳:Claude Desktop
适用情况: 你希望会话连续性最高,并能自动恢复上下文。
工作流:
1. Install MCP + hooks
2. Start task → hook auto-triggers smart_turn(start)
3. Work with devctx tools
4. End task → hook auto-triggers smart_turn(end)
自动化程度: 高(使用钩子时)——可在会话开始/结束时自动触发 smart_turn。
💻 终端首选:Codex CLI / Qwen Code
适用情况: 你偏好基于终端的工作流或脚本。
工作流:
1. Install MCP
2. Rules embedded in prompts
3. Agent reads rules, decides when to use
4. Explicit instructions work best
自动化程度: 低至中等——规则清晰可见,但需要明确提示。
📊 快速比较
| 客户端 | 自动化程度 | 最适合 |
|---|---|---|
| Cursor | 中等 | 复杂的 IDE 任务 |
| Claude Desktop | 高(钩子) | 会话连续性 |
| Codex CLI | 低至中等 | 终端工作流 |
| Qwen Code | 低至中等 | Cursor 的替代选择 |
重要提示: 是否使用 devctx 始终由 Agent 决定。规则会提高使用概率,但无法保证使用。
如果你希望流程更可重复: 请使用任务运行器或辅助启动器,而不要只依赖规则。参见 任务运行器工作流。
📖 完整设置说明: 客户端兼容性
🚀 如何调用 MCP
要点: MCP 不会自动拦截提示词。你需要告诉 Agent 使用它。
1️⃣ 使用 MCP 提示词(最简单——仅限 Cursor)
/prompt use-devctx
[Your task here]
其他提示词:
/prompt devctx-workflow- 完整工作流/prompt devctx-preflight- 构建索引 + 开始会话
2️⃣ 明确指示(适用于任何客户端)
Use smart_turn(start) to recover context, then [your task]
如需更有引导性的命令行流程:
smart-context-task task --prompt "your task"
smart-context-task implement --prompt "your task"
smart-context-task continue --session-id <session-id>
smart-context-task doctor
3️⃣ 通过规则自动使用(不保证)
如果规则已启用,Agent 应该在处理复杂任务时使用 devctx:
- Cursor:
.cursorrules - Claude Desktop:
CLAUDE.md - 其他:
AGENTS.md
但: Agent 会根据任务复杂度自行决定。
⚡ 快速参考
| 场景 | 命令 |
|---|---|
| 开始新任务 | /prompt devctx-workflow |
| 引导式终端工作流 | smart-context-task task --prompt "..." |
| 引导式实现 | smart-context-task implement --prompt "..." |
| 继续之前的任务 | smart_turn(start) and continue |
| 通过 runner 继续 | smart-context-task continue --session-id <id> |
| 强制使用 MCP | /prompt use-devctx |
| 首次在项目中使用 | /prompt devctx-preflight |
| 信任自动规则 | 直接正常描述任务 |
推荐工作流
✅ 设置检查清单(首次在项目中使用)
开始复杂任务前,请确保:
# 1. MCP is installed
npm list -g smart-context-mcp # or check your MCP client
# 2. Build the index (IMPORTANT)
npm run build-index
# or tell the agent: "Run build_index tool"
# 3. Rules are active
# - Cursor: .cursorrules exists
# - Claude Desktop: CLAUDE.md exists
# - Other clients: AGENTS.md exists
# 4. Start with smart_turn
# Tell the agent: "Use smart_turn(start) to begin"
复制粘贴给 Agent(首次使用):
Run build_index, then use smart_turn(start) to begin this task.
⚠️ 为什么索引很重要
没有索引时:
- ❌
smart_search返回的结果不按相关性排序 - ❌
smart_context无法构建最优上下文 - ❌ Agent 可能更倾向于使用原生工具 → 无法节省用量
有索引时:
- ✅
smart_search按相关性排序 - ✅
smart_context包含相关文件 - ✅ 可节省 90% 的令牌
何时重建:
- ✅ 首次在项目中使用
- ✅ 重大重构后(文件移动、重命名)
- ✅ 添加大量新文件后
- ❌ 不需要每次会话都重建(索引会保留在
.devctx/中)
入口:smart_turn(start)
对于非简单任务(调试、审查、重构、测试、架构),最佳流程是:
0. build_index (if first time in project)
↓ enables search ranking and context quality
1. smart_turn(start, userPrompt, ensureSession=true)
↓ recovers previous context, classifies task, checks repo safety
2. smart_context(...) or smart_search(intent=...)
↓ builds context or finds relevant code
3. smart_read(mode=outline|signatures|symbol)
↓ reads compressed, cascades to full only if needed
4. [work: make changes, analyze, review]
5. smart_shell('npm test')
↓ verifies changes safely
6. smart_turn(end, event=milestone|blocker|task_complete)
↓ checkpoints progress for recovery
为什么从 smart_turn 开始?
- ✅ 恢复之前的任务检查点(目标、状态、决策)
- ✅ 判断是继续任务还是开始新任务
- ✅ 提供仓库安全检查
- ✅ 中断后可恢复任务
- ✅ 跟踪指标以便优化
何时跳过 smart_turn:
- ❌ 简单任务(读取单个文件、简单搜索)
- ❌ 一次性问题(无需保持连续性)
- ❌ 快速诊断(无需会话上下文)
产品入口:smart-context-task
如果你希望将相同的生命周期封装为命名工作流,请使用任务运行器:
smart-context-task task --prompt "inspect the auth flow and continue the bugfix"
smart-context-task implement --prompt "add a token guard to loginHandler"
smart-context-task review --prompt "review the latest diff"
smart-context-task doctor
这一层会运行相同的 smart_turn(start) / 上下文 / 检查点流程,同时增加:
- 特定于工作流的预检(
smart_context或smart_search) - 考虑连续性的提示词指导
- 将受阻状态转交给
smart_doctor - 用于衡量质量的
task_runner信号
如需查看完整命令集和特定于客户端的用法,请参阅 任务运行器工作流。
实际运作方式
实际情况
这个 MCP 不会神奇地拦截你的提示词。实际过程如下:
- 你编写提示词:“修复登录错误”
- **Agent 读取规则:**看到调试工作流建议
- Agent 做出决定:“这是一个调试任务,我会从
smart_turn(start)开始” - Agent 调用:
smart_turn({ phase: 'start', userPrompt: '...', ensureSession: true }) - **MCP 返回:**之前的任务检查点(如果存在)+ 仓库安全检查
- **Agent 继续:**调用
smart_search(intent=debug)查找错误位置 - **Agent 读取:**调用
smart_read(mode=symbol)查看特定函数 - **Agent 修复错误:**进行更改
- **Agent 验证:**调用
smart_shell('npm test') - **Agent 创建检查点:**调用
smart_turn(end)保存进度
要点:
- ✅ Agent 会选择使用 devctx 工具(并非强制)
- ✅ 规则会引导 Agent(并非强制执行)
- ✅ 对于非简单任务,建议将
smart_turn(start)作为入口 - ✅ 简单任务可以跳过工作流
- ✅ 你无法直接控制任何事——由 Agent 决定
你将获得什么
工具(22 个): 高效替代内置操作
smart_read/smart_read_batch- 压缩读取文件(大纲、签名、符号、说明)smart_search- 根据意图进行代码搜索,支持排序、ADR 筛选和可选的语义重排smart_context- 一次调用即可构建上下文,支持图遍历 +paths: { from, to }smart_test- 通过图分析确定受影响的测试 + 沙盒运行器 + 持久化的last_failuresmart_review- 代码审查预检:差异 + 调用方 + 启发式发现smart_code- 按符号名称进行语义导航:定义、引用、实现、诊断、影响分析、试运行重命名smart_output- 持久化输出存储(shell/test/build/lint/diff):搜索、摘录、摘要,无需重新运行smart_playbook- 声明式组合工作流(内置 5 种:preflight-merge、debug-flake、refactor-safe、doc-sync、ramp-up)smart_shell- 安全的诊断命令(TAP/git-log/diff 压缩)smart_turn/smart_resume- 会话持久化 + 机器可读计划nextActions[]smart_summary/smart_status/smart_doctor/smart_metrics/smart_editglobal_memory- 可选的跨项目记忆,存储于~/.devctx/global.db(经过清理,支持语义回忆)build_index/warm_cache/git_blame/cross_project
规则(5 种配置): 面向特定任务的工作流
- 调试:错误优先,聚焦符号
- 代码审查:关注差异,聚焦 API
- 重构:了解代码图谱,通过测试验证
- 测试:关注覆盖率,支持 TDD
- 架构:索引优先,细节精简
存储(.devctx/): 本地上下文数据库
index.json- 符号索引(函数、类、导入、ADR、章节)—INDEX_VERSION 7state.sqlite- 会话、指标、模式、任务交接、测试失败、说明/读取缓存、持久化输出(Node 22+,node:sqlite,架构版本 9)metrics.jsonl- 可选的旧版文件,仅在设置DEVCTX_METRICS_FILE=path.jsonl时使用~/.devctx/global.db- 跨项目记忆(通过DEVCTX_GLOBAL_MEMORY=true可选启用)
持久化任务上下文(受支持时)
持久化的内容:
- 任务检查点(目标、状态、决策、阻碍因素)
- 文件访问模式(用于预测)
- Token 指标(用于优化)
- 会话摘要(压缩后约 100 个 Token)
使用时机:
- Agent 调用
smart_turn(start)- 恢复任务检查点 - Agent 调用
smart_context- 使用模式进行预测 - Agent 调用
smart_summary- 获取任务摘要
不会持久化的内容:
- ❌ 完整对话记录
- ❌ 完整消息历史
- ❌ Agent 的推理或思考
- ❌ 用户提示词原文
限制:
- 仅当 Agent 调用
smart_turn时才有效(不会自动运行) - 仅在项目内持久化(
.devctx/是本地目录) - 仅在会话 ID 匹配时恢复(手动或自动)
- 客户端必须支持 MCP(Cursor、Codex、Claude Desktop、Qwen)
实话实说: 任务上下文持久化由 Agent 的行为选择性启用,并非通过客户端拦截自动实现。
这对你意味着什么
最佳情况:
- Agent 始终遵循规则
- 50-80% 的操作使用 devctx 工具
- Token 用量降低 85-90%(已有实测数据)
- 由于需要处理的数据更少,响应通常更快(根据 Token 节省情况推断)
典型情况:
- Agent 在复杂任务中使用 devctx 工具
- 简单任务使用内置工具
- Token 用量降低 60-80%
- 效率有明显提升
最差情况:
- Agent 忽略规则(少见,但有可能)
- 完全使用内置工具
- Token 用量不变
- 没有坏处(MCP 是被动的)
你可以查看: npm run report:metrics 会显示实际工具使用情况和实测的 smart_turn 质量信号。
“更好的上下文”意味着什么
我们改进的方面:
- ✅ 上下文相关性(为任务提供合适的文件)
- ✅ 信噪比(减少模板内容,增加有效信息)
- ✅ 上下文效率(用更少的空间提供更多相关信息)
- ✅ 响应速度(需要处理的数据更少)
我们不保证的方面:
- ❌ Agent 总是正确
- ❌ 回复完美无缺
- ❌ 任务总能成功
- ❌ 回复会“更准确”(准确性取决于 Agent,而不仅仅是上下文)
好处: Agent 能获得更好的输入,但输出质量仍取决于 Agent 的能力和任务复杂度。
如实说明: 我们提供更好的上下文(更相关、噪声更少);遵循工作流时,这有助于 Agent 更高效地处理复杂任务。
已证实: 节省 90% 的令牌(根据 3,666 次操作测得)。
推断得出: 质量有所提升(更好的输入 → 可能带来更好的输出,但尚未明确测量)。
我们无法控制: Agent 是否正确、任务是否成功、回复是否准确。
工作流示例
调试
// 1. Start session
smart_turn({
phase: 'start',
userPrompt: 'TypeError: Cannot read property "user" of undefined',
ensureSession: true
})
// → Recovers: "Last worked on auth system, checked validateToken()"
// 2. Find error
smart_search({
query: 'TypeError user undefined',
intent: 'debug'
})
// → Returns: src/auth.js (error handling), src/routes/login.js (recent change)
// 3. Read structure
smart_read({
filePath: 'src/routes/login.js',
mode: 'signatures'
})
// → Returns: loginHandler, validateCredentials, generateToken
// 4. Extract failing function
smart_read({
filePath: 'src/routes/login.js',
mode: 'symbol',
symbol: 'loginHandler'
})
// → Returns: Full function code (250 tokens vs 5K for full file)
// 5. Reproduce error
smart_shell({ command: 'npm test -- login.test.js' })
// → Returns: Test failure output
// [Fix bug]
// 6. Verify fix
smart_shell({ command: 'npm test -- login.test.js' })
// → Returns: Tests pass
// 7. Checkpoint
smart_turn({
phase: 'end',
event: 'milestone',
summary: 'Fixed TypeError in loginHandler - null check added',
nextStep: 'Consider adding integration tests'
})
令牌用量: 150K → 15K(节省 90%)
代码审查
// 1. Start session
smart_turn({
phase: 'start',
userPrompt: 'Review PR #123 - Add JWT refresh token support',
ensureSession: true
})
// 2. Get changed files context
smart_context({
diff: true,
detail: 'balanced'
})
// → Returns: Changed files with graph, prioritizes API surface
// 3. Review API surface
smart_read({
filePath: 'src/auth.js',
mode: 'signatures'
})
// → Returns: Exported functions only
// 4. Check implementation
smart_read({
filePath: 'src/auth.js',
mode: 'symbol',
symbol: 'refreshToken'
})
// 5. Check authorship
git_blame({
mode: 'symbol',
filePath: 'src/auth.js'
})
// → Returns: Who wrote each function
// 6. Verify tests
smart_shell({ command: 'npm test' })
// 7. Checkpoint
smart_turn({
phase: 'end',
event: 'milestone',
summary: 'PR #123 approved - JWT refresh implemented correctly',
nextStep: 'Monitor production metrics after deploy'
})
令牌用量: 200K → 25K(节省 87%)
重构
// 1. Start session
smart_turn({
phase: 'start',
userPrompt: 'Extract authentication logic into separate service',
ensureSession: true
})
// 2. Build dependency graph
smart_context({
entryFile: 'src/routes/login.js',
detail: 'balanced'
})
// → Returns: Dependencies, imports, exports
// 3. Understand current structure
smart_read({
filePath: 'src/routes/login.js',
mode: 'signatures'
})
// 4. Extract target function
smart_read({
filePath: 'src/routes/login.js',
mode: 'symbol',
symbol: 'validateCredentials'
})
// 5. Check authorship
git_blame({
mode: 'symbol',
filePath: 'src/routes/login.js'
})
// [Refactor: create src/services/auth.js, move logic]
// 6. Verify tests still pass
smart_shell({ command: 'npm test' })
// 7. Checkpoint
smart_turn({
phase: 'end',
event: 'milestone',
summary: 'Extracted auth logic to AuthService - tests pass',
nextStep: 'Update other routes to use AuthService'
})
令牌用量: 180K → 20K(节省 89%)
测试
// 1. Start session
smart_turn({
phase: 'start',
userPrompt: 'Write tests for validateToken function',
ensureSession: true
})
// 2. Find existing test patterns
smart_search({
query: 'validateToken test',
intent: 'tests'
})
// → Returns: Existing test files, test patterns
// 3. Read function to test
smart_read({
filePath: 'src/auth.js',
mode: 'symbol',
symbol: 'validateToken'
})
// 4. Understand dependencies
smart_context({
entryFile: 'src/auth.js',
detail: 'minimal'
})
// → Returns: Dependencies (jwt, bcrypt, db)
// [Write test]
// 5. Run tests
smart_shell({ command: 'npm test -- auth.test.js' })
// 6. Checkpoint
smart_turn({
phase: 'end',
event: 'milestone',
summary: 'Added 5 tests for validateToken - all pass',
nextStep: 'Add edge case tests for expired tokens'
})
令牌用量: 120K → 12K(节省 90%)
架构探索
// 1. Start session
smart_turn({
phase: 'start',
userPrompt: 'Understand how authentication works in this codebase',
ensureSession: true
})
// 2. Get high-level overview
smart_context({
detail: 'minimal'
})
// → Returns: Project structure, key modules
// 3. Find auth-related code
smart_search({
query: 'authentication authorization',
intent: 'explore'
})
// → Returns: Ranked files by relevance
// 4. Review API surface
smart_read({
filePath: 'src/auth.js',
mode: 'signatures'
})
// → Returns: Exported functions only
// 5. Check cross-project patterns (if monorepo)
cross_project({
mode: 'search',
query: 'AuthService'
})
// → Returns: Similar auth patterns in other projects
// 6. Checkpoint
smart_turn({
phase: 'end',
event: 'milestone',
summary: 'Auth uses JWT with 1h expiry, refresh tokens in Redis',
nextStep: 'Document auth flow in architecture.md'
})
令牌用量: 300K → 30K(节省 90%)
核心工具
以下是你应该首先了解的基本工具:
smart_read
以压缩模式读取文件,而不是加载完整内容。
// Outline mode: structure only (~90% savings)
{ filePath: 'src/server.js', mode: 'outline' }
// Signatures mode: exported API only
{ filePath: 'src/api.js', mode: 'signatures' }
// Symbol mode: extract specific function/class
{ filePath: 'src/auth.js', mode: 'symbol', symbol: 'validateToken' }
模式: outline、signatures、symbol、range、full
适用场景: 任何需要了解文件结构但不必通读全部内容的时候。
smart_search
具备意图识别能力的代码搜索,可提供经过排序、去重并提升索引权重的结果。
// Find where a symbol is used
{ query: 'validateToken', intent: 'implementation' }
// Debug intent: prioritizes errors, logs, exception handling
{ query: 'authentication error', intent: 'debug' }
// Limit results
{ query: 'UserModel', maxFiles: 5 }
意图: implementation、debug、tests、config、docs、explore
最适合: 查找符号定义或用法、了解调用链、定位实现。
不太适合: 精确字符串匹配(请使用 Grep)、按名称查找文件(请使用 Glob)、宽泛的多词查询(会产生噪声——匹配文件超过 30 个时,结果会附带提示)。
smart_context
一次调用即可构建上下文:搜索 + 读取 + 图谱扩展。
{
task: 'Fix login authentication bug',
detail: 'balanced' // minimal | balanced | deep
}
返回相关文件及其压缩内容、符号详情和关系图谱。
智能模式检测: 自动检测任务中的字面模式(TODO、FIXME、/**、console.log、debugger),并在搜索结果中优先显示。
适用场景: 开始新任务并需要全面的上下文时。
build_index
为项目构建符号索引(函数、类、导入)。
{ incremental: true } // Only reindex changed files
适用场景: 检出代码后执行一次,或在重大变更后执行。可提升搜索排序和上下文相关性。
smart_metrics
查看令牌节省情况和使用统计信息。
{ window: '24h' } // or '7d', '30d', 'all'
适用场景: 验证 MCP 是否正常工作,并查看实际节省情况。
高级工具
这些工具为特定工作流提供专用功能:
smart_summary
在不同会话间维护压缩后的任务状态。
// Save checkpoint (flat API - recommended)
{ action: 'update', goal: '...', status: 'in_progress', nextStep: '...' }
// Or nested format (backward compatible)
{ action: 'update', update: { goal: '...', status: 'in_progress', nextStep: '...' }}
// Resume later
{ action: 'get' }
将任务上下文压缩至约 100 个令牌(目标、状态、决策、阻碍因素)。对长期任务至关重要。支持扁平和嵌套两种格式。
当 Git 卫生状况或 SQLite 健康状况影响本地状态时,回复还会显示 mutationSafety、repoSafety、degradedMode 和 storageHealth。
smart_doctor
执行一次运行前检查,涵盖仓库卫生状况、SQLite 健康状况、压缩和旧数据清理。
smart_doctor({})
smart_doctor({ verifyIntegrity: false })
发布前、长期在本地使用后,或任何时候 .devctx/state.sqlite 看起来可疑时,请使用此工具。
smart_status
显示当前会话上下文及进度。
{ format: 'detailed' } // Full formatted output with emojis
{ format: 'compact' } // Minimal JSON
显示目标、状态、近期决策、已修改文件、固定上下文和进度统计。每次 MCP 操作后自动更新。
当仓库安全或 SQLite 健康状况影响状态时,smart_status 会通过降级模式继续发挥作用,并展示 storageHealth 以及与 smart_turn 相同的 mutationSafety 契约。
smart_edit
通过模式替换批量编辑多个文件。
{
pattern: 'console.log',
replacement: 'logger.info',
files: ['src/a.js', 'src/b.js'],
mode: 'literal' // or 'regex'
}
支持使用 dryRun: true 进行预览。适用于批量重构、移除模式或跨文件重命名。
smart_turn
编排轮次的开始和结束,并自动恢复任务检查点。
{ phase: 'start', prompt: '...' } // Recovers task checkpoint
{ phase: 'end', event: 'milestone', update: {...} } // Saves checkpoint
恢复任务状态(目标、状态、决策、下一步),而非完整的对话历史。
smart_read_batch
一次调用读取多个文件。
{
files: [
{ path: 'src/a.js', mode: 'outline' },
{ path: 'src/b.js', mode: 'signatures' }
]
}
当你确定需要读取多个文件时,可减少往返延迟。
smart_shell
安全执行诊断命令(仅限允许列表中的命令)。
{ command: 'git status' }
按设计会拦截 shell 运算符和不安全命令。
Diff-Aware Context
智能分析 git 更改(属于 smart_context 的一部分):
{ task: 'Review changes', diff: 'main' }
按影响优先级返回已更改文件及相关文件(测试、导入该文件的文件)。
Context Prediction
从使用模式中学习并预测所需文件(属于 smart_context 的一部分):
{ task: 'Implement authentication', prefetch: true }
完成 3 项或更多相似任务后:往返次数减少 40-60%,额外节省 15-20%。
warm_cache
将常用文件预加载到 OS 缓存中。
{} // No parameters
首次查询:250ms → 50ms(冷启动速度提升 5 倍)。
git_blame
按函数追溯代码归属。
// Who wrote each function?
{ mode: 'symbol', filePath: 'src/server.js' }
// Find code by author
{ mode: 'author', authorQuery: '[email protected]' }
// Recent changes
{ mode: 'recent', daysBack: 7 }
cross_project
在单体仓库和微服务之间共享上下文。
// Search all related projects
{ mode: 'search', query: 'AuthService' }
// Find symbol across projects
{ mode: 'symbol', symbolName: 'validateToken' }
需要 .devctx-projects.json 配置文件。
客户端兼容性
| 客户端 | MCP | 规则 | 钩子 | smart_turn | 持久化 | 近乎自动化 | 主要限制 |
|---|---|---|---|---|---|---|---|
| Cursor | ✅ 完整 | ✅ 有条件 ( .cursor/rules/*.mdc) | ❌ 不支持 | ✅ 手动调用 | ✅ SQLite (Node 22+) | 🟡 中 由 Agent 决定何时使用 | • 不会自动调用 smart_turn• Agent 必须遵循规则 • 需要 Agent 模式 |
| Claude Desktop | ✅ 完整 | ✅ 内嵌 ( CLAUDE.md) | ✅ SessionStart PostToolUse Stop | ✅ 可通过钩子 自动触发 | ✅ SQLite (Node 22+) | 🟢 高 钩子自动触发 | • 钩子需选择启用 • 不支持条件规则 • 固定上下文:200t |
| Codex CLI | ✅ 完整 | ✅ 内嵌 ( AGENTS.md) | ❌ 不支持 | ✅ 手动调用 | ✅ SQLite (Node 22+) | 🟡 低-中 由 Agent 决定何时使用 | • 不会自动调用 smart_turn• 不支持条件规则 • 不支持钩子 |
| Qwen Code | ✅ 完整 | ✅ 内嵌 ( AGENTS.md) | ❌ 不支持 | ✅ 手动调用 | ✅ SQLite (Node 22+) | 🟡 低-中 由 Agent 决定何时使用 | • 不会自动调用 smart_turn• 不支持条件规则 • 不支持钩子 |
图例:
- 🟢 高:钩子可在特定时刻自动触发工具
- 🟡 中/低:Agent 阅读规则并决定何时使用工具
- ✅ 支持 | ⚠️ 部分支持 | ❌ 不支持
“近乎自动化”的含义
🟢 高(带钩子的 Claude Desktop):
- 开始会话时,钩子可自动触发
smart_turn(start) - 大量使用工具后,钩子可自动创建检查点
- Agent 仍会为每项任务决定使用哪些 devctx 工具
- 这是目前最接近“自动化”的行为
🟡 中(Cursor):
- Agent 自动读取基础规则(始终生效,占用 150 个 token)
- 根据文件 glob 激活条件配置文件(调试、审查等)
- Agent 根据任务决定何时使用 devctx 工具
- Agent 必须手动调用
smart_turn(不会自动触发)
🟡 低-中(Codex、Qwen):
- Agent 自动读取内嵌规则(始终生效,占用 200 个 token)
- Agent 根据任务决定何时使用 devctx 工具
- Agent 必须手动调用
smart_turn(不会自动触发) - 不支持条件激活或钩子
“近乎自动化”并不意味着什么
❌ 并非自动拦截提示词 - MCP 无法在 Agent 看到提示词之前拦截或修改它们
❌ 并非强制使用工具 - Agent 始终可以自主决定使用哪些工具
❌ 并非保证工作流 - 对于简单任务,Agent 可能会跳过 devctx 工具(这没问题)
❌ 并非客户端层面的魔法 - 行为取决于 Agent 是否遵循规则并做出良好决策
实际情况
所有客户端的工作方式都相同:
- Agent 阅读规则(关于何时适合使用 devctx 工具的指导)
- Agent 决定工具的使用(自主选择最佳方案)
- MCP 提供工具(被动响应,仅在被调用时才响应)
- 你使用指标进行验证(
npm run report:metrics)
不同之处:
- 钩子(Claude Desktop)可以在特定时刻自动触发特定工具(例如,在会话开始时运行
smart_turn(start)) - 条件规则(Cursor)可降低固定上下文开销,并在相关时激活特定任务配置
- 内嵌规则(Codex、Qwen)简单易用,始终生效,且适用于各种场景
我应该使用哪个客户端?
如果符合以下情况,请选择 Cursor:
- ✅ 你希望固定上下文开销最低(基础 150 tokens + 激活时配置 120 tokens)
- ✅ 你要处理复杂的多文件任务(调试、重构、架构设计)
- ✅ 你希望根据文件模式激活条件规则
如果符合以下情况,请选择 Claude Desktop:
- ✅ 你希望行为最接近“自动化”(钩子可以自动触发
smart_turn) - ✅ 你希望使用支持会话感知且带自动检查点的工作流
- ✅ 你可以接受选择加入钩子配置
如果符合以下情况,请选择 Codex 或 Qwen:
- ✅ 你希望使用简单的内嵌规则(无需单独的配置文件)
- ✅ 你更喜欢轻量的设置方式(只需一个
AGENTS.md文件) - ✅ 你可以接受手动调用
smart_turn,且不使用条件激活
总之: 所有客户端都很好用。选择取决于你更看重自动化程度还是简洁性。
详细对比请参阅客户端兼容性指南。
安装
步骤 1:安装 MCP 服务
最简安装(适用于任何客户端)
npm install -g smart-context-mcp
npx smart-context-init --target .
重启你的 AI 客户端。完成。
验证安装
# Check installed version
npm list -g smart-context-mcp
# Should show: [email protected] (or later)
# Update to latest version
npm update -g smart-context-mcp
# Or reinstall from scratch
npm uninstall -g smart-context-mcp
npm install -g smart-context-mcp
更新后: 二进制文件会全局更新,但每个项目中的 Agent 规则(.cursorrules、CLAUDE.md、AGENTS.md)由已安装的版本生成,不会自动更新。
每次更新后重新运行 init,以获取最新规则:
# Re-apply rules to a project after updating
npx smart-context-init --target /path/to/your/project --clients cursor
# or for all clients
npx smart-context-init --target /path/to/your/project --clients all
然后重启你的 AI 客户端,以加载新版本。
Cursor
npm install -g smart-context-mcp
npx smart-context-init --target . --clients cursor
重启 Cursor。工具会显示在 Agent 模式中。
创建的文件:
.cursor/mcp.json- MCP 服务配置.cursor/rules/devctx.mdc- 基础 Agent 规则(10 行,始终生效).cursor/rules/profiles-compact/*.mdc- 任务配置(条件激活).devctx/bin/cursor-devctx- 可选的辅助启动器,用于长时间任务.git/hooks/pre-commit- 安全钩子.gitignore- 添加.devctx/
Codex CLI
npm install -g smart-context-mcp
npx smart-context-init --target . --clients codex
重启 Codex。
创建的文件:
.codex/config.toml- MCP 服务配置AGENTS.md- Agent 规则.git/hooks/pre-commit- 安全钩子.gitignore- 添加.devctx/
Claude Desktop
npm install -g smart-context-mcp
npx smart-context-init --target . --clients claude
重启 Claude Desktop。
创建的文件:
.mcp.json- MCP 服务配置.claude/settings.json- 钩子配置CLAUDE.md- Agent 规则.git/hooks/pre-commit- 安全钩子.gitignore- 添加.devctx/
Qwen Code
npm install -g smart-context-mcp
npx smart-context-init --target . --clients qwen
重启 Qwen Code。
创建的文件:
.qwen/settings.json- MCP 服务配置AGENTS.md- Agent 规则.git/hooks/pre-commit- 安全钩子.gitignore- 添加.devctx/
Agent 规则:关键所在
这个 MCP 的独特之处在于针对特定任务的 Agent 指导。安装时会生成规则,指导 Agent 采用最佳工作流:
调试配置
smart_turn(start) → smart_search(intent=debug) → smart_read(symbol) →
smart_shell('npm test') → fix → smart_turn(end)
节省: 90%(150K → 15K tokens)
代码审查配置
smart_turn(start) → smart_context(diff=true) → smart_read(signatures) →
review → smart_turn(end)
节省: 87%(200K → 25K tokens)
重构配置
smart_turn(start) → smart_context(entryFile) → smart_read(signatures) →
refactor → smart_shell('npm test') → smart_turn(end)
节省: 89%(180K → 20K 个 token)
测试配置
smart_turn(start) → smart_search(intent=tests) → smart_read(symbol) →
write test → smart_shell('npm test') → smart_turn(end)
节省: 90%(120K → 12K 个 token)
架构配置
smart_turn(start) → smart_context(detail=minimal) → smart_read(signatures) →
analyze → smart_turn(end)
节省: 90%(300K → 30K 个 token)
关键见解: 价值不仅在于工具,更在于教会 Agent 何时以及如何使用这些工具。
步骤 2:设置 Agent 规则(推荐)
为确保 Agent 自动使用 devctx,请设置客户端专属规则:
Cursor 用户
已包含:项目中已提交 .cursorrules。
验证是否生效:
- Agent 应提及 devctx 使用策略
- Agent 应自动使用 devctx 工具
- 对于长任务,优先使用
./.devctx/bin/cursor-devctx task --prompt "..." -- <agent-command>
Claude Desktop 用户
在项目根目录创建 CLAUDE.md:
# Copy template
cp docs/agent-rules-template.md CLAUDE.md
# Edit to keep only the CLAUDE.md section
或者从 docs/agent-rules-template.md 复制内容。
其他 Agent 客户端
使用相同的模板,在项目根目录创建 AGENTS.md。
这些规则为何重要:
- ✅ Agent 自动使用 devctx(无需手动强制)
- ✅ 所有客户端的行为一致
- ✅ 使用 devctx 时会显示反馈
- ✅ 应使用 devctx 但未使用时会发出警告
请参阅 Agent 规则模板,了解完整设置方法。
未使用时的反馈
如果 Agent 在非简单任务中未使用 devctx 工具,它会添加提示:
Note: devctx not used because: [reason]
To use devctx next time: "Use smart-context-mcp: smart_turn(start) → ..."
这为何重要:
- 让未使用的情况清晰可见
- 帮助了解 devctx 何时能发挥价值
- 为下一轮提供强制提示词
- 发现设置问题(MCP 不可用、索引未构建)
如何强制使用 devctx
何时使用这些提示词:
- Agent 在非简单任务中未使用 devctx
- 你想恢复已保留的任务上下文
- 任务较复杂(调试、审查、重构、测试、架构)
官方提示词(完整工作流):
Use smart-context-mcp for this task:
1. Start with smart_turn(start, userPrompt, ensureSession=true) to recover context
2. Use smart_context or smart_search before reading files
3. Use smart_read(outline|signatures|symbol) instead of full reads
4. Close with smart_turn(end) when you reach a milestone
超短提示词(可直接复制粘贴):
Use devctx: smart_turn(start) → smart_context/smart_search → smart_read → smart_turn(end)
使用示例:
User: "Debug the authentication error"
Agent: [uses native tools]
Agent: "Note: devctx not used because: already had sufficient context..."
User: "Use devctx: smart_turn(start) → smart_context/smart_search → smart_read → smart_turn(end)"
Agent: [uses smart_turn, smart_search, smart_read]
Agent: "Found the issue in validateToken()..."
请参阅 agent-rules/ 查看完整配置文件。
开始使用
第 1 天:安装并构建索引(关键)
-
安装:
npm install smart-context-mcp npx smart-context-init --target . -
构建索引(保证质量所必需):
npm run build-index # or tell agent: "Run build_index tool"为何关键: 没有索引时,
smart_search和smart_context的效果会下降。Agent 可能会优先使用原生工具。不会节省 token。 -
使用核心工具:
- 使用
smart_read查看文件结构 - 使用
smart_search查找代码 - 使用
smart_context获取全面上下文 - 使用
smart_metrics验证节省效果
- 使用
-
让 Agent 自行决定: 不要强制使用工具。生成的规则会自然地引导 Agent。
1 周后:添加高级工具
- 如果你处理长任务,使用
smart_summary - 如果你使用 Claude Code CLI,使用
smart_turn - 使用
git_blame追溯代码归属 - 如果你在单体仓库中工作,使用
cross_project
1 个月后:优化
- 查看
smart_metrics了解使用模式 - 如果冷启动较慢,启用
warm_cache - 对重复性任务,在
smart_context中启用prefetch
指标与验证
运行完整基准测试
npm run benchmark
运行所有验证套件:
- 740 多项单元测试
- 14 项功能验证
- 合成语料评估
- 真实项目评估
- 编排回归基准测试(5 个核心场景)
- 生产指标报告
耗时 3-4 分钟。详情请参阅 基准测试文档。
此外,还可以通过 npm run benchmark:orchestration:release 对编排质量进行发布门控;现在,npm publish 会通过 prepublishOnly 阶段受该门控检查。
检查是否生效
npm run report:metrics
良好迹象:
- 工具使用量 > 0(Agent 正在使用 devctx)
- 节省 60-90%(压缩正常工作)
- 使用了多个工具(遵循了工作流)
不良迹象:
- 工具使用量 = 0(Agent 未使用 devctx)
- 请检查:是否已安装规则?MCP 是否正在运行?任务复杂度如何?
输出示例:
devctx metrics report
Entries: 3,696
Raw tokens: 14,492,131
Final tokens: 1,641,051
Saved tokens: 13,024,099 (89.87%)
By tool:
smart_search count=692 saved=5,817,485 (95.45%)
smart_read count=2108 saved=2,355,809 (70.52%)
smart_summary count=449 saved=1,897,628 (97.89%)
Adoption Analysis (Inferred from Tool Usage)
Total sessions: 156
Sessions with devctx: 89 (57%)
Sessions without: 67 (43%)
Non-Trivial Tasks Only:
Total: 112
With devctx: 78 (70%)
Without devctx: 34 (30%)
By Inferred Complexity:
- complex 56/68 (82%)
- moderate 25/52 (48%)
- simple 8/36 (22%)
When devctx IS used:
Avg tools/session: 2.8
Avg token savings: 146,337 tokens
Top Tools Used:
- smart_read 89 sessions
- smart_search 67 sessions
- smart_context 45 sessions
Limitations:
- Complexity inferred from operation count (not actual task complexity)
- Can only measure when devctx IS used (tool calls visible)
- Cannot measure feedback shown or forcing prompts (requires agent cooperation)
- Sessions without devctx may be simple tasks (not adoption failures)
采用指标(实验性)
指标报告现在包含采用情况分析,用于衡量 devctx 的实际使用频率。
衡量内容:
- ✅ 使用 devctx 工具的会话(自动根据工具调用统计)
- ✅ 总体采用率,以及按推断复杂度划分的采用率
- ✅ 每个会话中使用频率最高的工具
- ✅ 使用 devctx 时平均节省的令牌数
不衡量的内容:
- ❌ 反馈频率(需要 Agent 报告)
- ❌ 反馈原因(需要 Agent 配合)
- ❌ 是否强制使用提示词(无法从指标中检测)
- ❌ 实际任务复杂度(仅根据操作数量推断)
局限性:
- 复杂度是推断得出的(根据操作数量),并非实际值
- 只能衡量使用 devctx 的情况(工具调用可见)
- 除非 Agent 报告,否则无法检测未使用的情况
- 没有使用 devctx 的会话可能只是执行了简单任务(并非失败)
此功能的用途:
- 查看 devctx 在实践中是否得到采用
- 识别模式(复杂任务 → 更高的采用率)
- 验证规则和引导流程是否有效
- 用使用指标补充压缩指标
请参阅采用指标设计,了解完整分析。
实时使用反馈(新增!)
即时了解每次 Agent 响应中 devctx 工具的使用情况。
默认启用——每次调用 devctx 工具后都会显示反馈。
如果内容过多,可禁用:
export DEVCTX_SHOW_USAGE=false
你将看到:
---
📊 **devctx usage this session:**
- **smart_read**: 3 calls | ~45.0K tokens saved (file1.js, file2.js, file3.js)
- **smart_search**: 1 call | ~12.0K tokens saved (query)
**Total saved:** ~57.0K tokens
*To disable this message: `export DEVCTX_SHOW_USAGE=false`*
优势:
- ✅ 立即了解 Agent 是否正在使用 devctx
- ✅ 实时查看节省的令牌数
- ✅ 验证强制提示词是否生效
- ✅ 即时排查采用问题
适用场景:
- 验证 Agent 是否遵循规则
- 排查 devctx 未被使用的原因
- 衡量实时影响
- 安装后验证设置
请参阅使用反馈文档,了解完整指南。
决策说明(新增!)
了解 Agent 为何选择 devctx 工具,以及预期有哪些收益。
默认启用——每次调用 devctx 工具时都会显示决策说明。
如果内容过多,可禁用:
export DEVCTX_EXPLAIN=false
你将看到:
---
🤖 **Decision explanations:**
**smart_read** (read src/server.js (outline mode))
- **Why:** File is large (2500 lines), outline mode extracts structure only
- **Instead of:** Read (full file)
- **Expected benefit:** ~45.0K tokens saved
- **Context:** 2500 lines, 50000 tokens → 5000 tokens
**smart_search** (search "authentication" (intent: debug))
- **Why:** Intent-aware search prioritizes relevant results
- **Instead of:** Grep (unranked results)
- **Expected benefit:** ~12.0K tokens saved, Better result ranking
*To disable: `export DEVCTX_EXPLAIN=false`*
优势:
- ✅ 了解 Agent 的决策过程
- ✅ 学习何时使用哪种工具
- ✅ 排查工具选择问题
- ✅ 验证 Agent 是否做出了恰当的选择
适用场景:
- 学习 devctx 的工作方式
- 排查选择特定工具的原因
- 验证 Agent 的行为
- 了解最佳实践
与使用反馈结合使用,以获得最大程度的可见性:
export DEVCTX_SHOW_USAGE=true
export DEVCTX_EXPLAIN=true
请参阅决策说明文档,了解完整指南。
错失机会检测(新增!)
检测哪些情况下本应使用 devctx,却没有使用。
默认启用——devctx 采用率较低时会显示警告。
如果不需要,可禁用:
export DEVCTX_DETECT_MISSED=false
你将看到:
---
⚠️ **Missed devctx opportunities detected:**
**Session stats:**
- Duration: 420s
- devctx operations: 2
- Estimated total operations: 25
- devctx adoption: 8%
🟡 **low devctx adoption**
- **Issue:** Low devctx adoption: 2/25 operations (8%). Target: >50%.
- **Suggestion:** Agent may be using native tools. Consider forcing prompt.
- **Potential savings:** ~184.0K tokens
**How to fix:**
1. Use forcing prompt
2. Check if index is built
3. Verify MCP is active
检测内容:
- 🔴 长会话(>5 min)中没有使用 devctx
- 🟡 采用率低(低于操作总数的 30%)
- 🟡 使用量下降(超过 3 min 没有调用)
优势:
- ✅ 找出采用率不足的环节
- ✅ 量化潜在节省
- ✅ 验证强制提示词是否生效
- ✅ 检测 Agent 何时切换到原生工具
局限性:
- 操作总数为估算值(并非测量值)
- 对于简单任务,可能出现误报
- 仅限当前会话(重启后会重置)
默认启用所有功能。 如需全部禁用:
export DEVCTX_SHOW_USAGE=false
export DEVCTX_EXPLAIN=false
export DEVCTX_DETECT_MISSED=false
请参阅错失机会文档,了解完整指南。
Agent 规则(多客户端支持)
项目包含 Agent 规则,可强制不同客户端使用 devctx:
- Cursor:
.cursorrules(提交到 git) - Claude Desktop:
CLAUDE.md(根据docs/agent-rules-template.md中的模板创建) - 其他 Agent:
AGENTS.md(根据docs/agent-rules-template.md中的模板创建)
所有规则都强制执行相同的策略:
- 使用
smart_read而不是Read - 使用
smart_search而不是Grep - 使用
smart_context而不是多次读取 - 如果使用原生工具,则需说明
请参阅 Agent 规则模板 了解设置说明。
MCP 提示词(自动强制执行)
MCP 服务提供 提示词,可自动注入强制执行指令:
快速强制执行:
/prompt use-devctx
这会注入:Use devctx: smart_turn(start) → smart_context/smart_search → smart_read → smart_turn(end)
可用提示词:
/prompt use-devctx- 超短强制执行提示词/prompt devctx-workflow- 完整工作流模板/prompt devctx-preflight- 预检清单(索引 + 会话初始化)
优点:
- ✅ 无需记住或输入强制执行语法
- ✅ 集中管理(自动更新)
- ✅ 可在 Cursor 提示词菜单中找到
- ✅ 不会拼写错误
请参阅 MCP 提示词文档 了解完整指南。
快速验证
npm run verify # Feature verification (22 tools)
npm test # Unit tests (740+ tests)
npm run eval # Synthetic corpus
npm run eval:self # Real project
故障排除
Agent 未使用 devctx 工具
检查:
# 1. Rules installed?
cat .cursor/rules/devctx.mdc
# 2. MCP running?
# Cursor: Settings → MCP → Check "smart-context" active
# 3. Index built?
ls .devctx/index.json
# 4. Metrics show usage?
npm run report:metrics
可能的原因:
- 未安装规则 → 运行
npx smart-context-init --target . - MCP 未运行 → 重启客户端
- 未构建索引 → 运行
npm run build-index,或告诉 Agent“运行 build_index 工具” - 任务过于简单 → 内置工具已足够(这没问题)
- Agent 处于 Ask 模式 → 只读,无法访问 MCP
强制使用 devctx(可直接复制粘贴):
Use devctx: smart_turn(start) → smart_context/smart_search → smart_read → smart_turn(end)
请参阅如何强制使用 devctx 了解完整工作流。
启用工作流跟踪
如需跟踪完整工作流(调试、审查、重构、测试、架构):
export DEVCTX_WORKFLOW_TRACKING=true
然后重启 AI 客户端。查看工作流指标:
npm run report:workflows -- --summary
请参阅工作流指标了解详情。
使用 devctx 时仍然消耗大量 token
检查:
npm run report:metrics
请留意:
- 工具使用率低(操作次数低于 20%)
full模式使用率高(Agent 未逐步调用工具)- 压缩率低(低于 50%)
可能的原因:
- Agent 未遵循工作流
- 任务无法从压缩中受益
- 此类任务的规则不明确
上下文未持久化
检查:
# 1. Node version (need 22+ for SQLite)
node --version
# 2. SQLite exists?
ls -lh .devctx/state.sqlite
# 3. Agent calling smart_turn?
sqlite3 .devctx/state.sqlite "SELECT COUNT(*) FROM sessions"
可能的原因:
- Node 18-20 → 不支持 SQLite(升级到 22+)
- Agent 未调用
smart_turn→ 没有任务检查点 - 会话 ID 不匹配 → 无法恢复检查点
.devctx/state.sqlite被跟踪或暂存 → 在修复 git 规范问题前,会有意阻止运行时上下文写入.devctx/state.sqlite被锁定、损坏或过大 → 检查smart_status或smart_metrics中的storageHealth- 更全面的本地状态预检 → 运行
smart_doctor或smart-context-doctor --json
恢复流程:
missing→ 运行持久化操作,例如smart_summary update或smart_turn endoversized→ 运行smart_summary compactlocked→ 停止其他正在运行的 devctx 进程,然后重试corrupted→ 备份.devctx/state.sqlite,删除该文件,并让 devctx 重新创建本地状态
规则未生效
检查:
cat .cursor/rules/devctx.mdc # or AGENTS.md, CLAUDE.md
如果缺失:
npx smart-context-init --target .
如果文件存在但 Agent 忽略:
- 这是预期行为(规则是指导建议,而非强制措施)
- Agent 会根据任务自行判断
- 检查指标以了解实际使用情况
支持的语言
一等支持(AST 解析): JavaScript、TypeScript、JSX、TSX
启发式解析: Python、Go、Rust、Java、C#、Kotlin、PHP、Swift
结构提取: Shell、Terraform、HCL、Dockerfile、SQL、JSON、YAML、TOML
配置
环境变量
# Point to different project
export DEVCTX_PROJECT_ROOT=/path/to/project
# Disable cache warming
export DEVCTX_CACHE_WARMING=false
# Change warm file count
export DEVCTX_WARM_FILES=100
跨项目设置
创建 .devctx-projects.json:
{
"version": "1.0",
"projects": [
{ "name": "main-app", "path": ".", "type": "main" },
{ "name": "shared-lib", "path": "../shared-lib", "type": "library" },
{ "name": "api-service", "path": "../api-service", "type": "service" }
]
}
为每个项目构建索引:
cd main-app && npx build-index
cd ../shared-lib && npx build-index
cd ../api-service && npx build-index
存储
所有数据均存储在 .devctx/ 中:
index.json- 符号索引(INDEX_VERSION 7:ADR + ADR 章节,增强的 Python/Go 支持)state.sqlite- 会话、指标、模式、任务交接、测试失败记录、解释缓存(Node 22+)metrics.jsonl- 可选择启用的旧版文件,仅在设置DEVCTX_METRICS_FILE=path.jsonl时使用
跨项目(通过 DEVCTX_GLOBAL_MEMORY=true 选择启用):
~/.devctx/global.db- 经过清理的决策、模式、操作手册、笔记,支持语义检索
添加到 .gitignore:
.devctx/
安全性
此 MCP 默认安全:
- ✅ 仅允许列表中的命令 - 仅允许安全的诊断命令(
ls、git status、npm test等) - ✅ 不允许 Shell 运算符 - 阻止
|、&、;、>、<、`、$() - ✅ 路径验证 - 无法逃出项目根目录
- ✅ 无写入权限 - 无法修改代码
- ✅ 仓库安全 - 防止意外提交本地状态
- ✅ 资源限制 - 超时 15s,缓冲区 10MB
smart_shell 可以运行的命令:
# Allowed
git status # ✓ Safe git read operations
npm test # ✓ Safe package manager scripts
find . -name "*.js" # ✓ File discovery
rg "pattern" # ✓ Code search
# Blocked
git commit # ✗ Write operations blocked
npm install pkg # ✗ Package changes blocked
ls | grep secret # ✗ Shell operators blocked
rm -rf / # ✗ Dangerous commands blocked
实际拒绝示例:
// Shell operator blocked
smartShell({ command: "ls | grep secret" })
→ { exitCode: 126, blocked: true, output: "Shell operators are not allowed..." }
// Dangerous command blocked
smartShell({ command: "rm -rf /" })
→ { exitCode: 126, blocked: true, output: "Dangerous pattern detected..." }
// Git write blocked
smartShell({ command: "git commit -m 'test'" })
→ { exitCode: 126, blocked: true, output: "Git subcommand not allowed: commit..." }
// Package install blocked
smartShell({ command: "npm install malicious" })
→ { exitCode: 126, blocked: true, output: "Package manager subcommand not allowed: install..." }
验证:
# Run 60+ security tests to verify behavior
cd tools/devctx && npm test -- tests/smart-shell-security.test.js
配置:
# Disable shell execution entirely
export DEVCTX_SHELL_DISABLED=true
# Disable cache warming
export DEVCTX_CACHE_WARMING=false
完整安全文档:
- SECURITY.md - 完整的安全策略
- 安全拒绝示例 - 50+ 个具体示例
要求
- **Node.js:**18+(SQLite 功能建议使用 22+)
- **Git:**用于感知差异的上下文和 git blame
- **ripgrep:**通过
@vscode/ripgrep提供(无需系统安装)
性能对比
| 操作 | 不使用 MCP | 使用 MCP | 节省 |
|---|---|---|---|
| 读取文件 | 4,000 tokens | 400 tokens | 90% |
| 搜索代码 | 10,000 tokens | 500 tokens | 95% |
| 恢复会话 | 5,000 tokens | 100 tokens | 98% |
| 冷启动 | 250ms | 50ms | 快 5 倍 |
文档
功能
安全性
验证
开发
API 参考
核心工具
smart_read
{
filePath: string;
mode?: 'outline' | 'signatures' | 'symbol' | 'range' | 'full';
symbol?: string | string[];
startLine?: number;
endLine?: number;
maxTokens?: number;
context?: boolean;
}
smart_search
{
query: string;
intent?: 'implementation' | 'debug' | 'tests' | 'config' | 'docs' | 'explore';
cwd?: string;
maxFiles?: number; // 1-50, default 15
}
smart_context
{
task: string;
intent?: string;
detail?: 'minimal' | 'balanced' | 'deep';
maxTokens?: number;
entryFile?: string;
diff?: boolean | string;
prefetch?: boolean;
include?: string[];
}
build_index
{
incremental?: boolean;
warmCache?: boolean;
}
smart_metrics
{
window?: '24h' | '7d' | '30d' | 'all';
tool?: string;
sessionId?: string;
}
高级工具
smart_summary
{
action: 'get' | 'update' | 'append' | 'checkpoint' | 'reset' | 'list_sessions';
sessionId?: string;
update?: {
goal?: string;
status?: 'planning' | 'in_progress' | 'blocked' | 'completed';
nextStep?: string;
completed?: string[];
decisions?: string[];
};
maxTokens?: number;
}
smart_turn
{
phase: 'start' | 'end';
prompt?: string;
event?: string;
update?: object;
}
smart_read_batch
{
files: Array<{
path: string;
mode?: string;
symbol?: string;
}>;
maxTokens?: number;
}
smart_shell
{
command: string;
}
warm_cache
{} // No parameters
git_blame
{
mode: 'symbol' | 'file' | 'author' | 'recent';
filePath?: string;
authorQuery?: string;
limit?: number;
daysBack?: number;
}
cross_project
{
mode: 'discover' | 'search' | 'read' | 'symbol' | 'deps' | 'stats';
query?: string;
symbolName?: string;
maxResultsPerProject?: number;
}
核心能力
- ✅ 通过智能压缩减少 90% 的 token 消耗
- ✅ 借助共享层和客户端适配器实现自动编排
- ✅ 通过 SQLite 状态持久化保持会话连续性
- ✅ 工作流跟踪(调试、代码审查、重构、测试、架构)
- ✅ 支持连续性工作流的任务运行器 CLI
- ✅ 用于跨客户端基准测试的对比指标
- ✅ 可用于生产环境,拥有 740 多项测试和发布门控基准测试
完整的发布历史请参阅 CHANGELOG.md。
仓库结构
此仓库在 tools/devctx/ 中包含 smart-context-mcp npm 包:
/
├── tools/devctx/ ← Publishable package
│ ├── src/ ← Source code
│ ├── tests/ ← 740+ unit tests
│ ├── evals/ ← Benchmarks & scenarios
│ ├── scripts/ ← CLI binaries
│ └── package.json ← Package metadata (v1.21.0)
├── docs/ ← Documentation (GitHub only)
├── .github/workflows/ ← CI/CD with release gating
└── README.md ← This file
发布到 npm 的内容: 仅包含 tools/devctx/ 中的内容(src + scripts)
开发: 所有工作都在 tools/devctx/ 中进行
开发环境设置请参阅 CONTRIBUTING.md。
贡献
欢迎提交以下方面的拉取请求:
- 添加语言解析器
- 性能优化
- 修复 Bug
贡献指南请参阅 CONTRIBUTING.md。
作者
Francisco Caballero Portero
邮箱:[email protected]
GitHub: @Arrayo
许可证
MIT 许可证 — 详情请参阅 LICENSE 文件。
链接
评论
一个开放协议,规定了 AI 应用如何以统一方式连接外部工具与数据源。客户端负责与模型对话,MCP 服务负责提供工具、资源和提示模板,两者通过标准消息通信,同一个服务可以被不同客户端复用。