npm package: @notprolands/ast-grep-mcp
Description: AST-grep MCP server for AI-assisted code search and transformation
Author: notprolands
Latest version: 1.1.1

# AST-grep MCP Server

**Linux/Unix optimized MCP server** for AI-assisted code search, transformation, and analysis using AST-based patterns. Perfect for large codebases and complex refactoring tasks.

> **Platform Support**: Linux/Unix environments (including WSL). Windows users should use WSL, Docker, or a Linux environment.

## 🚀 Features

### 🔍 **Code Search & Analysis**
- **dump_syntax_tree**: Debug and understand AST structure and patterns  
- **find_code**: Simple pattern-based code search with metavariables
- **find_code_by_rule**: Advanced YAML rule-based search with complex conditions
- **analyze-imports**: Track import usage and dependencies for refactoring

### ⚡ **Code Transformation**  
- **rewrite_code**: Transform and refactor code using AST patterns with safety features
- **test_match_code_rule**: Test YAML rules against code before applying changes

### 🔬 **Quality Analysis**
- **scan-code**: Analyze TypeScript code for bugs, performance issues, and best practices
- **TypeScript focus**: Specialized tools for TypeScript/JavaScript codebases

## 🎯 Why AST-grep for AI Agents?

Unlike text-based search tools, AST-grep understands code structure:
- **Semantic search**: Find `console.log($ARG)` regardless of formatting
- **Safe refactoring**: Transform code while preserving semantics  
- **Complex patterns**: Find nested structures, conditional logic, and relationships
- **Language-aware**: Understands TypeScript, JavaScript, Python, Rust, Go, and more

## 📦 Installation

### Global Installation
```bash
npm install -g @notprolands/ast-grep-mcp
```

### Project-specific Installation  
```bash
# pnpm workspaces
pnpm add -wD @notprolands/ast-grep-mcp

# bun workspaces
bun add -D @notprolands/ast-grep-mcp

# npm projects
npm install --save-dev @notprolands/ast-grep-mcp
```

## 🔧 Usage

### With Claude Code
```bash
# Using global install
claude mcp add ast-grep -- npx @notprolands/ast-grep-mcp

# Using workspace install (recommended for teams)
claude mcp add ast-grep -s project -- pnpm exec @notprolands/ast-grep-mcp
```

### With Other MCP Clients

**For pnpm workspaces** (`.mcp.json`):
```json
{
  "mcpServers": {
    "ast-grep": {
      "type": "stdio",
      "command": "pnpm", 
      "args": ["exec", "@notprolands/ast-grep-mcp"]
    }
  }
}
```

**For bun workspaces** (`.mcp.json`):
```json
{
  "mcpServers": {
    "ast-grep": {
      "type": "stdio",
      "command": "bun",
      "args": ["x", "@notprolands/ast-grep-mcp"]
    }
  }
}
```

**For global installs** (`.mcp.json`):
```json
{
  "mcpServers": {
    "ast-grep": {
      "type": "stdio", 
      "command": "npx",
      "args": ["@notprolands/ast-grep-mcp"]
    }
  }
}
```

## 🛠️ Tool Reference

### dump_syntax_tree - Debug AST Structure
```javascript
// Understand how ast-grep parses your code
{
  "name": "dump_syntax_tree",
  "arguments": {
    "code": "console.log('hello')",
    "language": "javascript",
    "format": "cst"  // or "ast", "pattern"
  }
}
```

### find_code - Simple Pattern Search
```javascript
// Find all console.log statements
{
  "name": "find_code", 
  "arguments": {
    "project_folder": "/path/to/project",
    "pattern": "console.log($ARG)",
    "language": "javascript"
  }
}
```

### find_code_by_rule - Advanced YAML Search
```javascript
// Find async/await inside loops (performance issue)
{
  "name": "find_code_by_rule",
  "arguments": {
    "project_folder": "/path/to/project", 
    "yaml": `id: async-in-loop
language: javascript
rule:
  pattern: await $EXPR
  inside:
    any:
      - kind: for_statement
      - kind: while_statement`
  }
}
```

### rewrite_code - AST-based Refactoring
```javascript
// Replace console.log with logger.info
{
  "name": "rewrite_code",
  "arguments": {
    "project_folder": "/path/to/project",
    "pattern": "console.log($ARG)", 
    "replacement": "logger.info($ARG)",
    "language": "javascript",
    "auto_apply": true
  }
}
```

### test_match_code_rule - Validate Rules
```javascript
// Test a rule before using it
{
  "name": "test_match_code_rule",
  "arguments": {
    "code": "const x = await fetch('/api')",
    "yaml": `id: test-rule
language: javascript
rule:
  pattern: await $CALL`
  }
}
```

### analyze-imports - Dependency Analysis
```javascript
// Find unused imports for cleanup
{
  "name": "analyze-imports",
  "arguments": {
    "mode": "usage",     // or "discovery"
    "path": "src/components"
  }
}
```

### scan-code - Quality Analysis  
```javascript
// Scan for TypeScript code issues
{
  "name": "scan-code",
  "arguments": {}  // Scans entire project
}
```

## 📋 Requirements

### Core Requirements
- **Node.js 18+**
- **ast-grep**: Install from [ast-grep.github.io](https://ast-grep.github.io/guide/quick-start.html#installation)

### Installation Commands
```bash
# Install ast-grep (choose one method)

# Using cargo (recommended)
cargo install ast-grep

# Using npm
npm install -g @ast-grep/cli

# Using homebrew (macOS)
brew install ast-grep

# Using pacman (Arch Linux)
pacman -S ast-grep

# Verify installation
ast-grep --version
```

### Package Manager Support
- **Multi-workspace support**: Works with pnpm, bun, npm, and yarn workspaces
- **Auto-detection**: Automatically detects workspace type and project root
- **Enhanced bun support**: Detects both bun.lock and bun.lockb files
- **Linux/Unix optimized**: Clean, reliable implementation for Unix-like systems

## 🔍 Advanced Features

### Multi-Language Support
- **TypeScript/JavaScript**: Full support with modern syntax
- **Python**: Classes, functions, imports, async/await patterns
- **Rust**: Structs, traits, macros, error handling patterns  
- **Go**: Interfaces, goroutines, error handling
- **Java/C/C++**: Object-oriented and system programming patterns

### AI Agent Optimizations
- **Focused tools**: Each tool has a single, clear purpose
- **Pattern validation**: Test rules before applying to avoid errors
- **Rich output**: JSON results with file locations and context
- **Error handling**: Clear error messages with actionable suggestions

### Security & Safety Features
- **Path validation**: Prevents directory traversal attacks
- **Safe rewrites**: Preview changes before applying
- **Workspace boundaries**: Operations limited to project scope
- **Backup recommendations**: Encourages version control before major changes

## 🎯 Best Practices for AI Agents

1. **Start with `dump_syntax_tree`** when debugging patterns
2. **Use `test_match_code_rule`** before running searches
3. **Choose `find_code`** for simple patterns with metavariables  
4. **Use `find_code_by_rule`** for complex relational searches
5. **Test `rewrite_code`** with `auto_apply: false` first
6. **Use `analyze-imports`** to understand dependencies before refactoring
7. **Run `scan-code`** for comprehensive quality analysis

## 🏗️ Architecture

- **Modular Design**: 7 focused tools, each with specific purpose
- **AST-based**: Semantic understanding vs text-based search
- **Type Safety**: Full TypeScript with Zod validation  
- **MCP Compliant**: Follows MCP 2025-06-18 specifications
- **Workspace Aware**: Detects project structure automatically

## 🔄 Migration from Legacy Tools

If you were using older ast-grep integrations:
- **Simple searches** → use `find_code`
- **Complex searches** → use `find_code_by_rule` with YAML
- **Debugging patterns** → use `dump_syntax_tree` with `format='pattern'`
- **Testing rules** → use `test_match_code_rule`

## 📝 License

MIT - see [LICENSE](LICENSE) file for details

## 🤝 Contributing

Contributions welcome! This server is part of a larger dev-tools monorepo. See the main repository for contribution guidelines.

## 🔗 Related Packages

- **[@notprolands/dev-tools-mcp](https://www.npmjs.com/package/@notprolands/dev-tools-mcp)**: Essential development tools (tree, linter, jq)
- **[ast-grep](https://ast-grep.github.io/)**: The underlying AST-based search and rewrite tool
- **[MCP TypeScript SDK](https://github.com/modelcontextprotocol/typescript-sdk)**: Official MCP SDK for TypeScript

## 📚 Further Reading

- **[AST-grep Documentation](https://ast-grep.github.io/)**: Complete guide to AST patterns and rules
- **[MCP Specification](https://spec.modelcontextprotocol.io/)**: Model Context Protocol standard
- **[Pattern Syntax Guide](https://ast-grep.github.io/guide/pattern-syntax.html)**: Learn AST pattern matching