Skip to main content
Glama

ast_grep_search

Search code using structural pattern matching to find specific syntax patterns across multiple programming languages for refactoring, security auditing, and code analysis.

Instructions

πŸ” AST-Grep structural code search tool

Performs powerful structural code search using ast-grep's pattern matching capabilities. Unlike text-based search, this matches syntactical AST node structures.

Key Features:

  • Structural pattern matching (not just text)

  • Multi-language support (JS, TS, Python, Go, Rust, etc.)

  • Wildcard variables ($VAR, $FUNC, $ARGS)

  • Precise code location information

  • Fast Rust-based execution with performance optimizations

  • Comprehensive pattern validation with helpful error messages

  • 120-second timeout for very large projects

  • Automatic respect for .gitignore files (no manual exclusions needed)

Pattern Syntax:

  • Use $ + UPPERCASE for wildcards: $FUNC, $VAR, $ARGS

  • Patterns look like real code: 'function $NAME($ARGS) { $BODY }'

  • Match specific constructs: 'new $CLASS($ARGS)'

  • Valid characters: (), {}, [], "", '', numbers, operators, keywords

  • NOT regex: do NOT use '|', '.*', '.+', '/pattern/', or escapes like '(' or '{'.

Common Mistakes to Avoid: ❌ Don't use: 'function $FUNC' (ambiguous, multiple AST interpretations) ❌ Don't use: 'export $TYPE' (ambiguous, multiple AST interpretations) ❌ Don't use: '$NAME' (too generic, matches everything) ❌ Don't use: /pattern/ (regex syntax not supported)

βœ… Good Patterns:

  • 'function $NAME($ARGS) { $BODY }' (complete function structure)

  • 'export const $NAME = $VALUE' (exported constant)

  • 'import $NAME from "$MODULE"' (import statement)

  • 'new $CLASS($ARGS)' (constructor call)

  • 'def ' (Python function definitions)

  • 'class $NAME:' (Python class)

  • 'await $PROMISE' inside 'for ($COND) { $BODY }' (relational patterns)

Examples:

  • Find all functions: 'function $NAME($ARGS) { $BODY }'

  • Find all exports: 'export const $NAME = $VALUE'

  • Find imports: 'import $NAME from "$MODULE"'

  • Find class instantiation: 'new $CLASS($ARGS)'

  • Find method calls: '$OBJ.$METHOD($ARGS)'

  • Find async functions: 'async function $NAME($ARGS) { $BODY }'

  • Find arrow functions: 'const $NAME = ($ARGS) => $BODY'

  • Find React components: 'export function $NAME($PROPS) { return $JSX }'

  • Find Python function definitions: 'def '

  • Find Python classes: 'class $NAME:'

Advanced Usage:

  • Use $$$ for zero or more arguments: 'console.log($$$ARGS)'

  • Use relational rules: 'await $PROMISE' inside 'for ($COND) { $BODY }'

  • Use multiple searches for OR conditions (alternation not supported)

Direct CLI Usage (for agents with command line access): Agents with command line access can run ast-grep directly:

Basic usage

npx ast-grep --pattern "function $NAME($ARGS) { $BODY }" --lang ts

Python function definitions

npx ast-grep --pattern "def " --lang py

Python classes

npx ast-grep --pattern "class $NAME:" --lang py

With file filtering (recommended for large projects)

npx ast-grep --pattern "def " --lang py src/**/*.py

JSON output

npx ast-grep --pattern "class $NAME:" --lang py --json=stream

Full documentation

npx ast-grep --help

Note: ast-grep respects .gitignore files automatically - no --exclude-dir flags needed

Use Cases:

  • Code refactoring and migration

  • Finding specific patterns across codebase

  • Security auditing for dangerous patterns

  • Architecture analysis and dependency tracking

  • Finding unused imports or exports

  • API usage analysis

Performance Optimizations for Large Projects:

  • 120-second timeout for very large projects

  • Automatically respects .gitignore files for exclusions

  • For additional exclusions, configure .gitignore in your project

Tips for Large Projects (like D:\Dev\SWE-agent):

  • Use filePattern to search specific directories: "src/**/*.py"

  • Add large directories to .gitignore: node_modules/, tests/, docs/, etc.

  • Consider CLI usage for better performance: npx ast-grep --pattern "import json" --lang py src/**/*.py

Input Schema

NameRequiredDescriptionDefault
patternNoAST pattern, not regex. Use $UPPERCASE wildcards. Examples: "$FUNC($ARGS)", "new $CLASS($ARGS)", "import $NAME from "express""
rulePathNoPath to an ast-grep rule file (YAML/JSON). When provided, rule mode is used instead of pattern.
ruleYamlNoInline ast-grep rule content in YAML (JSON is also valid YAML). Will be written to a temp file and used with --rule.
ruleJsonNoInline ast-grep rule object (JSON). Optionally validated against local schemas and written to a temp file for --rule.
projectPathYesProject directory path to search in. Can be absolute or relative to workspace.
languageNoProgramming language (auto-detected if not provided). Supported: js, ts, py, go, rs, java, c, cpp
filePatternNoSpecific directory or file path to search within the project (e.g., "src", "lib", "*.py", "src/**/*.ts"). **RECOMMENDED for large projects** - if not provided, searches entire project respecting .gitignore. Use wildcards like "src/**/*.py" to search recursively in specific directories. This can dramatically improve performance on large codebases.
maxMatchesNoMaximum number of matches to return (default: 100)
includeContextNoInclude surrounding context lines for each match (default: true)
contextLinesNoNumber of context lines to include around matches (default: 3)
respectGitignoreNoRespect .gitignore files and other ignore patterns (default: true)
excludePatternsNoAdditional patterns to exclude from search (e.g., ["test/**", "docs/**"])

Input Schema (JSON Schema)

{ "properties": { "contextLines": { "default": 3, "description": "Number of context lines to include around matches (default: 3)", "maximum": 10, "minimum": 0, "type": "number" }, "excludePatterns": { "description": "Additional patterns to exclude from search (e.g., [\"test/**\", \"docs/**\"])", "items": { "type": "string" }, "type": "array" }, "filePattern": { "description": "Specific directory or file path to search within the project (e.g., \"src\", \"lib\", \"*.py\", \"src/**/*.ts\"). **RECOMMENDED for large projects** - if not provided, searches entire project respecting .gitignore. Use wildcards like \"src/**/*.py\" to search recursively in specific directories. This can dramatically improve performance on large codebases.", "type": "string" }, "includeContext": { "default": true, "description": "Include surrounding context lines for each match (default: true)", "type": "boolean" }, "language": { "description": "Programming language (auto-detected if not provided). Supported: js, ts, py, go, rs, java, c, cpp", "enum": [ "js", "ts", "tsx", "jsx", "py", "go", "rs", "java", "c", "cpp", "php", "rb", "kt", "swift" ], "type": "string" }, "maxMatches": { "default": 100, "description": "Maximum number of matches to return (default: 100)", "maximum": 1000, "minimum": 1, "type": "number" }, "pattern": { "description": "AST pattern, not regex. Use $UPPERCASE wildcards. Examples: \"$FUNC($ARGS)\", \"new $CLASS($ARGS)\", \"import $NAME from \"express\"\"", "type": "string" }, "projectPath": { "description": "Project directory path to search in. Can be absolute or relative to workspace.", "type": "string" }, "respectGitignore": { "default": true, "description": "Respect .gitignore files and other ignore patterns (default: true)", "type": "boolean" }, "ruleJson": { "description": "Inline ast-grep rule object (JSON). Optionally validated against local schemas and written to a temp file for --rule.", "type": "object" }, "rulePath": { "description": "Path to an ast-grep rule file (YAML/JSON). When provided, rule mode is used instead of pattern.", "type": "string" }, "ruleYaml": { "description": "Inline ast-grep rule content in YAML (JSON is also valid YAML). Will be written to a temp file and used with --rule.", "type": "string" } }, "required": [ "projectPath" ], "type": "object" }

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/sbarron/AmbianceMCP'

If you have feedback or need assistance with the MCP directory API, please join our Discord server