上下文窗口优化工具 是 AI Skill Hub 本期精选MCP工具之一。在 GitHub 上收获超过 14.5k 颗 Star,综合评分 8.5 分,整体质量较高。我们强烈推荐将其纳入你的 AI 工具库,帮助提升工作效率。
MCP协议的开源工具,专为AI编码代理优化上下文窗口管理。通过沙箱隔离工具输出、减少token消耗98%,显著提升Claude等大模型的编码效率和性能。适合AI编程工作流和代理应用开发者。
上下文窗口优化工具 是一款遵循 MCP(Model Context Protocol)标准协议的 AI 工具扩展。通过 MCP 协议,它可以让 Claude、Cursor 等主流 AI 客户端直接访问和操作外部工具、数据源和服务,实现 AI 能力的无缝扩展。无论是文件操作、数据库查询还是 API 调用,都可以通过自然语言在 AI 对话中直接触发,极大提升生产效率。
MCP协议的开源工具,专为AI编码代理优化上下文窗口管理。通过沙箱隔离工具输出、减少token消耗98%,显著提升Claude等大模型的编码效率和性能。适合AI编程工作流和代理应用开发者。
上下文窗口优化工具 是一款遵循 MCP(Model Context Protocol)标准协议的 AI 工具扩展。通过 MCP 协议,它可以让 Claude、Cursor 等主流 AI 客户端直接访问和操作外部工具、数据源和服务,实现 AI 能力的无缝扩展。无论是文件操作、数据库查询还是 API 调用,都可以通过自然语言在 AI 对话中直接触发,极大提升生产效率。
# 方式一:通过 Claude Code CLI 一键安装
claude skill install https://github.com/mksglu/context-mode
# 方式二:手动配置 claude_desktop_config.json
{
"mcpServers": {
"---------": {
"command": "npx",
"args": ["-y", "context-mode"]
}
}
}
# 配置文件位置
# macOS: ~/Library/Application Support/Claude/claude_desktop_config.json
# Windows: %APPDATA%/Claude/claude_desktop_config.json
# 安装后在 Claude 对话中直接使用 # 示例: 用户: 请帮我用 上下文窗口优化工具 执行以下任务... Claude: [自动调用 上下文窗口优化工具 MCP 工具处理请求] # 查看可用工具列表 # 在 Claude 中输入:"列出所有可用的 MCP 工具"
// claude_desktop_config.json 配置示例
{
"mcpServers": {
"_________": {
"command": "npx",
"args": ["-y", "context-mode"],
"env": {
// "API_KEY": "your-api-key-here"
}
}
}
}
// 保存后重启 Claude Desktop 生效
The other half of the context problem.
<p align="center"> <sub>Used across teams at</sub> <br><br> <a href="#"><img src="https://img.shields.io/badge/Microsoft-141414?style=flat" alt="Microsoft" /></a> <a href="#"><img src="https://img.shields.io/badge/Google-141414?style=flat&logo=google&logoColor=white" alt="Google" /></a> <a href="#"><img src="https://img.shields.io/badge/Meta-141414?style=flat&logo=meta&logoColor=white" alt="Meta" /></a> <a href="#"><img src="https://img.shields.io/badge/Amazon-141414?style=flat" alt="Amazon" /></a> <a href="#"><img src="https://img.shields.io/badge/IBM-141414?style=flat" alt="IBM" /></a> <a href="#"><img src="https://img.shields.io/badge/NVIDIA-141414?style=flat&logo=nvidia&logoColor=white" alt="NVIDIA" /></a> <a href="#"><img src="https://img.shields.io/badge/ByteDance-141414?style=flat&logo=bytedance&logoColor=white" alt="ByteDance" /></a> <a href="#"><img src="https://img.shields.io/badge/Stripe-141414?style=flat&logo=stripe&logoColor=white" alt="Stripe" /></a> <a href="#"><img src="https://img.shields.io/badge/Datadog-141414?style=flat&logo=datadog&logoColor=white" alt="Datadog" /></a> <a href="#"><img src="https://img.shields.io/badge/Salesforce-141414?style=flat" alt="Salesforce" /></a> <a href="#"><img src="https://img.shields.io/badge/GitHub-141414?style=flat&logo=github&logoColor=white" alt="GitHub" /></a> <a href="#"><img src="https://img.shields.io/badge/Red%20Hat-141414?style=flat&logo=redhat&logoColor=white" alt="Red Hat" /></a> <a href="#"><img src="https://img.shields.io/badge/Supabase-141414?style=flat&logo=supabase&logoColor=white" alt="Supabase" /></a> <a href="#"><img src="https://img.shields.io/badge/Canva-141414?style=flat" alt="Canva" /></a> <a href="#"><img src="https://img.shields.io/badge/Notion-141414?style=flat&logo=notion&logoColor=white" alt="Notion" /></a> <a href="#"><img src="https://img.shields.io/badge/Hasura-141414?style=flat&logo=hasura&logoColor=white" alt="Hasura" /></a> <a href="#"><img src="https://img.shields.io/badge/Framer-141414?style=flat&logo=framer&logoColor=white" alt="Framer" /></a> <a href="#"><img src="https://img.shields.io/badge/Cursor-141414?style=flat&logo=cursor&logoColor=white" alt="Cursor" /></a> </p>
Platforms are grouped by install complexity. Hook-capable platforms get automatic routing enforcement. Non-hook platforms need a one-time routing file copy.
<details open> <summary><strong>Claude Code</strong> — plugin marketplace, fully automatic</summary>
Prerequisites: Claude Code v1.0.33+ (claude --version). If /plugin is not recognized, update first: brew upgrade claude-code or npm update -g @anthropic-ai/claude-code.
Install:
/plugin marketplace add mksglu/context-mode
/plugin install context-mode@context-mode
Restart Claude Code (or run /reload-plugins).
Verify:
/context-mode:ctx-doctor
All checks should show [x]. The doctor validates runtimes, hooks, FTS5, and plugin registration.
Routing: Automatic. The SessionStart hook injects routing instructions at runtime — no file is written to your project. The plugin registers all hooks (PreToolUse, PostToolUse, PreCompact, SessionStart) and 11 MCP tools — six sandbox tools (ctx_batch_execute, ctx_execute, ctx_execute_file, ctx_index, ctx_search, ctx_fetch_and_index) plus five meta-tools (ctx_stats, ctx_doctor, ctx_upgrade, ctx_purge, ctx_insight).
| Slash Command | What it does |
|---|---|
/context-mode:ctx-stats | Context savings — per-tool breakdown, tokens consumed, savings ratio. |
/context-mode:ctx-doctor | Diagnostics — runtimes, hooks, FTS5, plugin registration, versions. |
/context-mode:ctx-upgrade | Pull latest, rebuild, migrate cache, fix hooks. |
/context-mode:ctx-purge | Permanently delete all indexed content from the knowledge base. |
/context-mode:ctx-insight | Personal analytics dashboard — 90 metrics, 37 insight patterns, 4 composite scores (productivity, quality, delegation, context health) across 23 event categories. Opens a local web UI. |
Note: Slash commands are a Claude Code plugin feature. On other platforms, typectx stats,ctx doctor,ctx upgrade, orctx insightin the chat — the model calls the MCP tool automatically. See Utility Commands.
Status line (optional): Claude Code's plugin manifest cannot declare a status line, so this is a one-time manual edit to ~/.claude/settings.json:
{
"statusLine": {
"type": "command",
"command": "context-mode statusline"
}
}
After saving, restart Claude Code. The bar shows $ saved this session · $ saved across sessions · % efficient so you can see savings accumulate in real time. The wiring is path-free — context-mode statusline resolves through the bundled CLI regardless of where the plugin cache lives.
<details> <summary>Alternative — MCP-only install (no hooks or slash commands)</summary>
claude mcp add context-mode -- npx -y context-mode
This gives you all 11 MCP tools without automatic routing. The model can still use them — it just won't be nudged to prefer them over raw Bash/Read/WebFetch. Good for trying it out before committing to the full plugin.
</details>
</details>
<details> <summary><strong>Gemini CLI</strong> — one config file, hooks included</summary>
Prerequisites: Node.js >= 22.5 (or Bun), Gemini CLI installed.
Install:
npm install -g context-mode
~/.gemini/settings.json. This single file registers the MCP server and all four hooks: {
"mcpServers": {
"context-mode": {
"command": "context-mode"
}
},
"hooks": {
"BeforeTool": [
{
"matcher": "run_shell_command|read_file|read_many_files|grep_search|search_file_content|web_fetch|activate_skill|mcp__plugin_context-mode|mcp__context-mode|mcp__(?!.*context-mode)",
"hooks": [{ "type": "command", "command": "context-mode hook gemini-cli beforetool" }]
}
],
"AfterTool": [
{
"matcher": "",
"hooks": [{ "type": "command", "command": "context-mode hook gemini-cli aftertool" }]
}
],
"PreCompress": [
{
"matcher": "",
"hooks": [{ "type": "command", "command": "context-mode hook gemini-cli precompress" }]
}
],
"SessionStart": [
{
"matcher": "",
"hooks": [{ "type": "command", "command": "context-mode hook gemini-cli sessionstart" }]
}
]
}
}
Verify:
/mcp list
You should see context-mode: ... - Connected.
Routing: Automatic via SessionStart hook. Optionally copy routing instructions for full model awareness:
cp node_modules/context-mode/configs/gemini-cli/GEMINI.md ./GEMINI.md
Why the BeforeTool matcher? It targets only tools that produce large output (run_shell_command,read_file,read_many_files,grep_search,search_file_content,web_fetch,activate_skill) plus context-mode's own tools (mcp__plugin_context-mode). This avoids unnecessary hook overhead on lightweight tools while intercepting every tool that could flood your context window.
Full config reference: configs/gemini-cli/settings.json
</details>
<details> <summary><strong>VS Code Copilot</strong> — hooks with SessionStart</summary>
Prerequisites: Node.js >= 22.5 (or Bun), VS Code with Copilot Chat v0.32+.
Install:
npm install -g context-mode
.vscode/mcp.json in your project root: {
"servers": {
"context-mode": {
"command": "context-mode"
}
}
}
.github/hooks/context-mode.json: {
"hooks": {
"PreToolUse": [
{ "type": "command", "command": "context-mode hook vscode-copilot pretooluse" }
],
"PostToolUse": [
{ "type": "command", "command": "context-mode hook vscode-copilot posttooluse" }
],
"SessionStart": [
{ "type": "command", "command": "context-mode hook vscode-copilot sessionstart" }
]
}
}
Verify: Open Copilot Chat and type ctx stats. Context-mode tools should appear and respond.
Routing: Automatic via SessionStart hook. Optionally copy routing instructions for full model awareness:
cp node_modules/context-mode/configs/vscode-copilot/copilot-instructions.md .github/copilot-instructions.md
Full hook config including PreCompact: configs/vscode-copilot/hooks.json
</details>
<details> <summary><strong>JetBrains Copilot</strong> — hooks with SessionStart</summary>
Prerequisites: Node.js >= 22.5 (or Bun), JetBrains IDE with GitHub Copilot plugin v1.5.57+.
Install:
npm install -g context-mode
2. Add MCP server via Settings UI: Settings > Tools > AI Assistant > Model Context Protocol (MCP) > Add Server: - Name: context-mode - Command: context-mode
.github/hooks/context-mode.json: {
"hooks": {
"PreToolUse": [
{ "type": "command", "command": "context-mode hook jetbrains-copilot pretooluse" }
],
"PostToolUse": [
{ "type": "command", "command": "context-mode hook jetbrains-copilot posttooluse" }
],
"SessionStart": [
{ "type": "command", "command": "context-mode hook jetbrains-copilot sessionstart" }
]
}
}
Verify: Open Copilot Chat and type ctx stats. Context-mode tools should appear and respond.
Routing: Automatic via SessionStart hook. Optionally copy routing instructions for full model awareness:
cp node_modules/context-mode/configs/jetbrains-copilot/copilot-instructions.md .github/copilot-instructions.md
Full hook config including PreCompact: configs/jetbrains-copilot/hooks.json
Full setup guide: docs/jetbrains-copilot.md
</details>
<details> <summary><strong>Cursor</strong> — hooks with stop support</summary>
Prerequisites: Node.js >= 22.5 (or Bun), Cursor with agent mode.
🚧 Work in progress — the Marketplace plugin is awaiting Cursor team review. Until it's listed, install via the local-folder path described in Option A. Tracking in #485 / #489.
npm install -g context-mode
.cursor/mcp.json in your project root (or ~/.cursor/mcp.json for global): {
"mcpServers": {
"context-mode": {
"command": "context-mode"
}
}
}
.cursor/hooks.json (or ~/.cursor/hooks.json for global): {
"version": 1,
"hooks": {
"preToolUse": [
{
"command": "context-mode hook cursor pretooluse",
"matcher": "Shell|Read|Grep|WebFetch|Task|MCP:ctx_execute|MCP:ctx_execute_file|MCP:ctx_batch_execute"
}
],
"postToolUse": [
{
"command": "context-mode hook cursor posttooluse"
}
],
"stop": [
{
"command": "context-mode hook cursor stop"
}
]
}
}
The preToolUse matcher is optional — without it, the hook fires on all tools. The stop hook fires when the agent turn ends and can send a followup message to continue the loop. afterAgentResponse is also available (fire-and-forget, receives full response text).
mkdir -p .cursor/rules
cp node_modules/context-mode/configs/cursor/context-mode.mdc .cursor/rules/context-mode.mdc
Verify: Open Cursor Settings > MCP and confirm "context-mode" shows as connected. In agent chat, type ctx stats.
Routing: Hooks enforce routing programmatically via preToolUse/postToolUse/stop. The .cursor/rules/context-mode.mdc file provides routing instructions at session start since Cursor's sessionStart hook is currently rejected by their validator (forum report). Project .cursor/hooks.json overrides ~/.cursor/hooks.json.
Known limitation: Cursor accepts additional_context in hook responses but does not surface it to the model (forum #155689). Routing relies on the .mdc rules file instead of hook context injection.
Full configs: configs/cursor/hooks.json | configs/cursor/mcp.json | configs/cursor/context-mode.mdc
</details>
<details> <summary><strong>OpenCode</strong> — TypeScript plugin with hooks</summary>
Prerequisites: Node.js >= 22.5 (or Bun), OpenCode installed.
Install:
npm install -g context-mode
opencode.json in your project root (or ~/.config/opencode/opencode.json for global): {
"$schema": "https://opencode.ai/config.json",
"plugin": ["context-mode"]
}
The plugin entry registers all 11 ctx_* tools natively and enables hooks — OpenCode calls context-mode's TypeScript plugin in-process, so there is no redundant stdio MCP child per session.
AGENTS.md file for routing awareness: cp node_modules/context-mode/configs/opencode/AGENTS.md AGENTS.md
This tells the model which tools to use and which commands are blocked. Without it, hooks still enforce routing — but the model won't know why a command was denied.
Verify: In the OpenCode session, type ctx stats. Context-mode tools should appear and respond.
Upgrade note: If an existing config has BOTH plugin: ["context-mode"] AND mcp.context-mode, OpenCode will register zero ctx_* tools — the plugin path correctly suppresses MCP duplicates, but the legacy MCP entry confuses the loader. Run context-mode upgrade to remove the legacy mcp.context-mode entry; your other MCP servers are preserved. v1.0.140+ emits a stderr diagnostic with the same guidance when this happens.
Routing: Hooks enforce routing programmatically via tool.execute.before and tool.execute.after. The optional AGENTS.md file provides routing instructions for model awareness. The experimental.session.compacting hook builds resume snapshots when the conversation compacts. The experimental.chat.system.transform hook injects the routing block and prior-session snapshots at session start, enabling session continuity across restarts. The chat.message hook captures user prompts and decisions (UserPromptSubmit equivalent).
Note: OpenCode lacks a real SessionStart hook (#14808, #5409). The plugin usesexperimental.chat.system.transformas a surrogate — it injects both the routing block and resume snapshots into the system prompt. User-prompt capture useschat.messageinstead of the missing UserPromptSubmit hook. AGENTS.md/CLAUDE.md/CONTEXT.md rules are captured automatically on first hook fire per project.
Full configs: configs/opencode/opencode.json | configs/opencode/AGENTS.md
</details>
<details> <summary><strong>KiloCode</strong> — TypeScript plugin with hooks</summary>
Prerequisites: Node.js >= 22.5 (or Bun), KiloCode installed.
Install:
npm install -g context-mode
kilo.json in your project root (or ~/.config/kilo/kilo.json for global): {
"$schema": "https://app.kilo.ai/config.json",
"plugin": ["context-mode"]
}
The plugin entry registers all 11 ctx_* tools natively and enables hooks — KiloCode calls context-mode's TypeScript plugin in-process, so there is no redundant stdio MCP child per session.
AGENTS.md file for routing awareness: cp node_modules/context-mode/configs/opencode/AGENTS.md AGENTS.md
Verify: In the KiloCode session, type ctx stats. Context-mode tools should appear and respond.
Upgrade note: If an existing config has BOTH plugin: ["context-mode"] AND mcp.context-mode, KiloCode will register zero ctx_* tools — the plugin path correctly suppresses MCP duplicates, but the legacy MCP entry confuses the loader. Run context-mode upgrade to remove the legacy mcp.context-mode entry; your other MCP servers are preserved. v1.0.140+ emits a stderr diagnostic with the same guidance when this happens.
Routing: Hooks enforce routing programmatically via tool.execute.before and tool.execute.after. The optional AGENTS.md file provides routing instructions for model awareness. The experimental.session.compacting hook builds resume snapshots when the conversation compacts. The experimental.chat.system.transform hook injects the routing block and prior-session snapshots at session start, enabling session continuity across restarts. The chat.message hook captures user prompts and decisions (UserPromptSubmit equivalent).
Note: KiloCode shares the same plugin architecture as OpenCode, using the OpenCodeAdapter with platform-specific configuration paths (kilo.jsoninstead ofopencode.json,~/.config/kilo/instead of~/.config/opencode/). Like OpenCode, it lacks a real SessionStart hook — the plugin usesexperimental.chat.system.transformas a surrogate. User-prompt capture useschat.messageinstead of the missing UserPromptSubmit hook. AGENTS.md/CLAUDE.md/CONTEXT.md rules are captured automatically on first hook fire per project.
</details>
<details> <summary><strong>OpenClaw / Pi Agent</strong> — native gateway plugin</summary>
Prerequisites: OpenClaw gateway running (>2026.1.29), Node.js 22+.
context-mode runs as a native OpenClaw gateway plugin, targeting Pi Agent sessions (Read/Write/Edit/Bash tools). Unlike other platforms, there's no separate MCP server — the plugin registers directly into the gateway runtime via OpenClaw's plugin API.
Install:
git clone https://github.com/mksglu/context-mode.git
cd context-mode
npm run install:openclaw
The installer uses $OPENCLAW_STATE_DIR from your environment (default: /openclaw). To specify a custom path:
npm run install:openclaw -- /path/to/openclaw-state
Common locations: Docker — /openclaw (the default). Local — ~/.openclaw or wherever you set OPENCLAW_STATE_DIR.
The installer handles everything: npm install, npm run build, better-sqlite3 native rebuild, extension registration in runtime.json, and gateway restart via SIGUSR1.
Verify: The plugin registers 8 hooks via api.on() (lifecycle) and api.registerHook() (commands). Type ctx stats to confirm tools are loaded.
Routing: Automatic. All tool interception, session tracking, and compaction recovery hooks activate automatically — no manual hook configuration or routing file needed.
Minimum version: OpenClaw >2026.1.29 — this includes the api.on() lifecycle fix from PR #9761. On older versions, lifecycle hooks silently fail. The adapter falls back to DB snapshot reconstruction (less precise but preserves critical state).
Full documentation: docs/adapters/openclaw.md
</details>
<details> <summary><strong>Codex CLI</strong> — MCP + hooks</summary>
Prerequisites: Node.js >= 22.5 (or Bun), Codex CLI installed.
Install:
codex plugin marketplace add mksglu/context-mode
[features]
plugin_hooks = true
hooks = true
Feature flag note: Current Codex builds expose hooks under[features].hooks> (orcodex --enable hooks). Prefer[features].hooks;[features].codex_hooks> remains accepted as a legacy alias in current Codex builds. Bundled plugin hooks > additionally requireplugin_hooksuntil Codex enables plugin hooks by default.
ctx stats.ctx stats proves the plugin MCP server is installed and reachable; it does not prove hooks are trusted or running.
4. Review and trust the context-mode plugin hooks if Codex prompts for hook approval. Plugin hooks are only active after both feature flags are enabled and Codex has accepted the hook commands.
The Codex plugin manifest provides MCP via .codex-plugin/mcp.json, skills via skills/, and bundled hooks via .codex-plugin/hooks.json. No manual [mcp_servers.context-mode] block or $CODEX_HOME/hooks.json is needed when plugin_hooks is enabled and the plugin hooks are trusted.
Node/PATH note: context-mode still needs node visible to the Codex process. The plugin removes manual Codex config, but it does not vendor Node or inherit login-shell PATH fixes automatically.
Manual fallback for Codex builds without plugin_hooks:
npm install -g context-mode
~/.codex/config.toml: [features]
hooks = true
[mcp_servers.context-mode]
command = "context-mode"
$CODEX_HOME/hooks.json (or ~/.codex/hooks.json when CODEX_HOME is unset): {
"hooks": {
"PreToolUse": [{ "matcher": "local_shell|shell|shell_command|exec_command|Bash|Shell|apply_patch|Edit|Write|grep_files|ctx_execute|ctx_execute_file|ctx_batch_execute|ctx_fetch_and_index|ctx_search|ctx_index|mcp__", "hooks": [{ "type": "command", "command": "context-mode hook codex pretooluse" }] }],
"PostToolUse": [{ "hooks": [{ "type": "command", "command": "context-mode hook codex posttooluse" }] }],
"SessionStart": [{ "hooks": [{ "type": "command", "command": "context-mode hook codex sessionstart" }] }],
"PreCompact": [{ "hooks": [{ "type": "command", "command": "context-mode hook codex precompact" }] }],
"UserPromptSubmit": [{ "hooks": [{ "type": "command", "command": "context-mode hook codex userpromptsubmit" }] }],
"Stop": [{ "hooks": [{ "type": "command", "command": "context-mode hook codex stop" }] }]
}
}
PreToolUse enforces deny/block routing today and is prepared for input rewrites once Codex supports them. PostToolUse captures session events. PreCompact builds the resume snapshot before compaction. SessionStart restores state after compaction. UserPromptSubmit captures user decisions and corrections. Stop records turn-end state.
Note: Codex PreToolUse routing currently supports deny rules only (blocks dangerous commands). It still needs upstreamupdatedInputsupport before context-mode can rewrite tool input; track openai/codex#18491. Context injection (additionalContext) is not supported in Codex PreToolUse — it works via PostToolUse and SessionStart instead. This is handled automatically. > >PreCompactsupport is runtime-gated: it is present in Codex CLI 0.130.0, while the public Codex hooks docs may lag the shipped hook-event list. Older Codex builds that do not emitPreCompactwill not create pre-compaction snapshots.
CM_ROOT="$(npm root -g)/context-mode"
cp "$CM_ROOT/configs/codex/AGENTS.md" ./AGENTS.md
For global use: CM_ROOT="$(npm root -g)/context-mode"; cp "$CM_ROOT/configs/codex/AGENTS.md" ~/.codex/AGENTS.md. Global applies to all projects. If both exist, Codex CLI merges them.
Verify: Start a session and type ctx stats to verify MCP. To verify hook routing, confirm Codex lists/trusts the context-mode plugin hooks, then run a command that matches the routing rules.
Routing: MCP tools work after plugin install. Plugin hook routing is active only when hooks and plugin_hooks are enabled and Codex trusts the plugin hook commands. Manual hook routing is active when $CODEX_HOME/hooks.json or ~/.codex/hooks.json is configured. The AGENTS.md file provides routing instructions for model awareness.
</details>
<details> <summary><strong>Qwen Code</strong> — MCP + hooks (identical wire protocol to Claude Code)</summary>
Prerequisites: Node.js >= 22.5 (or Bun), Qwen Code installed (npm install -g @qwen-code/qwen-code).
npm install -g context-mode
~/.qwen/settings.json: {
"mcpServers": {
"context-mode": {
"command": "context-mode",
"args": []
}
}
}
~/.qwen/settings.json: {
"hooks": {
"PreToolUse": [{ "matcher": "run_shell_command|read_file|read_many_files|grep_search|web_fetch|agent|mcp__plugin_context-mode_context-mode__ctx_execute|mcp__plugin_context-mode_context-mode__ctx_execute_file|mcp__plugin_context-mode_context-mode__ctx_batch_execute|mcp__(?!.*context-mode)", "hooks": [{ "type": "command", "command": "context-mode hook qwen-code pretooluse" }] }],
"PostToolUse": [{ "matcher": "", "hooks": [{ "type": "command", "command": "context-mode hook qwen-code posttooluse" }] }],
"SessionStart": [{ "matcher": "", "hooks": [{ "type": "command", "command": "context-mode hook qwen-code sessionstart" }] }],
"PreCompact": [{ "matcher": "", "hooks": [{ "type": "command", "command": "context-mode hook qwen-code precompact" }] }],
"UserPromptSubmit": [{ "matcher": "", "hooks": [{ "type": "command", "command": "context-mode hook qwen-code userpromptsubmit" }] }]
}
}
cp node_modules/context-mode/configs/qwen-code/QWEN.md ./QWEN.md
For global use: cp node_modules/context-mode/configs/qwen-code/QWEN.md ~/.qwen/QWEN.md
Verify: Start a session and type ctx stats. Context-mode tools should appear and respond.
Note: Qwen Code uses the same hook wire protocol as Claude Code (JSON stdin/stdout, same event names). Auto-detected via MCP clientInfo (qwen-cli-mcp-client-*) or QWEN_PROJECT_DIR env var.
</details>
<details> <summary><strong>Antigravity</strong> — MCP-only, no hooks</summary>
Prerequisites: Node.js >= 22.5 (or Bun), Antigravity installed.
Install:
npm install -g context-mode
~/.gemini/antigravity/mcp_config.json: {
"mcpServers": {
"context-mode": {
"command": "context-mode"
}
}
}
cp node_modules/context-mode/configs/antigravity/GEMINI.md ./GEMINI.md
Verify: In an Antigravity session, type ctx stats. Context-mode tools should appear and respond.
Routing: Manual. The GEMINI.md file is the only enforcement method (~60% compliance). There is no programmatic interception. Auto-detected via MCP protocol handshake (clientInfo.name) — no manual platform configuration needed.
Full configs: configs/antigravity/mcp_config.json | configs/antigravity/GEMINI.md
</details>
<details> <summary><strong>Kiro</strong> — hooks with steering file</summary>
Prerequisites: Node.js >= 22.5 (or Bun), Kiro with MCP enabled (Settings > search "MCP").
Install:
npm install -g context-mode
.kiro/settings/mcp.json in your project (or ~/.kiro/settings/mcp.json for global): {
"mcpServers": {
"context-mode": {
"command": "context-mode"
}
}
}
.kiro/hooks/context-mode.json: {
"name": "context-mode",
"description": "Context-mode hooks for context window protection",
"hooks": {
"preToolUse": [
{ "matcher": "execute_bash|fs_read|@context-mode/ctx_execute|@context-mode/ctx_execute_file|@context-mode/ctx_batch_execute|@(?!context-mode/)", "command": "context-mode hook kiro pretooluse" }
],
"postToolUse": [
{ "matcher": "*", "command": "context-mode hook kiro posttooluse" }
]
}
}
agentSpawn (SessionStart) is not yet implemented, so the model needs a routing file at session start: cp node_modules/context-mode/configs/kiro/KIRO.md ./KIRO.md
Verify: Open the Kiro panel > MCP Servers tab and confirm "context-mode" shows a green status indicator. In chat, type ctx stats.
Routing: Hooks enforce routing programmatically via preToolUse/postToolUse. The KIRO.md file provides routing instructions since agentSpawn (SessionStart equivalent) is not yet wired. Tool names appear as @context-mode/ctx_batch_execute, @context-mode/ctx_search, etc. Auto-detected via MCP protocol handshake.
Full configs: configs/kiro/mcp.json | configs/kiro/agent.json | configs/kiro/KIRO.md
</details>
<details> <summary><strong>Zed</strong> — MCP-only, no hooks</summary>
Prerequisites: Node.js >= 22.5 (or Bun), Zed installed.
Install:
npm install -g context-mode
~/.config/zed/settings.json (Windows: %APPDATA%\Zed\settings.json): {
"context_servers": {
"context-mode": {
"command": {
"path": "context-mode"
}
}
}
}
Note: Zed uses "context_servers" and "command": { "path": "..." } syntax, not "mcpServers" or "command": "..." like other platforms.
cp node_modules/context-mode/configs/zed/AGENTS.md ./AGENTS.md
settings.json — Zed auto-restarts context servers on config change).Verify: Open the Agent Panel (Cmd+Shift+A), go to settings, and check the indicator dot next to "context-mode" — green means active. Type ctx stats in the agent chat.
Routing: Manual. The AGENTS.md file is the only enforcement method (~60% compliance). There is no programmatic interception. Tool names appear as mcp:context-mode:ctx_batch_execute, mcp:context-mode:ctx_search, etc. Auto-detected via MCP protocol handshake.
</details>
<details> <summary><strong>Pi Coding Agent</strong> — extension with full hook support</summary>
Prerequisites: Node.js >= 22.5 (or Bun), Pi Coding Agent installed.
Install:
npm install -g context-mode
pi install npm:context-mode
Alternative — add it manually to ~/.pi/agent/settings.json (or .pi/settings.json for project-level):
{
"packages": ["npm:context-mode"]
}
~/.pi/agent/mcp.json (or .pi/mcp.json for project-level): {
"mcpServers": {
"context-mode": {
"command": "context-mode"
}
}
}
Verify: In a Pi session, type ctx stats. Context-mode tools should appear and respond.
Routing: Automatic. The extension registers all key lifecycle events (tool_call, tool_result, session_start, session_before_compact), providing full session continuity and routing enforcement.
</details>
<details> <summary><strong>OMP (Oh My Pi)</strong> — plugin with full hook support</summary>
Prerequisites: Node.js >= 22.5 (or Bun), Oh My Pi installed.
Install — plugin path (recommended):
omp plugin install context-mode
omp plugin list
omp plugin doctor
Both should show context-mode as enabled.
Install — manual plugin path (if omp plugin install is unavailable):
OMP loads anything listed under ~/.omp/plugins/package.json dependencies whose own package.json carries an omp (or pi) field. New plugins default to enabled — the lock file at ~/.omp/plugins/omp-plugins.lock.json is only consulted when a plugin needs to be explicitly disabled (loader skips runtimeState && !runtimeState.enabled per extensibility/plugins/loader.ts:89-94). So the manual install is two commands:
cd ~/.omp/plugins
bun add context-mode # or: npm install context-mode
Then restart OMP. No lock file edit, no version pin — version is read from the freshly-installed package each time the loader runs (see loader.ts:87 manifest.version = pluginPkg.version).
Install — MCP-only path (no plugin):
npm install -g context-mode
~/.omp/agent/mcp.json (user scope) or <project>/.omp/mcp.json (project scope): {
"mcpServers": {
"context-mode": {
"command": "context-mode"
}
}
}
cp node_modules/context-mode/configs/omp/SYSTEM.md ~/.omp/agent/SYSTEM.md
Project-scoped alternative: cp ... .omp/SYSTEM.md. OMP also auto-discovers any AGENTS.md in the project tree.
Verify (any path): In an OMP session, type ctx stats. Context-mode tools should appear and respond.
Routing: Plugin path — programmatic enforcement via four pi.on(...) handlers (tool_call returns { block: true, reason } for curl/wget/inline-fetch per upstream hooks/types.ts:566, tool_result captures session events, session_start initializes the per-session DB row, session_before_compact persists a resume snapshot). ~98% compliance, parity with Claude Code hooks. MCP-only path — rule-based via SYSTEM.md, ~60% compliance. Auto-detected via PI_CODING_AGENT_DIR env var or presence of ~/.omp/. Storage roots at ~/.omp/context-mode/ so OMP and Pi installs never share session DBs, content indices, or stats files.
Full configs: configs/omp/mcp.json | configs/omp/SYSTEM.md | plugin source: src/adapters/omp/plugin.ts
</details>
<details> <summary><strong>Build Prerequisites</strong> <sup>(CentOS, RHEL, Alpine)</sup></summary>
Context Mode uses better-sqlite3 on Node.js, which ships prebuilt native binaries for most platforms. On glibc >= 2.31 systems (Ubuntu 20.04+, Debian 11+, Fedora 34+, macOS, Windows), npm install works without any build tools.
Linux + Node.js >= 22.5: Context Mode automatically uses the built-in node:sqlite module instead of better-sqlite3. This eliminates the native addon entirely, avoiding sporadic SIGSEGV crashes caused by V8's madvise(MADV_DONTNEED) corrupting the addon's .got.plt section on Linux. No configuration needed — detection is automatic. Linux + Node < 22.5 is unsupported (#564) — npm install will fail with remediation instructions.
Bun users: No native compilation needed. Context Mode automatically detects Bun and uses the built-in bun:sqlite module via a compatibility adapter. better-sqlite3 and all its build dependencies are skipped entirely.
On older glibc systems (CentOS 7/8, RHEL 8, Debian 10), prebuilt binaries don't load and better-sqlite3 automatically falls back to compiling from source via prebuild-install || node-gyp rebuild --release. This requires a C++20 compiler (GCC 10+), Make, and Python with setuptools.
Windows / missing binding self-heal: if better_sqlite3.node ends up missing after install (e.g. prebuild-install not on cmd.exe PATH, no MSVC toolchain), the postinstall script and the runtime hook automatically re-fetch the prebuild and repair the binding — no manual npm rebuild needed (#408).
CentOS 8 / RHEL 8 (glibc 2.28):
dnf install -y gcc-toolset-10-gcc gcc-toolset-10-gcc-c++ make python3 python3-setuptools
scl enable gcc-toolset-10 'npm install -g context-mode'
CentOS 7 / RHEL 7 (glibc 2.17):
yum install -y centos-release-scl
yum install -y devtoolset-10-gcc devtoolset-10-gcc-c++ make python3
pip3 install setuptools
scl enable devtoolset-10 'npm install -g context-mode'
Alpine Linux:
Alpine prebuilt binaries (musl) are available in better-sqlite3 v12.8.0+. With the ^12.6.2 dependency range, npm install resolves to the latest 12.x and works without build tools on Alpine. If you pin an older version:
apk add build-base python3 py3-setuptools
npm install -g context-mode
</details>
After Cursor lists context-mode in the Marketplace, install with one click. The plugin auto-registers MCP, hooks (preToolUse, postToolUse, sessionStart, stop, afterAgentResponse), rules, and skills. No manual config required.
Until then, use the local-folder path:
Windows (PowerShell) — Cursor does not follow Windows symlinks/junctions, so use robocopy:
git clone https://github.com/mksglu/context-mode.git
cd context-mode
robocopy . "$env:USERPROFILE\.cursor\plugins\local\context-mode" /MIR `
/XD node_modules .git build insight web tests scripts .vscode `
/XF *.log .gitignore *.bundle.mjs.map
macOS / Linux:
git clone https://github.com/mksglu/context-mode.git
ln -s "$PWD/context-mode" ~/.cursor/plugins/local/context-mode
Restart Cursor. The plugin appears in Settings → Plugins as "Context Mode (Local)". To pull updates, re-run the same robocopy / ln -s line.
Note: if.cursor/hooks.jsonalready contains context-mode entries from a priorOption Binstall,context-mode doctorwill warn about duplicate hook firings. Remove one configuration to keep events single-fire.
高星项目,创新的token优化方案。MCP生态集成度高,对编码代理性能提升明显,维护活跃,生产可用。
该工具使用 NOASSERTION 协议,商用场景请仔细阅读协议条款,必要时咨询法律意见。
AI Skill Hub 为第三方内容聚合平台,本页面信息基于公开数据整理,不对工具功能和质量作任何法律背书。
建议在沙箱或测试环境中充分验证后,再部署至生产环境,并做好必要的安全评估。
📄 NOASSERTION — 请查阅原始协议条款了解具体使用限制。
经综合评估,上下文窗口优化工具 在MCP工具赛道中表现稳健,质量优秀。如果你已有明确的使用需求,可以直接上手体验;如果还在评估阶段,建议对比同类工具后再做决策。
| 原始名称 | context-mode |
| 原始描述 | 开源MCP工具:Context window optimization for AI coding agents. Sandboxes tool output, 98% red。⭐14.5k · TypeScript |
| Topics | 上下文优化token节省编码代理MCP协议Claude集成 |
| GitHub | https://github.com/mksglu/context-mode |
| License | NOASSERTION |
| 语言 | TypeScript |
收录时间:2026-05-13 · 更新时间:2026-05-16 · License:NOASSERTION · AI Skill Hub 不对第三方内容的准确性作法律背书。
选择 Agent 类型,复制安装指令后粘贴到对应客户端