smart-context-packer
Parses FiveM fxmanifest.lua tables (shared_scripts, client_scripts, server_scripts, including glob expansion) and Lua dot-notation require(...) calls, so FiveM resource scripts are traced as dependencies and packed into the context bundle.
Extracts Prisma schema models and enums referenced by the packed code: detects @prisma/client and prisma.<model> usage, parses schema.prisma, and includes only the referenced models/enums (plus one level of relations) in the generated context prompt.
This server does not currently have a deployable release on Glama. Follow the repository's setup instructions to install and configure it for your MCP client, including any required credentials and local dependencies.
๐ฌ๐ง English | ๐น๐ท Tรผrkรงe Dokรผmantasyon
๐ฆ smart-context-packer (scp)
High-Fidelity AI Context Packer & Multi-Language Dependency Graph Analyzer
Pack only the code your AI assistant actually needs to see โ zero hallucinations, minimal tokens.
Quickstart โข Features โข 16-Language Polyglot โข Universal Agent Presets โข Active Task Engine โข Tool Output Sandbox โข PageRank Repo-Map โข BM25 Intent Search โข OSS Comparison โข CLI Usage โข 15-Tool MCP Suite
๐ก The Problem
When developing with AI assistants (ChatGPT, Claude, Gemini, Cursor, Copilot, Codex, OpenCode, Aider, Windsurf), developers constantly face two extremes:
The "Full Repository Dump" Trap: Tools dump the entire codebase into a 90k+ token mega-prompt. The AI loses focus on the real task, exceeds context budgets, racks up enormous API bills, and gets confused by irrelevant boilerplate.
The "Isolated File" Trap: The developer copies a single file. The AI immediately hallucinates missing function implementations, invents nonexistent interfaces, and generates code that breaks workspace imports.
The Solution: smart-context-packer (scp v2.4)
scp takes your target entry file(s), analyzes their directed dependency graph across 16 programming languages, redacts sensitive credentials, and packages ONLY the target files and their direct/transitive local dependencies into a clean, token-counted prompt equipped with an AI pre-flight directive header.
In v2.4.0, smart-context-packer brings Symbol-Level AST Tree-Shaking (--tree-shake), Automatic Monorepo Workspace Resolution (packages/*, apps/*, pnpm-workspace.yaml), Git Commit & PR Packing (--commit, --pr), Live File Watch Mode (-w, --watch), 16-Language Ultra-Polyglot AST Support, 12 Universal AI Agent Presets, and Surgical Layer 4 MCP Suite (15 native tools) โ all with zero external binary dependencies (no Python, no Bun, no ChromaDB, no SQLite).
Related MCP server: io.github.pmgarg/cgraphy
๐ How scp v2.4 Compares to the Best OSS Tools
Capability / Architecture |
|
|
|
|
|
Symbol-Level AST Tree-Shaking | โ | โ | โ | โ | โ
( |
Monorepo Workspace Resolution | โ | โ | โ | โ | โ
( |
Commit Range & PR Context Packing | Partial | โ | โ | โ | โ
( |
Live File Watch Mode | โ | โ | โ | โ | โ
( |
Universal Multi-Agent Presets | โ | โ | โ | โ | โ
12 Agents ( |
Ultra-Polyglot AST & Manifests | Partial (2-3) | None | None | Partial | โ 16 Languages + 12 Manifests (C#, Java, Kotlin, C++, PHP, Dart, Swift, Ruby, Svelte, TS, Go, Rust, Python, Vue, Lua, Prisma) |
Surgical Layer 4 MCP Tools | โ | โ | โ | โ | โ
( |
Active Task & Plan Checklist Engine | โ | โ | โ | โ | โ
(BM25 seed routing + crash-proof |
External Dependency Manifest Grounding | โ | โ | โ | โ | โ
(12 manifests: |
Tool Output Sandboxing (Tests/Logs) | โ | โ | โ | Partial | โ (Preserves root causes/failures, saves 80-95% tokens) |
Visual Context Budget HUD | โ | โ | โ | โ | โ (ASCII progress gauge & token category breakdown) |
PageRank Architectural Repo-Map | โ | โ | โ | โ | โ (Centrality scored ~500-1024 token bird's-eye map) |
In-Memory BM25 Semantic Intent Routing | โ | โ | โ | โ | โ
(CamelCase & symbol boosted intent query |
Interactive Offline Canvas Visualizer | โ | โ | โ | โ | โ (Self-contained HTML force graph + risk heatmap) |
Built-in Secret & Credential Redactor | โ | โ | โ | โ | โ (AWS, GitHub, Stripe, OpenAI, JWT, DB URLs) |
Incremental SHA-256 AST Caching | โ | โ | โ | โ | โ
( |
Blast-Radius & Test Impact Risk Scoring | โ | โ | โ | โ | โ (Reverse graph + test map + 0-10 risk score) |
Progressive MCP Disclosure Suite | โ | โ | โ | โ | โ (15 Native MCP Tools, zero-overhead stdio) |
File-Linked Persistent Project Memory | โ | โ | โ | โ | โ
(Git-friendly |
Smart Middle-Out Slicing | โ | โ | โ | โ | โ (Preserves imports & exports, slices massive middle) |
Runtime & Dependency Footprint | Heavy Python / ChromaDB | Bun / SQLite | Vector DB / Python | Node | โก Pure Node.js / TS (Zero Bloat / Zero C++ DBs) |
โก Quickstart
No installation required โ run instantly with npx:
# Analyze a file, bundle dependencies up to depth 2, and copy to clipboard:
npx smart-context-packer src/auth/login.ts -c
# Shorthand alias with skeleton mode:
npx scp src/server.ts -d 2 -s -c
# Auto-skeletonize deep dependencies to strictly fit within token budget:
npx scp src/server.ts -m 4000 -c
# Pack all uncommitted Git changes + dependencies + unified diff patch:
npx scp --diff -c
# Configure AI coding assistants (Cursor, Antigravity, Copilot) background rules:
npx scp --init-agent
# Start zero-dependency Model Context Protocol (MCP) stdio server:
npx scp --mcp
# Generate VS Code / Cursor Command Palette tasks:
npx scp --init-vscodeOr install globally / locally:
# Global installation
npm install -g smart-context-packer
# Local dependency
npm install -D smart-context-packer๐ Terminal Experience
When you run scp, you receive an instant terminal breakdown:
โญโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโฎ
โ ๐ฆ smart-context-packer summary โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโค
โ Targets: 1 target file(s) โ
โ Packed Files: 4 total (3 deps, 1 skeleton) โ
โ Lines of Code: 248 โ
โ Total Characters: 6,820 โ
โ Estimated Tokens: 1,640 tokens โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโค
โ Context Window Usage: โ
โ โข 128k (GPT-4o): 1.25% โ
โ โข 200k (Claude/Gemini): 0.80% โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโค
โ Output File: .context-pack.md โ
โ Clipboard: โ Copied to system clipboard โ
โฐโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโฏ
โ Prompt saved to /workspace/.context-pack.md
โ Copied to clipboard! Ready to paste into ChatGPT, Claude, Cursor, or Gemini.๐ Key Features
1. ๐ง Multi-Language Dependency Graph Engine
TypeScript, JavaScript, JSX, TSX: Resolves static
import, dynamicimport(),export ... from, and CommonJSrequire().NodeNext Extension Mapping: Automatically resolves
.jsimport specifiers to.ts/.tsxsource files on disk.Path Aliases: Automatically reads
tsconfig.jsonorjsconfig.jsonpath mappings (e.g.@/*->src/*,~/*->./*).Vue 3 SFCs: Extracts script blocks from
.vuecomponents and traces subcomponent/composable imports.Lua & FiveM: Parses
fxmanifest.luatables (shared_scripts,client_scripts,server_scriptswith glob expansion) and Lua dot-notationrequire('client.utils').
2. ๐ก๏ธ Automatic Secret & Token Redaction
Never accidentally leak API keys to third-party LLMs:
OpenAI Keys (
sk-...,sk-proj-...) ->[REDACTED_OPENAI_KEY]Anthropic Keys (
sk-ant-...) ->[REDACTED_ANTHROPIC_KEY]GitHub Tokens (
ghp_...,github_pat_...) ->[REDACTED_GITHUB_TOKEN]AWS Credentials (
AKIA...) ->[REDACTED_AWS_KEY]Private Key PEM Blocks (
-----BEGIN PRIVATE KEY-----) ->[REDACTED_PRIVATE_KEY]Database Connection Strings (
postgres://user:pass@host/db) ->postgres://user:[REDACTED]@host/db.env*assignments masked automatically.
3. โ๏ธ Skeleton / Signature Mode (--skeleton)
Save up to 85% more tokens on deep dependencies. Deep files have their internal function and method bodies replaced with type signatures:
// Original in deep dependency:
export function computeLargeData(items: Item[]): ProcessedResult {
// 150 lines of complex internal algorithmic logic...
}
// In Skeleton Mode:
export function computeLargeData(items: Item[]): ProcessedResult { /* [Implementation omitted for token efficiency] */ }The AI assistant gains 100% type and API awareness with 85% less token overhead.
4. ๐งญ AI Pre-flight Directive & Visual Directory Tree
Every generated prompt begins with a standardized instruction header:
<!-- ============================================================================== -->
<!-- SMART CONTEXT PACKER: AI DIRECTIVE -->
<!-- ============================================================================== -->
<!-- CRITICAL PRE-FLIGHT INSTRUCTIONS FOR AI CODING ASSISTANT: -->
<!-- 1. CAREFULLY INSPECT the visual directory tree and dependency graph below. -->
<!-- 2. ANALYZE all imported symbols, types, and architectural boundaries BEFORE -->
<!-- proposing or generating any code changes. -->
<!-- 3. PRESERVE existing conventions, naming styles, and strict typing. -->
<!-- 4. DO NOT invent or hallucinate modules not present in the workspace. -->
<!-- ============================================================================== -->Accompanied by a visual ASCII directory tree and dependency relationship map:
.
โโโ src
โโโ models
โ โโโ user.ts [DEP: depth 2]
โโโ services
โ โโโ auth.ts [DEP: depth 1, SKELETON]
โโโ index.ts [TARGET]
src/index.ts -> imports -> ["src/services/auth.ts"]
src/services/auth.ts -> imports -> ["src/models/user.ts"]5. ๐ฟ Git Diff & Working Tree Resolver (--diff, --staged)
Resolve uncommitted modified and untracked files as targets, calculate their full dependency graph, and append a unified ## Git Diff Patch section into the prompt for rapid PR reviews and bugfixes.
6. ๐๏ธ Smart Prisma Schema Model Extractor
Detects @prisma/client and prisma.<model> usage, parsing schema.prisma and extracting ONLY the models and enums referenced in the packed code (along with 1-level relations) to prevent DB hallucinations without bloating prompts.
7. ๐ Native Model Context Protocol (MCP) Server (--mcp)
Zero-dependency JSON-RPC 2.0 stdio server enabling AI coding agents (Claude Desktop, Cursor, Antigravity, Cline) to pack context and inspect dependency graphs autonomously.
8. ๐ป VS Code & AI IDE Tasks Generator (--init-vscode)
One-command setup of .vscode/tasks.json with three Command Palette tasks for instant clipboard copying of active file context, skeleton signatures, or git diffs.
9. ๐ฏ Auto Token-Budget Optimizer (--max-tokens)
Automatically monitors the total estimated token count. If the pack exceeds your specified budget, it progressively converts deep dependencies into skeleton signatures (from deepest depth down to depth 1, keeping depth 0 targets intact) to guarantee fitting within LLM window limits.
10. ๐ฅ Blast-Radius & Impacted Test Analyzer (-b, --blast-radius)
Performs reverse fan-in analysis to identify every workspace file calling your targets, locates all associated unit test files (*.test.ts, *.spec.ts, tests/**), warns of untested modifications, and computes a 0.0-10.0 Risk Score (LOW, MEDIUM, HIGH).
11. โก Incremental SHA-256 AST Cache (.scp/cache.json)
Caches parsed AST dependencies, exported symbols, and token metrics keyed by content SHA-256 hash and file mtime. Subsequent runs on large repos execute in milliseconds without any external databases.
12. ๐ง File-Linked Persistent Project Memory (.scp/memory.json)
Store git-friendly architectural decisions, bug gotchas, and invariants linked to file globs. Whenever matching files are packed or edited, their linked memories are automatically injected into the AI context!
13. ๐ 3-Layer Progressive Disclosure MCP Suite
Enables AI coding agents to interact with massive codebases progressively:
Layer 1:
search_codebase_index(~50 tokens per file summary with exported symbols)Layer 1:
search_codebase_index(ultra-fast compact symbol/file index ~50t)Layer 2:
inspect_dependency_graph(visual tree, dependency map, circular checks, blast radius)Layer 3:
pack_context&pack_git_diff(complete or skeletonized source code + diffs + memories)Spatial Awareness:
generate_repo_map(PageRank architectural bird's-eye map)Semantic Intent:
search_codebase_intent(BM25 intent search with camelCase boosting)Interactive Visualizer:
generate_visualizer(offline HTML force-directed canvas report)Memory Tools:
save_project_memory&query_project_memoryfor persistent cross-session knowledge.
๐บ๏ธ PageRank Architectural Repo-Map (v2.1.0)
When coding in large repositories, LLMs suffer from "tunnel vision" โ seeing isolated files without understanding the global architecture. Inspired by Aider's repo-map, scp v2.1 implements Graph PageRank Centrality Ranking (damping factor 0.85, 20 iterations):
# Generate a bird's-eye architectural repo-map (defaults to 1024 token budget):
scp --repo-map -c
# Pack an entry file along with a 500-token global architectural map:
scp src/server.ts --repo-map 500 -cWhat It Generates:
Traverses the entire codebase dependency graph.
Calculates PageRank scores based on in-degree and dependency authority.
Extracts exported signatures, interfaces, classes, and types from top architectural hubs.
Produces a strictly token-budgeted bird's-eye view injected directly into the prompt:
## ๐บ๏ธ Codebase Architectural Repo-Map (PageRank Centrality)
### `src/server.ts` (Score: 0.1852)
- `startServer(port: number): Promise<void>`
- `app: Express`
### `src/auth/service.ts` (Score: 0.1420)
- `verifySessionToken(token: string): Promise<User>`
- `interface UserSession`๐ In-Memory BM25 Semantic Intent Routing (v2.1.0)
Don't remember the exact path to a file? With -i, --query, describe what you want in plain English:
# Query by intent: Automatically discovers matching seed files and packs them!
scp -i "jwt auth token verification" -c
# Pipe intent results into skeleton packing with a token budget:
scp -i "stripe payment webhook handler" -m 2000 -cSmart Code Tokenizer: Splits
camelCase,PascalCase,snake_case, and kebab identifiers into constituent semantic terms (e.g.verifySessionToken->verify,session,token).Symbol Boosting: Exported function/class/interface names receive a 2.5x score multiplier over general file contents.
Pure In-Memory BM25: Runs in sub-10 milliseconds without external embedding models, Python runtimes, or vector databases.
๐จ Interactive Canvas Dependency Visualizer (v2.1.0)
Inspect your codebase architecture, dependency clusters, and blast radius visually through a standalone, zero-dependency HTML report:
# Generate an interactive HTML report (.scp/visualizer.html) and open it:
scp src/index.ts --visualize
# Specify custom report output:
scp --diff --visualize ./reports/diff-impact.htmlKey Visualizer Features:
Zero-Dependency Native HTML5 Canvas: Embeds physics, styles, and data directly into one file โ works completely offline without CDN dependencies.
Physics Force-Directed Simulation: Real-time interactive node dragging, zooming, and panning.
Dynamic Node Sizing & Heatmap: Node radius scales by estimated token count. Colors indicate Blast-Radius risk levels (Green = Low, Orange = Medium, Red = High).
Interactive Inspector Sidebar: Click any node to view incoming/outgoing dependencies, token counts, and full source code.
๐ก๏ธ Built-in Enterprise Secret & Credential Redactor (v2.1.0)
Never accidentally upload production credentials, private keys, or API secrets into an LLM context:
# Secret redaction is ENABLED BY DEFAULT across all CLI runs and MCP tools:
scp src/config.ts -c
# Opt out only if specifically needed:
scp src/config.ts --no-redact -cDetected & Sanitized Secret Patterns:
Private Keys: RSA, EC, DSA, OpenSSH, and PGP
-----BEGIN PRIVATE KEY-----blocks.AWS Credentials:
AKIA...Access Key IDs and 40-character secret access keys.GitHub Tokens: Personal Access Tokens (
ghp_...,github_pat_...), OAuth keys, and refresh tokens.Stripe Keys: Live and test secret keys (
sk_live_...,rk_live_...,sk_test_...).AI Platform Keys: OpenAI (
sk-proj-...,sk-...), Anthropic (sk-ant-...).Slack Tokens: Bot, user, and app tokens (
xoxb-...,xoxp-...).Database Connection URIs: PostgreSQL, MySQL, MongoDB, Redis URIs with embedded passwords.
Bearer & JWT Tokens: RFC 7519 3-segment base64url JSON Web Tokens.
๐ 16-Language Ultra-Polyglot AST Engine (v2.3.0)
smart-context-packer v2.3 expands beyond the JavaScript ecosystem into enterprise-grade multi-language AST import resolution, symbol extraction, and skeletonization across 16 programming languages:
Language | Extensions | Manifest File | Import & Module Resolver | Skeleton Signature Support |
TypeScript / JS |
|
| Static & dynamic imports, CommonJS | Functions, methods, classes, interfaces, types |
C# / .NET |
|
|
| Classes, interfaces, records, methods, properties |
Java |
|
|
| Classes, interfaces, methods, constructors |
Kotlin |
|
|
|
|
C / C++ |
|
|
| Functions, struct/class methods, signatures |
PHP |
|
|
|
|
Dart / Flutter |
|
|
| Functions, classes, mixins, widgets |
Swift |
|
|
|
|
Ruby |
|
|
|
|
Svelte |
|
|
| Script signatures, collapses template/styles |
Python |
|
|
|
|
Go |
|
| Single & multi-line |
|
Rust |
|
|
|
|
Vue 3 SFCs |
|
|
| Script signatures, collapses template/styles |
Lua / FiveM |
|
|
| Functions, local functions, module tables |
Prisma |
|
| Zero-hallucination model and enum relation extractor | Model definitions, relations, enum variants |
๐ฅ Blast-Radius & Impacted Test Analyzer (v2.0.0)
Inspired by tirth8205/code-review-graph, scp v2.0 eliminates fear of unexpected regression breakage during AI refactorings:
# Analyze impact, callers, and tests when editing auth.ts:
scp src/auth.ts -b -c
# Combine with git diff to score the risk of your uncommitted changes:
scp --diff -b -cRisk Scoring Formula & Levels:
LOW(0.0 - 3.5): Isolated changes or comprehensive test suite coverage with limited callers.MEDIUM(3.6 - 6.9): Moderate fan-in dependencies (1-3 callers) or untested utility modules.HIGH(7.0 - 10.0): Critical shared core modules with 4+ callers or zero matching test suites.
AI Context Injection:
When -b is enabled, scp injects a dedicated directive block into the AI prompt:
## ๐ฅ Blast-Radius & Impact Analysis
- **Target Files**: `src/services/auth.ts`
- **Risk Level**: `MEDIUM` (5.2/10)
- **Summary**: โ ๏ธ MODERATE RISK: 2 callers impacted. 1 test file covers this scope.
- **Impacted Callers (Fan-in)**:
- `src/controllers/login.ts`
- `src/server.ts`
- **Impacted Unit Tests**:
- `tests/auth.test.ts`โก Incremental SHA-256 AST Cache (v2.0.0)
Parsing hundreds of TypeScript and Vue files repeatedly slows down interactive developer loops. scp v2.0 introduces a zero-dependency local disk cache stored in .scp/cache.json:
# Normal runs use the incremental cache automatically:
scp src/index.ts -c
# Bypass the cache:
scp src/index.ts --no-cache -c
# Purge the local cache:
scp --clear-cacheTwo-tier validation: First validates file
mtimeMsandfileSize(instant sub-millisecond check). If modified, computescrypto.createHash('sha256')to check if contents actually changed.Stored metadata: Caches raw imports, line/token stats, and exported symbol lists (
exportedSymbols).Zero Bloat: No SQLite binaries, no native C++ bindings, no ChromaDB. Pure Node.js JSON storage.
๐ง File-Linked Persistent Project Memory (v2.0.0)
Inspired by mem0, scp v2.0 provides cross-session architectural retention stored directly in .scp/memory.json (git-tracked so your entire team and AI agents benefit):
# Save an architectural decision or gotcha linked to a file pattern:
scp --add-memory "src/mcp.ts:Never log to stdout in stdio MCP mode to prevent JSON-RPC corruption"
scp --add-memory "src/auth/**:Always verify JWT expiration against UTC server time"
# List all stored project memories:
scp --list-memoryAutomatic Context Injection:
Whenever files matching pattern globs are packed (either via CLI scp, VS Code tasks, or MCP tool calls), their linked memories are automatically attached to the AI prompt:
## ๐ง Persistent Project Memory (.scp/memory.json)
- **GOTCHA** (`src/mcp.ts`): Never log to stdout in stdio MCP mode to prevent JSON-RPC corruption๐ 4-Layer Progressive Disclosure MCP Engine (v2.3.0)
Inspired by claude-mem and modern agentic architectures, scp v2.3 organizes 15 native MCP tools into 4 progressive disclosure layers so autonomous AI agents never exhaust context windows:
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ Layer 1: Index & Discovery (~50t compact index, BM25, Repo-Map) โ
โ search_codebase_index | search_codebase_intent | generate_repo_map โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโฌโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โผ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ Layer 2: Topology & Architecture (Imports, Visualizer, Manifests) โ
โ inspect_dependency_graph | generate_visualizer | framework_manifest โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโฌโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โผ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ Layer 3: Slicing & Context Packing (Budget-Optimized Slices & Diffs) โ
โ pack_context | pack_git_diff โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโฌโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โผ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ Layer 4: Surgical Fetch & Verification (<200t Symbols, Tests, Leaks) โ
โ extract_symbol_definition | get_impacted_tests | audit_context_leak โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโLayer 1 (Discovery & Index):
search_codebase_index: Cheaply inspect workspace files, sizes, and exported symbols (~50 tokens per file).search_codebase_intent: Natural-language BM25 semantic intent ranking matching identifiers and stems.generate_repo_map: PageRank architectural bird's-eye map fitting within a strict token budget.
Layer 2 (Topology & Architecture):
inspect_dependency_graph: Inspect imports, exports, circular cycles, and risk scores without file bodies.generate_visualizer: Interactive offline HTML force-directed canvas report.get_framework_manifest: Grounded workspace dependencies across 12 manifest formats.
Layer 3 (Context Slicing):
pack_context: Package full or skeletonized file bodies with automatic token-budget optimizer.pack_git_diff: Package uncommitted working tree or staged Git modifications and diff patch.
Layer 4 (Surgical Extraction & Auditing):
extract_symbol_definition: Surgically extract exact function, class, or struct definitions in <200 tokens.get_impacted_tests: Locate all unit tests covering modified targets via reverse graph traversal.audit_context_leak: Scan prompt text or files for accidental secret or credential leaks.
Ops & Cross-Session Memory:
manage_task_context: Crash-proof implementation plans and progress checklists (.scp/tasks.json).sandbox_tool_output: Compress noisy test and linter outputs by 80-95%.save_project_memory&query_project_memory: Persistent cross-session architectural rules (.scp/memory.json).
๐ฏ Auto Token-Budget Optimizer (v1.3.0)
Context limits (or expensive inference costs) often require fitting within a precise token budget. Instead of manually guessing whether to include dependencies or strip function bodies, use --max-tokens:
# Automatically skeletonize dependencies if total pack exceeds 4,000 tokens:
scp src/server.ts -m 4000 -cHow It Works:
scpanalyzes the full dependency graph and calculates the estimated tokens for all nodes.If total tokens exceed
maxTokens:It leaves depth 0 target files intact (preserving all implementation details for files you are actively editing).
It sorts non-target dependency files starting from the highest dependency depth (depth 3, then depth 2, then depth 1) and by largest token size.
It progressively converts these dependency nodes into skeleton type signatures until the total estimated tokens fall within
maxTokens.
The terminal summary reports
Budget Optimized: โand shows the exact tokens saved (Budget Saved: X tokens).
๐ค Universal AI Agent Presets (v2.3.0)
Stop running manual CLI commands every time you chat with an AI assistant. With one command, configure your AI coding assistants to automatically engineer their own context:
# Generate all 12 agent presets at once:
scp --init-agent
# Or target specific assistants:
scp --init-agent opencode
scp --init-agent codex
scp --init-agent continue
scp --init-agent zed
scp --init-agent clinerules
scp --init-agent aider
scp --init-agent jetbrainsSupported AI Agent Presets:
Preset | Target Files Generated | Configured Agent Directive |
| All 12 configuration files below | Full cross-platform autonomous context directives |
|
| Cursor Composer & Agent MCP orchestration |
|
| Claude Desktop, Claude CLI & Coworker loops |
|
| GitHub Copilot Chat in VS Code / Visual Studio |
|
| Windsurf Cascade autonomous coding engine |
|
| Google Antigravity IDE, agentic CLI pipelines |
|
| OpenCode open-source terminal agent |
|
| OpenAI Codex CLI & autonomous execution loops |
|
| Continue.dev open-source VS Code / JetBrains extension |
|
| Zed High-Performance Editor AI Assistant & Context Servers |
|
| Cline & Roo Code VS Code Autonomous Coding Extensions |
|
| Aider AI Pair Programming CLI |
|
| JetBrains AI Assistant (IntelliJ, PyCharm, WebStorm, Rider) |
Autonomous Agent Behavior:
Once initialized, any of your AI assistants will automatically:
Autonomously invoke
inspect_dependency_graphbefore proposing file modifications.Call
pack_contextwith optimal depth and token budgets instead of dumping raw directories.Call
pack_git_diffto review your uncommitted working tree and staged patches.Call surgical Layer 4 tools (
extract_symbol_definition,get_impacted_tests,audit_context_leak) to verify changes without burning tokens.
๐ฟ Git Diff & Working Tree Resolver (v1.2.0)
When you are fixing a bug or building a feature, you usually want the AI to understand what you've modified and how those changes impact adjacent modules.
Using --diff or --staged:
scpautomatically runsgit diff --name-onlyandgit status --porcelainto identify changed, added, or untracked files.It feeds those files as root targets into the
DependencyGraphengine, automatically bundling all imported modules and type definitions.It appends a clean unified patch block under
## Git Diff Patch:
## Git Diff Patch
```diff
diff --git a/src/auth/service.ts b/src/auth/service.ts
--- a/src/auth/service.ts
+++ b/src/auth/service.ts
@@ -12,4 +12,6 @@
+export function verifySessionToken(token: string): boolean {
+ return token.startsWith("sess_");
+}
### Usage Examples:
```bash
# Pack all uncommitted working tree changes + dependencies + unified diff:
scp --diff -c
# Pack staged changes only:
scp --staged -c
# Combine specific entry files with git diff:
scp src/index.ts --diff -c๐๏ธ Smart Prisma Schema Model Extractor (v1.2.0)
In enterprise TypeScript projects using Prisma, prisma/schema.prisma can easily exceed 2,000 lines of database models. Dumping the entire schema wastes thousands of tokens on irrelevant tables.
smart-context-packer introduces Zero-Hallucination Prisma Extraction:
It automatically inspects every packed file for imports of
@prisma/clientor references likeprisma.user.findManyordb.order.create.It locates
prisma/schema.prisma(or./schema.prisma) in the workspace.It parses all
model <Name> { ... }andenum <Name> { ... }blocks.It extracts ONLY the referenced models/enums, plus their direct 1-level relational models (e.g., if
UserreferencesPostandProfile, those models are also included).It injects a clean virtual file block into the prompt:
// prisma/schema.prisma [Extracted Models]
model User {
id String @id @default(cuid())
email String @unique
role Role @default(USER)
posts Post[]
}
model Post {
id String @id @default(cuid())
title String
authorId String
author User @relation(fields: [authorId], references: [id])
}
enum Role {
USER
ADMIN
}๐ Model Context Protocol (MCP) Server (v2.3.0)
smart-context-packer includes a built-in, zero-dependency JSON-RPC 2.0 Model Context Protocol (MCP) server running over stdio with 15 native tools organized across 4 progressive disclosure layers. AI IDEs and autonomous coding agents can invoke scp as a native tool without any external wrappers.
Launch manually:
scp --mcpAI Client Configuration
Claude Desktop (claude_desktop_config.json)
{
"mcpServers": {
"smart-context-packer": {
"command": "npx",
"args": ["-y", "smart-context-packer", "--mcp"]
}
}
}Cursor (.cursor/mcp.json) / Antigravity (mcp_config.json) / Windsurf / Cline / OpenCode
{
"mcpServers": {
"smart-context-packer": {
"command": "npx",
"args": ["-y", "smart-context-packer", "--mcp"]
}
}
}๐ ๏ธ Exposed MCP Tools Suite (15 Native Tools)
Layer | Tool | Parameters | Description |
Layer 1 (Index) |
|
| Compact ~50-token index of workspace files and exported symbols without loading file contents. |
Layer 1 (Intent) |
|
| Fast in-memory BM25 semantic intent ranking matching file paths, symbols, and code stems. |
Layer 1 (RepoMap) |
|
| PageRank-based bird's-eye architectural repo-map fitting within a strict token budget. |
Layer 2 (Topology) |
|
| Analyzes module imports/exports and returns ASCII hierarchy tree, dependency map, and risk scoring without file bodies. |
Layer 2 (Visualizer) |
|
| Generates self-contained interactive offline HTML canvas visualizer with force graph and risk heatmap. |
Layer 2 (Manifest) |
|
| Extracts active project dependencies & frameworks with exact versions across 12 manifest formats ( |
Layer 3 (Pack) |
|
| Packages target files, local dependencies, auto token-budget optimizer, active task context, and framework manifests. |
Layer 3 (Git) |
|
| Packages uncommitted working-tree or staged git modifications, unified diff patch, and surrounding dependency graph. |
Layer 4 (Surgical) |
|
| Surgically extracts the exact definition of a function, class, interface, type, or struct in <200 tokens without loading full files. |
Layer 4 (Impact) |
|
| Performs reverse call-graph analysis to locate every unit test suite covering modified target files. |
Layer 4 (Audit) |
|
| Scans prompt text or files for accidental secret, API key, JWT, or credential leaks before transmitting to LLMs. |
Ops & Tasks |
|
| Manages crash-proof active task context, tracking multi-step implementation plans and progress checklists in |
Ops & Logs |
|
| Compresses massive noisy tool outputs (tests, linters, build logs, stack traces) by 80-95% while keeping root causes and failures. |
Memory |
|
| Saves persistent architectural rule, bug pattern, or invariant to |
Memory |
|
| Retrieves project memories matching query or category to prevent repeated agent mistakes. |
๐ป VS Code & AI IDE Tasks Generator (v1.2.0)
Integrate scp directly into your daily IDE workflow with zero manual JSON writing:
scp --init-vscodeThis creates or safely merges into .vscode/tasks.json with three ready-to-run tasks. Open the Command Palette (Ctrl+Shift+P on Windows/Linux, Cmd+Shift+P on macOS) and run Tasks: Run Task:
SCP: Pack Active File + Dependencies (Copy to Clipboard)Runsnpx scp ${relativeFile} --copyon whichever file tab is currently active.SCP: Pack Active File (Skeleton Mode -> Clipboard)Runsnpx scp ${relativeFile} --skeleton --copyfor ultra-compact signature-only packing.SCP: Pack Git Diff + Dependencies (Copy to Clipboard)Runsnpx scp --diff --copyto bundle all current unstaged/uncommitted changes and copy to clipboard.
๐ Token Economy Benchmarks
Project Type | Target File | Full Repo Dump |
|
| Token Savings |
Next.js Full-Stack App |
| 84,200 tokens | 4,310 tokens | 1,850 tokens | 97.8% |
Vue 3 Dashboard |
| 56,100 tokens | 3,890 tokens | 1,420 tokens | 97.4% |
FiveM Game Resource |
| 31,500 tokens | 2,740 tokens | 1,190 tokens | 96.2% |
Node.js Microservice |
| 42,900 tokens | 2,150 tokens | 980 tokens | 97.7% |
๐ ๏ธ CLI Usage & Flags
scp [options] [targets...]Note:
targetsare optional when using--diff,--staged,--mcp, or--init-vscode.
Options Reference
Flag | Shorthand | Description | Default |
|
| Track active task & generate prompt checklist directive with BM25 seed discovery | |
| List recorded tasks and checklist items stored in |
| |
| Mark a task or checklist item index completed | ||
| Execute shell command and compress test/linter/build output by 80-95% | ||
| Exclude external framework dependencies manifest header from output |
| |
|
| In-memory BM25 semantic intent routing to auto-discover seed files | |
| Generate PageRank architectural repo-map (token budget default: 1024) |
| |
| Generate interactive offline HTML canvas visualizer report |
| |
| Discover all uncommitted modified/untracked files as targets & include diff patch |
| |
| Discover staged files as targets & include staged diff patch |
| |
| Pack files modified in a specific Git commit, branch, or range (e.g. | ||
| Pack files modified in a Pull Request number, URL, or branch | ||
| Prune unreferenced exported symbols from dependencies (AST Dead-Code Slicing) |
| |
|
| Watch packed files and dependencies for changes and live-reload context pack |
|
|
| Trace callers, identify unit tests, and compute 0-10 Risk Score |
|
|
| Auto-skeletonize dependencies from deepest depth to fit token budget | |
| Disable SHA-256 AST local disk caching |
| |
| Purge local |
| |
| Save persistent project memory note linked to file pattern | ||
| List all persistent project memories stored in |
| |
| Universal multi-agent rule setup ( |
| |
| Generate or update |
| |
| Start native JSON-RPC 2.0 Model Context Protocol (MCP) stdio server (15 tools) |
| |
|
| Dependency traversal depth ( |
|
|
| Discover workspace files that import the target file |
|
|
| Strip function bodies of dependencies to type signatures |
|
|
| Output format: Markdown or structured XML |
|
|
| Output file destination path |
|
|
| Copy packed prompt directly to system clipboard |
|
| Stream packed prompt directly to standard output (for piping) |
| |
| Generate only hierarchy tree and dependency map without code bodies |
| |
| Disable automatic credential and secret redaction |
| |
|
| Suppress terminal summary report |
|
|
| Output version | |
|
| Display help screen |
Practical Examples
# 1. Daily Driver: Pack auth handler, copy to clipboard, and paste into ChatGPT
scp src/controllers/auth.ts -c
# 2. Maximum Token Efficiency: Depth 3 with Skeleton signatures
scp src/main.ts -d 3 -s -c
# 3. Review uncommitted git changes + dependencies before creating a PR
scp --diff -c
# 4. XML Mode for specialized LLMs / Claude artifacts
scp src/index.ts -f xml -o prompt.xml
# 5. Reverse Dependency Analysis: What files will be impacted if I edit utils.ts?
scp src/utils/formatters.ts --reverse -c
# 6. Pipe directly into another tool or CLI assistant
scp src/server.ts --stdout | claude๐ฎ FiveM & Game Scripting Support
smart-context-packer includes first-class support for Grand Theft Auto V / FiveM game server developers:
# Point directly to a resource's fxmanifest.lua:
scp resources/[gameplay]/banking/fxmanifest.lua -cscp automatically:
Parses
shared_scripts,client_scripts, andserver_scriptsarrays.Expands wildcards (e.g.
'client/**/*.lua','config.lua').Resolves internal Lua
require('utils.math')dot-notation paths.Masks sensitive database credentials in server configuration scripts.
๐ป Programmatic Library API
smart-context-packer is also an enterprise TypeScript library. Integrate it into VS Code extensions, MCP servers, or automated CI bots:
import { packContext, analyzeDependencies, formatContext } from 'smart-context-packer';
// 1. One-shot high-level packing (with git diff support)
const result = await packContext({
targets: ['src/index.ts'],
depth: 2,
skeleton: true,
diff: true,
copy: true,
output: '.context-pack.md',
});
console.log(`Packed ${result.graph.nodes.size} files.`);
console.log(`Estimated Tokens: ${result.stats.totalTokens}`);
// 2. Low-level dependency analysis
const graph = await analyzeDependencies(['src/services/payment.ts'], {
cwd: process.cwd(),
maxDepth: 3,
reverse: true,
});
for (const [filePath, node] of graph.nodes) {
console.log(`${filePath} (depth: ${node.depth}) imports:`, node.imports);
}๐ค OpenAI Open Source Grant Alignment
smart-context-packer was engineered from the ground up to advance the mission of open-source AI tooling:
Inference Compute Reduction: By filtering out irrelevant files and skeletonizing non-critical dependency bodies,
scpcuts prompt tokens by up to 97%. This drastically reduces global GPU compute and server energy requirements.Context Fidelity & Hallucination Suppression: AI assistants hallucinate when context boundaries are missing.
scpguarantees that every imported interface, type definition, and helper signature is present and verified.Developer Privacy & Safety: Native, zero-telemetry secret redaction ensures that credentials, access tokens, and sensitive private keys never cross network boundaries.
๐บ๏ธ Roadmap
TypeScript / JavaScript / TSX / JSX dependency resolver
Vue 3 Single File Component script parser
tsconfig.jsonpath alias resolver (@/*,~/*)FiveM
fxmanifest.luaand Luarequire()resolverFast BPE token counter & context window budget calculations
Automatic credential & secret redaction engine
Skeleton signature extraction mode (
--skeleton)Dual ESM/CJS library distribution with strict TypeScript types
Git working tree diff and staged context resolver (
--diff,--staged)Smart Prisma schema model & relation extractor (
prisma/schema.prisma)Official Model Context Protocol (MCP) server integration (
--mcp)VS Code Command Palette tasks generator (
--init-vscode)Auto Token-Budget Optimizer (
--max-tokens) with smart depth-descending skeletonizationBackground Agent Rule Generator (
--init-agentfor Cursor & Antigravity IDE)Autonomous
pack_git_diffMCP tool for working tree and staged diff inspectionIncremental SHA-256 AST local disk cache (
src/cache.ts)Blast-radius reverse caller & test impact risk scoring (
src/blast-radius.ts)File-linked persistent project memory (
src/memory.ts)3-Layer progressive disclosure MCP tool suite (
search_codebase_index,inspect_dependency_graph,pack_context,save_project_memory,query_project_memory)Python AST dependency analyzer (
import,from ... import)Go module and package resolver (
import,go.mod)Rust module and crate resolver (
mod,use crate::*)PageRank architectural repo-map generator (
--repo-map)In-memory BM25 semantic intent routing (
-i, --query)Offline zero-dependency HTML canvas visualizer (
--visualize)Universal Multi-Assistant Presets (
--init-agentfor 12 assistants)Crash-Proof Active Task & Planning Context Engine (
-t, --task,.scp/tasks.json)External Frameworks & Dependencies Manifest Grounding across 12 formats
Visual Context Budget HUD with ASCII gauges & category breakdown (
src/hud.ts)Tool Output Sandboxing & Compression (
--sandbox <cmd>, 80-95% token savings)Smart Middle-Out Slicing for massive files (>500 lines)
16-Language Ultra-Polyglot AST Support (C#, Java, Kotlin, C++, PHP, Dart, Swift, Ruby, Svelte, TS, Go, Rust, Python, Vue, Lua, Prisma)
Complete 15-Tool Model Context Protocol (MCP) Suite with Surgical Layer 4
Symbol-Level AST Tree-Shaking (
--tree-shake) for Dead-Code Slicing of dependenciesAutomatic Monorepo Workspace Package Resolution (
package.jsonworkspaces,pnpm-workspace.yaml,packages/*,apps/*)Git Commit Range & Pull Request Context Packing (
--commit,--pr)Live File System Watch Mode (
-w, --watch)Interactive VS Code extension with one-click "Pack Context" context menu
๐ License
Distributed under the MIT License. See LICENSE for details.
This server cannot be deployed
Maintenance
Related MCP Connectors
Codebase knowledge graph โ architectural awareness for AI coding agents via MCP
Codebase intelligence for agents: 152 structured artifacts across 21 programs, one call.
Deterministic context layer for your codebase: change impact, blast radius, answers with receipts.
Hosted code graph over MCP: exact callers, dependencies, and cross-repo blast radius for AI agents.
Related MCP Servers
- AlicenseNot gradedqualityDmaintenanceServes structured code context via MCP, enabling AI agents to understand codebases with dependency graphs and significantly reduce token usage.11 npm1MIT
- AlicenseNot gradedqualityCmaintenanceEnables AI coding agents to query a codebase as a knowledge graph, providing token-budgeted context, search, and impact analysis via MCP tools.33 PyPIMIT
- FlicenseNot gradedqualityCmaintenanceEnables LLMs to explore codebases structurally via MCP tools for outlines, function sources, imports, complexity, git changes, and dead code detection, reducing token usage by avoiding raw file ingestion.1-
- AlicenseNot gradedqualityBmaintenanceEnables AI agents to locally search, query, and understand codebases with token-efficient context, dependency graphs, history, architecture diagrams, and metrics through MCP.15 npm3MIT