close-session

Close a named session. A background session's command is signalled on the host (INT, then TERM, then KILL) before its channel is dropped; an interactive session's shell is ended. The response says so if the command could not be signalled or had not stopped in time.

Session name to close

Profile name

list-connections

List all configured SSH profiles and their connection status. Use this to discover available hosts before running commands.

list-sessions

List active sessions for a given SSH profile.

Profile name (uses default if omitted)

open-session

Open a named session on a remote host. Use type="interactive" for stateful shell (CWD/env persists between commands) or type="background" for long-running processes.

Command for background sessions

Session name (alphanumeric, dash, underscore, max 64 chars)

Profile name (uses default if omitted)

Session type

privileged-command

Execute a command with sudo elevation. Goes through the approval gate; approvalPolicy on the profile decides whether that is a prompt, an automatic allow, or a refusal. The sudo password is piped via stdin (never visible in process list).

Command to execute with sudo

Profile name

read-command

Execute a READ-ONLY command from an allowlist (ls, cat, grep, find, stat, df, etc.). This tool does NOT modify the system. Prefer this tool for all read operations.

Read-only shell command (must be in the allowlist)

Profile name

read-session-output

Read recent output from a background session (e.g., tail -f logs).

Number of recent lines to read

Background session name

Profile name

run-command

Execute an arbitrary shell command on the remote server. May modify the system. Commands classified destructive or privileged go through the approval gate; approvalPolicy on the profile decides whether that is a prompt, an automatic allow, or a refusal.

Shell command to execute

Profile name

Run in an existing interactive session (stateful)

Allocate a pseudo-terminal

sftp-download

Download a file from the remote server via SFTP.

Profile name

Remote file path to download

sftp-upload

Upload a file to the remote server via SFTP (secure file transfer, not shell-based).

File content to upload

Profile name

Remote file path

signal-process

Send a signal (INT, TERM, KILL) to a remote process by PID.

Process ID to signal (positive integer)

Profile name

Signal to send


Read a webpage's full content as clean markdown. Use after web_search_exa when highlights are insufficient or to read any URL.

Best for: Extracting full content from known URLs. Batch multiple URLs in one call.
Returns: Clean text content and metadata from the page(s).

Maximum characters to extract per page (default: 3000)

URLs to read. Batch multiple URLs in one call.

Search the web for any topic and get clean, ready-to-use content.

      Best for: Finding current information, news, facts, people, companies, or answering questions about any topic.
      Returns: Clean text content from top search results.

      Query tips:
      describe the ideal page, not keywords. "blog post comparing React and Vue performance" not "React vs Vue".
      Use category:people / category:company to search through Linkedin profiles / companies respectively.
      If highlights are insufficient, follow up with web_fetch_exa on the best URLs.

Number of search results to return (default: 10).

Natural language search query. Should be a semantically rich description of the ideal page, not just keywords. Optionally include category:<type> (company, people) to focus results — e.g. 'category:people John Doe software engineer'.


Crawl a website starting from a URL. Extracts content from pages with configurable depth and breadth.

Whether to return external links in the final response

Advanced extraction retrieves more data, including tables and embedded content, with higher success but may increase latency

The format of the extracted web page content. markdown returns content in markdown format. text returns plain text and may increase latency.

Whether to include the favicon URL for each result

Natural language instructions for the crawler. Instructions specify which types of pages the crawler should return.

Total number of links the crawler will process before stopping

Max number of links to follow per level of the tree (i.e., per page)

Max depth of the crawl. Defines how far from the base URL the crawler can explore.

Regex patterns to restrict crawling to specific domains or subdomains (e.g., ^docs\.example\.com$)

Regex patterns to select only URLs with specific path patterns (e.g., /docs/.*, /api/v1.*)

The root URL to begin the crawl

Extract content from URLs. Returns raw page content in markdown or text format.

Use 'advanced' for LinkedIn, protected sites, or tables/embedded content

Output format

Include favicon URLs

Include images from pages

Query to rerank content chunks by relevance

List of URLs to extract content from

Map a website's structure. Returns a list of URLs found starting from the base URL.

Natural language instructions for the crawler

Max depth of the mapping. Defines how far from the base URL the crawler can explore

The root URL to begin the mapping

Perform comprehensive research on a given topic or question. Use this tool when you need to gather information from multiple sources to answer a question or complete a task. Returns a detailed response based on the research findings. Rate limit: 20 requests per minute.

A comprehensive description of the research task

Defines the degree of depth of the research. 'mini' is good for narrow tasks with few subtopics. 'pro' is good for broad tasks with many subtopics. 'auto' automatically selects the best model.

Search the web for current information on any topic. Use for news, facts, or data beyond your knowledge cutoff. Returns snippets and source URLs.

Boost search results from a specific country. Must be a full country name (e.g., 'United States', 'Japan', 'Germany'). ISO country codes (e.g., 'us', 'jp') are not supported. Available only if topic is general. See https://docs.tavily.com/documentation/api-reference/search for the full list of supported countries.

Will return all results before the specified end date. Required to be written in the format YYYY-MM-DD

Only return results containing the exact phrase(s) in quotes in your query

List of domains to specifically exclude, if the user asks to exclude a domain set this to the domain of the site

A list of domains to specifically include in the search results, if the user asks to search on specific sites set this to the domain of the site

Include a list of query-related images and their descriptions in the response

Include a list of query-related images in the response

Include the cleaned and parsed HTML content of each search result

The maximum number of search results to return

Search query

The depth of the search. 'basic' for generic results, 'advanced' for more thorough search, 'fast' for optimized low latency with high relevance, 'ultra-fast' for prioritizing latency above all else

Will return all results after the specified start date. Required to be written in the format YYYY-MM-DD.

The time range back from the current date to include in the search results

The category of the search. This will determine which of our agents will be used for the search


Discovers capabilities from all reachable configured SearXNG instances via /config, including categories.common/available, engines.common/available, defaults, locales, and plugins.

Filter categories and engines to a single category name.

Include disabled engine names when includeEngines is true.

Include enabled engine names in the response.

Bypass the process cache and fetch fresh /config data.

Returns autocomplete suggestions from the configured SearXNG instance. Use this to refine vague or partial queries before searching.

Language code for suggestions (e.g., 'en', 'fr', 'de') or 'all'. Default: all.

Partial or complete query to autocomplete.

Searches the web using SearXNG and returns a list of results, each with a title, URL, and content snippet. CRITICAL: The required parameter name is exactly `query` (not `prompt`, `q`, or any other name). Calls an external SearXNG instance; availability depends on the `SEARXNG_URL` configuration. Use `pageno` to paginate results; combine `time_range` and `language` to narrow scope. When `engines` and `time_range` are both provided, every selected engine must explicitly advertise time-range support via SearXNG /config; otherwise the request is rejected before search. To read the full text of a result URL, follow up with `web_url_read`.

Comma-separated SearXNG categories. Live /config capabilities are aggregated across reachable instances; prefer searxng_instance_info categories.common for consistent multi-instance results. Values in categories.available are best-effort and may only be honored by some instances. Known values are normalized case-insensitively; unknown values are forwarded trimmed so SearXNG can ignore or honor them. If /config is unavailable, values are forwarded as-is with a warning. If omitted, each instance uses its server-side default.

Comma-separated SearXNG engine names to query (e.g. 'google,bing,ddg'). Live /config capabilities are aggregated across reachable instances; prefer searxng_instance_info engines.common.enabled for consistent multi-instance results. Values in engines.available.enabled are best-effort and may only be honored by some instances. Known values are normalized case-insensitively; unknown values are forwarded trimmed so SearXNG can ignore or honor them. If /config is unavailable, values are forwarded as-is with a warning. If omitted, each instance uses its server-side default.

Language code for search results (e.g., 'en', 'fr', 'de'). Default is instance-dependent.

Minimum relevance score threshold from 0.0 to 1.0. Results below this score are filtered out.

Maximum number of results to return (1-20). Operator cap SEARXNG_MAX_RESULTS applies as a ceiling.

Search page number (starts at 1)

The search query string. This is the required parameter name — use exactly `query`, not `prompt` or `q`.

Response format: formatted text for agents or raw JSON for programmatic clients. If omitted, SEARXNG_DEFAULT_RESPONSE_FORMAT applies; if unset or invalid, text is used. An explicit response_format always takes precedence.

Result detail: full preserves SearXNG metadata and search signals; compact returns only title, URL, and content-snippet fields for each result (JSON keys: title, url, content). If omitted, full is used.

Safe search filter level (0: None, 1: Moderate, 2: Strict)

Time range of search (day, week, month, year). With explicit engines, all selected engines must confirm time_range_support=true via /config.

Fetches a URL and returns readable content as markdown. Content-type aware: HTML is converted to markdown; JSON is pretty-printed; plain text, YAML, TOML, and XML are returned as fenced readable text. PDF text extraction is supported with bounded input, output, page count, time, concurrency, and memory; OCR is not supported. Binary, media, archive, and octet-stream downloads other than PDFs are intentionally rejected instead of being returned as raw bytes. When the operator configures browser solvers, mcp-searxng attempts FlareSolverr first and then Byparr only after a busy or transient-unavailable acquisition; cache hits bypass acquisition and a final busy or unavailable provider uses one uncached direct-fetch fallback. Three modes: (1) Full content — omit filtering params; use `startChar`/`maxLength` to paginate large pages. (2) Section extraction — set `section` to return content under a specific heading. (3) Headings only — set `readHeadings: true` to list all headings (mutually exclusive with other filtering params). Returns an error string if the URL is unreachable or content cannot be extracted. Use after `searxng_web_search` to read the full content of individual result URLs.

Maximum number of characters to return

Return specific paragraph ranges (e.g., '1-5', '3', '10-')

Return only a list of headings instead of full content

Extract content under a specific heading (searches for heading text)

Starting character position for content extraction (default: 0)

URL


Run multiple commands in ONE call. Every command's output is auto-indexed into the knowledge base; if you also pass `queries`, the matching sections come back in the same round trip so a follow-up search call is not needed.

Concurrency parallelizes the FETCH phase (run-the-commands). The DERIVATION phase — turning raw output into an answer — still belongs in code: add a processing command that consumes the indexed output and prints only the answer, so the raw bytes never enter your conversation (Think-in-Code, same principle as the sandbox tool).

WHEN:
  - You have 3+ related commands you would otherwise run sequentially (multi-issue lookups, git log + git diff + git blame, multi-file reads, multi-region cloud queries)
  - You want to gather AND query in one round trip — pass `queries` so the matching sections come back inline
  - You want to parallelize I/O-bound work — pass `concurrency` 2-8 (network calls, gh CLI, cloud APIs, multi-repo git reads)
  - The combined output is large enough that piping it through ctx_search later would itself be expensive — let auto-index + inline queries do both in one shot

WHEN NOT:
  - Single command with no follow-up query — run it in the sandbox tool directly
  - CPU-bound or stateful commands — keep concurrency at 1 (npm test, build, lint, port-binding servers, lock-file holders, anything that races on the same resource)

RETURNS:
  Auto-indexed section list per command label, plus top matches per query (when `queries` is passed). Raw output is NOT echoed in full — only the matched windows. Concurrency>1 switches each command to its own per-command timeout (no shared budget); concurrency=1 preserves the legacy shared-budget cascading-skip-on-timeout path. Use 4-8 for I/O-bound batches; keep at 1 for CPU work or shared-state commands; lower the value when target hosts enforce per-IP rate limits.

EXAMPLE: ctx_batch_execute(
  commands: [
    {label: "issue 1", command: "gh issue view 1"},
    {label: "issue 2", command: "gh issue view 2"},
    {label: "summarize", command: "echo done"}
  ],
  queries: ["root cause", "proposed fix"],
  concurrency: 2
)

Commands to execute as a batch. Output is labeled with the section header. Default order is sequential; pass concurrency>1 to run in parallel (output stays in input order).

Shell command to execute

Section header for this command's output (e.g., 'README', 'Package.json', 'Source Tree')

Max commands to run in parallel (1-8, default: 1). Use 4-8 for I/O-bound batches (network, gh, curl, multi-repo git reads). Keep at 1 for CPU-bound (npm test, build, lint) or stateful commands (ports, locks). >1 switches to per-command timeouts (no shared budget) and individual `(timed out)` blocks instead of cascading skip.

Optional working directory for all shell commands in this batch.

Search queries to extract information from indexed output. Use 5-8 comprehensive queries. Each returns top 5 matching sections with full content. This is your ONLY chance — put ALL your questions here. No follow-up calls needed.

Scope for `queries` (default: `batch`). `batch` searches ONLY the chunks produced by this batch's commands — useful when you want answers about the just-fetched output. `global` searches the entire persistent index (same scope as ctx_search) — useful when you want the batch commands to enrich context and the queries to also surface related prior knowledge in one round trip.

Max execution time in ms. When omitted, no server-side timer fires — the MCP host's RPC timeout governs. With concurrency=1, the value (when set) is a shared budget across commands; with concurrency>1, it is applied per-command.

Batch Execute & Search

Diagnose context-mode installation. Runs all checks server-side and returns a plain-text status report with [OK]/[FAIL]/[WARN] prefixes (renderer-safe across MCP clients). No CLI execution needed.

Run Diagnostics

Run code in a sandboxed subprocess. Languages: javascript, shell, python, go, rust, perl.

Think-in-Code — the core philosophy: the bytes your code processes never enter your conversation memory; only what you console.log() does. Reading a 700 KB log directly means 700 KB of your remaining reasoning capacity gets spent on raw bytes. Running code over that same log in this sandbox and printing a 3 KB summary leaves you with 697 KB of capacity for the actual work.

Concrete shape — analyze 47 source files without reading any of them:
  ctx_execute(language: "javascript", code: `
    const fs = require('fs');
    const files = fs.readdirSync('src').filter(f => f.endsWith('.ts'));
    files.forEach(f => {
      const lines = fs.readFileSync('src/'+f,'utf8').split('\\n').length;
      console.log(f + ': ' + lines + ' lines');
    });
  `)
  // 47 files analyzed, 15,314 LoC summarized — output ~3.6 KB instead of 47 Read() calls = ~700 KB.

WHEN:
  - You intend to derive an answer FROM data (filter, count, aggregate, parse, compare, transform) — do the derivation in code and print only the answer
  - Output shape or size cannot be predicted before execution (recursive finds, repo-wide greps, list endpoints, query results, log scans)
  - You would otherwise read raw output and then mentally compute — that compute belongs here, in code, where its inputs stay out of your conversation
  - You need to keep a long-running process alive (dev server, watcher, daemon) — pass `background: true` to detach on timeout instead of killing the process
  - The output may legitimately be large but you only want recall-by-topic later — pass an `intent` string; outputs over ~5KB are auto-indexed into the knowledge base and only the section titles + previews come back, retrievable via ctx_search

WHEN NOT:
  - Single observational command whose entire short output you intend to consume verbatim (whoami, pwd, git status on a clean tree) — Bash is simpler
  - File mutations (Edit/Write) or navigation (cd/ls) — Bash is the right surface
  - You already know the output is one short fixed line and you want to read it as-is

RETURNS:
  Only what your code prints. Wrap risky calls in try/catch — uncaught errors go to stderr and may leak more than intended. When `intent` is set and output exceeds the auto-index threshold, the response carries searchable section titles + previews instead of the raw stdout; use ctx_search(queries: [...]) to drill into specific sections.

EXAMPLE: ctx_execute(language: "javascript", code: "const out = require('child_process').execSync('npm test', {encoding:'utf8', stdio:['ignore','pipe','pipe']}); console.log(out.split('\\n').filter(l => /(FAIL|✗|×|Error:|Tests +.*(failed|passed))/i.test(l)).slice(0, 60).join('\\n'))")
EXAMPLE: ctx_execute(language: "javascript", code: "const out = require('child_process').execSync('gh issue list --json number,title --limit 100', {encoding:'utf8'}); const hooks = JSON.parse(out).filter(i => /hook|routing/i.test(i.title)); console.log(`${hooks.length} hook-related issues`)")

Keep process running after timeout (for servers/daemons). Returns partial output without killing the process. IMPORTANT: Do NOT add setTimeout/self-close timers in background scripts — the process must stay alive until the timeout detaches it. For server+fetch patterns, prefer putting both server and fetch in ONE ctx_execute call instead of using background.

Source code to execute. Use console.log (JS/TS), print (Python/Ruby/Perl/R), echo (Shell), echo (PHP), fmt.Println (Go), IO.puts (Elixir), or Console.WriteLine (C#) to output a summary to context.

Optional working directory for shell commands. Non-shell languages still execute from their sandbox temp directory.

What you're looking for in the output. When provided and output is large (>5KB), indexes output into knowledge base and returns section titles + previews — not full content. Use ctx_search(queries: [...]) to retrieve specific sections. Example: 'failing tests', 'HTTP 500 errors'.

TIP: Use specific technical terms, not just concepts. Check 'Searchable terms' in the response for available vocabulary.

Runtime language

javascript typescript python shell ruby go rust php perl r elixir csharp

Max execution time in ms. When omitted, no server-side timer fires — the MCP host's RPC timeout governs (which is the right layer for this policy). Pass an explicit value for long-running builds (Gradle/Maven/SBT).

Run code in a sandbox (executes the supplied code)

Read a file into a sandboxed FILE_CONTENT variable and run code over it. Only what you console.log() enters your conversation — the file bytes stay in the sandbox.

Think-in-Code applied to file-level analysis: Reading the whole file means every byte enters your conversation memory and costs reasoning capacity for the rest of the session. Running code over it here lets you keep the raw bytes out and only the derived answer in. Same principle as ctx_execute, scoped to one named file via the FILE_CONTENT variable.

WHEN:
  - You want to KNOW SOMETHING ABOUT a file (line count, matches of a pattern, parsed structure, statistical aggregate) without needing to SEE all of it
  - The file is structured (CSV, JSON, log, code) and a code-level derivation is cheaper than reading verbatim
  - The file is large enough that reading the full content would burn meaningful conversation memory you need for the actual work
  - The derivation may itself produce a large output you want recall-by-topic on later — pass an `intent` string; outputs over ~5KB are auto-indexed and only matching sections come back, retrievable via ctx_search

WHEN NOT:
  - You intend to EDIT the file — use Read so the subsequent Edit can match the exact text
  - You only need one specific line and you know its offset — Read with offset/limit is the simplest path
  - The file is small AND you will consume all of it for understanding/editing — Read directly

RETURNS:
  Only what your code prints. The FILE_CONTENT variable holds the raw bytes inside the sandbox; nothing else leaves. When `intent` is set and output exceeds the auto-index threshold, the response carries searchable section titles + previews instead of the raw stdout.

EXAMPLE: ctx_execute_file(path: "huge.log", language: "javascript", code: "const errs = FILE_CONTENT.split('\\n').filter(l => /ERROR|FATAL/.test(l)); console.log(`${errs.length} error lines`); console.log(errs.slice(-5).join('\\n'))")
EXAMPLE: ctx_execute_file(path: "data.csv", language: "javascript", code: "const rows = FILE_CONTENT.split('\\n'); console.log(`rows: ${rows.length - 1}, header: ${rows[0]}`)")

Code to process FILE_CONTENT (file_content in Elixir). Print summary via console.log/print/echo/IO.puts/Console.WriteLine.

What you're looking for in the output. When provided and output is large (>5KB), returns only matching sections via BM25 search instead of truncated output.

Runtime language

Absolute file path or relative to project root

Run code over a file (executes code, reads the given path)

Fetches URL content, converts HTML to markdown (JSON is chunked by key paths, plain text indexed directly), persists it in a searchable knowledge base, and returns a small preview window per source. The raw page bytes never enter your conversation — they live in storage and you retrieve any section on-demand via ctx_search.

Caching: every fetch is cached on disk and reused for repeat calls within the TTL window. The default TTL is 24 hours; override per-call with the `ttl` parameter (milliseconds, `ttl: 0` bypasses cache like `force: true`). Stored content older than 14 days is cleaned up on startup.

WHEN:
  - You need web content (docs, changelogs, API references, spec pages) and the raw page bytes should NOT enter your conversation
  - Multi-URL research (library evaluation, migration scans, doc comparisons): pass the `requests` array and a `concurrency` value 2-8 for parallel I/O
  - You want repeat lookups against the same URL to be cheap (TTL cache hits return only a hint, no re-fetch)
  - You want a long-lived cache window (override `ttl` upward for stable specs) or a guaranteed-fresh fetch (`ttl: 0` or `force: true`)

WHEN NOT:
  - You already have the content locally — store it via the inline index tool
  - The page is SPA-rendered (JavaScript-required to materialize content) — this is a plain HTTP fetch, no headless browser

RETURNS:
  Per-source preview windows extracted around indexable headings plus indexing metadata (chunk counts, source labels, cache state). Raw content is NOT echoed back — retrieve any section on-demand via ctx_search(source: "<label>"). Concurrency parallelizes the fetch phase up to your chosen value (capped by the host's logical CPU count); the FTS5 write phase always runs serially because SQLite is a single-writer store. Net latency = max(fetch latency across the pool) + sum(per-source index write time). Cache hits skip both phases and return a small freshness hint instead of re-fetching. Use 4-8 for stable I/O-bound batches; lower the value when the target host enforces a per-IP rate limit you cannot raise.

EXAMPLE: ctx_fetch_and_index(
  requests: [{url: "https://react.dev/...", source: "react"}, {url: "https://vuejs.org/...", source: "vue"}],
  concurrency: 5
)

Max URLs to fetch in parallel (1-8, default: 1). Use 4-8 for I/O-bound multi-URL batches (library docs, changelogs, pricing pages). Capped by os.cpus().length on small machines (response notes when capped). Indexing is always serial regardless — only fetches race.

Skip cache and re-fetch even if content was recently indexed

Batch shape: array of {url, source?} entries. Use with concurrency>1 for parallel fetch. Each request indexed under its own source label. Output preserves input order.

Label for this URL's indexed content

URL to fetch

Label for the indexed content when using single `url` (e.g., 'React useEffect docs', 'Supabase Auth API'). For batch, put source in each requests entry.

Override the cache freshness window for this call, in milliseconds. `ttl: 0` bypasses the cache like `force: true`; omit to use the default 24h TTL.

Single URL to fetch and index (legacy single-shape)

Fetch & Index URL(s)

Store content in a searchable knowledge base (BM25 over FTS5). Splits markdown by headings, keeps code blocks intact, and persists the raw chunks. The full content stays in storage — retrieve any section on-demand via ctx_search; nothing is summarized or truncated.

WHEN:
  - Documentation from Context7, Skills, or MCP tools (API docs, framework guides, code examples)
  - API references (endpoint details, parameter specs, response schemas)
  - MCP tools/list output (exact tool signatures and descriptions)
  - Skill prompts and instructions that are too large to keep verbatim in conversation
  - README files, migration guides, changelog entries
  - Any content with code examples you may need to reference precisely later

WHEN NOT:
  - Log files, test output, CSV, or build output — use ctx_execute_file, which processes in-sandbox without persisting bytes
  - Single-use ephemeral content you will not query later — keep it inline if it fits, or ctx_execute_file it

RETURNS:
  Indexing metadata: chunk counts (total, code-bearing), source label, and the exact ctx_search call shape to query the indexed content. Raw content is NOT echoed back — it lives in storage, retrievable via ctx_search(source: "<label>"). When `path` is provided, a content hash is stored so ctx_search results auto-flag staleness on future calls.

EXAMPLE: ctx_index(content: "# React useEffect\n\nThe Effect Hook lets you ...", source: "react-useeffect-docs")
EXAMPLE: ctx_index(path: "/path/to/large-spec.md", source: "openapi-v2-spec")

Raw text/markdown to index. Provide this OR path, not both.

Directory-only: glob patterns to exclude. Merged with defaults (node_modules, .git, dist, build, .next, coverage, .venv, __pycache__, .DS_Store).

Directory-only: allowed file extensions (default: .md .mdx .txt .json .yaml .yml .ts .tsx .js .jsx .py .rs .go .sh).

Directory-only: follow directory symlinks (default: false — cycle hazard + escape risk).

Directory-only: glob patterns to include (default: all matching extensions).

Directory-only: max recursion depth from root (default: 5).

Directory-only: hard cap on files indexed (default: 200) — FTS5 blow-up guard.

File OR directory path to read and index (content never enters context). Provide this OR content. Directory paths trigger a bounded recursive walk (#687).

Directory-only: apply nearest .gitignore (default: true).

Label for the indexed content (e.g., 'Context7: React useEffect', 'Skill: frontend-design')

Index Content

Opens the context-mode Insight dashboard (https://context-mode.com/insight) in your default browser — a dashboard launcher for the hosted analytics layer, not a Q&A engine. Insight surfaces per-engineer productive rate, retry waste, blocker detection, and role-narrowed views for CTO, EM, IC, CISO, FinOps, and DevOps. For natural-language queries over your indexed content, use ctx_search.

Open Insight Dashboard

DESTRUCTIVE: permanently delete indexed content. Cannot be undone. Requires confirm:true and exactly one scope.

WHEN:
  - User explicitly asks to clear a specific session ('purge this session', 'wipe this conversation')
  - User explicitly asks to reset the whole project ('reset everything', 'wipe the knowledge base')

WHEN NOT:
  - User says 'reset', 'clear', or 'wipe' without naming a scope -> ask which scope before calling
  - User wants to free memory or improve performance -> recommend ctx_stats first, do not purge

SCOPES (pass exactly one):
  - Per-session: ctx_purge(confirm: true, sessionId: "<uuid>") deletes that session's events (auto-captured decisions, errors, plans, user prompts, rejected approaches, etc.) and per-session FTS5 chunks; sibling sessions and stats file are preserved.
  - Per-project: ctx_purge(confirm: true, scope: "project") wipes FTS5 knowledge base, every session DB row, events markdown, and resets the stats file. Use ctx_stats first to preview category counts before purging.

CONTRACT:
  - confirm:true is required; confirm:false returns 'purge cancelled'.
  - sessionId and scope:'project' together return 'ambiguous - pick one'.
  - scope:'session' without sessionId throws (sessionId required).
  - Bare {confirm:true} is deprecated: maps to scope:'project' with a stderr warning; will hard-error in a future major.

RETURNS:
  A summary of removed rows + the resolved scope.

EXAMPLE: ctx_purge(confirm: true, sessionId: "7c8a-1234-5678-9abc-def012345678")
EXAMPLE: ctx_purge(confirm: true, scope: "project")

MUST be true. Destructive operation; false returns 'purge cancelled'.

Explicit scope selector. 'session' REQUIRES sessionId. 'project' wipes the entire project (FTS5 + every session + stats). Omit only for the deprecated bare-{confirm:true} back-compat path.

UUID of a single session. Pairs with confirm:true to wipe only that session's events + per-session FTS5 chunks. Sibling sessions and the stats file are preserved. MUST NOT be combined with scope:'project'.

Purge Knowledge Base

Search a unified knowledge base with a multi-strategy ranking pipeline. Two parallel matchers run on every query: a Porter-stemming matcher ("caching" finds "cached", "caches", "cach") and a trigram-substring matcher ("useEff" finds "useEffect"). Their ranked lists are merged via Reciprocal Rank Fusion, so a document that ranks well in both surfaces above one that wins only on a single strategy. Multi-term queries get an additional proximity-rerank pass that boosts passages where the query terms appear close together. Typos are corrected via Levenshtein distance and re-searched. Result snippets are window-extracted around the matched terms, not blindly truncated.

The knowledge base is unified: queries reach indexed content you stored (ctx_index, ctx_fetch_and_index, ctx_batch_execute output) AND auto-captured session memory written by hooks (decisions, errors, blockers, plans, user prompts, rejected approaches, tool failures, compaction guides — 26 event categories). File-backed sources carry a content hash and auto-flag staleness when the source file changes.

WHEN:
  - You want to recall something that exists in storage (recently indexed content, prior session events, auto-memory) instead of re-reading raw sources
  - You have multiple related questions about the same body of knowledge — batch every question into one call (the ranking pipeline runs per-query but the round-trip cost is paid once)
  - You want to scope the query to one labelled source (pass `source` — partial match is fine)
  - You want a chronological view across current session + prior sessions + persistent auto-memory (pass `sort: "timeline"` — the default `relevance` mode only ranks within the current session)
  - You want to filter ranked results by content shape (pass `contentType: "code"` to surface implementation snippets or `contentType: "prose"` to surface explanations)

WHEN NOT:
  - The data you want to query has never been stored in the knowledge base AND no session memory has accumulated around it — capture first (run a gather-and-index call), then come back here to query
  - You have one ad-hoc question against data that is not in the knowledge base — answer it inline by running code in the sandbox tool; one round-trip instead of capture-then-query

RETURNS:
  Per-query ranked sections with window-extracted snippets. Use 2-4 specific technical terms per query. Common session-memory source labels: `decision` (user corrections / preferences), `error` and `error-resolution` (past failures + their fixes), `blocker`, `plan`, `user-prompt`, `rejected-approach`, `compaction` (post-compact session guide). See ctx_stats for live category counts. Each response carries a throttle counter (call #N/M in the rolling time window); results taper toward the soft cap and calls block after the hard cap. Tune via CONTEXT_MODE_SEARCH_WINDOW_MS, CONTEXT_MODE_SEARCH_MAX_RESULTS_AFTER, CONTEXT_MODE_SEARCH_BLOCK_AFTER.

EXAMPLE: ctx_search(queries: ["root cause", "proposed fix", "test coverage"], source: "issue-#683")
EXAMPLE: ctx_search(queries: ["what did we decide about caching"], source: "decision", sort: "timeline")
EXAMPLE: ctx_search(queries: ["useEffect cleanup pattern"], source: "react-docs", contentType: "code", limit: 5)
EXAMPLE: ctx_search(queries: ["last user prompt", "active skills", "open blockers"], sort: "timeline")

Filter results by content type: 'code' or 'prose'.

Results per query (default: 3)

Array of search queries. Batch ALL questions in one call.

Sort mode. 'relevance' (default): BM25 ranked, current session only. 'timeline': chronological across current session, prior sessions, and auto-memory.

Filter to a specific indexed source (partial match).

Search Indexed Content

Returns context consumption statistics for the current session. Shows total bytes returned to context, breakdown by tool, call counts, estimated token usage, and context savings ratio.

Session Statistics

Upgrade context-mode to the latest version. Returns a shell command to execute. You MUST run the returned command using your shell tool (Bash, shell_execute, run_in_terminal, etc.) and display the output as a checklist. Tell the user to restart their session after upgrade.

Upgrade Plugin