|
| 1 | +from typing import Any, List, Optional |
| 2 | +from mcp.server.fastmcp import FastMCP |
| 3 | +import subprocess |
| 4 | +from pydantic import Field |
| 5 | +import json |
| 6 | + |
| 7 | +# Initialize FastMCP server |
| 8 | +mcp = FastMCP("ast-grep") |
| 9 | + |
| 10 | +@mcp.tool() |
| 11 | +def find_code( |
| 12 | + project_folder: str = Field(description="The path to the project folder"), |
| 13 | + pattern: str = Field(description="The ast-grep pattern to search for"), |
| 14 | + language: str = Field(description="The language of the query", default=""), |
| 15 | +) -> List[dict[str, Any]]: |
| 16 | + """Find code in a project folder that matches the given ast-grep pattern. |
| 17 | + """ |
| 18 | + return run_ast_grep_command(pattern, project_folder, language) |
| 19 | + |
| 20 | +def run_ast_grep_command(pattern: str, project_folder: str, language: Optional[str]) -> List[dict[str, Any]]: |
| 21 | + try: |
| 22 | + args = ["ast-grep", "--pattern", pattern, project_folder] |
| 23 | + if language: |
| 24 | + args.extend(["--lang", language]) |
| 25 | + # Run command and capture output |
| 26 | + result = subprocess.run( |
| 27 | + args, |
| 28 | + capture_output=True, |
| 29 | + text=True, |
| 30 | + check=True # Raises CalledProcessError if return code is non-zero |
| 31 | + ) |
| 32 | + return json.loads(result.stdout) |
| 33 | + except subprocess.CalledProcessError as e: |
| 34 | + print(f"Command failed with return code {e.returncode}") |
| 35 | + print("Error output:", e.stderr) |
| 36 | + return e.stderr |
| 37 | + except FileNotFoundError: |
| 38 | + print("Command not found") |
| 39 | + return [] |
| 40 | + |
| 41 | +if __name__ == "__main__": |
| 42 | + mcp.run(transport = "stdio") |
0 commit comments