智能上下文mcp
MCP服务器,通过智能上下文压缩(在本项目中测量)将AI代理令牌的使用率降低了90%。
](https://www.npmjs.com/package/smart-context-mcp) 
这是什么
MCP(模型上下文协议)服务器,提供用于高效读取、搜索和管理代码上下文的专用工具。它不是加载完整文件或返回大量搜索结果,而是压缩信息,同时保留对任务重要的内容。
生产使用的真实指标:
- 约700万个代币→ ~800K代币(约减少89%)
- 在整个开发过程中跟踪了1500多个操作
- 压缩比: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.19.0
五步质量跳跃以连续提交的形式执行,并带有完整的dogfooding。MCP从 18 → 20 tools+68次测试, 零新依赖项,绿色套房882/883(跳过1个)。
smart_playbook(新工具)。 运行多个应用程序的声明性复合工作流smart_*在单个MCP调用中使用工具。该套装附带五本内置剧本:preflight-merge(审查+受影响的测试+检查点),debug-flake(上次失败+精心策划的调试上下文+受影响),refactor-safe(策划的上下文+受影响的+检查点),doc-sync(ADR搜索+文档上下文),ramp-up(状态+医生+ADR概述)。通过以下方式进行项目级覆盖.devctx/playbooks/*.{yaml,json}随着{{args.X}}插值,when/label/stopOnFail/dryRun工具分配仅限于smart_*.Zero deps:内置最小YAML解析器。- 索引的响应式FS监视器。
fs.watch(本机、递归、去抖动600ms+每2秒进行一次批量刷新)使符号索引在调用之间保持热状态。过滤器.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因此,未来的树形解析器可以在不接触的情况下插入index.js.INDEX_VERSION撞6→ 7 (自动重新索引)。 - 局部语义重新排序
smart_search. 加入semantic: true(与semanticLimit)返回asemantic: { embedder, symbols[], files[] }按哈希/TF-IDF嵌入进行块排名(256个dim,FNV-1a桶,L2归一化,余弦相似性,\ “MCP在长时间、多会话任务或你不知道代码库的情况下表现出色。对于已经知道要处理什么的包含重构,原生工具同样快或更快。真正的价值在于smart_read(outline)以便初始分析和检查点不会在会话之间丢失线程。"
90%的代币节省是真实的,但它们需要正确的任务类型才能实现。
______________________________________________________________________
为什么它存在
AI代理以三种方式浪费代币:
- 正在读取完整文件 当它们只需要结构或特定功能时
- 海量搜索结果 有数百场不相关的比赛
- 重复上下文 跨越对话的转折
此MCP通过提供返回压缩、排序和缓存上下文的工具来解决这三个问题。
______________________________________________________________________
🚨 特工忽略了devctx? → 粘贴此下一页
📋 官方提示(复制粘贴)
Use smart-context-mcp for this task.
Start with smart_turn(start), then use smart_context or smart_search before reading full files.
End with smart_turn(end) if you make progress.⚡ 超短版本
Use devctx: smart_turn(start) → smart_context → smart_turn(end)何时使用: 代理使用读取大文件 Read,使用 Grep 重复,或者在复杂的任务中看不到devctx工具。
为什么会发生这种情况: 任务似乎很简单,没有构建索引,原生工具看起来更直接,或者规则不够强大。
______________________________________________________________________
快速入门:我应该使用哪个客户端?
🎯 最佳默认值:光标
在以下情况下使用: 您在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自动化: 中低-规则可见,但需要明确提示。
______________________________________________________________________
📊 快速比较
| 客户端 | 自动化 | 最适合 |
|---|---|---|
| 光标 | 中等 | 复杂的IDE任务 |
| 克劳德桌面版 | 高(挂钩) | 会话连续性 |
| Codex CLI | 中低 | 终端工作流程 |
| Qwen代码 | 中低 | 光标的替代品 |
重要提示: Agent总是决定是否使用devctx。规则会增加概率,但不能保证。
如果你想要一个更可重复的路径: 使用任务运行器或辅助启动器,而不是仅依赖规则。看 任务运行器工作流.
📖 完整设置: 客户端兼容性
______________________________________________________________________
🚀 如何调用MCP
重点: MCP不会自动拦截提示。你需要告诉代理人使用它。
1.️⃣ 使用MCP提示(最简单-仅限光标)
/prompt use-devctx
[Your task here]其他提示:
/prompt devctx-workflow-完整的工作流程/prompt devctx-preflight-构建索引+启动会话
2.️⃣ 明确指示(任何客户)
Use smart_turn(start) to recover context, then [your task]有关更具指导性的CLI路径:
smart-context-task task --prompt "your task"
smart-context-task implement --prompt "your task"
smart-context-task continue --session-id
smart-context-task doctor3.️⃣ 通过规则自动(不保证)
代理 *应该* 如果规则处于活动状态,请使用devctx执行复杂任务:
- 光标:
.cursorrules - 克劳德桌面:
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 |
| 强制使用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"复制粘贴到代理(第一次):
Run build_index, then use smart_turn(start) to begin this task.______________________________________________________________________
⚠️ 为什么指数很重要
无索引:
- ❌
smart_search返回未排名的结果 - ❌
smart_context无法构建最佳上下文 - ❌ 代理可能更喜欢本机工具→ 没有积蓄
带索引:
- ✅
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 不拦截 你的提示神奇。实际情况如下:
- 你写一个提示: “修复登录错误”
- 代理读取规则: 查看调试工作流程建议
- 代理人决定: “这是一个调试任务,我将从
smart_turn(start)" - 客服电话:
smart_turn({ phase: 'start', userPrompt: '...', ensureSession: true }) - MCP返回: 上一个任务检查点(如果存在)+仓库安全检查
- 代理继续: 呼叫
smart_search(intent=debug)用于错误定位 - 代理人写道: 呼叫
smart_read(mode=symbol)用于特定功能 - 代理修复了错误: 进行更改
- 代理验证: 呼叫
smart_shell('npm test') - 代理检查点: 呼叫
smart_turn(end)坚持进步
要点:
- ✅ 代理 选择 使用devctx工具(非强制)
- ✅ 规则 引导 代理人(不强制执行)
- ✅
smart_turn(start)是 推荐入口点 用于非琐碎任务 - ✅ 代理可以跳过工作流处理琐碎的任务
- ✅ 你什么也不能直接控制——由代理人决定
所得
工具(20): 内置操作的有效替代方案
smart_read/smart_read_batch-压缩文件读取(大纲、签名、符号、解释)smart_search-具有排名、ADR过滤和选择性语义重新排名的意图感知代码搜索smart_context-一个带图形的调用上下文生成器+paths: { from, to }遍历smart_test-通过图形+沙盒运行器+持久化受影响的测试last_failuresmart_review-飞行前代码审查:差异+调用者+启发式发现smart_playbook-声明式复合工作流(5个内置:飞行前合并、调试片、重构安全、文档同步、启动)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-会话、指标、模式、任务切换、测试失败、解释缓存(节点22+,node:sqlite)metrics.jsonl-仅在以下情况下选择使用旧文件DEVCTX_METRICS_FILE=path.jsonl已设置~/.devctx/global.db-跨项目内存(通过选择加入DEVCTX_GLOBAL_MEMORY=true)
持久任务上下文(支持时)
坚持什么:
- 任务检查点(目标、状态、决策、阻断器)
- 文件访问模式(用于预测)
- 令牌指标(用于优化)
- 会话摘要(压缩约100个令牌)
咨询时:
- 客服电话
smart_turn(start)-恢复任务检查点 - 客服电话
smart_context-使用模式进行预测 - 客服电话
smart_summary-获取任务摘要
未坚持的内容:
- ❌ 完整对话记录
- ❌ 完整的消息历史记录
- ❌ 代理人推理或思考
- ❌ 用户逐字提示
限制:
- 仅在代理呼叫时有效
smart_turn(非自动) - 仅在项目内持续存在(
.devctx/是本地的) - 仅在会话ID匹配时恢复(手动或自动)
- 客户必须支持MCP(游标、Codex、Claude Desktop、Qwen)
诚实的事实: 任务上下文持久性是 选择加入 通过代理行为,而不是 自动的 通过客户端拦截。
这对你意味着什么
最佳情况:
- 代理人始终如一地遵守规则
- 50-80%的操作使用devctx工具
- 代币使用率下降85-90%(经过验证、测量)
- 由于要处理的数据较少(从令牌节省推断),响应通常更快
典型场景:
- Agent使用devctx工具执行复杂任务
- 使用内置工具执行简单任务
- 代币使用量下降60-80%
- 效率明显提高
最坏情况:
- 代理忽略规则(罕见但可能)
- 仅使用内置工具
- 令牌使用情况不变
- 没有造成伤害(MCP是被动的)
您可以查看: npm run report:metrics 显示实际工具使用情况和测量结果 smart_turn 质量信号。
“更好的背景”意味着什么
我们改进的内容:
- ✅ 上下文相关性(任务的正确文件)
- ✅ 信噪比(更少样板,更多信号)
- ✅ 上下文效率(在更少的空间中提供更多相关信息)
- ✅ 响应速度(处理的数据更少)
我们不保证的是:
- ❌ 代理人总是正确的
- ❌ 答案将是完美的
- ❌ 任务总是会成功的
- ❌ 响应将“更准确”(准确性取决于代理,而不仅仅是上下文)
好处: 代理使用更好的输入,但输出质量仍然取决于代理的能力和任务的复杂性。
诚实的声明: 我们提供 更好的上下文 (相关性更强,噪音更小) 可以帮助 当遵循工作流时,代理在复杂任务中的响应效率更高。
已证明的内容: 90%的代币节省(在3666次操作中衡量)。\ 推断内容: 质量改进(更好的投入→ 潜在的更好的输出,但没有明确测量)。\ 我们无法控制的: 代理正确性、任务成功、响应准确。
______________________________________________________________________
工作流示例
调试
// 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
何时使用: 任何时候你都需要理解文件结构,而无需阅读所有内容。
______________________________________________________________________
智能搜索
具有排名、重复数据消除和索引提升功能的意图感知代码搜索。
// 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个时,结果会包含提示)。
______________________________________________________________________
智能文本
一个调用上下文构建器:搜索+读取+图形扩展。
{
task: 'Fix login authentication bug',
detail: 'balanced' // minimal | balanced | deep
}返回包含压缩内容、符号详细信息和关系图的相关文件。
智能模式检测: 自动检测任务中的文字模式(TODO、FIXME、/\*\*、console.log、调试器),并在搜索结果中对其进行优先级排序。
何时使用: 开始一项新任务,需要全面的背景。
______________________________________________________________________
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 看起来很可疑。
______________________________________________________________________
智能状态
显示当前会话上下文和进度可见性。
{ format: 'detailed' } // Full formatted output with emojis
{ format: 'compact' } // Minimal JSON显示目标、状态、最近的决定、触摸的文件、固定的上下文和进度统计数据。每次MCP操作都会自动更新。 当回购安全或SQLite健康影响状态时, smart_status 通过降级模式和曲面保持有用 storageHealth 加上同样的 mutationSafety 合同作为 smart_turn.
______________________________________________________________________
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运算符和不安全命令。
______________________________________________________________________
差异感知上下文
智能分析git变化(部分 smart_context):
{ task: 'Review changes', diff: 'main' }返回按影响+相关文件(测试、导入程序)优先级排列的更改文件。
______________________________________________________________________
上下文预测
从使用模式中学习并预测所需的文件(部分 smart_context):
{ task: 'Implement authentication', prefetch: true }完成3个以上类似任务后:往返次数减少40-60%,额外节省15-20%。
______________________________________________________________________
温热疼痛
将频繁访问的文件预加载到操作系统缓存中。
{} // No parameters第一个查询:250ms→ 50ms(冷启动速度快5倍)。
______________________________________________________________________
git_blame
功能级代码归因。
// Who wrote each function?
{ mode: 'symbol', filePath: 'src/server.js' }
// Find code by author
{ mode: 'author', authorQuery: 'alice@example.com' }
// Recent changes
{ mode: 'recent', daysBack: 7 }______________________________________________________________________
交叉工程
跨monorepos和微服务共享上下文。
// Search all related projects
{ mode: 'search', query: 'AuthService' }
// Find symbol across projects
{ mode: 'symbol', symbolName: 'validateToken' }需要 .devctx-projects.json 配置文件。
客户端兼容性
| 客户端 | MCP | 规则 | 钩子 | smart_turn | 持久性 | 近乎自动 | 关键限制 |
|---|---|---|---|---|---|---|---|
| 光标 | ✅ 已满 | ✅ 条件式 | |||||
(.cursor/rules/*.mdc) | ❌ 否 | ✅ 手动呼叫 | ✅ SQLite | ||||
| (节点22+) | 🟡 中等 | ||||||
| 代理决定何时 | •无自动 smart_turn |
•代理人必须遵守规则 •需要代理模式| | 克劳德桌面版 | ✅ 已满|✅ 嵌入式 (CLAUDE.md) | ✅ 会话开始 后工具使用 停止|✅ 可以自动触发 通过钩子|✅ SQLite (节点22+)|🟢 高 挂钩自动触发|•挂钩可选择加入 •无条件规则 •固定上下文:200t| | Codex CLI | ✅ 已满|✅ 嵌入式 (AGENTS.md) | ❌ 否|✅ 手动呼叫|✅ SQLite (节点22+)|🟡 低中等 代理决定何时|•无自动 smart_turn •无条件规则 •无挂钩| | Qwen代码 | ✅ 已满|✅ 嵌入式 (AGENTS.md) | ❌ 否|✅ 手动呼叫|✅ SQLite (节点22+)|🟡 低中等 代理决定何时|•无自动 smart_turn •无条件规则 •无挂钩|
传说:
- 🟢 高:钩子可以在特定时刻自动触发工具
- 🟡 中/低:代理读取规则并决定何时使用工具
- ✅ 支持|⚠️ 部分|❌ 不支持
______________________________________________________________________
“近乎自动”是什么意思
🟢 高(带挂钩的克劳德桌面):
- 挂钩可以自动触发
smart_turn(start)当您开始会话时 - 钩子可以在大量使用工具后自动检查点
- 代理仍然决定为每个任务使用哪些devctx工具
- 这是最接近“自动”的行为
🟡 中等(光标):
- 代理自动读取基本规则(始终处于活动状态,150个令牌)
- 基于文件glob激活条件配置文件(调试、审查等)
- Agent根据任务决定何时使用devctx工具
- 代理人必须手动呼叫
smart_turn(非自动触发)
🟡 中低(食品法典委员会,Qwen):
- 代理自动读取嵌入规则(始终处于活动状态,200个令牌)
- Agent根据任务决定何时使用devctx工具
- 代理人必须手动呼叫
smart_turn(非自动触发) - 无条件激活或挂钩
______________________________________________________________________
“近乎自动”不是什么意思
❌ 非自动提示拦截 -MCP无法在代理看到您的提示之前拦截或修改它们\ ❌ 不强制使用工具 -Agent始终拥有决定使用哪些工具的自主权\ ❌ 不保证工作流程 -代理可以跳过devctx工具执行简单任务(这很好)\ ❌ 不是客户端级别的魔法 -行为取决于代理人遵守规则并做出正确决策
______________________________________________________________________
现实
所有客户都以相同的方式工作:
- 代理读取规则(关于devctx工具何时有用的指导)
- 代理决定工具的使用(自主选择最佳方法)
- MCP提供工具(被动,仅在调用时响应)
- 您使用指标进行验证(
npm run report:metrics)
差异:
- 钩子 (Claude Desktop)可以在特定时刻自动触发特定工具(例如。,
smart_turn(start)会话开始时) - 条件规则 (光标)降低固定上下文成本,并在相关时激活特定任务的配置文件
- 嵌入式规则 (Codex,Qwen)简单,总是积极,到处工作
______________________________________________________________________
我应该使用哪个客户端?
在以下情况下选择光标:
- ✅ 您希望最低的固定上下文成本(150个令牌基数+活动时的120个令牌配置文件)
- ✅ 您处理复杂的多文件任务(调试、重构、架构)
- ✅ 您需要基于文件模式激活的条件规则
如果出现以下情况,请选择克劳德桌面:
- ✅ 你想要最接近“自动”的行为(钩子可以自动触发
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: smart-context-mcp@1.19.0 (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更新后: 二进制文件全局更新,但代理规则(.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客户端以加载新版本。
______________________________________________________________________
光标
npm install -g smart-context-mcp
npx smart-context-init --target . --clients cursor重新启动游标。工具以代理模式显示。
创建的文件:
.cursor/mcp.json-MCP服务器配置.cursor/rules/devctx.mdc-基本代理规则(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-代理规则.git/hooks/pre-commit-安全钩.gitignore-添加.devctx/
______________________________________________________________________
克劳德桌面版
npm install -g smart-context-mcp
npx smart-context-init --target . --clients claude重新启动克劳德桌面。
创建的文件:
.mcp.json-MCP服务器配置.claude/settings.json-挂钩配置CLAUDE.md-代理规则.git/hooks/pre-commit-安全钩.gitignore-添加.devctx/
______________________________________________________________________
Qwen代码
npm install -g smart-context-mcp
npx smart-context-init --target . --clients qwen重新启动Qwen Code。
创建的文件:
.qwen/settings.json-MCP服务器配置AGENTS.md-代理规则.git/hooks/pre-commit-安全钩.gitignore-添加.devctx/
特工规则:秘密酱汁
这个MCP的不同之处在于 特定任务代理指导安装程序生成规则,指导代理优化工作流程:
调试配置文件
smart_turn(start) → smart_search(intent=debug) → smart_read(symbol) →
smart_shell('npm test') → fix → smart_turn(end)节省: 90%(15万)→ 15K代币)
代码审查配置文件
smart_turn(start) → smart_context(diff=true) → smart_read(signatures) →
review → smart_turn(end)节省: 87%(20万)→ 25K代币)
重构配置文件
smart_turn(start) → smart_context(entryFile) → smart_read(signatures) →
refactor → smart_shell('npm test') → smart_turn(end)节省: 89%(18万)→ 20K代币)
试验剖面
smart_turn(start) → smart_search(intent=tests) → smart_read(symbol) →
write test → smart_shell('npm test') → smart_turn(end)节省: 90%(12万)→ 12K代币)
架构简介
smart_turn(start) → smart_context(detail=minimal) → smart_read(signatures) →
analyze → smart_turn(end)节省: 90%(30万)→ 30K代币)
关键见解: 价值不仅在于工具,还在于教育代理人 当 和 怎么 使用它们。
______________________________________________________________________
步骤2:设置代理规则(推荐)
为确保代理自动使用devctx,请设置特定于客户端的规则:
游标用户
已包含: .cursorrules 已承诺参与该项目。
验证它是否正常工作:
- 代理应提及devctx使用策略
- 代理应自动使用devctx工具
- 对于长任务,更喜欢
./.devctx/bin/cursor-devctx task --prompt "..." --
Claude桌面用户
创建 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.
其他代理客户
创建 AGENTS.md 在项目根目录中使用相同的模板。
为什么这些规则很重要:
- ✅ 代理自动使用devctx(无需手动强制)
- ✅ 所有客户行为一致
- ✅ 使用devctx时可见反馈
- ✅ 应使用devctx但不应使用的警告
看 代理规则模板 完成设置。
______________________________________________________________________
未使用时的反馈
如果代理在非平凡任务中不使用devctx工具,它将添加一条注释:
Note: devctx not used because: [reason]
To use devctx next time: "Use smart-context-mcp: smart_turn(start) → ..."为什么这很重要:
- 使非使用情况可见
- 教育devctx何时增值
- 提供下一个转弯的强制提示
- 识别设置问题(MCP不可用,未构建索引)
______________________________________________________________________
如何强制使用devctx
何时使用这些提示:
- 代理在一项非平凡的任务中没有使用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()..."看 代理人规则/ 获取完整的个人资料。
入门指南
第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 退化。代理可能更喜欢本机工具。没有象征性的节省。
- 使用核心工具:
- smart_read 用于文件结构 - smart_search 用于查找代码 - smart_context 全面的背景 - smart_metrics 验证储蓄
- 让代理人决定: 不要强迫使用工具。生成的规则将自然地指导代理。
1周后:添加高级工具
smart_summary如果你做长任务smart_turn如果使用Claude Code CLIgit_blame用于代码归因cross_project如果在monorepos工作
1个月后:优化
- 检查
smart_metrics关于使用模式 - 启用
warm_cache如果冷启动缓慢 - 启用
prefetch在smart_context用于重复性任务
度量与验证
运行完整基准测试
npm run benchmark运行所有验证套件:
- 740+单元测试
- 14个特征验证
- 综合语料库评价
- 实际项目评估
- 编排回归基准(5个核心场景)
- 生产指标报告
需要3-4分钟。看 基准文件 了解详情。
编排质量的发布门控也可用于 npm run benchmark:orchestration:release,以及 npm publish 现在封锁了那扇门 prepublishOnly.
检查它是否正常工作
npm run report:metrics好兆头:
- 工具使用率>0(代理使用devctx)
- 节省60-90%(压缩工作)
- 使用多种工具(遵循工作流程)
不良迹象:
- 工具使用率=0(代理未使用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时的平均代币节省
我们不测量的:
- ❌ 反馈频率(要求代理报告)
- ❌ 反馈原因(需要代理商配合)
- ❌ 强制提示使用(无法从指标中检测到)
- ❌ 实际任务复杂性(仅从操作计数推断)
限制:
- 复杂性是推断的(操作计数),而不是实际的
- 只能测量何时使用devctx IS(工具调用可见)
- 除非代理报告,否则无法检测到未使用
- 没有devctx的会话可能是简单的任务(而不是失败)
为什么这很有用:
- 看看devctx在实践中是否被采用
- 识别模式(复杂任务→ 更高的采用率)
- 验证规则和入职培训是否有效
- 用使用率指标补充压缩指标
看 采用指标设计 进行完整分析。
______________________________________________________________________
实时使用反馈(新增!)
获取 即时能见度 在每个代理响应中使用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`*优点:
- ✅ 立即知道代理是否正在使用devctx
- ✅ 实时查看代币节省
- ✅ 验证强制提示是否有效
- ✅ 立即调试采用问题
何时使用:
- 验证代理是否遵循规则
- 调试为什么不使用devctx
- 测量实时影响
- 安装后验证安装程序
看 使用反馈文档 完整的指南。
______________________________________________________________________
决策解释(新增!)
理解 为什么 代理选择了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`*优点:
- ✅ 了解代理决策
- ✅ 了解何时使用哪种工具
- ✅ 调试工具选择问题
- ✅ 验证代理是否做出了正确的选择
何时使用:
- 学习devctx的工作原理
- 调试为什么选择某些工具
- 正在验证代理行为
- 了解最佳实践
结合使用反馈 为了获得最大的能见度:
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分钟)中不使用devctx
- 🟡 采用率低(\
,;
maxTokens?: number; }
**smart_shell**
{ command: string; }
**温热疼痛**
{} // No parameters
**git_blame**
{ mode: 'symbol' | 'file' | 'author' | 'recent'; filePath?: string; authorQuery?: string; limit?: number; daysBack?: number; }
**交叉工程**
{ mode: 'discover' | 'search' | 'read' | 'symbol' | 'deps' | 'stats'; query?: string; symbolName?: string; maxResultsPerProject?: number; }
## 核心能力
- ✅ **代币减少90%** 通过智能压缩
- ✅ **自动编排** 具有共享层和客户端适配器
- ✅ **会话连续性** 通过SQLite状态持久化
- ✅ **工作流跟踪** (调试、代码审查、重构、测试、架构)
- ✅ **任务运行器CLI** 具有连续性意识的工作流程
- ✅ **比较指标** 用于跨客户基准测试
- ✅ **生产就绪** 拥有740多个测试和发布门控基准
看 [更改日志.md](./CHANGELOG.md) 完整的发布历史。
## 仓库结构
此存储库包含 `smart-context-mcp` npm包在 `tools/devctx/`:
/ ├── tools/devctx/ ← Publishable package │ ├── src/ ← Source code │ ├── tests/ ← 740+ unit tests │ ├── evals/ ← Benchmarks & scenarios │ ├── scripts/ ← CLI binaries │ └── package.json ← Package metadata (v1.19.0) ├── docs/ ← Documentation (GitHub only) ├── .github/workflows/ ← CI/CD with release gating └── README.md ← This file
**发布到npm的内容:** 仅 `tools/devctx/` 内容(src+脚本)
**发展:** 所有工作都发生在 `tools/devctx/`
看 [贡献.md](./CONTRIBUTING.md) 用于开发设置。
## 贡献
欢迎拉取请求:
- 其他语言解析器
- 性能优化
- 错误修复
看 [贡献.md](./CONTRIBUTING.md) 作为指导方针。
## 作者
**弗朗西斯科·卡瓦列罗·波特罗**\
电子邮件:fcp1978@hotmail.com\
github: [@阵列或](https://github.com/Arrayo)
## 许可证
MIT许可证-请参阅 [许可证](./LICENSE) 文件以获取详细信息。
## 链接
-
-
- [问题追踪器](https://github.com/Arrayo/smart-context-mcp/issues)