Skip to main content
Prerequisites
  • Python 3.10 or higher
  • PraisonAI Agents package installed
  • ast-grep CLI (pip install ast-grep-cli or npm install -g @ast-grep/cli)

AST-Grep Tools

Use AST-Grep Tools to search, analyze, and rewrite code using structural patterns instead of regex.
Unlike regex, AST patterns understand code structure — they won’t match patterns inside comments or strings. $VAR captures a single node, $$$ captures multiple nodes.
1

Install Dependencies

Install PraisonAI Agents and ast-grep:
pip install praisonaiagents
pip install ast-grep-cli
2

Import Components

Import the AST-grep tools:
from praisonaiagents import Agent
from praisonaiagents.tools import ast_grep_search, ast_grep_rewrite, ast_grep_scan
3

Create Agent

Create a code analysis agent:
agent = Agent(
    name="CodeAnalyzer",
    instructions="Analyze and refactor code using AST patterns.",
    tools=[ast_grep_search, ast_grep_rewrite, ast_grep_scan],
)
4

Run Agent

Start the agent:
result = agent.start("Find all async function definitions in ./src")

How It Works

Quick Start

from praisonaiagents import Agent
from praisonaiagents.tools import ast_grep_search

agent = Agent(
    name="CodeSearcher",
    instructions="Search code for structural patterns.",
    tools=[ast_grep_search],
)

result = agent.start("Find all function definitions in ./src")

Available Functions

from praisonaiagents.tools import ast_grep_search
from praisonaiagents.tools import ast_grep_rewrite
from praisonaiagents.tools import ast_grep_scan
from praisonaiagents.tools import get_ast_grep_tools
from praisonaiagents.tools import is_ast_grep_available

Function Details

ast_grep_search(pattern, lang, path=”.”, json_output=True)

Searches code using AST patterns. Returns structured JSON results.
ParameterTypeDefaultDescription
patternstrrequiredAST pattern ($VAR = single node, $$$ = multiple)
langstrrequiredLanguage: python, javascript, typescript, rust, go, java, c, cpp
pathstr"."File or directory to search
json_outputboolTrueReturn JSON format
# Find all Python function definitions
result = ast_grep_search("def $FN($$$)", lang="python", path="./src")

# Find all console.log calls in JavaScript
result = ast_grep_search("console.log($$$)", lang="javascript")

# Find all async functions
result = ast_grep_search("async def $FN($$$)", lang="python")

# Find all class definitions with inheritance
result = ast_grep_search("class $NAME($BASE):", lang="python")

ast_grep_rewrite(pattern, replacement, lang, path=”.”, dry_run=True)

Rewrites code matching an AST pattern. Dry-run by default (shows changes without modifying files).
ParameterTypeDefaultDescription
patternstrrequiredAST pattern to match
replacementstrrequiredReplacement pattern (can reference $VAR captures)
langstrrequiredProgramming language
pathstr"."File or directory
dry_runboolTruePreview only — set False to apply
Setting dry_run=False will modify files in place. Always preview first with the default dry_run=True.
# Preview: rename a function (dry run)
result = ast_grep_rewrite(
    "def old_name($$$)",
    "def new_name($$$)",
    lang="python",
    path="./src"
)

# Actually apply: replace console.log with logger.info
result = ast_grep_rewrite(
    "console.log($MSG)",
    "logger.info($MSG)",
    lang="javascript",
    dry_run=False
)

ast_grep_scan(path=”.”, rule_file=None)

Scans code using YAML-based lint rules.
ParameterTypeDefaultDescription
pathstr"."File or directory to scan
rule_filestrNonePath to YAML rule file (uses sgconfig.yml if not set)
# Scan with default rules
result = ast_grep_scan(path="./src")

# Scan with custom rules
result = ast_grep_scan(path="./src", rule_file="./rules/security.yml")

Autonomy Mode

AST-grep tools are automatically included when using autonomy mode:
from praisonaiagents import Agent

# Tools auto-included via get_autonomy_default_tools()
agent = Agent(autonomy=True)
agent.start("Refactor the codebase to use consistent naming")
In autonomy mode, ast-grep tools are available without explicit tools= — the agent can use them whenever it decides to search or rewrite code.

Graceful Fallback

AST-grep tools work safely even when ast-grep is not installed:
from praisonaiagents.tools import is_ast_grep_available, ast_grep_search

# Check availability
if is_ast_grep_available():
    result = ast_grep_search("def $FN($$$)", lang="python")
else:
    print("ast-grep not installed")

# Or just call it — returns helpful install instructions
result = ast_grep_search("def $FN($$$)", lang="python")
# If not installed, returns:
# "ast-grep is not installed or not available in PATH.
#  To install: pip install ast-grep-cli"
Agents with ast-grep tools will never crash if ast-grep is missing. The tools return install instructions instead.

Pattern Syntax

PatternMeaningExample
$VARMatch single AST nodedef $FN() matches any no-arg function
$$$Match multiple nodesdef $FN($$$) matches any function
Literal codeMatch exactlyprint("hello") matches that exact call

Pattern Examples by Language

# All function definitions
"def $FN($$$)"

# All class definitions
"class $NAME($$$):"

# All if statements
"if $COND: $$$"

# All async functions
"async def $FN($$$)"

# All list comprehensions
"[$EXPR for $VAR in $ITER]"
// All arrow functions
"($$$) => $BODY"

// All console.log calls
"console.log($$$)"

// All async functions
"async function $FN($$$) { $$$ }"

// All React useState hooks
"const [$STATE, $SETTER] = useState($$$)"

// All fetch calls
"fetch($URL, $$$)"
// All function definitions
"fn $FN($$$) -> $RET { $$$ }"

// All impl blocks
"impl $TYPE { $$$ }"

// All match expressions
"match $EXPR { $$$ }"

// All unsafe blocks
"unsafe { $$$ }"

Examples

from praisonaiagents import Agent, Task, AgentTeam
from praisonaiagents.tools import ast_grep_search, ast_grep_scan

security_agent = Agent(
    name="SecurityAuditor",
    instructions="""Audit code for security vulnerabilities:
    - Find eval() and exec() calls
    - Find SQL string concatenation
    - Find hardcoded credentials""",
    tools=[ast_grep_search, ast_grep_scan],
)

audit_task = Task(
    description="Audit ./src for security issues: eval/exec usage, SQL injection, hardcoded secrets.",
    expected_output="Security report with findings and recommendations.",
    agent=security_agent,
    name="security_audit"
)

team = AgentTeam(agents=[security_agent], tasks=[audit_task], process="sequential")
team.start()
from praisonaiagents import Agent
from praisonaiagents.tools import ast_grep_search, ast_grep_rewrite

migrator = Agent(
    name="Migrator",
    instructions="""Migrate code patterns:
    - Replace deprecated APIs with new ones
    - Always preview first (dry_run=True)
    - Only apply changes after confirming the preview""",
    tools=[ast_grep_search, ast_grep_rewrite],
)

result = migrator.start(
    "Replace all console.log calls with logger.info in JavaScript files under ./app"
)
from praisonaiagents import Agent, Task, AgentTeam
from praisonaiagents.tools import ast_grep_search, ast_grep_scan

# Searcher finds patterns
searcher = Agent(
    name="PatternFinder",
    instructions="Find code patterns and anti-patterns using AST search.",
    tools=[ast_grep_search],
)

# Reviewer analyzes findings
reviewer = Agent(
    name="CodeReviewer",
    instructions="Review code quality findings and provide recommendations.",
)

search_task = Task(
    description="Find all functions longer than 50 lines and deeply nested conditionals.",
    agent=searcher,
    name="pattern_search"
)

review_task = Task(
    description="Review the search findings and provide refactoring recommendations.",
    agent=reviewer,
    name="code_review"
)

team = AgentTeam(
    agents=[searcher, reviewer],
    tasks=[search_task, review_task],
    process="sequential"
)
team.start()

Dependencies

PackageRequiredInstall
praisonaiagentsYespip install praisonaiagents
ast-grep-cliOptionalpip install ast-grep-cli or npm install -g @ast-grep/cli
Install the optional autonomy extras for ast-grep + other autonomy tools:
pip install praisonaiagents[autonomy]

Error Handling

All functions include comprehensive error handling:
  • Not installed: Returns helpful install instructions
  • Empty pattern: Returns clear error message
  • Timeout: 60s for search, 120s for rewrite/scan
  • Subprocess errors: Captured and returned as strings
  • No matches: Returns “No matches found” (not an error)