Code Context Builder
Code Context Builder is a local Visual Studio Code and Cursor extension that bundles workspace files into structured Markdown or XML context documents and exposes that session to local AI assistants through a loopback MCP server. Everything runs locally in the extension host: there are no language-model calls and no outbound network requests. The only listener is http://127.0.0.1:<ephemeral>/mcp.
Highlights
- First-Class YAML Presets (
*.ctx.yaml): Save shared presets as diff-friendly .ctx.yaml files in .code-context/presets/ (or custom directories) alongside private local presets in workspace state.
- Split Contexts & Auto-Packing: Organize large architectures into named parts—or auto-pack selected files under a configurable KB ceiling (e.g.,
190 KB for web LLM upload limits)—and batch-export every part in one click.
- Crystallize Snapshots: Freeze point-in-time context bundles into
.code-context/snapshots/ stamped with the current Git branch, commit SHA, and timestamp.
- Activity Bar Sidebar & Explorer Integration: Manage active selections, apply or copy
.ctx.yaml presets, and open crystallized snapshots directly from the Code Context Activity Bar view or the File Explorer context menu.
- Short Slash Commands & Agent Skills: Use
/ccb-curate and /ccb-preset in Cursor or VS Code Copilot without dirtying .cursor/mcp.json, backed by a non-blocking loopback MCP server.
The Code Context Activity Bar container (codeContextBuilderSidebar) provides two native views:
- Active Context: Displays currently checked files (or split parts and their files) with mode badges and estimated token counts, even when the builder tab is closed. View title actions let you Open Context Builder, Copy Current Bundle to Clipboard, Crystallize Active Snapshot, and Clear Active Context.
- Presets & Snapshots: Groups Shared Presets (
*.ctx.yaml) (expandable to individual parts for split presets), Local Presets, and Snapshots (.code-context/snapshots/). When a legacy .vscode/code-context-presets.json file is present, a one-click migration entry converts entries into .ctx.yaml files.
Core Commands
- Code Context: Open Context Builder (
codeContextBuilder.open) opens or reveals the builder panel for the active workspace folder.
- Open in Code Context Builder (
codeContextBuilder.openWithSelection) on the Explorer context menu opens the builder with the clicked files or folders selected (respecting .gitignore when enabled; .git/ is always skipped).
- Add Selection to Code Context (
codeContextBuilder.addEditorSelection) on the editor context menu adds the active editor selection as line ranges while preserving already-checked files.
- Code Context: Copy Current Bundle to Clipboard (
codeContextBuilder.copyActiveContext, Ctrl+Alt+Shift+C / Cmd+Alt+Shift+C) re-reads checked files and copies a fresh bundle. If a hard limit, invalid range, or unacknowledged warning blocks copying, the builder opens on Issues Only.
- Explorer
*.ctx.yaml Actions: Right-clicking any .ctx.yaml file in the File Explorer exposes Apply Preset in Builder, Copy Preset Context Bundle, and Export Preset Bundle....
- Code Context: Install Workspace Agent Skills & Slash Commands (
codeContextBuilder.installWorkspaceSkills) writes workspace commands, rules, and prompt files for Cursor, VS Code Copilot, or both.
- Code Context: Migrate Legacy JSON Presets to YAML (
codeContextBuilder.migrateLegacyPresets) converts .vscode/code-context-presets.json entries into .code-context/presets/*.ctx.yaml without overwriting existing files.
Builder Workspace
The webview builder uses a compact two-pane layout:
- Header Bar: Edit the document title, open the + Overview / Overview popover for an architectural prompt preamble, switch between Standalone and Split Parts (N) modes, manage presets (Save Active Preset, Save As..., Delete Active Preset, Migrate Legacy JSON...), and configure Output Format (
Markdown / XML) and Target Part Max KB (190 KB default).
- File Explorer Pane: Includes a filter box, workspace Root selector, Quick Select menu (Select Open Tabs, Select Git Changes, Select vs. Git Ref..., Set Selected to Diff, Select Visible, Clear Selection), and expand/collapse controls.
- Configure Selected Inspector: Renders compact single-line accordion cards (
path, mode badge, part pill in split mode, size/token/share summary, and quick remove). Cards expand on click or automatically when a file has an issue. Secondary actions (Open in Editor, Mark Size Skipped, Reset Sensitive, Move to Part) live in the card's ••• menu.
Quick Selection & Git Integration
- Select Open Tabs: Checks open text editor tabs inside the current custom root.
- Select Git Changes & Select vs. Git Ref...: Uses VS Code's built-in Git extension API (
getBranches, diffBetween, diffWith, repo.show) without spawning a git subprocess.
- Set Selected to Diff: Switches checked files in a Git repository to Diff mode against the active ref (
HEAD by default).
YAML Presets (*.ctx.yaml) & Guarded Drift
Presets are live queries over the current branch:
- Shared Presets (
*.ctx.yaml): Stored in .code-context/presets/ (configurable via codeContextBuilder.presets.directories) and discovered automatically via **/*.ctx.yaml.
- Local Presets: Stored privately in VS Code
workspaceState.
- Legacy Migration: Existing
.vscode/code-context-presets.json files trigger a non-intrusive migration prompt and Sidebar/Preset menu action that generates slugified .ctx.yaml files without deleting or overwriting existing YAML presets.
# .code-context/presets/auth-architecture.ctx.yaml
version: 1
name: Auth Architecture
mode: split # 'standalone' | 'split'
customRoot: ""
outputFormat: markdown
targetPartMaxKB: 190
documentTitle: Auth Architecture
documentPreamble: |
End-to-end authentication flow across API gateway and web client.
parts:
- id: schemas-and-db
title: "Schemas & Models"
preamble: Database models and session types.
files:
- path: packages/db/prisma/schema.prisma
mode: ranges
note: User and Session models
ranges:
- spec: L42:98
note: Session revocation fields
anchor:
sliceHash: 8f3a19c2
headLine: "model Session {"
tailLine: "}"
spanLength: 57
- id: controllers
title: "API Controllers"
files:
- path: apps/api/src/auth/loginController.ts
mode: full
Each saved line range stores a RangeAnchor (sliceHash, headLine, tailLine, spanLength):
- Shifted ranges show a drift badge (such as
Shifted +12 lines -> L54:100) with one-click Relocate and Relocate All Drifted Ranges.
- Unmatched ranges (
drifted_unmatched) no longer silently emit shifted lines. They raise an explicit drift warning displaying the saved headLine ... tailLine fingerprint, with Inspect in Code Peek and an acknowledgable Acknowledge Drift gate.
- Missing files stay visible in a warning banner with Remove Missing and Update Preset.
Split Contexts & Snapshot Crystallization
Split Mode & Auto-Packing
Switch to Split Parts in the header (or load a mode: split .ctx.yaml preset) to organize files into multiple named parts—each file belongs to one part at a time:
- Split Parts Bar: Displays per-part tabs with live
KB / targetPartMaxKB indicators, per-part titles and optional preambles, + Add Part, Delete Part, and Auto-Pack.
- Auto-Pack: Groups selected files by directory locality in tree order so each generated part's rendered byte size stays at or below
targetPartMaxKB. If a single file exceeds the budget, it is isolated in its own flagged part with a recommendation to switch to Line Ranges.
- Exporting: Use Copy Active Part for the selected tab or Batch Export All Parts (N)... to write
<slug>-part-0-index.md (an overview manifest containing the shared preamble, parts summary table, unified aggregated file tree, and file-to-part map) alongside <slug>-part-1-<part-id>.md..<slug>-part-N-<part-id>.md (or .xml) into a chosen directory. Rendered parts include a cross-reference header (Split Context Bundle — Part i of N) so receiving LLMs know the bundle is multi-part.
Crystallize Snapshot
When you want an immutable, point-in-time record rather than a live preset query, choose Crystallize Snapshot (from the Standalone save menu, Split footer, Sidebar, or MCP):
- Writes
.code-context/snapshots/<YYYY-MM-DD>-<slug>.md (or .xml), or .code-context/snapshots/<YYYY-MM-DD>-<slug>/part-0-index.md plus part-1-<part-id>.md..part-N-<part-id>.md (or .xml) for split bundles.
- Stamps every rendered document (including
part-0-index) with the preset/title, current Git branch, short commit SHA, and UTC timestamp (<!-- code-context-snapshot: ... --> in Markdown or <context ... snapshot_sha="..." created_at="..."> / <context_index ...> in XML).
Local MCP Server & Short Slash Commands
When codeContextBuilder.mcp.enabled is true and a workspace folder is open, the extension starts a loopback HTTP MCP server (127.0.0.1:<ephemeral>/mcp) immediately on activation without waiting for the initial disk tree scan to finish. Code Context: Restart Local MCP Server (codeContextBuilder.restartMcpServer) rotates the bearer token and refreshes IDE registrations.
Native Short Slash Commands (/ccb-curate, /ccb-preset)
Instead of mutating .cursor/mcp.json or .vscode/mcp.json with a stdio bridge, v0.3.0 uses native IDE command and prompt files:
- Cursor (Auto-Provisioned): When
codeContextBuilder.skills.autoInstallUserSlashCommands is true (default), activating inside Cursor automatically keeps ~/.cursor/commands/ccb-curate.md and ~/.cursor/commands/ccb-preset.md up to date (following codeContextBuilder.mcp.shortName).
- Workspace Skills & VS Code Copilot: Run Code Context: Install Workspace Agent Skills & Slash Commands (
codeContextBuilder.installWorkspaceSkills) to write:
- Cursor:
.cursor/commands/ccb-curate.md, .cursor/commands/ccb-preset.md, and .cursor/rules/code-context.mdc.
- VS Code Copilot:
.github/prompts/ccb-curate.prompt.md and .github/prompts/ccb-preset.prompt.md.
/ccb-curate guides the assistant to trace the requested feature or bug across schemas, controllers, callers, and tests, then call curate_ui_selection without closing or stealing focus from an already-open builder tab.
/ccb-preset guides the assistant to curate a slice (automatically choosing mode: "split" under 190 KB when large) and save it via save_context_preset.
IDE Registration & External Clients
- VS Code (
vscode.lm.registerMcpServerDefinitionProvider): Registers provider codeContextBuilder.mcpProvider labeled ccb (or mcp.shortName) using Authorization: Bearer <token>.
- Cursor (
vscode.cursor.mcp.registerServer): Registers ccb (or mcp.shortName) via /mcp/<token>.
- External Clients (Claude Code, Windsurf, Cline): Use Code Context: Copy MCP Server Config (JSON) (
codeContextBuilder.copyMcpConfig) or click the MCP: Active pill in the builder footer:
{
"mcpServers": {
"ccb": {
"type": "http",
"url": "http://127.0.0.1:<port>/mcp",
"headers": {
"Authorization": "Bearer <token>"
}
}
}
}
- Resource
context://active: Renders the active selection in text/markdown or application/xml.
- Prompts:
curate (focus, action) and preset (presetName, focus, scope) for MCP clients.
- Tools (accepting optional
workspaceFolder):
get_active_context: Returns the active bundle, file count, bytes, token estimate, and warnings (outputFormat, includeBlocked).
generate_context_bundle: Builds a bundle from paths, rangesByFile, notesByFile, customRoot, documentTitle, documentPreamble, and outputFormat.
list_context_presets: Lists workspace-state and *.ctx.yaml presets with mode, part summaries, and path previews.
get_preset_context: Renders a standalone or split preset (name, scope, partId, outputFormat), reporting driftWarnings.
save_context_preset: Creates or updates a standalone or split preset (*.ctx.yaml when scope: "shared", workspaceState when scope: "local"), attaching range anchors automatically.
crystallize_context_snapshot: Writes an immutable Git-SHA-stamped snapshot from the active selection or a saved preset into .code-context/snapshots/.
curate_ui_selection: Replaces or appends files/ranges in the active builder session (revealPanel defaults to true).
Security
- Loopback Isolation: Binds
127.0.0.1 only; non-IPv4-loopback sockets (including ::1), mismatched Host headers, and requests with an Origin header receive 403. Missing or invalid tokens receive 401 (constant-time comparison). Bodies over 1 MiB receive 413.
- Policy Enforcement:
sensitiveFiles, binary omission, .gitignore directory expansion, path-escape/internal-.git rejection, and fileHardLimitKB / totalHardLimitKB are enforced on every MCP call and YAML preset read.
- Inline Secret Redaction: When
enableInlineRedaction is enabled, built-in credential patterns and redactPatterns mask matches with <REDACTED> in full, range, and diff outputs across the builder, Quick Re-Copy, snapshots, and MCP responses.
- Mutation Gates:
mcp.allowPresetMutation controls save_context_preset and crystallize_context_snapshot; mcp.allowUiMutation controls curate_ui_selection and panel reveal after saves.
Output Modes & Templates
Each selected file uses one of four modes: Full file, Line ranges (picked manually or via Inline Code Peek), Diff (against a Git ref or HEAD), or Custom description.
Markdown documents use # Title, ## File Tree, and ## Files with fenced code blocks. XML documents emit <context>, <file_tree>, and <files><file ...><code>...</code></file></files> (wrapping bodies containing <, &, or ]]> in CDATA).
Paths & .gitignore
sensitiveFiles, languageOverrides, and .gitignore rules are always evaluated against POSIX paths relative to the workspace root, even when a custom root directory is selected in the builder.
Size Limits & Token Estimates
Sizes use kibibytes (1 KB = 1024 bytes). Token estimates use ceil(character count / 4) for context window awareness.
| Limit |
Default |
Effect |
| File soft |
50 KB |
Warning; acknowledge the file or choose Suppress All Warnings. |
| File hard |
250 KB |
Error; blocks copy/export until shortened with ranges or replaced with a description. |
| Total soft |
512 KB |
Document-level warning; acknowledge to proceed. |
| Total hard |
2048 KB |
Document-level error; blocks copy/export until reduced. |
Settings
All settings live under codeContextBuilder.*:
| Setting |
Default |
Description |
documentTitle |
Code Context |
Default top-level document title. |
treeStyle |
unicode |
Tree connectors (unicode or ascii). |
respectGitignore |
true |
Skip .gitignored files during folder selection using workspace-root POSIX paths. |
fileSoftLimitKB |
50 |
Per-file warning threshold in kibibytes. |
fileHardLimitKB |
250 |
Per-file blocking error threshold in kibibytes. |
totalSoftLimitKB |
512 |
Whole-document warning threshold in kibibytes. |
totalHardLimitKB |
2048 |
Whole-document blocking error threshold in kibibytes. |
sensitiveFiles |
**/.env, **/.env.*, **/*.pem, **/*.key |
Workspace-root globs mapped to default custom descriptions. |
outputFormat |
markdown |
Default template (markdown or xml). |
statusBar.enabled |
true |
Show active file count, token estimate, and MCP state in the status bar. |
enableInlineRedaction |
true |
Mask matched inline secrets with <REDACTED> across full, range, and diff outputs. |
builtInRedactPatterns |
true |
Include built-in credential redaction regexes. |
redactPatterns |
[] |
Custom JavaScript regular expressions (evaluated with g flag). |
languageOverrides |
**/.env, **/.env.*, **/.husky/*, **/Dockerfile*, **/Makefile |
Workspace-root globs mapped to code-fence languages. |
presets.directories |
[".code-context/presets"] |
Workspace-relative directories scanned for *.ctx.yaml presets. |
snapshots.directory |
".code-context/snapshots" |
Workspace-relative directory where crystallized snapshots are written. |
mcp.enabled |
true |
Start the local loopback MCP server and register it with supported AI editors. |
mcp.allowUiMutation |
true |
Allow curate_ui_selection and panel reveal from MCP tools. |
mcp.allowPresetMutation |
true |
Allow save_context_preset and crystallize_context_snapshot via MCP. |
mcp.shortName |
ccb |
Server identifier (^[a-z0-9_-]{2,16}$) used for registration, client JSON, and slash commands. |
skills.autoInstallUserSlashCommands |
true |
Automatically keep ~/.cursor/commands/ccb-curate.md and ccb-preset.md up to date on startup in Cursor. |
| |