Surgical Code Patching & Grafting Engine with Compiler Verification for Agentic AI
Byte-precision AST refactoring, automatic indentation alignment, and compiler-verified zero-disk-corruption protection for autonomous coding agents.
Autonomous coding agents (Cursor, Claude Code, Antigravity, Cline, Windsurf, custom agents) repeatedly fail at brownfield codebase edits:
- Lazy Truncation (
// TODO: rest of code...): Agents rewrite 1,000-line files withwrite_to_file, accidentally discarding existing functions, interfaces, or comments. - Context Window Bankruptcy: Reading full files to edit a 5-line function wastes 85%+ of the agent's context window.
- Fragile String Replace: Naive search-replace tools fail when whitespace, indentation, or line endings don't match character-for-character.
- Syntax Corruption: Agents introduce missing braces or unindented blocks, then spend 5 turns failing to locate the compiler error.
codegraft operates directly on Tree-sitter Abstract Syntax Trees (AST):
- Zero Truncation Guarantee: Only the exact byte range of the target symbol (function, method, class) is grafted. Surrounding code, comments, docstrings, and formatting are 100% untouched.
- Context-Light Outlines (
ast_outline): Returns hierarchical symbol trees with line ranges and signatures in < 500 tokens instead of loading 15,000 tokens of file content. - Pre-Write Syntax Verification Gate: The grafted AST is compiled and validated in memory. If any syntax error (
ERRORorMISSINGnode) is detected, the write is rejected and disk content remains 100% untouched. - Indentation Auto-Alignment: Normalizes incoming code to match the target scope's indentation level (e.g. methods inside classes automatically inherit class body indent).
- Multi-Language Native: Python, TypeScript, TSX, JavaScript, Go, Rust, and JSON.
- Model Context Protocol (MCP): Native stdio JSON-RPC 2.0 server ready to plug into Antigravity, Claude Desktop, Cursor, or Cline.
# Using uv (recommended)
uv tool install --from . codegraft
# Or editable development install
uv pip install -e .Add codegraft to your MCP configuration (~/.gemini/config/mcp_config.json or claude_desktop_config.json):
{
"mcpServers": {
"codegraft": {
"command": "uv",
"args": ["run", "--directory", "C:/ProjectIseng/codegraft", "codegraft", "mcp"]
}
}
}| Tool | Purpose |
|---|---|
ast_outline |
Extract class/function/method hierarchy without dumping full files (saves 85% context tokens). |
ast_get_symbol |
Retrieve the exact source code of a symbol by name. |
ast_patch_symbol |
Surgically replace a function/method/class with compiler verification before write. |
ast_insert_symbol |
Insert code before, after, inside_start, or inside_end of an existing symbol. |
ast_delete_symbol |
Surgically delete a symbol with clean whitespace hygiene. |
ast_check_syntax |
Check AST syntax validity and extract line-by-line syntax errors. |
# 1. Inspect file outline (without loading entire body into context)
codegraft outline src/api.ts
# 2. View a specific function
codegraft get src/services/user.py calculate_score
# 3. Surgically graft/patch a function
codegraft patch src/services/user.py calculate_score --code "def calculate_score(user):\n return user.points * 2"
# 4. Insert a new method inside a class
codegraft insert src/models.py --code "def validate(self):\n return True" --relative-to "User" --position inside_end
# 5. Delete a deprecated method cleanly
codegraft delete src/api.ts oldHandler
# 6. Check syntax validity across multiple files
codegraft check src/complex.rs
# 7. Run MCP Server over stdio
codegraft mcpuv run pytest -v
============================= 131 passed in 1.84s =============================- Python (25 tests): Async, generators, type annotations, try-except, classmethods, properties, nested closures, walrus operator, lambdas.
- TypeScript / TSX (25 tests): Generics, interfaces, arrow functions, union types, React JSX elements, optional chaining, rest parameters.
- Go (20 tests): Struct fields, pointer & value receivers, variadics, goroutines, channels, selects, automatic semicolon insertion, EOF newline enforcement.
- Rust (20 tests): Structs, Result/Option types, lifetimes (
'a), impl blocks, mutable references, generics, trait definitions. - Stress & Edge Cases (10 tests): Multibyte UTF-8 emojis, 2,000-line files, sequential multi-patching, nested scopes (3 levels).
- Core Engine & MCP (31 tests): Outline extraction, diffing, dry-run simulation,
.bakbackups, Windows CRLF preservation, JSON-RPC 2.0 stdio handshake.
[Agent Intent] ──> [MCP JSON-RPC Stdio / CLI]
│
▼
[CodeGraft Dispatcher]
│
┌────────────────┼────────────────┐
▼ ▼ ▼
[Tree-sitter AST] [Indentation Engine] [Syntax Verification]
│ │ │
└────────────────┼────────────────┘
▼
[Memory AST Validation: has_error?]
├── True ──> [ABORT: Return Compiler Errors to Agent]
└── False ──> [Atomic Disk Write + Unified Diff]
Apache-2.0