Context Mode: Default for All Large Output
MANDATORY RULE
Bash whitelist (safe to run directly):
- File mutations:
mkdir, mv, cp, rm, touch, chmod
- Git writes:
git add, git commit, git push, git checkout, git branch, git merge
- Navigation:
cd, pwd, which
- Process control:
kill, pkill
- Package management:
npm install, npm publish, pip install
- Simple output:
echo, printf
Everything else → ctx_execute or ctx_execute_file. Any command that reads, queries, fetches, lists, logs, tests, builds, diffs, inspects, or calls an external service. This includes ALL CLIs (gh, aws, kubectl, docker, terraform, wrangler, fly, heroku, gcloud, etc.) — there are thousands and we cannot list them all.
When uncertain, use context-mode. Every KB of unnecessary context reduces the quality and speed of the entire session.
Decision Tree
About to run a command / read a file / call an API?
│
├── Command is on the Bash whitelist (file mutations, git writes, navigation, echo)?
│ └── Use Bash
│
├── Output MIGHT be large or you're UNSURE?
│ └── Use context-mode ctx_execute or ctx_execute_file
│
├── Fetching web documentation or HTML page?
│ └── Use ctx_fetch_and_index → ctx_search
│
├── Using Playwright (navigate, snapshot, console, network)?
│ └── ALWAYS use filename parameter to save to file, then:
│ browser_snapshot(filename) → ctx_index(path) or ctx_execute_file(path)
│ browser_console_messages(filename) → ctx_execute_file(path)
│ browser_network_requests(filename) → ctx_execute_file(path)
│ ⚠ browser_navigate returns a snapshot automatically — ignore it,
│ use browser_snapshot(filename) for any inspection.
│ ⚠ Playwright MCP uses a SINGLE browser instance — NOT parallel-safe.
│ For parallel browser ops, use agent-browser via execute instead.
│
├── Using agent-browser (parallel-safe browser automation)?
│ └── Run via execute (shell) — each call gets its own subprocess:
│ execute("agent-browser open example.com && agent-browser snapshot -i -c")
│ ✓ Supports sessions for isolated browser instances
│ ✓ Safe for parallel subagent execution
│ ✓ Lightweight accessibility tree with ref-based interaction
│
├── Processing output from another MCP tool (Context7, GitHub API, etc.)?
│ ├── Output already in context from a previous tool call?
│ │ └── Use it directly. Do NOT re-index with ctx_index(content: ...).
│ ├── Need to search the output multiple times?
│ │ └── Save to file via ctx_execute, then ctx_index(path) → ctx_search
│ └── One-shot extraction?
│ └── Save to file via ctx_execute, then ctx_execute_file(path)
│
└── Reading a file to analyze/summarize (not edit)?
└── Use ctx_execute_file (file loads into FILE_CONTENT, not context)
When to Use Each Tool
| Situation |
Tool |
Example |
| Hit an API endpoint |
ctx_execute |
fetch('http://localhost:3000/api/orders') |
| Run CLI that returns data |
ctx_execute |
gh pr list, aws s3 ls, kubectl get pods |
| Run tests |
ctx_execute |
npm test, pytest, go test ./... |
| Git operations |
ctx_execute |
git log --oneline -50, git diff HEAD~5 |
| Docker/K8s inspection |
ctx_execute |
docker stats --no-stream, kubectl describe pod |
| Read a log file |
ctx_execute_file |
Parse access.log, error.log, build output |
| Read a data file |
ctx_execute_file |
Analyze CSV, JSON, YAML, XML |
| Read source code to analyze |
ctx_execute_file |
Count functions, find patterns, extract metrics |
| Fetch web docs |
ctx_fetch_and_index |
Index React/Next.js/Zod docs, then search |
| Playwright snapshot |
browser_snapshot(filename) → ctx_index(path) → ctx_search |
Save to file, index server-side, query |
| Playwright snapshot (one-shot) |
browser_snapshot(filename) → ctx_execute_file(path) |
Save to file, extract in sandbox |
| Playwright console/network |
browser_*(filename) → ctx_execute_file(path) |
Save to file, analyze in sandbox |
| MCP output (already in context) |
Use directly |
Don't re-index — it's already loaded |
| MCP output (need multi-query) |
ctx_execute to save → ctx_index(path) → ctx_search |
Save to file first, index server-side |
| Wipe indexed KB content |
ctx_purge(confirm: true) |
Permanently deletes all indexed content |
Automatic Triggers
Use context-mode for ANY of these, without being asked:
- API debugging: "hit this endpoint", "call the API", "check the response", "find the bug in the response"
- Log analysis: "check the logs", "what errors", "read access.log", "debug the 500s"
- Test runs: "run the tests", "check if tests pass", "test suite output"
- Git history: "show recent commits", "git log", "what changed", "diff between branches"
- Data inspection: "look at the CSV", "parse the JSON", "analyze the config"
- Infrastructure: "list containers", "check pods", "S3 buckets", "show running services"
- Dependency audit: "check dependencies", "outdated packages", "security audit"
- Build output: "build the project", "check for warnings", "compile errors"
- Code metrics: "count lines", "find TODOs", "function count", "analyze codebase"
- Web docs lookup: "look up the docs", "check the API reference", "find examples"
Language Selection
| Situation |
Language |
Why |
| HTTP/API calls, JSON |
javascript |
Native fetch, JSON.parse, async/await |
| Data analysis, CSV, stats |
python |
csv, statistics, collections, re |
| Shell commands with pipes |
shell |
grep, awk, jq, native tools |
| File pattern matching |
shell |
find, wc, sort, uniq |
Search Query Strategy
- BM25 uses OR semantics — results matching more terms rank higher automatically
- Use 2-4 specific technical terms per query
- Always use
source parameter when multiple docs are indexed to avoid cross-source contamination
- Partial match works:
source: "Node" matches "Node.js v22 CHANGELOG"
- Always use
queries array — batch ALL search questions in ONE call:
ctx_search(queries: ["transform pipe", "refine superRefine", "coerce codec"], source: "Zod")
- NEVER make multiple separate ctx_search() calls — put all queries in one array
External Documentation
- Always use
ctx_fetch_and_index for external docs — NEVER cat or ctx_execute with local paths for packages you don't own
- For GitHub-hosted projects, use the raw URL:
https://raw.githubusercontent.com/org/repo/main/CHANGELOG.md
- After indexing, use the
source parameter in search to scope results to that specific document
Critical Rules
- Always console.log/print your findings. stdout is all that enters context. No output = wasted call.
- Write analysis code, not just data dumps. Don't
console.log(JSON.stringify(data)) — analyze first, print findings.
- Be specific in output. Print bug details with IDs, line numbers, exact values — not just counts.
- For files you need to EDIT: Use the normal Read tool. context-mode is for analysis, not editing.
- For Bash whitelist commands only: Use Bash for file mutations, git writes, navigation, process control, package install, and echo. Everything else goes through context-mode.
- Never use
ctx_index(content: large_data). Use ctx_index(path: ...) to read files server-side. The content parameter sends data through context as a tool parameter — use it only for small inline text.
- Always use
filename parameter on Playwright tools (browser_snapshot, browser_console_messages, browser_network_requests). Without it, the full output enters context.
- Don't re-index data already in context. If an MCP tool returned data in a previous response, it's already loaded — use it directly or save to file first.
Sandboxed Data Workflow
This is the universal pattern for context preservation regardless of
the source tool (Playwright, GitHub API, AWS CLI, etc.).
Examples
Debug an API endpoint
const resp = await fetch('http://localhost:3000/api/orders');
const { orders } = await resp.json();
const bugs = [];
const negQty = orders.filter(o => o.quantity < 0);
if (negQty.length) bugs.push(`Negative qty: ${negQty.map(o => o.id).join(', ')}`);
const nullFields = orders.filter(o => !o.product || !o.customer);
if (nullFields.length) bugs.push(`Null fields: ${nullFields.map(o => o.id).join(', ')}`);
console.log(`${orders.length} orders, ${bugs.length} bugs found:`);
bugs.forEach(b => console.log(`- ${b}`));
Analyze test output
npm test 2>&1
echo "EXIT=$?"
Check GitHub PRs
gh pr list --json number,title,state,reviewDecision --jq '.[] | "\(.number) [\(.state)] \(.title) — \(.reviewDecision // "no review")"'
Read and analyze a large file
# FILE_CONTENT is pre-loaded by ctx_execute_file
import json
data = json.loads(FILE_CONTENT)
print(f"Records: {len(data)}")
# ... analyze and print findings
Browser & Playwright Integration
When a task involves Playwright snapshots, screenshots, or page inspection, ALWAYS route through file → sandbox.
Playwright browser_snapshot returns 10K–135K tokens of accessibility tree data. Calling it without filename dumps all of that into context. Passing the output to ctx_index(content: ...) sends it into context a SECOND time as a parameter. Both are wrong.
The key insight: browser_snapshot has a filename parameter that saves to file instead of returning to context. ctx_index has a path parameter that reads files server-side. ctx_execute_file processes files in a sandbox. None of these touch context.
Workflow A: Snapshot → File → Index → Search (multiple queries)
Step 1: browser_snapshot(filename: "/tmp/playwright-snapshot.md")
→ saves to file, returns ~50B confirmation (NOT 135K tokens)
Step 2: ctx_index(path: "/tmp/playwright-snapshot.md", source: "Playwright snapshot")
→ reads file SERVER-SIDE, indexes into FTS5, returns ~80B confirmation
Step 3: ctx_search(queries: ["login form email password"], source: "Playwright")
→ returns only matching chunks (~300B)
Total context: ~430B instead of 270K tokens. Real 99% savings.
Workflow B: Snapshot → File → Execute File (one-shot extraction)
Step 1: browser_snapshot(filename: "/tmp/playwright-snapshot.md")
→ saves to file, returns ~50B confirmation
Step 2: ctx_execute_file(path: "/tmp/playwright-snapshot.md", language: "javascript", code: "
const links = [...FILE_CONTENT.matchAll(/- link \"([^\"]+)\"/g)].map(m => m[1]);
const buttons = [...FILE_CONTENT.matchAll(/- button \"([^\"]+)\"/g)].map(m => m[1]);
const inputs = [...FILE_CONTENT.matchAll(/- textbox|- checkbox|- radio/g)];
console.log('Links:', links.length, '| Buttons:', buttons.length, '| Inputs:', inputs.length);
console.log('Navigation:', links.slice(0, 10).join(', '));
")
→ processes in sandbox, returns ~200B summary
Total context: ~250B instead of 135K tokens.
Workflow C: Console & Network (save to file if large)
browser_console_messages(level: "error", filename: "/tmp/console.md")
→ ctx_execute_file(path: "/tmp/console.md", ...) or ctx_index(path: "/tmp/console.md", ...)
browser_network_requests(includeStatic: false, filename: "/tmp/network.md")
→ ctx_execute_file(path: "/tmp/network.md", ...) or ctx_index(path: "/tmp/network.md", ...)
CRITICAL: Why filename + path is mandatory
| Approach |
Context cost |
Correct? |
browser_snapshot() → raw into context |
135K tokens |
NO |
browser_snapshot() → ctx_index(content: raw) |
270K tokens (doubled!) |
NO |
browser_snapshot(filename) → ctx_index(path) → ctx_search |
~430B |
YES |
browser_snapshot(filename) → ctx_execute_file(path) |
~250B |
YES |
Key Rule
ALWAYS use filename parameter when calling browser_snapshot, browser_console_messages, or browser_network_requests.
Then process via ctx_index(path: ...) or ctx_execute_file(path: ...) — never ctx_index(content: ...).
Data flow: Playwright → file → server-side read → context. Never: Playwright → context → ctx_index(content) → context again.
Subagent Usage
Subagents automatically receive context-mode tool routing via a PreToolUse hook. You do NOT need to manually add tool names to subagent prompts — the hook injects them. Just write natural task descriptions.
Anti-Patterns
- Using
curl http://api/endpoint via Bash → 50KB floods context. Use ctx_execute with fetch instead.
- Using
cat large-file.json via Bash → entire file in context. Use ctx_execute_file instead.
- Using
gh pr list via Bash → raw JSON in context. Use ctx_execute with --jq filter instead.
- Piping Bash output through
| head -20 → you lose the rest. Use ctx_execute to analyze ALL data and print summary.
- Narrowing
ctx_execute output upstream of capture → ctx_execute captures, ctx_search filters; merging the layers drops data that the index never sees. See references/anti-patterns.md §8.
- Running
npm test via Bash → full test output in context. Use ctx_execute to capture and summarize.
- Calling
browser_snapshot() WITHOUT filename parameter → 135K tokens flood context. Always use browser_snapshot(filename: "/tmp/snap.md").
- Calling
browser_console_messages() or browser_network_requests() WITHOUT filename → entire output floods context. Always use the filename parameter.
- Passing ANY large data to
ctx_index(content: ...) → data enters context as a parameter. Always use ctx_index(path: ...) to read server-side. The content parameter should only be used for small inline text you're composing yourself.
- Calling an MCP tool (Context7
query-docs, GitHub API, etc.) then passing the response to ctx_index(content: response) → doubles context usage. The response is already in context — use it directly or save to file first.
- Ignoring
browser_navigate auto-snapshot → navigation response includes a full page snapshot. Don't rely on it for inspection — call browser_snapshot(filename) separately.
- Expecting
ctx_stats to reset or wipe anything → ctx_stats is read-only (shows stats only). Use ctx_purge(confirm: true) to permanently delete all indexed content.
Reference Files
1---2name: context-mode3description: Use context-mode tools (ctx_execute, ctx_execute_file) instead of Bash/cat when processing large outputs. Triggers: "analyze logs", "summarize output", "process data", "parse JSON", "filter results", "extract errors", "check build output", "analyze dependencies", "process API response", "large file analysis", "page snapshot", "browser snapshot", "DOM structure", "inspect page", "accessibility tree", "Playwright snapshot", "run tests", "test output", "coverage report", "git log", "recent commits", "diff between branches", "list containers", "pod status", "disk usage", "fetch docs", "API reference", "index documentation", "call API", "check response", "query results", "find TODOs", "count lines", "codebase statistics", "security audit", "outdated packages", "dependency tree", "cloud resources", "CI/CD output". Also triggers on ANY MCP tool output that may exceed 20 lines. Subagent routing is handled automatically via PreToolUse hook.4---5
6# Context Mode: Default for All Large Output
7
8## MANDATORY RULE
9
10<context_mode_logic>
11 <mandatory_rule>
12 Default to context-mode for ALL commands. Only use Bash for guaranteed-small-output operations.
13 </mandatory_rule>
14</context_mode_logic>
15
16Bash whitelist (safe to run directly):
17- **File mutations**: `mkdir`, `mv`, `cp`, `rm`, `touch`, `chmod`
18- **Git writes**: `git add`, `git commit`, `git push`, `git checkout`, `git branch`, `git merge`
19- **Navigation**: `cd`, `pwd`, `which`
20- **Process control**: `kill`, `pkill`
21- **Package management**: `npm install`, `npm publish`, `pip install`
22- **Simple output**: `echo`, `printf`
23
24**Everything else → `ctx_execute` or `ctx_execute_file`.** Any command that reads, queries, fetches, lists, logs, tests, builds, diffs, inspects, or calls an external service. This includes ALL CLIs (gh, aws, kubectl, docker, terraform, wrangler, fly, heroku, gcloud, etc.) — there are thousands and we cannot list them all.
25
26**When uncertain, use context-mode.** Every KB of unnecessary context reduces the quality and speed of the entire session.
27
28## Decision Tree
29
30```
31About to run a command / read a file / call an API?
32│
33├── Command is on the Bash whitelist (file mutations, git writes, navigation, echo)?
34│ └── Use Bash
35│
36├── Output MIGHT be large or you're UNSURE?
37│ └── Use context-mode ctx_execute or ctx_execute_file
38│
39├── Fetching web documentation or HTML page?
40│ └── Use ctx_fetch_and_index → ctx_search
41│
42├── Using Playwright (navigate, snapshot, console, network)?
43│ └── ALWAYS use filename parameter to save to file, then:
44│ browser_snapshot(filename) → ctx_index(path) or ctx_execute_file(path)
45│ browser_console_messages(filename) → ctx_execute_file(path)
46│ browser_network_requests(filename) → ctx_execute_file(path)
47│ ⚠ browser_navigate returns a snapshot automatically — ignore it,
48│ use browser_snapshot(filename) for any inspection.
49│ ⚠ Playwright MCP uses a SINGLE browser instance — NOT parallel-safe.
50│ For parallel browser ops, use agent-browser via execute instead.
51│
52├── Using agent-browser (parallel-safe browser automation)?
53│ └── Run via execute (shell) — each call gets its own subprocess:
54│ execute("agent-browser open example.com && agent-browser snapshot -i -c")
55│ ✓ Supports sessions for isolated browser instances
56│ ✓ Safe for parallel subagent execution
57│ ✓ Lightweight accessibility tree with ref-based interaction
58│
59├── Processing output from another MCP tool (Context7, GitHub API, etc.)?
60│ ├── Output already in context from a previous tool call?
61│ │ └── Use it directly. Do NOT re-index with ctx_index(content: ...).
62│ ├── Need to search the output multiple times?
63│ │ └── Save to file via ctx_execute, then ctx_index(path) → ctx_search
64│ └── One-shot extraction?
65│ └── Save to file via ctx_execute, then ctx_execute_file(path)
66│
67└── Reading a file to analyze/summarize (not edit)?
68 └── Use ctx_execute_file (file loads into FILE_CONTENT, not context)
69```
70
71## When to Use Each Tool
72
73| Situation | Tool | Example |
74|-----------|------|---------|
75| Hit an API endpoint | `ctx_execute` | `fetch('http://localhost:3000/api/orders')` |
76| Run CLI that returns data | `ctx_execute` | `gh pr list`, `aws s3 ls`, `kubectl get pods` |
77| Run tests | `ctx_execute` | `npm test`, `pytest`, `go test ./...` |
78| Git operations | `ctx_execute` | `git log --oneline -50`, `git diff HEAD~5` |
79| Docker/K8s inspection | `ctx_execute` | `docker stats --no-stream`, `kubectl describe pod` |
80| Read a log file | `ctx_execute_file` | Parse access.log, error.log, build output |
81| Read a data file | `ctx_execute_file` | Analyze CSV, JSON, YAML, XML |
82| Read source code to analyze | `ctx_execute_file` | Count functions, find patterns, extract metrics |
83| Fetch web docs | `ctx_fetch_and_index` | Index React/Next.js/Zod docs, then search |
84| Playwright snapshot | `browser_snapshot(filename)` → `ctx_index(path)` → `ctx_search` | Save to file, index server-side, query |
85| Playwright snapshot (one-shot) | `browser_snapshot(filename)` → `ctx_execute_file(path)` | Save to file, extract in sandbox |
86| Playwright console/network | `browser_*(filename)` → `ctx_execute_file(path)` | Save to file, analyze in sandbox |
87| MCP output (already in context) | Use directly | Don't re-index — it's already loaded |
88| MCP output (need multi-query) | `ctx_execute` to save → `ctx_index(path)` → `ctx_search` | Save to file first, index server-side |
89| Wipe indexed KB content | `ctx_purge(confirm: true)` | Permanently deletes all indexed content |
90
91## Automatic Triggers
92
93Use context-mode for ANY of these, without being asked:
94
95- **API debugging**: "hit this endpoint", "call the API", "check the response", "find the bug in the response"
96- **Log analysis**: "check the logs", "what errors", "read access.log", "debug the 500s"
97- **Test runs**: "run the tests", "check if tests pass", "test suite output"
98- **Git history**: "show recent commits", "git log", "what changed", "diff between branches"
99- **Data inspection**: "look at the CSV", "parse the JSON", "analyze the config"
100- **Infrastructure**: "list containers", "check pods", "S3 buckets", "show running services"
101- **Dependency audit**: "check dependencies", "outdated packages", "security audit"
102- **Build output**: "build the project", "check for warnings", "compile errors"
103- **Code metrics**: "count lines", "find TODOs", "function count", "analyze codebase"
104- **Web docs lookup**: "look up the docs", "check the API reference", "find examples"
105
106## Language Selection
107
108| Situation | Language | Why |
109|-----------|----------|-----|
110| HTTP/API calls, JSON | `javascript` | Native fetch, JSON.parse, async/await |
111| Data analysis, CSV, stats | `python` | csv, statistics, collections, re |
112| Shell commands with pipes | `shell` | grep, awk, jq, native tools |
113| File pattern matching | `shell` | find, wc, sort, uniq |
114
115## Search Query Strategy
116
117- BM25 uses **OR semantics** — results matching more terms rank higher automatically
118- Use 2-4 specific technical terms per query
119- **Always use `source` parameter** when multiple docs are indexed to avoid cross-source contamination
120 - Partial match works: `source: "Node"` matches `"Node.js v22 CHANGELOG"`
121- **Always use `queries` array** — batch ALL search questions in ONE call:
122 - `ctx_search(queries: ["transform pipe", "refine superRefine", "coerce codec"], source: "Zod")`
123 - NEVER make multiple separate ctx_search() calls — put all queries in one array
124
125## External Documentation
126
127- **Always use `ctx_fetch_and_index`** for external docs — NEVER `cat` or `ctx_execute` with local paths for packages you don't own
128- For GitHub-hosted projects, use the raw URL: `https://raw.githubusercontent.com/org/repo/main/CHANGELOG.md`
129- After indexing, use the `source` parameter in search to scope results to that specific document
130
131## Critical Rules
132
1331. **Always console.log/print your findings.** stdout is all that enters context. No output = wasted call.
1342. **Write analysis code, not just data dumps.** Don't `console.log(JSON.stringify(data))` — analyze first, print findings.
1353. **Be specific in output.** Print bug details with IDs, line numbers, exact values — not just counts.
1364. **For files you need to EDIT**: Use the normal Read tool. context-mode is for analysis, not editing.
1375. **For Bash whitelist commands only**: Use Bash for file mutations, git writes, navigation, process control, package install, and echo. Everything else goes through context-mode.
1386. **Never use `ctx_index(content: large_data)`.** Use `ctx_index(path: ...)` to read files server-side. The `content` parameter sends data through context as a tool parameter — use it only for small inline text.
1397. **Always use `filename` parameter** on Playwright tools (`browser_snapshot`, `browser_console_messages`, `browser_network_requests`). Without it, the full output enters context.
1408. **Don't re-index data already in context.** If an MCP tool returned data in a previous response, it's already loaded — use it directly or save to file first.
141
142## Sandboxed Data Workflow
143
144<sandboxed_data_workflow>
145 <critical_rule>
146 When using tools that support saving to a file: ALWAYS use the 'filename' parameter.
147 NEVER return large raw datasets directly to context.
148 </critical_rule>
149 <workflow>
150 LargeDataTool(filename: "path") → mcp__context-mode__ctx_index(path: "path") → ctx_search()
151 </workflow>
152</sandboxed_data_workflow>
153
154This is the universal pattern for context preservation regardless of
155the source tool (Playwright, GitHub API, AWS CLI, etc.).
156
157## Examples
158
159### Debug an API endpoint
160```javascript
161const resp = await fetch('http://localhost:3000/api/orders');
162const { orders } = await resp.json();
163
164const bugs = [];
165const negQty = orders.filter(o => o.quantity < 0);
166if (negQty.length) bugs.push(`Negative qty: ${negQty.map(o => o.id).join(', ')}`);
167
168const nullFields = orders.filter(o => !o.product || !o.customer);
169if (nullFields.length) bugs.push(`Null fields: ${nullFields.map(o => o.id).join(', ')}`);
170
171console.log(`${orders.length} orders, ${bugs.length} bugs found:`);
172bugs.forEach(b => console.log(`- ${b}`));
173```
174
175### Analyze test output
176```shell
177npm test 2>&1
178echo "EXIT=$?"
179```
180
181### Check GitHub PRs
182```shell
183gh pr list --json number,title,state,reviewDecision --jq '.[] | "\(.number) [\(.state)] \(.title) — \(.reviewDecision // "no review")"'
184```
185
186### Read and analyze a large file
187```python
188# FILE_CONTENT is pre-loaded by ctx_execute_file
189import json
190data = json.loads(FILE_CONTENT)
191print(f"Records: {len(data)}")
192# ... analyze and print findings
193```
194
195## Browser & Playwright Integration
196
197**When a task involves Playwright snapshots, screenshots, or page inspection, ALWAYS route through file → sandbox.**
198
199Playwright `browser_snapshot` returns 10K–135K tokens of accessibility tree data. Calling it without `filename` dumps all of that into context. Passing the output to `ctx_index(content: ...)` sends it into context a SECOND time as a parameter. Both are wrong.
200
201**The key insight**: `browser_snapshot` has a `filename` parameter that saves to file instead of returning to context. `ctx_index` has a `path` parameter that reads files server-side. `ctx_execute_file` processes files in a sandbox. **None of these touch context.**
202
203### Workflow A: Snapshot → File → Index → Search (multiple queries)
204
205```
206Step 1: browser_snapshot(filename: "/tmp/playwright-snapshot.md")
207 → saves to file, returns ~50B confirmation (NOT 135K tokens)
208
209Step 2: ctx_index(path: "/tmp/playwright-snapshot.md", source: "Playwright snapshot")
210 → reads file SERVER-SIDE, indexes into FTS5, returns ~80B confirmation
211
212Step 3: ctx_search(queries: ["login form email password"], source: "Playwright")
213 → returns only matching chunks (~300B)
214```
215
216**Total context: ~430B** instead of 270K tokens. Real 99% savings.
217
218### Workflow B: Snapshot → File → Execute File (one-shot extraction)
219
220```
221Step 1: browser_snapshot(filename: "/tmp/playwright-snapshot.md")
222 → saves to file, returns ~50B confirmation
223
224Step 2: ctx_execute_file(path: "/tmp/playwright-snapshot.md", language: "javascript", code: "
225 const links = [...FILE_CONTENT.matchAll(/- link \"([^\"]+)\"/g)].map(m => m[1]);
226 const buttons = [...FILE_CONTENT.matchAll(/- button \"([^\"]+)\"/g)].map(m => m[1]);
227 const inputs = [...FILE_CONTENT.matchAll(/- textbox|- checkbox|- radio/g)];
228 console.log('Links:', links.length, '| Buttons:', buttons.length, '| Inputs:', inputs.length);
229 console.log('Navigation:', links.slice(0, 10).join(', '));
230 ")
231 → processes in sandbox, returns ~200B summary
232```
233
234**Total context: ~250B** instead of 135K tokens.
235
236### Workflow C: Console & Network (save to file if large)
237
238```
239browser_console_messages(level: "error", filename: "/tmp/console.md")
240→ ctx_execute_file(path: "/tmp/console.md", ...) or ctx_index(path: "/tmp/console.md", ...)
241
242browser_network_requests(includeStatic: false, filename: "/tmp/network.md")
243→ ctx_execute_file(path: "/tmp/network.md", ...) or ctx_index(path: "/tmp/network.md", ...)
244```
245
246### CRITICAL: Why `filename` + `path` is mandatory
247
248| Approach | Context cost | Correct? |
249|----------|-------------|----------|
250| `browser_snapshot()` → raw into context | **135K tokens** | NO |
251| `browser_snapshot()` → `ctx_index(content: raw)` | **270K tokens** (doubled!) | NO |
252| `browser_snapshot(filename)` → `ctx_index(path)` → `ctx_search` | **~430B** | YES |
253| `browser_snapshot(filename)` → `ctx_execute_file(path)` | **~250B** | YES |
254
255### Key Rule
256
257> **ALWAYS use `filename` parameter when calling `browser_snapshot`, `browser_console_messages`, or `browser_network_requests`.**
258> Then process via `ctx_index(path: ...)` or `ctx_execute_file(path: ...)` — never `ctx_index(content: ...)`.
259>
260> Data flow: **Playwright → file → server-side read → context**. Never: **Playwright → context → ctx_index(content) → context again**.
261
262## Subagent Usage
263
264Subagents automatically receive context-mode tool routing via a PreToolUse hook. You do NOT need to manually add tool names to subagent prompts — the hook injects them. Just write natural task descriptions.
265
266## Anti-Patterns
267
268- Using `curl http://api/endpoint` via Bash → 50KB floods context. Use `ctx_execute` with fetch instead.
269- Using `cat large-file.json` via Bash → entire file in context. Use `ctx_execute_file` instead.
270- Using `gh pr list` via Bash → raw JSON in context. Use `ctx_execute` with `--jq` filter instead.
271- Piping Bash output through `| head -20` → you lose the rest. Use `ctx_execute` to analyze ALL data and print summary.
272- Narrowing `ctx_execute` output upstream of capture → `ctx_execute` captures, `ctx_search` filters; merging the layers drops data that the index never sees. See `references/anti-patterns.md` §8.
273- Running `npm test` via Bash → full test output in context. Use `ctx_execute` to capture and summarize.
274- Calling `browser_snapshot()` WITHOUT `filename` parameter → 135K tokens flood context. **Always** use `browser_snapshot(filename: "/tmp/snap.md")`.
275- Calling `browser_console_messages()` or `browser_network_requests()` WITHOUT `filename` → entire output floods context. **Always** use the `filename` parameter.
276- Passing ANY large data to `ctx_index(content: ...)` → data enters context as a parameter. **Always** use `ctx_index(path: ...)` to read server-side. The `content` parameter should only be used for small inline text you're composing yourself.
277- Calling an MCP tool (Context7 `query-docs`, GitHub API, etc.) then passing the response to `ctx_index(content: response)` → **doubles** context usage. The response is already in context — use it directly or save to file first.
278- Ignoring `browser_navigate` auto-snapshot → navigation response includes a full page snapshot. Don't rely on it for inspection — call `browser_snapshot(filename)` separately.
279- Expecting `ctx_stats` to reset or wipe anything → `ctx_stats` is read-only (shows stats only). Use `ctx_purge(confirm: true)` to permanently delete all indexed content.
280
281## Reference Files
282
283- [JavaScript/TypeScript Patterns](./references/patterns-javascript.md)
284- [Python Patterns](./references/patterns-python.md)
285- [Shell Patterns](./references/patterns-shell.md)
286- [Anti-Patterns & Common Mistakes](./references/anti-patterns.md)