Search patterns in code files Args: pattern: Search pattern file_pattern: File pattern (e.g., '*.py') use_regex: Whether to use regular expressions search_directory: Specify search directory (optional, uses WORKSPACE_DIR if not specified) Returns:
(
pattern: str,
file_pattern: str = "*.json",
use_regex: bool = False,
search_directory: str = None,
)
| 1154 | |
| 1155 | @mcp.tool() |
| 1156 | async def search_code( |
| 1157 | pattern: str, |
| 1158 | file_pattern: str = "*.json", |
| 1159 | use_regex: bool = False, |
| 1160 | search_directory: str = None, |
| 1161 | ) -> str: |
| 1162 | """ |
| 1163 | Search patterns in code files |
| 1164 | |
| 1165 | Args: |
| 1166 | pattern: Search pattern |
| 1167 | file_pattern: File pattern (e.g., '*.py') |
| 1168 | use_regex: Whether to use regular expressions |
| 1169 | search_directory: Specify search directory (optional, uses WORKSPACE_DIR if not specified) |
| 1170 | |
| 1171 | Returns: |
| 1172 | JSON string of search results |
| 1173 | """ |
| 1174 | try: |
| 1175 | # Determine search directory |
| 1176 | if search_directory: |
| 1177 | # If search directory is specified, use the specified directory |
| 1178 | if os.path.isabs(search_directory): |
| 1179 | search_path = Path(search_directory) |
| 1180 | else: |
| 1181 | # Relative path, relative to current working directory |
| 1182 | search_path = Path.cwd() / search_directory |
| 1183 | else: |
| 1184 | # 如果没有指定Search directory,使用默认的WORKSPACE_DIR |
| 1185 | ensure_workspace_exists() |
| 1186 | search_path = WORKSPACE_DIR |
| 1187 | |
| 1188 | # 检查Search directory是否存在 |
| 1189 | if not search_path.exists(): |
| 1190 | result = { |
| 1191 | "status": "error", |
| 1192 | "message": f"Search directory不存在: {search_path}", |
| 1193 | "pattern": pattern, |
| 1194 | } |
| 1195 | return json.dumps(result, ensure_ascii=False, indent=2) |
| 1196 | |
| 1197 | import glob |
| 1198 | |
| 1199 | # Get matching files |
| 1200 | file_paths = glob.glob(str(search_path / "**" / file_pattern), recursive=True) |
| 1201 | |
| 1202 | matches = [] |
| 1203 | total_files_searched = 0 |
| 1204 | |
| 1205 | for file_path in file_paths: |
| 1206 | try: |
| 1207 | with open(file_path, "r", encoding="utf-8") as f: |
| 1208 | lines = f.readlines() |
| 1209 | |
| 1210 | total_files_searched += 1 |
| 1211 | relative_path = os.path.relpath(file_path, search_path) |
| 1212 | |
| 1213 | for line_num, line in enumerate(lines, 1): |
nothing calls this directly
no test coverage detected