Skip to content

Commit 48da8aa

Browse files
feat: add debug syntax tool
1 parent d23a4c1 commit 48da8aa

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed

main.py

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,10 +3,32 @@
33
import subprocess
44
from pydantic import Field
55
import json
6+
from enum import Enum
67

78
# Initialize FastMCP server
89
mcp = FastMCP("ast-grep")
910

11+
class DumpFormat(Enum):
12+
Pattern = "pattern"
13+
CST = "cst"
14+
AST = "ast"
15+
16+
@mcp.tool()
17+
def dump_syntax_tree(
18+
code: str = Field(description = "The code you need"),
19+
language: str = Field(description = "The language of the code"),
20+
format: DumpFormat = Field(description = "Code dump format. Available values: pattern, ast, cst", default = "cst"),
21+
) -> str:
22+
"""
23+
Dump code's syntax structure or dump a query's pattern structure.
24+
This is useful to discover correct syntax kind and syntax tree structure. Call it when debugging a rule.
25+
The tool requires three argument: code, language and format. The first two are self-explanatory.
26+
`format` is the output format of the syntax tree.
27+
use `format=cst` to inspect the code's concrete syntax tree structure, useful to debug target code.
28+
use `format=pattern` to inspect how ast-grep interprets a pattern, useful to debug pattern rule.
29+
"""
30+
return run_ast_grep_dump(code, language, format.value)
31+
1032
@mcp.tool()
1133
def find_code(
1234
project_folder: str = Field(description="The path to the project folder"),
@@ -32,6 +54,21 @@ def find_code_by_rule(
3254
"""
3355
return run_ast_grep_yaml(yaml, project_folder)
3456

57+
def run_ast_grep_dump(code: str, language: str, format: str) -> str:
58+
args = ["ast-grep", "--pattern", code, "--lang", language, f"--debug-query={format}"]
59+
try:
60+
result = subprocess.run(
61+
args,
62+
capture_output=True,
63+
text=True,
64+
check=True # Raises CalledProcessError if return code is non-zero
65+
)
66+
return result.stderr.strip() # Return the output of the command
67+
except subprocess.CalledProcessError as e:
68+
print(f"Command failed with return code {e.returncode}")
69+
print("Error output:", e.stderr)
70+
return e.stderr.strip()
71+
3572
def run_ast_grep_command(pattern: str, project_folder: str, language: Optional[str]) -> List[dict[str, Any]]:
3673
try:
3774
args = ["ast-grep", "--pattern", pattern, "--json", project_folder]

0 commit comments

Comments
 (0)