achatainga

mcp-code-context

Community achatainga
Updated

MCP server that compresses any codebase into LLM-ready semantic context. AST-based compression for TypeScript, JavaScript, PHP, Dart & Python โ€” works with Claude, Cursor, Windsurf, Copilot, Amazon Q, and any MCP client.

mcp-code-context

License: MITnpm versionnpm downloadsTypeScriptTestsKo-fiPayPal

MCP server with Tree-sitter WASM parsers for 100% AST accuracy. Zero native dependencies. Production-ready with persistent caching, structured logging, fuzzy search, and multi-process safety.

๐Ÿš€ Quick Start (Claude Desktop)

  1. Install: npm install -g mcp-code-context
  2. Configure: Add to claude_desktop_config.json:
{
  "mcpServers": {
    "code-context": {
      "command": "npx",
      "args": ["-y", "mcp-code-context"]
    }
  }
}
  1. Enjoy: Use symbols like @code-context to map repos or edit code surgically.

No build tools required - Works on Windows/Mac/Linux without Visual Studio, Python, or node-gyp.

Works with Claude Desktop, Cursor, Windsurf, GitHub Copilot, Amazon Q, and any Model Context Protocol compatible client.

๐Ÿ“– For AI Agents: See INSTRUCTIONS.md for essential usage patterns and best practices.

๐Ÿ’ก Why This Exists

This tool was born out of necessity in Caracas, Venezuela ๐Ÿ‡ป๐Ÿ‡ช, where economic limitations made every API token count. When you're choosing between groceries and Claude API credits, you learn to optimize fast.

What started as a personal script to compress context windows became a full MCP server when I realized others faced the same problem: LLM APIs are expensive, and most tools waste tokens on boilerplate.

If this tool saves you money or time, consider supporting its development. Every contribution helps keep this project maintained and free for everyone.

The Problem

LLMs working with code face two bottlenecks:

  1. Reading: Sending raw source files wastes the context window on function bodies and boilerplate. A 500-line file might contain only 30 lines of structural information the LLM needs.
  2. Writing: Rewriting entire files to change one function is error-prone, token-expensive, and risks corrupting unrelated code.

The Solution

mcp-code-context provides 13 tools โ€” 6 for reading, 2 for cleanup, and 5 for writing โ€” that operate at the symbol level (functions, classes, methods). Furthermore, tools support a className scope which correctly isolates identical symbol names in the same file (e.g. Flutter build() methods) to avoid reading or changing the wrong logic. Read tools extract structural skeletons. Write tools splice changes into the exact AST location.

File Original Compressed Reduction
PHP class (426 lines) 426 60 85.9%
Dart repository (230 lines) 230 30 87.0%
PHP config (68 lines) 68 15 77.9%

Reliability & Testing

Built to be robust and precise. Both read and write engines are tested against real-world, complex codebases (including nested generic types in Dart, complex interfaces in PHP, and multi-file rename operations) with a 100% test pass rate across all languages and operations.

Features

What's New in v3.6.3

Feature Description
โšก Persistent Cache WASM SQLite cache โ€” <100ms hits, 10ร— faster on repeated reads
๐Ÿ“ Structured Logging pino JSON logging to stderr (MCP-safe, never pollutes stdio)
๐Ÿ‘๏ธ File Watcher chokidar auto-invalidates cache on file changes
๐Ÿ” Fuzzy Search fuse.js finds authUser when you search authenticateUser
๐Ÿ“„ Pagination Search defaults to 10 results with startIndex for navigation
๐Ÿ”’ Multi-process Safe Filesystem locks via proper-lockfile (was in-memory)
๐Ÿ’พ OS Temp Backups Backups in os.tmpdir() โ€” no more hot-reload loops
๐Ÿงช 74 Tests Unit + integration + performance + stress tests
๐ŸŽฏ Token Savings 50-80% reduction: compact diffs, no Phase 2 repeat, auto-optimize output

Read

  • ๐ŸŒณ AST-based compression โ€” Real Tree-sitter WASM parsers for TypeScript/JavaScript/Python/PHP/Dart. Zero regex-based parsing.
  • ๐Ÿ”ฌ Surgical symbol extraction โ€” Extract a single function, class, or method from a file by name. Use className to scope disambiguation (e.g., getting multiple build() methods in Dart).
  • ๐Ÿ’ฅ Impact analysis โ€” Discover all files that depend on a given file before refactoring. Supports ES imports, CommonJS require(), Python imports, PHP use/require_once/include, and Dart imports.
  • ๐Ÿ“ Smart file walking โ€” Respects .gitignore and .repomixignore rules. Automatically excludes node_modules, dist, vendor, .git, etc.
  • ๐Ÿ“„ Multi-format output โ€” XML (optimized for LLM consumption) or Markdown (human-readable).

Write

  • โœ๏ธ Surgical symbol replacement โ€” Replace a function, method, or class body without touching the rest of the file. Narrow down the target using the className parameter.
  • โž• Precise code insertion โ€” Insert new code before/after a symbol, or inside a class at the start/end.
  • ๐Ÿ”„ Repository-wide rename โ€” Rename a symbol in its definition AND all files that import it, atomically.
  • ๐Ÿ—‘๏ธ Safe symbol removal โ€” Delete code with automatic dependency checking to prevent breakage.
  • ๐Ÿ” Mandatory dry-run flow โ€” Write tools return a preview diff and a confirmationToken by default. Changes are only applied after explicit confirmation.
  • ๐Ÿ’พ Robust rolling backups โ€” Automatically keeps the last 5 versions of modified files in a hidden .mcp-backups/ directory.
  • โช Surgical rollback โ€” Revert files to any of the 5 previous states using the rollback_file tool.
  • ๐Ÿค– Fuzzy symbol matching โ€” When a symbol is not found, the server provides structured suggestions based on Levenshtein distance.
  • ๐Ÿ” Private symbol support โ€” Full support for _ and __ prefixed symbols in Dart and Python.

Supported Languages

Language Read (Compress + Extract) Write (Replace + Insert + Rename + Remove) Import Analysis
TypeScript / JavaScript โœ… AST (Tree-sitter WASM) โœ… AST (Tree-sitter WASM) โœ…
PHP โœ… AST (Tree-sitter WASM) โœ… AST + line-splice โœ…
Dart โœ… AST (Tree-sitter WASM) โœ… AST + line-splice โœ…
Python โœ… AST (Tree-sitter WASM) โœ… Indentation-aware โœ…
Others (JSON, YAML, CSS, etc.) Passthrough / truncation โ€” โ€”

โš ๏ธ Known Limitations

rename_symbol Tool

All languages: The definition file is renamed using AST (Tree-sitter) โ€” safe and precise. โœ…

Cross-file rename (dependent files): Updated using regex word-boundaries for all languages, including TypeScript, JavaScript, and PHP.

  • Risk: Regex may match strings, comments, or unrelated identifiers sharing the same name
  • Dart and Python: Higher risk โ€” import syntax (import 'package:...', from module import name) is less reliably matched by the current regex patterns
  • Recommendation: Always review the generated diff carefully before confirming
  • Alternative: Use write_file_surgical to rename within a single file safely

get_semantic_repo_map Tool

  • Max files: Limited to 500 files to prevent timeouts
  • Performance: Synchronous I/O may take 10-30 seconds on large repositories
  • Recommendation: Use @folder syntax to target specific directories

General

  • Validation: No automatic syntax checking after edits. Always review diffs carefully before confirming.
  • Backups: 5-version rolling backup system. Use rollback_file if something goes wrong.
  • Large files: Files >10MB are skipped for safety.

Installation

# Global installation (recommended)
npm install -g mcp-code-context

# Or use directly with npx (no installation)
npx -y mcp-code-context

Note: Unlike v2.x, this version uses web-tree-sitter (WASM) instead of native bindings. No Visual Studio, Python, or node-gyp required!

Configuration

Claude Desktop

Add to your claude_desktop_config.json:

{
  "mcpServers": {
    "mcp-code-context": {
      "command": "npx",
      "args": ["-y", "mcp-code-context"]
    }
  }
}

Cursor

Add to your Cursor MCP settings (.cursor/mcp.json):

{
  "mcpServers": {
    "mcp-code-context": {
      "command": "npx",
      "args": ["-y", "mcp-code-context"]
    }
  }
}

Windsurf

Add to your Windsurf MCP config:

{
  "mcpServers": {
    "mcp-code-context": {
      "command": "npx",
      "args": ["-y", "mcp-code-context"]
    }
  }
}

Amazon Q / Other MCP Clients

Any MCP-compatible client can use this server. The transport is stdio (JSON-RPC over stdin/stdout). Point your client to npx -y mcp-code-context.

Tools

Read Tools

1. get_semantic_repo_map

Generate a compressed architectural overview of an entire repository.

  • directoryPath (required) โ€” Path to the repo root
  • format (optional) โ€” "xml" (default) or "markdown"
2. read_file_surgical

Read a file, or extract only a specific named symbol. Returns structured suggestions if the symbol is missing.

  • filePath (required) โ€” Path to the source file
  • symbolName (optional) โ€” Name of a function, class, method, or type
  • className (optional) โ€” Scope the symbol to a specific class (to avoid duplicates)
3. analyze_impact

Find all files that depend on a given file.

  • filePath (required) โ€” Path to the file being modified
  • rootDir (optional) โ€” Repository root (auto-detected)
4. read_file_lines

Read specific line ranges from a file without loading the entire content. More efficient than read_file_surgical for small fragments.

  • filePath (required) โ€” Path to the source file
  • startLine (optional) โ€” Starting line number (1-indexed)
  • endLine (optional) โ€” Ending line number (1-indexed)
  • aroundPattern (optional) โ€” Search pattern to find and return surrounding lines
  • contextLines (optional) โ€” Number of lines before/after pattern (default: 5)
5. search_code_pattern

Search for code patterns across multiple files with context. Respects .gitignore rules.

  • rootDir (required) โ€” Repository root directory
  • pattern (required) โ€” Regular expression pattern to search
  • fileExtensions (optional) โ€” Array of extensions to search (e.g., [".ts", ".dart"])
  • excludeDirs (optional) โ€” Directories to exclude (default: ["node_modules", "dist", "build"])
  • maxResults (optional) โ€” Maximum matches per page (default: 10)
  • startIndex (optional) โ€” Pagination offset (default: 0)
  • fuzzyMatch (optional) โ€” Enable fuzzy/typo-tolerant matching (default: false)
  • fuzzyThreshold (optional) โ€” Fuzzy sensitivity 0.0โ€“1.0 (default: 0.4)
6. rollback_file

Surgically restore a file to a previous state from the automated backup system.

  • filePath (required) โ€” Path to the file to restore
  • steps (optional) โ€” Number of versions to go back (1-5, default: 1)
7. clean_backups

Remove all backup files for a project to keep the working directory clean.

  • projectRoot (required) โ€” Absolute path to the project root

Note: Backups are stored centrally at [project-root]/.mcp-backups/ to keep your project organized.

Write Tools (Two-Phase Workflow)

All write tools follow a Two-Phase Workflow:

  1. Call without token: Returns a unified diff and a confirmationToken.
  2. Call with token: Set confirm: true and provide the token to apply the changes.
8. write_file_surgical

Replace the full source code of a named symbol in a file.

  • filePath (required) โ€” Path to the file
  • symbolName (required) โ€” Symbol to replace
  • newContent (required) โ€” Replacement code (signature + body)
  • confirmationToken (optional) โ€” Token from Phase 1 to apply changes
  • confirm (optional) โ€” Set to true to apply
  • className (optional) โ€” Scope the symbol to a specific class
9. insert_symbol

Insert new code at a precise location relative to an existing symbol.

  • filePath (required) โ€” Path to the file
  • code (required) โ€” Code to insert
  • anchorSymbol (optional) โ€” Symbol to position relative to
  • position (optional) โ€” "before", "after", "inside_start", "inside_end"
  • className (optional) โ€” Scope the anchor to a specific class
  • confirmationToken, confirm (optional)
10. rename_symbol

Rename a symbol across the entire repository (definition + all usages).

  • filePath (required) โ€” File where the symbol is defined
  • oldName (required) โ€” Current name
  • newName (required) โ€” New name
  • rootDir (optional) โ€” Repository root
  • confirmationToken, confirm (optional)
11. remove_symbol

Safely remove a symbol from a file with dependency checking.

  • filePath (required) โ€” Path to the file
  • symbolName (required) โ€” Symbol to remove
  • className (optional) โ€” Scope the symbol to a specific class
  • force (optional) โ€” Skip dependency check
  • confirmationToken, confirm (optional)

Recommended Workflow

  1. Understand โ†’ get_semantic_repo_map to see the architecture
  2. Read โ†’ read_file_surgical with symbol name for specific implementations
  3. Assess โ†’ analyze_impact before modifying shared files
  4. Edit (Preview) โ†’ Call write tools to generate a diff and confirmationToken
  5. Confirm โ†’ Call the same write tool with the token and confirm: true to apply
  6. Recovery โ†’ Use rollback_file if something goes wrong after confirmation

๐Ÿ’ฐ Support This Project

Why Support?

This tool was born in Caracas, Venezuela ๐Ÿ‡ป๐Ÿ‡ช, where economic limitations mean every API token counts. What started as a personal script to save money on Claude API became a full MCP server when I realized others faced the same problem.

Current Reality:

  • โฐ ~10 hours/week of maintenance
  • ๐Ÿ’ต ~$20/month in costs (npm, testing, domain)
  • ๐Ÿ†“ 100% free and open source (always will be)

If this tool saves you time or money, consider supporting its development.

๐Ÿ’ณ Ways to Support

๐Ÿ”น One-Time Donation

Ko-fi (PayPal + Cards, 0% fees) ko-fi.com/achatainga

PayPal (Direct) paypal.me/achatainga

Binance (USDT) (Crypto, lowest fees)

  • TRC20/ERC20: 0xa68d53f7853ce0175eb96aaad4a30c068ca96444
  • Binance Pay ID: 367669339

Recommended: TRC20 for lower gas fees

Suggested Amounts:
  • โ˜• $5 - A coffee (1 hour of development)
  • ๐Ÿ• $25 - A pizza (testing a new language)
  • ๐Ÿš€ $100 - Rocket fuel (major feature development)
๐Ÿ”น Recurring Support

Ko-fi Membership ko-fi.com/achatainga/tiers

Monthly tiers:

  • $5/month - Supporter (name in SPONSORS.md)
  • $25/month - Contributor (priority support, early access)
  • $100/month - Sponsor (feature requests, 1-on-1 consultation)
๐Ÿ”น Hire Me

Need custom MCP tools or AI integrations?

  • ๐Ÿ’ผ Available for: Freelance contracts
  • ๐ŸŒ Location: Caracas, Venezuela (Remote)
  • ๐Ÿ’ป Skills: TypeScript, Node.js, MCP, AI/LLM integrations
  • ๐Ÿ’ต Rate: $50-75/hour

๐Ÿ“ง Contact: [email protected] ๐Ÿ“„ Details: HIRE_ME.md

๐Ÿ“Š Transparency

I believe in radical transparency:

Current Status:

  • ๐Ÿ’ฐ Donations received: $0
  • ๐Ÿ’ธ Expenses: $20/month (npm, testing)
  • โฐ Time invested: ~10 hours/week
  • ๐Ÿ“ฆ Downloads: 10,000+/month

(Updated monthly)

๐Ÿ† Hall of Fame

Thank you to these amazing supporters:

(No sponsors yet - be the first!)

See full list: SPONSORS.md

โค๏ธ Non-Financial Support

Can't donate? No problem! You can still help:

  • โญ Star the repo on GitHub
  • ๐Ÿ› Report bugs or suggest features
  • ๐Ÿ“ Improve documentation
  • ๐Ÿ—ฃ๏ธ Share with others who might benefit
  • ๐Ÿ’ฌ Join discussions and help other users

Every contribution matters, financial or not.

Development

# Build
npm run build

# Run tests
npm test

# Development (build + start)
npm run dev

Technical Details

  • Transport: stdio (JSON-RPC over stdin/stdout)
  • Runtime: Node.js >= 18
  • Protocol: Model Context Protocol
  • AST Engines: [email protected] (WASM) for TypeScript/JS/Python/PHP/Dart
  • Language Grammars: [email protected] (ABI v15)
  • Cache: [email protected] (WASM SQLite, zero native deps)
  • Logging: [email protected] (JSON to stderr, MCP-safe)
  • File Watcher: [email protected] (auto cache invalidation)
  • Fuzzy Search: [email protected] (typo-tolerant matching)
  • File Locking: [email protected] (multi-process safe, OS temp)
  • Diff: [email protected] (Myers algorithm, O(n+dยฒ))
  • Ignore Engine: ignore npm package (full .gitignore spec support)
  • Safety Features: Mandatory two-phase confirmation, rolling 5-version backups, fuzzy matching, dependency checking, surgical restoration, ReDoS protection via worker_threads.
  • Portability: 100% WASM - no native dependencies, works on all platforms
  • Tests: 74 passing (unit + integration + performance + stress)

Contributing

See CONTRIBUTING.md for guidelines.

Security

See SECURITY.md for security policies and reporting vulnerabilities.

Troubleshooting

See TROUBLESHOOTING.md for common issues and solutions.

Viewing Logs

Because MCP uses stdout for protocol communication, all logs are safely routed to stderr. You can view them in your client's log files:

  • Claude Desktop (macOS): ~/Library/Logs/Claude/mcp-server-mcp-code-context.log
  • Claude Desktop (Windows): %APPDATA%\Claude\logs\mcp-server-mcp-code-context.log
  • Cursor: Output panel โ†’ Select mcp-code-context from the dropdown

Environment Variables (optional):

{
  "mcpServers": {
    "mcp-code-context": {
      "command": "npx",
      "args": ["-y", "mcp-code-context"],
      "env": {
        "NODE_ENV": "development",
        "LOG_LEVEL": "debug"
      }
    }
  }
}

Supported LOG_LEVEL values: fatal, error, warn, info, debug, trace (default: info).

Changelog

See CHANGELOG.md for version history.

License

MIT

Built with โค๏ธ from Caracas, Venezuela ๐Ÿ‡ป๐Ÿ‡ช

MCP Server ยท Populars

MCP Server ยท New

    TickDB

    TickDB โ€” Unified Real-time Market Data API for Forex, Stocks, Crypto

    ็ปŸไธ€็š„ๅฎžๆ—ถ้‡‘่ž่กŒๆƒ…ๆ•ฐๆฎAPI๏ผŒ่ฆ†็›–ๅค–ๆฑ‡ใ€่ดต้‡‘ๅฑžใ€ๆŒ‡ๆ•ฐใ€็พŽ่‚กใ€ๆธฏ่‚กใ€A่‚กๅ’ŒๅŠ ๅฏ†่ดงๅธ๏ผŒๆ”ฏๆŒ WebSocket ๅฎžๆ—ถๆŽจ้€ไธŽ REST ๆŽฅๅฃ่ฎฟ้—ฎ | Unified real-time market data API covering forex, commodities, indices, US stocks, HK stocks, A-shares and cryptocurrencies, with WebSocket streaming and REST access

    Community TickDB
    Patdolitse

    piia-engram

    One memory. Every AI tool. Yours to keep. Local-first, MCP-compatible, Apache 2.0.

    Community Patdolitse
    ada20204

    antigravity-sync

    MCP Server

    Community ada20204
    SepineTam

    mcp-for-stata

    Integrate Stata into your agent.

    Community SepineTam
    Keesan12

    martin-loop

    The control plane for autonomous work and coding agent teams.

    Community Keesan12