Appearance
Context Mode 提供 6 个 MCP 沙盒工具,核心是 ctx_execute(单命令执行)和 ctx_batch_execute(批量执行+搜索)。所有脚本在独立子进程中运行,只有 console.log() 的 stdout 进入对话。支持 JavaScript、TypeScript、Python、Shell、Go、Rust 等 11 种语言,自动检测运行时(Bun 优先),支持凭证透传(gh、aws、kubectl 等 CLI 工具可在沙盒中使用)。
沙盒工具总览
Context Mode 注册 6 个 MCP 工具:
| 工具 | 用途 | 上下文消耗 |
|---|---|---|
ctx_execute | 在沙盒中运行单段代码 | 仅 stdout |
ctx_batch_execute | 批量执行命令 + 搜索(一次调用完成多步) | 仅 stdout |
ctx_execute_file | 处理文件内容(不读进上下文) | 仅 stdout |
ctx_index | 将 Markdown 分块索引到知识库 | 仅统计信息 |
ctx_search | 全文搜索已索引内容 | 搜索结果 |
ctx_fetch_and_index | 抓取 URL 并索引(24h TTL 缓存) | 仅统计信息 |
ctx_execute:核心沙盒工具
基本用法
js
ctx_execute("javascript", `
const files = fs.readdirSync('src');
console.log('Total files:', files.length);
`);第一个参数是语言标识,第二个参数是要执行的代码。代码在独立子进程中运行,console.log() 的输出返回到对话。
11 种支持的语言
| 语言 | 运行时标识 | 执行方式 |
|---|---|---|
| JavaScript | javascript / js | Node.js(优先 Bun) |
| TypeScript | typescript / ts | Bun(优先)或 tsx |
| Python | python / py | python / python3 |
| Shell | shell / bash / sh | bash / sh |
| Ruby | ruby / rb | ruby |
| Go | go | go run |
| Rust | rust / rs | rustc + 临时二进制 |
| PHP | php | php |
| Perl | perl / pl | perl |
| R | r / Rscript | Rscript |
| Elixir | elixir / exs | elixir |
运行时检测
Context Mode 在启动时扫描 PATH 中可用的运行时,按优先级选择:
TypeScript: bun (Bun 内置 tsx) > npx tsx > npx ts-node
JavaScript: bun > node
Python: python > python3
Shell: bash > shTIP
检测到 Bun 运行时后,JS/TS 执行速度提升 3-5 倍。Bun 内置 SQLite、TypeScript 编译和文件系统 API,无需额外依赖。
实战场景
场景一:统计项目结构
传统方式:Read × 50 = 250 KB
沙盒方式:1 × ctx_execute = 2 KBjs
ctx_execute("javascript", `
const path = require('path');
function walk(dir, depth = 0) {
if (depth > 2) return;
const entries = fs.readdirSync(dir, { withFileTypes: true });
for (const e of entries) {
if (e.name.startsWith('.') || e.name === 'node_modules') continue;
const full = path.join(dir, e.name);
console.log(' '.repeat(depth) + e.name + (e.isDirectory() ? '/' : ''));
if (e.isDirectory()) walk(full, depth + 1);
}
}
walk('.');
`);场景二:分析 Git 历史
传统方式:Bash("git log --oneline -100") = 15 KB
沙盒方式:脚本过滤,只输出统计 = 0.5 KBjs
ctx_execute("javascript", `
const { execSync } = require('child_process');
const log = execSync('git log --oneline --since="1 month ago"', { encoding: 'utf8' });
const lines = log.trim().split('\\n');
const authors = {};
lines.forEach(l => {
const match = l.match(/^[a-f0-9]+ (.+?):/);
if (match) authors[match[1]] = (authors[match[1]] || 0) + 1;
});
console.log('Commits by author (last month):');
Object.entries(authors).sort((a, b) => b[1] - a[1])
.forEach(([a, c]) => console.log(' ' + a + ': ' + c));
`);场景三:TypeScript 类型检查
ts
ctx_execute("typescript", `
const { execSync } = require('child_process');
try {
execSync('npx tsc --noEmit', { encoding: 'utf8', stdio: 'pipe' });
console.log('Type check passed ✓');
} catch (e) {
const errors = e.stdout.split('\\n').filter(l => l.includes('error TS'));
console.log('Type errors: ' + errors.length);
errors.slice(0, 5).forEach(err => console.log(' ' + err));
}
`);ctx_batch_execute:批量执行
为什么需要批量
当你需要执行多个相关命令时,每个 ctx_execute 都是一次 MCP 调用——虽然每次只返回精简结果,但多次调用的 MCP 开销(请求/响应元数据)也会累积。ctx_batch_execute 让你一次调用完成多步操作。
用法
js
ctx_batch_execute({
commands: [
{ lang: "shell", code: "npm test 2>&1 | tail -20" },
{ lang: "shell", code: "npm run build 2>&1 | tail -10" },
{ lang: "javascript", code: "console.log(JSON.stringify(require('./package.json').dependencies, null, 2))" }
],
search: ["error", "warning"]
});search 参数可以在结果中高亮匹配关键词,帮你快速定位问题。
适用场景
- CI 流水线式检查:lint → type check → test → build
- 代码审计:多维度分析同一个文件
- 日志分析:多个搜索关键词并行查询
ctx_execute_file:处理文件
用途
当需要处理大文件(如日志、JSON 配置)但只关心其中的特定信息时,用 ctx_execute_file 把文件交给沙盒处理。
js
ctx_execute_file({
path: "logs/app.log",
lang: "shell",
code: "grep -c ERROR $FILE && echo '---' && grep ERROR $FILE | tail -5"
});$FILE 是 Context Mode 自动注入的临时文件路径,文件内容不会进入对话上下文。
安全机制
命令验证
Context Mode 的 security.ts 在执行前检查每条命令:
| 检查项 | 说明 |
|---|---|
| deny/allow 规则 | 继承宿主平台的权限规则(Claude Code settings.json 中的 allowedTools 等) |
| 命令拆分 | &&、;、` |
| 危险命令拦截 | rm -rf /、chmod 777、覆写系统文件等 |
| glob 模式匹配 | 支持 Tool(what to match) 格式 |
权限优先级
deny(最高)> allow > 默认拒绝(最低)
项目级规则 > 全局规则沙盒隔离
- 每个
ctx_execute在独立子进程中运行 - 没有共享内存、没有状态残留
- 环境变量从宿主进程继承(包括凭证)
- 工作目录默认为项目根目录
凭证透传
沙盒中的脚本可以使用你本地配置的 CLI 工具:
js
// GitHub CLI
ctx_execute("shell", `gh pr list --state open --limit 5`)
// AWS CLI
ctx_execute("shell", `aws s3 ls my-bucket/`)
// kubectl
ctx_execute("shell", `kubectl get pods -n production`)这些工具使用你本地已配置的凭证(gh auth token、AWS profile、kubeconfig),Context Mode 不存储、不拦截、不上传。
WARNING
凭证透传意味着沙盒中的脚本有和你终端相同的权限。虽然有危险命令拦截,但仍建议在高安全环境中配合 Hook 规则使用。
知识库工具
ctx_index:索引文档
将 Markdown 文件分块索引到 FTS5 知识库:
ctx_index({
path: "docs/api-reference.md",
chunk_size: 500
})ctx_search:全文搜索
查询已索引的内容:
ctx_search({
queries: ["authentication", "JWT token"],
limit: 5
})搜索使用 FTS5 + BM25 + RRF 融合排序,支持 Porter 词干提取(running 匹配 ran)和 Trigram 分词(useEff 匹配 useEffect)。
ctx_fetch_and_index:抓取并索引
从 URL 抓取内容并索引,带 24 小时 TTL 缓存:
ctx_fetch_and_index({
url: "https://docs.example.com/api/v2",
chunk_size: 500
})FAQ
Q: ctx_execute 和直接用 Bash 工具有什么区别?
两个核心区别:(1) stdout 输出是唯一的上下文入口——stderr、文件写入、子进程输出都不进对话;(2) 路由指令强制 AI 优先使用 ctx_execute,减少原始数据涌入。直接用 Bash 也行,但输出可能几 KB 几十 KB 全进上下文。
Q: 脚本出错了怎么办?
错误信息(exit code + stderr 摘要)会返回到对话。你可以要求 AI 根据错误信息修复脚本再跑。比直接读文件的好处是:错误信息是精简的,而不是整个文件内容。
Q: 可以在脚本里 require/import 第三方包吗?
可以,但只限于项目 node_modules 中已安装的包。沙盒继承项目的工作目录和 NODE_PATH。