
Smart Context Mcp
io.github.ArrayoPublished by GitHub account Arrayov1.21.0Updated Oct 24, 2026
Reduces AI agent token usage by 90% via context compression and task checkpoint persistence.
Overview
A local MCP server that compresses code context and saves task checkpoints so AI coding agents use fewer tokens across sessions.
- What you can do
- Read files in compressed modes (outline, signatures, single symbol, range) and batch-read several files at once, instead of loading full contents. Search code by intent with ranked, deduplicated results, and build a symbol index to improve ranking. Assemble task context in one call, including git diff-aware context and predicted files. Start and end work turns with checkpoint recovery of goal, status, decisions and next step, and inspect session status and token-savings metrics. Run allowlisted diagnostic shell commands, batch pattern edits with dry-run preview, function-level git blame, and cross-project symbol search.
- When to use it
- Useful for developers working on multi-file debugging, code review, refactoring, testing or architecture exploration in Cursor, Claude Desktop, Codex CLI or Qwen Code, where cutting token usage and resuming task state between sessions matters.
- Requirements
- Local Node.js process installed from the npm package smart-context-mcp, plus a one-time init step that writes client config and agent rule files into the project. An index build is required for good search and context quality. SQLite persistence is noted as needing Node 22 or later. No accounts, API keys or environment variables are declared.
Installation
In SourceWeft
- Open Smart Context Mcp in the dashboard and add it to a workspace.
- Enable the server for the chats that should use its tools.
Desktop only via STDIO. STDIO servers start a local process, so they need the SourceWeft desktop host.
Other MCP clients
Follow the launch instructions in the repository.
README
smart-context-mcp
MCP server that reduces AI agent token usage by up to 90% through intelligent context compression (measured on this project).
[Smart Context MCP on MCPRush]
What it is
An MCP (Model Context Protocol) server that provides specialized tools for reading, searching, and managing code context efficiently. Instead of loading full files or returning massive search results, it compresses information while preserving what matters for the task.
Real metrics from production use:
- ~7M tokens → ~800K tokens (approximately 89% reduction)
- 1,500+ operations tracked across development
- Compression ratios: 3x to 46x depending on tool
- Context overhead is tracked separately so reports can show gross and net savings
Workflow-level savings:
- Debugging: ~85-90% token reduction
- Code Review: ~85-90% token reduction
- Refactoring: ~85-90% token reduction
- Testing: ~85-90% token reduction
- Architecture: ~85-90% token reduction
Real adoption in non-trivial tasks:
- Approximately 70-75% of complex tasks use devctx tools
- Most used:
smart_read(850+ uses),smart_search(280+ uses),smart_shell(220+ uses) - Primary reasons for non-usage: task too simple, no index built, native tools preferred
See Workflow Metrics and Adoption Metrics for details.
Latest Release: 1.21.0
Minor release built around a semantic engine. MCP grows from 20 → 22 tools (smart_code + smart_output). SQLite schema bumps 8 → 9 (new outputs table; auto-migrates on first run). Zero new runtime dependencies — the TypeScript LanguageService comes from the typescript package you already have, and degrades to a fallback provider when it isn't there.
-
smart_code(new tool). Semantic code navigation for JS/TS via the TypeScript LanguageService, resolving by symbol name (plus optionalfilePath) instead of forcing you to know a line and column. Actions:definition,references,implementations,diagnostics,impact,rename. Returns compact locations (file + 1-based start/end), never full file bodies.includeTests=falsedrops test paths;maxResultscaps the payload. -
Impact analysis.
smart_code(action='impact')splits direct hits (semantic: definitions, references, implementations) from transitive files (import graph,maxHopsdefault 2) and related tests, plus coverage flags.risk.levelis labelledbasis: 'heuristic'and says so in its ownnote— it is a ranking aid, not semantic certainty. -
Scope-aware rename, dry run by default.
smart_code(action='rename')usesfindRenameLocationsanddryRun: trueis the default: the first call returns the planned per-file diff hunks (before/afterper line) and writes nothing. Error conflicts (invalid or reservednewName, same name, unresolved target, path escape, missing file, blast radius overmaxFiles) always block the write.name-collisionis a heuristic warning that only blocks withstrict: true, because the check doesn't verify scope overlap. After a real write,diagnosticsAfterreports remaining TypeScript errors in the touched files.smart_editremains the tool for non-semantic textual replacements. -
smart_output(new tool). Persistent output/artifact store (shell,test,build,lint,diff) so a stack trace from twenty turns ago is recoverable without rerunning the command. Actions:save,search,excerpt,summary,list,stats,prune. Content is scrubbed for likely secrets before persistence and truncated head+tail aboveDEVCTX_OUTPUT_MAX_BYTES(256KB) so the failing tail always survives. Retention viaDEVCTX_OUTPUT_RETENTION_DAYS(14) andDEVCTX_OUTPUT_MAX_PER_KIND(50). Identical output for the samekind+commandis deduped intorepeat_count. Automatic capture fromsmart_shell/smart_testis opt-in viaDEVCTX_OUTPUT_STORE=true(thensmart_shellreturns anoutputRef); explicitsave/searchalways work. Degrades withdegraded: trueinstead of throwing when SQLite is unavailable or locked. -
Opt-in semantic expansion in
smart_context.include: ['semantic']expands context through real definitions, references and implementations rather than text similarity, and every item gains awhyIncludedexplanation. Off by default until the precision@5 benchmark justifies otherwise. -
Richer ADR/spec awareness and graph paths carried over from the same roadmap: ADR sections are indexed as
kind='adr'/'adr-section', andsmart_contextcan return graph paths between two files or symbols. -
Shared
tokenBudgetacross tools.smart_read,smart_read_batch,smart_context,smart_turn(start+end) andsmart_resumenow accepttokenBudget: number | { id?, maxTokens, shared? }. Whenshared:true(oridset), the budget is reused across calls inside the same task — so a multi-step agent flow can stay under a hard token ceiling without per-call bookkeeping. Responses includetaskBudget,remainingBudget, andbudgetDetails(scope,actions, degraded mode) when the budget actually changed the output. -
smart_searchsearch modes. Newmode: 'needle' | 'balanced' | 'semantic'(defaultbalanced).needle= literal exact only (no regex / no term expansion) — kills noise on debug queries.balanced= exact + regex + term expansion.semantic= exact-first plus the local semantic block only when exact signal is weak. The previoussemantic: trueflag remains as a legacy alias formode: 'semantic'. DefaultmaxFilestightened 15 → 5. NewmaxTokenscaps the whole response and compacts intelligently (matches first, then diagnostics, then semantic block). Per-file ranking is now inspectable viamatchedBy,boostSource,scoreBreakdown,whyRanked. Response also returnshasMore/totalFiles/nextSuggestedMaxFilesand actionablesuggestionswhen the query is too broad or empty. -
smart_readpersistent cache + budget-awarefulldegradation. New SQLiteread_cachetable keyed by(filePath, mode, selector, content_hash). Second read of an unchanged file is virtually free. Modefullis now an explicit last resort: if atokenBudget/maxTokensis set, it degrades to lighter modes first (outline → signatures → truncated) and reports the real mode used infullMode+budgetDetails. NewclearReadCachePersistent+ GC integration inrunStorageMaintenance. -
smart_turnsimple-task skip heuristic. When the prompt is short (≤ 40 chars after normalization), classified as a simple task, and no session/task is pinned,smart_turn(start)now returnsskipSmartTurn: truewithrecommendedPath.mode='simple_task_skip'instead of paying the full orchestration cost. Saves continuity-resolution overhead on trivial prompts.minimalverbosity additionally compacts summary/refreshedContext to the fields agents actually consume. -
global_memorynoise hints. Per-project, scrubbed noise telemetry persisted to~/.devctx/global.db(noise_hintstable). New actionsnoise_statsandnoise_reset(full or viaquery). Letssmart_searchlearn which queries the agent already discovered to be noisy in a given repo and adjust ranking, without ever leaking content. -
KPI baseline infrastructure. New scripts
evals/kpi-baseline.js+evals/kpi-utils.jsaggregateharness.jsandrealworld-eval.jsruns into a single JSON snapshot with top-5 precision, recall, reread task/call rate, and per-task-size buckets (short / long). Persistskpi-baseline-latest.jsonfor regression detection across releases. New test suitetests/eval-kpis.test.js.
Highlights from 1.20.0 (still current)
Same tool count as 1.19.0, but several tools gained hard token-budget control, search-mode discipline and second-read cache reuse.
- Shared
tokenBudgetacross tools.smart_read,smart_read_batch,smart_context,smart_turnandsmart_resumeaccepttokenBudget: number | { id?, maxTokens, shared? }, reusable across calls inside one task so a multi-step flow stays under a hard ceiling. smart_searchmodes.mode: 'needle' | 'balanced' | 'semantic'(defaultbalanced),maxTokenscapping the whole response, and inspectable ranking viamatchedBy/scoreBreakdown/whyRanked.smart_readpersistent cache. SQLiteread_cachekeyed by(filePath, mode, selector, content_hash); a second read of an unchanged file is virtually free. Modefulldegrades to lighter modes under a budget and reports the real mode used.smart_turnsimple-task skip on short trivial prompts, andglobal_memorynoise hints that letsmart_searchlearn which queries proved noisy per repo.- KPI baseline infrastructure (
evals/kpi-baseline.js) snapshotting precision@5, recall, reread rate and latency for regression detection.
Highlights from 1.19.0
Five-step quality jump executed as sequential commits with full dogfooding. MCP grew from 18 → 20 tools, +68 tests, zero new dependencies.
smart_playbook(new tool). Declarative composite workflows that run multiplesmart_*tools in a single MCP call. Five built-in playbooks ship with the package:preflight-merge(review + affected tests + checkpoint),debug-flake(last failure + curated debug context + affected),refactor-safe(curated context + affected + checkpoint),doc-sync(ADR search + docs context),ramp-up(status + doctor + ADR overview). Project-level overrides via.devctx/playbooks/*.{yaml,json}with{{args.X}}interpolation,when/label/stopOnFail/dryRun. Tool allowlist restricted tosmart_*. Zero deps: built-in minimal YAML parser.- Reactive FS watcher for the index.
fs.watch(native, recursive, debounced 600ms + batch flush every 2s) keeps the symbol index hot between calls. Filters.git,node_modules,.devctx,dist,build, lockfiles,.min.*,.map,.snap, and non-indexable extensions. Stats surface insmart_status(enabled,flushes,eventsObserved,filesReindexed,filesRemoved,errors,lastFlushAt,pending). Opt-out viaDEVCTX_WATCH_INDEX=false. Wired to MCP shutdown for clean close + final flush. - Richer Python / Go parsers + pluggable parser registry. Python now captures decorators (
decorators: ["dataclass", ...]),async def(kindsasync-function/async-method),TypeAliasandTypeVar/NewType/ParamSpec/TypeVarTupleaskind="type", and respects class indent for accurate scope. Go now captures methods with receiver type asparent, interfaces askind="interface", top-levelconst/var.src/parsers/registry.jsexposesregisterParser/getParserso future tree-sitter parsers can plug in without touchingindex.js.INDEX_VERSIONbumped 6 → 7 (auto-reindex). - Local semantic re-rank on
smart_search. Opt-insemantic: true(withsemanticLimit) returns asemantic: { embedder, symbols[], files[] }block ranked by hashing/TF-IDF embeddings (256-dim, FNV-1a buckets, L2-normalized, cosine similarity, <5ms). Default behavior unchanged. Pluggable embedder interface (id,dimensions,embed,similarity) ready to swap in ONNX/transformers without touching callers. global_memory(new tool, opt-in). Cross-project memory persisted to~/.devctx/global.db(override viaDEVCTX_GLOBAL_DB, gated byDEVCTX_GLOBAL_MEMORY=true). Stores canonical decisions, recurring patterns, playbook drafts, and notes across repos. Content scrubbed for likely API keys / bearer tokens / JWT / PEM private keys / AWS / OpenAI / GitHub / Slack / Google API / DB URLs / emails / home paths before persistence. Project paths stored as FNV-1a hash, not raw path. Recall uses the local hashing/TF-IDF embedder for semantic ranking.
See CHANGELOG.md for the full v1.21.0 + v1.20.0 entries.
See CHANGELOG.md for full release history.
When to Use (and When Not To)
Use devctx when:
- You're exploring an unfamiliar codebase
- The task spans multiple sessions (checkpoints save context)
- You need to understand how files relate to each other (graph/imports)
- The context is too large to manage manually
- You're doing complex multi-file refactors or debugging across layers
Skip devctx when:
- You already know exactly which files to touch
- It's a single-file or surgical change (2-3 edits max)
- You have the full mental map from a recent exploration
- Native tools (Grep, Read, StrReplace) are more direct for the task
Honest verdict from real users:
"The MCP shines in long, multi-session tasks or when you don't know the codebase. For contained refactors where you already know what to touch, native tools are just as fast or faster. The real value was
smart_read(outline)for the initial analysis and checkpoints to not lose the thread between sessions."
The 90% token savings are real, but they require the right task type to materialize.
Why it exists
AI agents waste tokens in three ways:
- Reading full files when they only need structure or specific functions
- Massive search results with hundreds of irrelevant matches
- Repeating context across conversation turns
This MCP solves all three by providing tools that return compressed, ranked, and cached context.
🚨 Agent Ignored devctx? → Paste This Next
When to use: Agent read large files with Read, used Grep repeatedly, or you see no devctx tools in a complex task.
Why this happens: Task seemed simple, no index built, native tools appeared more direct, or rules weren't strong enough.
Quick Start: Which Client Should I Use?
🎯 Best Default: Cursor
Use if: You work in Cursor IDE and want the best balance of guidance and flexibility.
Workflow:
Automaticity: Medium by default. Medium-High if you use the assisted launcher ./.devctx/bin/cursor-devctx for task-runner workflows.
🔄 Best Continuity: Claude Desktop
Use if: You want highest session continuity with automatic context recovery.
Workflow:
Automaticity: High (with hooks) - Can auto-trigger smart_turn on session start/end.
💻 Best Terminal: Codex CLI / Qwen Code
Use if: You prefer terminal-based workflows or scripting.
Workflow:
Automaticity: Low-Medium - Rules are visible but require explicit prompting.
📊 Quick Comparison
Important: Agent always decides whether to use devctx. Rules increase probability, but don't guarantee it.
If you want a more repeatable path: use the task runner or the assisted launcher instead of relying on rules alone. See Task Runner Workflows.
📖 Full setup: Client Compatibility
🚀 How to Invoke the MCP
Key point: The MCP doesn't intercept prompts automatically. You need to tell the agent to use it.
1️⃣ Use MCP Prompts (Easiest - Cursor only)
Other prompts:
/prompt devctx-workflow- Full workflow/prompt devctx-preflight- Build index + start session
2️⃣ Explicit Instruction (Any client)
For a more guided CLI path:
3️⃣ Automatic via Rules (Not guaranteed)
Agent should use devctx for complex tasks if rules are active:
- Cursor:
.cursorrules - Claude Desktop:
CLAUDE.md - Others:
AGENTS.md
But: Agent decides based on task complexity.
⚡ Quick Reference
Recommended Workflow
✅ Setup Checklist (First Time in Project)
Before starting complex tasks, ensure:
Copy-paste to agent (first time):
⚠️ Why Index Matters
Without index:
- ❌
smart_searchreturns unranked results - ❌
smart_contextcan't build optimal context - ❌ Agent may prefer native tools → no savings
With index:
- ✅
smart_searchranks by relevance - ✅
smart_contextincludes related files - ✅ 90% token savings enabled
When to rebuild:
- ✅ First time in project
- ✅ After major refactors (file moves, renames)
- ✅ After adding many new files
- ❌ Not needed every session (index persists in
.devctx/)
The Entry Point: smart_turn(start)
For non-trivial tasks (debugging, review, refactor, testing, architecture), the optimal flow is:
Why start with smart_turn?
- ✅ Recovers previous task checkpoint (goal, status, decisions)
- ✅ Classifies task continuation vs new task
- ✅ Provides repo safety check
- ✅ Enables task recovery if interrupted
- ✅ Tracks metrics for optimization
When to skip smart_turn:
- ❌ Trivial tasks (read single file, simple search)
- ❌ One-off questions (no continuity needed)
- ❌ Quick diagnostics (no session context)
The Product Entry Point: smart-context-task
If you want the same lifecycle packaged into named workflows, use the task runner:
This layer runs the same smart_turn(start) / context / checkpoint flow, but adds:
- workflow-specific preflight (
smart_contextorsmart_search) - continuity-aware prompt guidance
- blocked-state routing to
smart_doctor - measured
task_runnerquality signals
For the full command set and client-specific usage, see Task Runner Workflows.
How it Works in Practice
The Reality
This MCP does not intercept your prompts magically. Here's what actually happens:
- You write a prompt: "Fix the login bug"
- Agent reads rules: Sees debugging workflow suggestion
- Agent decides: "This is a debugging task, I'll start with
smart_turn(start)" - Agent calls:
smart_turn({ phase: 'start', userPrompt: '...', ensureSession: true }) - MCP returns: Previous task checkpoint (if exists) + repo safety check
- Agent continues: Calls
smart_search(intent=debug)for error location - Agent reads: Calls
smart_read(mode=symbol)for specific function - Agent fixes bug: Makes changes
- Agent verifies: Calls
smart_shell('npm test') - Agent checkpoints: Calls
smart_turn(end)to persist progress
Key points:
- ✅ Agent chooses to use devctx tools (not forced)
- ✅ Rules guide the agent (not enforce)
- ✅
smart_turn(start)is recommended entry point for non-trivial tasks - ✅ Agent can skip workflow for trivial tasks
- ✅ You control nothing directly—the agent decides
What You Get
Tools (22): Efficient alternatives to built-in operations
smart_read/smart_read_batch- Compressed file reading (outline, signatures, symbol, explain)smart_search- Intent-aware code search with ranking, ADR filtering, and opt-in semantic re-ranksmart_context- One-call context builder with graph +paths: { from, to }traversalsmart_test- Affected tests via graph + sandboxed runner + persistedlast_failuresmart_review- Code review preflight: diff + callers + heuristic findingssmart_code- Semantic navigation by symbol name: definition, references, implementations, diagnostics, impact, dry-run renamesmart_output- Persistent output store (shell/test/build/lint/diff): search, excerpt, summary without rerunningsmart_playbook- Declarative composite workflows (5 built-in: preflight-merge, debug-flake, refactor-safe, doc-sync, ramp-up)smart_shell- Safe diagnostic commands (TAP/git-log/diff compression)smart_turn/smart_resume- Session persistence +nextActions[]machine-readable plansmart_summary/smart_status/smart_doctor/smart_metrics/smart_editglobal_memory- Opt-in cross-project memory in~/.devctx/global.db(scrubbed, semantic recall)build_index/warm_cache/git_blame/cross_project
Rules (5 profiles): Task-specific workflows
- Debugging: Error-first, symbol-focused
- Code Review: Diff-aware, API-focused
- Refactoring: Graph-aware, test-verified
- Testing: Coverage-aware, TDD-friendly
- Architecture: Index-first, minimal-detail
Storage (.devctx/): Local context database
index.json- Symbol index (functions, classes, imports, ADRs, sections) —INDEX_VERSION 7state.sqlite- Sessions, metrics, patterns, task handoffs, test failures, explain/read caches, persisted outputs (Node 22+,node:sqlite, schema 9)metrics.jsonl- Opt-in legacy file, only whenDEVCTX_METRICS_FILE=path.jsonlis set~/.devctx/global.db- Cross-project memory (opt-in viaDEVCTX_GLOBAL_MEMORY=true)
Persistent Task Context (When Supported)
What gets persisted:
- Task checkpoints (goal, status, decisions, blockers)
- File access patterns (for prediction)
- Token metrics (for optimization)
- Session summaries (~100 tokens compressed)
When it's consulted:
- Agent calls
smart_turn(start)- Recovers task checkpoint - Agent calls
smart_context- Uses patterns for prediction - Agent calls
smart_summary- Gets task summary
What is NOT persisted:
- ❌ Full conversation transcript
- ❌ Complete message history
- ❌ Agent reasoning or thoughts
- ❌ User prompts verbatim
Limitations:
- Only works if agent calls
smart_turn(not automatic) - Only persists within project (
.devctx/is local) - Only recovers if session ID matches (manual or auto)
- Client must support MCP (Cursor, Codex, Claude Desktop, Qwen)
Honest truth: Task context persistence is opt-in via agent behavior, not automatic via client interception.
What This Means for You
Best case scenario:
- Agent follows rules consistently
- Uses devctx tools for 50-80% of operations
- Token usage drops 85-90% (proven, measured)
- Responses often faster due to less data to process (inferred from token savings)
Typical scenario:
- Agent uses devctx tools for complex tasks
- Uses built-in tools for simple tasks
- Token usage drops 60-80%
- Noticeable improvement in efficiency
Worst case scenario:
- Agent ignores rules (rare but possible)
- Uses built-in tools exclusively
- Token usage unchanged
- No harm done (MCP is passive)
You can check: npm run report:metrics shows actual tool usage and measured smart_turn quality signals.
What "Better Context" Means
What we improve:
- ✅ Context relevance (right files for the task)
- ✅ Signal-to-noise ratio (less boilerplate, more signal)
- ✅ Context efficiency (more relevant info in less space)
- ✅ Response speed (less data to process)
What we don't guarantee:
- ❌ Agent will always be correct
- ❌ Responses will be perfect
- ❌ Tasks will always succeed
- ❌ Responses will be "more accurate" (accuracy depends on agent, not just context)
The benefit: Agents work with better input, but output quality still depends on agent capability and task complexity.
Honest claim: We provide better context (more relevant, less noise), which can help agents respond more efficiently in complex tasks when the workflow is followed.
What's proven: 90% token savings (measured across 3,666 operations).
What's inferred: Quality improvement (better input → potentially better output, but not explicitly measured).
What we don't control: Agent correctness, task success, response accuracy.
Workflow Examples
Debugging
Token usage: 150K → 15K (90% savings)
Code Review
Token usage: 200K → 25K (87% savings)
Refactoring
Token usage: 180K → 20K (89% savings)
Testing
Token usage: 120K → 12K (90% savings)
Architecture Exploration
Token usage: 300K → 30K (90% savings)
Core Tools
These are the essential tools you should understand first:
smart_read
Read files in compressed modes instead of loading full content.
Modes: outline, signatures, symbol, range, full
When to use: Any time you need to understand file structure without reading everything.
smart_search
Intent-aware code search with ranked, deduplicated results and index boosting.
Intents: implementation, debug, tests, config, docs, explore
Best for: Finding symbol definitions/usages, understanding call chains, locating implementations.
NOT ideal for: Exact string matching (use Grep), finding files by name (use Glob), broad multi-word queries (generates noise — results include a hint when >30 files match).
smart_context
One-call context builder: search + read + graph expansion.
Returns relevant files with compressed content, symbol details, and relationship graph.
Smart pattern detection: Automatically detects literal patterns in your task (TODO, FIXME, /**, console.log, debugger) and prioritizes them in search results.
When to use: Starting a new task and need comprehensive context.
build_index
Build a symbol index for the project (functions, classes, imports).
When to use: Once after checkout, or after major changes. Improves search ranking and context relevance.
smart_metrics
Inspect token savings and usage statistics.
When to use: Verify the MCP is working and see actual savings.
Advanced Tools
These tools provide specialized capabilities for specific workflows:
smart_summary
Maintain compressed task state across sessions.
Compresses task context to ~100 tokens (goal, status, decisions, blockers). Critical for long tasks. Supports both flat and nested formats.
When git hygiene or SQLite health affects local state, responses also surface mutationSafety, repoSafety, degradedMode, and storageHealth.
smart_doctor
Run one operational preflight across repo hygiene, SQLite health, compaction, and legacy cleanup.
Use this before release, after long-lived local usage, or whenever .devctx/state.sqlite looks suspicious.
smart_status
Display current session context with progress visibility.
Shows goal, status, recent decisions, touched files, pinned context, and progress stats. Updates automatically with each MCP operation.
When repo safety or SQLite health affects state, smart_status stays useful via degraded mode and surfaces storageHealth plus the same mutationSafety contract as smart_turn.
smart_edit
Batch edit multiple files with pattern replacement.
Supports dryRun: true for preview. Useful for bulk refactoring, removing patterns, or renaming across files.
smart_turn
Orchestrate turn start/end with automatic task checkpoint recovery.
Recovers task state (goal, status, decisions, next step), not full conversation history.
smart_read_batch
Read multiple files in one call.
Reduces round-trip latency when you know you need several files.
smart_shell
Safe diagnostic command execution (allowlisted commands only).
Blocks shell operators and unsafe commands by design.
Diff-Aware Context
Analyze git changes intelligently (part of smart_context):
Returns changed files prioritized by impact + related files (tests, importers).
Context Prediction
Learn from usage patterns and predict needed files (part of smart_context):
After 3+ similar tasks: 40-60% fewer round-trips, 15-20% additional savings.
warm_cache
Preload frequently accessed files into OS cache.
First query: 250ms → 50ms (5x faster cold start).
git_blame
Function-level code attribution.
cross_project
Share context across monorepos and microservices.
Requires .devctx-projects.json config file.
Client Compatibility
Legend:
- 🟢 High: Hooks can auto-trigger tools at specific moments
- 🟡 Medium/Low: Agent reads rules and decides when to use tools
- ✅ Supported | ⚠️ Partial | ❌ Not supported
What "Near-Automatic" Means
🟢 High (Claude Desktop with hooks):
- Hooks can auto-trigger
smart_turn(start)when you start a session - Hooks can auto-checkpoint after significant tool use
- Agent still decides which devctx tools to use for each task
- This is the closest to "automatic" behavior available
🟡 Medium (Cursor):
- Agent reads base rules automatically (always active, 150 tokens)
- Conditional profiles activate based on file globs (debugging, review, etc.)
- Agent decides when to use devctx tools based on task
- Agent must manually call
smart_turn(not auto-triggered)
🟡 Low-Medium (Codex, Qwen):
- Agent reads embedded rules automatically (always active, 200 tokens)
- Agent decides when to use devctx tools based on task
- Agent must manually call
smart_turn(not auto-triggered) - No conditional activation or hooks
What "Near-Automatic" Does NOT Mean
❌ Not automatic prompt interception - MCP cannot intercept or modify your prompts before the agent sees them
❌ Not forced tool usage - Agent always has autonomy to decide which tools to use
❌ Not guaranteed workflow - Agent may skip devctx tools for simple tasks (this is fine)
❌ Not client-level magic - Behavior depends on agent following rules and making good decisions
The Reality
All clients work the same way:
- Agent reads rules (guidance about when devctx tools are useful)
- Agent decides tool usage (autonomy to choose best approach)
- MCP provides tools (passive, only responds when called)
- You verify with metrics (
npm run report:metrics)
The differences:
- Hooks (Claude Desktop) can auto-trigger specific tools at specific moments (e.g.,
smart_turn(start)on session start) - Conditional rules (Cursor) reduce fixed context cost and activate task-specific profiles when relevant
- Embedded rules (Codex, Qwen) are simple, always active, and work everywhere
Which Client Should I Use?
Choose Cursor if:
- ✅ You want lowest fixed context cost (150 tokens base + 120 tokens profile when active)
- ✅ You work on complex, multi-file tasks (debugging, refactoring, architecture)
- ✅ You want conditional rules that activate based on file patterns
Choose Claude Desktop if:
- ✅ You want closest to "automatic" behavior (hooks can auto-trigger
smart_turn) - ✅ You want session-aware workflows with automatic checkpointing
- ✅ You're okay with opt-in hook configuration
Choose Codex or Qwen if:
- ✅ You want simple, embedded rules (no separate config files)
- ✅ You prefer lightweight setup (single
AGENTS.mdfile) - ✅ You're okay with manual
smart_turncalls and no conditional activation
Bottom line: All clients work well. The choice depends on your preference for automation level vs simplicity.
See Client Compatibility Guide for detailed comparison.
Installation
Step 1: Install the MCP Server
Minimal (Any Client)
Restart your AI client. Done.
Verify Installation
After updating: The binary is updated globally, but agent rules (.cursorrules, CLAUDE.md, AGENTS.md) in each project are generated from the installed version and are not updated automatically.
Re-run init after each update to get the latest rules:
Then restart your AI client to load the new version.
Cursor
Restart Cursor. Tools appear in Agent mode.
Files created:
.cursor/mcp.json- MCP server config.cursor/rules/devctx.mdc- Base agent rules (10 lines, always active).cursor/rules/profiles-compact/*.mdc- Task profiles (conditional).devctx/bin/cursor-devctx- Optional assisted launcher for long tasks.git/hooks/pre-commit- Safety hook.gitignore- Adds.devctx/
Codex CLI
Restart Codex.
Files created:
.codex/config.toml- MCP server configAGENTS.md- Agent rules.git/hooks/pre-commit- Safety hook.gitignore- Adds.devctx/
Claude Desktop
Restart Claude Desktop.
Files created:
.mcp.json- MCP server config.claude/settings.json- Hook configCLAUDE.md- Agent rules.git/hooks/pre-commit- Safety hook.gitignore- Adds.devctx/
Qwen Code
Restart Qwen Code.
Files created:
.qwen/settings.json- MCP server configAGENTS.md- Agent rules.git/hooks/pre-commit- Safety hook.gitignore- Adds.devctx/
Agent Rules: The Secret Sauce
What makes this MCP different is task-specific agent guidance. Installation generates rules that teach agents optimal workflows:
Debugging Profile
Savings: 90% (150K → 15K tokens)
Code Review Profile
Savings: 87% (200K → 25K tokens)
Refactoring Profile
Savings: 89% (180K → 20K tokens)
Testing Profile
Savings: 90% (120K → 12K tokens)
Architecture Profile
Savings: 90% (300K → 30K tokens)
Key insight: The value isn't just in the tools—it's in teaching agents when and how to use them.
Step 2: Set Up Agent Rules (Recommended)
To ensure agents use devctx automatically, set up client-specific rules:
Cursor Users
Already included: .cursorrules is committed in the project.
Verify it's working:
- Agent should mention devctx usage policy
- Agent should use devctx tools automatically
- For long tasks, prefer
./.devctx/bin/cursor-devctx task --prompt "..." -- <agent-command>
Claude Desktop Users
Create CLAUDE.md in your project root:
Or copy the content from docs/agent-rules-template.md.
Other Agent Clients
Create AGENTS.md in your project root using the same template.
Why these rules matter:
- ✅ Agents use devctx automatically (no manual forcing)
- ✅ Consistent behavior across all clients
- ✅ Visible feedback when devctx is used
- ✅ Warnings when devctx should be used but isn't
See Agent Rules Template for complete setup.
Feedback When Not Used
If the agent doesn't use devctx tools in a non-trivial task, it will add a note:
Why this matters:
- Makes non-usage visible
- Educates about when devctx adds value
- Provides forcing prompt for next turn
- Identifies setup issues (MCP unavailable, index not built)
How to Force devctx Usage
When to use these prompts:
- Agent didn't use devctx in a non-trivial task
- You want to recover persisted task context
- Task is complex (debugging, review, refactor, testing, architecture)
Official prompt (complete workflow):
Ultra-short prompt (copy-paste ready):
Example usage:
See agent-rules/ for complete profiles.
Getting Started
Day 1: Install + Build Index (Critical)
-
Install:
-
Build index (REQUIRED for quality):
Why critical: Without index,
smart_searchandsmart_contextare degraded. Agent may prefer native tools. No token savings. -
Use core tools:
smart_readfor file structuresmart_searchfor finding codesmart_contextfor comprehensive contextsmart_metricsto verify savings
-
Let the agent decide: Don't force tool usage. The generated rules will guide the agent naturally.
After 1 week: Add advanced tools
smart_summaryif you work on long taskssmart_turnif using Claude Code CLIgit_blamefor code attributioncross_projectif working in monorepos
After 1 month: Optimize
- Check
smart_metricsfor usage patterns - Enable
warm_cacheif cold starts are slow - Enable
prefetchinsmart_contextfor repetitive tasks
Metrics & Verification
Run full benchmark
Runs all verification suites:
- 740+ unit tests
- 14 feature verifications
- Synthetic corpus evaluation
- Real project evaluation
- Orchestration regression benchmark (5 core scenarios)
- Production metrics report
Takes 3-4 minutes. See Benchmark Documentation for details.
Release gating for orchestration quality is also available with npm run benchmark:orchestration:release, and npm publish now blocks on that gate via prepublishOnly.
Check it's working
Good signs:
- Tool usage > 0 (agent using devctx)
- Savings 60-90% (compression working)
- Multiple tools used (workflows followed)
Bad signs:
- Tool usage = 0 (agent not using devctx)
- Check: Rules installed? MCP running? Task complexity?
Example output:
Adoption Metrics (Experimental)
The metrics report now includes adoption analysis to measure how often devctx is actually used.
What we measure:
- ✅ Sessions with devctx tool usage (automatic, from tool calls)
- ✅ Adoption rate overall and by inferred complexity
- ✅ Top tools used per session
- ✅ Average token savings when devctx is used
What we DON'T measure:
- ❌ Feedback frequency (requires agent to report it)
- ❌ Feedback reasons (requires agent cooperation)
- ❌ Forcing prompt usage (can't detect from metrics)
- ❌ Actual task complexity (only inferred from operation count)
Limitations:
- Complexity is inferred (operation count), not actual
- Can only measure when devctx IS used (tool calls visible)
- Can't detect non-usage unless agent reports it
- Sessions without devctx may be simple tasks (not failures)
Why this is useful:
- See if devctx is being adopted in practice
- Identify patterns (complex tasks → higher adoption)
- Verify rules and onboarding are working
- Complement compression metrics with usage metrics
See Adoption Metrics Design for complete analysis.
Real-Time Usage Feedback (New!)
Get immediate visibility into devctx tool usage in every agent response.
ENABLED BY DEFAULT - Shows feedback after every devctx tool call.
Disable if too verbose:
What you'll see:
Benefits:
- ✅ Know immediately if agent is using devctx
- ✅ See token savings in real-time
- ✅ Verify forcing prompts worked
- ✅ Debug adoption issues instantly
When to use:
- Verifying agent follows rules
- Debugging why devctx isn't used
- Measuring real-time impact
- Validating setup after installation
See Usage Feedback Documentation for complete guide.
Decision Explanations (New!)
Understand why the agent chose devctx tools and what benefits are expected.
ENABLED BY DEFAULT - Shows decision explanations for every devctx tool call.
Disable if too verbose:
What you'll see:
Benefits:
- ✅ Understand agent decision-making
- ✅ Learn when to use which tool
- ✅ Debug tool selection issues
- ✅ Validate agent is making good choices
When to use:
- Learning how devctx works
- Debugging why certain tools were chosen
- Validating agent behavior
- Understanding best practices
Combine with usage feedback for maximum visibility:
See Decision Explainer Documentation for complete guide.
Missed Opportunities Detection (New!)
Detect when devctx should have been used but wasn't.
ENABLED BY DEFAULT - Shows warnings when devctx adoption is low.
Disable if not needed:
What you'll see:
Detects:
- 🔴 No devctx usage in long sessions (>5 min)
- 🟡 Low adoption (<30% of operations)
- 🟡 Usage dropped (no calls for >3 min)
Benefits:
- ✅ Identify adoption gaps
- ✅ Quantify potential savings
- ✅ Validate forcing prompts worked
- ✅ Detect when agent switches to native tools
Limitations:
- Total operations are estimated (not measured)
- May have false positives for simple tasks
- Session-scoped only (resets on restart)
All features enabled by default. To disable all:
See Missed Opportunities Documentation for complete guide.
Agent Rules (Multi-Client Support)
The project includes agent rules that enforce devctx usage across different clients:
- Cursor:
.cursorrules(committed to git) - Claude Desktop:
CLAUDE.md(create from template indocs/agent-rules-template.md) - Other agents:
AGENTS.md(create from template indocs/agent-rules-template.md)
All rules enforce the same policy:
- Use
smart_readinstead ofRead - Use
smart_searchinstead ofGrep - Use
smart_contextinstead of multiple reads - Explain if native tools are used
See Agent Rules Template for setup instructions.
MCP Prompts (Automatic Forcing)
The MCP server provides prompts that automatically inject forcing instructions:
Quick forcing:
This injects: Use devctx: smart_turn(start) → smart_context/smart_search → smart_read → smart_turn(end)
Available prompts:
/prompt use-devctx- Ultra-short forcing prompt/prompt devctx-workflow- Complete workflow template/prompt devctx-preflight- Preflight checklist (index + session init)
Benefits:
- ✅ No need to remember/type forcing syntax
- ✅ Centrally managed (updates automatically)
- ✅ Discoverable in Cursor prompts menu
- ✅ No typos
See MCP Prompts Documentation for complete guide.
Quick verification
Troubleshooting
Agent not using devctx tools
Check:
Possible causes:
- Rules not installed → Run
npx smart-context-init --target . - MCP not running → Restart client
- Index not built → Run
npm run build-indexor tell agent "Run build_index tool" - Task too simple → Built-in tools sufficient (this is fine)
- Agent in Ask mode → Read-only, no MCP access
Force devctx usage (copy-paste ready):
See How to Force devctx Usage for complete workflow.
Enable Workflow Tracking
To track complete workflows (debugging, review, refactor, testing, architecture):
Then restart your AI client. View workflow metrics:
See Workflow Metrics for details.
High token usage despite devctx
Check:
Look for:
- Low tool usage (< 20% of operations)
- High
fullmode usage (agent not cascading) - Low compression ratios (< 50%)
Possible causes:
- Agent not following workflows
- Task doesn't benefit from compression
- Rules unclear for this task type
Context not persisting
Check:
Possible causes:
- Node 18-20 → No SQLite (upgrade to 22+)
- Agent not calling
smart_turn→ No task checkpoints - Session ID mismatch → Can't recover checkpoint
.devctx/state.sqlitetracked/staged → runtime context writes are intentionally blocked until git hygiene is fixed.devctx/state.sqlitelocked/corrupted/oversized → inspectstorageHealthfromsmart_statusorsmart_metrics- broader local-state preflight → run
smart_doctororsmart-context-doctor --json
Recovery flow:
missing→ run a persisted action likesmart_summary updateorsmart_turn endoversized→ runsmart_summary compactlocked→ stop competing devctx processes, then retrycorrupted→ back up.devctx/state.sqlite, remove it, and let devctx recreate local state
Rules not applied
Check:
If missing:
If exists but agent ignores:
- This is expected (rules are guidance, not enforcement)
- Agent decides based on task
- Check metrics to see actual usage
Supported Languages
First-class (AST parsing): JavaScript, TypeScript, JSX, TSX
Heuristic parsing: Python, Go, Rust, Java, C#, Kotlin, PHP, Swift
Structural extraction: Shell, Terraform, HCL, Dockerfile, SQL, JSON, YAML, TOML
Configuration
Environment Variables
Cross-Project Setup
Create .devctx-projects.json:
Build indexes for each project:
Storage
All data stored in .devctx/:
index.json- Symbol index (INDEX_VERSION 7: ADR + ADR sections, richer Python/Go)state.sqlite- Sessions, metrics, patterns, task handoffs, test failures, explain cache (Node 22+)metrics.jsonl- Opt-in legacy file, only whenDEVCTX_METRICS_FILE=path.jsonlis set
Cross-project (opt-in via DEVCTX_GLOBAL_MEMORY=true):
~/.devctx/global.db- Scrubbed decisions, patterns, playbooks, notes with semantic recall
Add to .gitignore:
Security
This MCP is secure by default:
- ✅ Allowlist-only commands - Only safe diagnostic commands (
ls,git status,npm test, etc.) - ✅ No shell operators - Blocks
|,&,;,>,<,`,$() - ✅ Path validation - Cannot escape project root
- ✅ No write access - Cannot modify your code
- ✅ Repository safety - Prevents accidental commit of local state
- ✅ Resource limits - 15s timeout, 10MB buffer
What smart_shell can run:
Real rejection examples:
Verification:
Configuration:
Complete security documentation:
- SECURITY.md - Full security policy
- Security Rejection Examples - 50+ concrete examples
Requirements
- Node.js: 18+ (22+ recommended for SQLite features)
- Git: For diff-aware context and git blame
- ripgrep: Included via
@vscode/ripgrep(no system install needed)
Performance Comparison
Documentation
Features
- Streaming Progress - Real-time progress notifications
- Context Prediction - Intelligent file prediction
- Diff-Aware Context - Smart change analysis
- Cache Warming - Cold-start optimization
- Git Blame - Code attribution
- Cross-Project Context - Multi-project support
Security
- Security Policy - Security guarantees and threat model
- Threat Model - Attack surface analysis
- Security Configuration - Hardening and profiles
Verification
- Benchmark - Reproducible benchmark
- E2E Test Report - Production usage analysis
- Verification Report - Feature verification
- Workflow Metrics - Complete workflow savings
Development
- Architecture - Repository structure and development guide
- Contributing - How to contribute
- Changelog - Version history
API Reference
Core Tools
smart_read
smart_search
smart_context
build_index
smart_metrics
Advanced Tools
smart_summary
smart_turn
smart_read_batch
smart_shell
warm_cache
git_blame
cross_project
Core Capabilities
- ✅ 90% token reduction through intelligent compression
- ✅ Automatic orchestration with shared layer and client adapters
- ✅ Session continuity via SQLite state persistence
- ✅ Workflow tracking (debugging, code review, refactoring, testing, architecture)
- ✅ Task runner CLI with continuity-aware workflows
- ✅ Comparative metrics for cross-client benchmarking
- ✅ Production-ready with 740+ tests and release-gated benchmarks
See CHANGELOG.md for full release history.
Repository Structure
This repository contains the smart-context-mcp npm package in tools/devctx/:
What gets published to npm: Only tools/devctx/ contents (src + scripts)
Development: All work happens in tools/devctx/
See CONTRIBUTING.md for development setup.
Contributing
Pull requests welcome for:
- Additional language parsers
- Performance optimizations
- Bug fixes
See CONTRIBUTING.md for guidelines.
Author
Francisco Caballero Portero
Email: [email protected]
GitHub: @Arrayo
License
MIT License - see LICENSE file for details.
Links
Source: README.md at commit 1ade0e7
Tools
0Version history
2- v1.21.0LatestSep 18, 2026
- v1.20.0Sep 16, 2026
Score
50% of the applicable checks met
How complete this listing is, computed from the registry entry, the endpoint and public sources. Not a rating of the server and not a statement that it is safe or working today: reachability is a dated check, and no installs or reviews go into the score.
- Reached in the last 30 days25 pts
Keep the endpoint answering the MCP handshake; SourceWeft probes it every 30 days.
- Auth declared10 pts
Declare the credential headers in the registry entry, or keep the endpoint answering the probe so its auth can be classified.
- Tools listed15 pts
Answer tools/list without a credential, or ship a package that starts in a sandbox without one.
- DescriptionRequired15 pts
- Logo10 pts
- Documentation15 pts
- License10 pts