tree-sitter-analyzer 0.7.0__py3-none-any.whl → 0.8.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of tree-sitter-analyzer might be problematic. Click here for more details.

Files changed (70) hide show
  1. tree_sitter_analyzer/__init__.py +132 -132
  2. tree_sitter_analyzer/__main__.py +11 -11
  3. tree_sitter_analyzer/api.py +533 -533
  4. tree_sitter_analyzer/cli/__init__.py +39 -39
  5. tree_sitter_analyzer/cli/__main__.py +12 -12
  6. tree_sitter_analyzer/cli/commands/__init__.py +26 -26
  7. tree_sitter_analyzer/cli/commands/advanced_command.py +88 -88
  8. tree_sitter_analyzer/cli/commands/base_command.py +178 -160
  9. tree_sitter_analyzer/cli/commands/default_command.py +18 -18
  10. tree_sitter_analyzer/cli/commands/partial_read_command.py +141 -141
  11. tree_sitter_analyzer/cli/commands/query_command.py +88 -81
  12. tree_sitter_analyzer/cli/commands/structure_command.py +138 -138
  13. tree_sitter_analyzer/cli/commands/summary_command.py +101 -101
  14. tree_sitter_analyzer/cli/commands/table_command.py +235 -235
  15. tree_sitter_analyzer/cli/info_commands.py +121 -121
  16. tree_sitter_analyzer/cli_main.py +303 -297
  17. tree_sitter_analyzer/core/__init__.py +15 -15
  18. tree_sitter_analyzer/core/analysis_engine.py +580 -555
  19. tree_sitter_analyzer/core/cache_service.py +320 -320
  20. tree_sitter_analyzer/core/engine.py +566 -566
  21. tree_sitter_analyzer/core/parser.py +293 -293
  22. tree_sitter_analyzer/encoding_utils.py +459 -459
  23. tree_sitter_analyzer/exceptions.py +406 -337
  24. tree_sitter_analyzer/file_handler.py +210 -210
  25. tree_sitter_analyzer/formatters/__init__.py +1 -1
  26. tree_sitter_analyzer/formatters/base_formatter.py +167 -167
  27. tree_sitter_analyzer/formatters/formatter_factory.py +78 -78
  28. tree_sitter_analyzer/interfaces/__init__.py +9 -9
  29. tree_sitter_analyzer/interfaces/cli.py +528 -528
  30. tree_sitter_analyzer/interfaces/cli_adapter.py +343 -343
  31. tree_sitter_analyzer/interfaces/mcp_adapter.py +206 -206
  32. tree_sitter_analyzer/interfaces/mcp_server.py +425 -405
  33. tree_sitter_analyzer/languages/__init__.py +10 -10
  34. tree_sitter_analyzer/languages/javascript_plugin.py +446 -446
  35. tree_sitter_analyzer/languages/python_plugin.py +755 -755
  36. tree_sitter_analyzer/mcp/__init__.py +31 -31
  37. tree_sitter_analyzer/mcp/resources/__init__.py +44 -44
  38. tree_sitter_analyzer/mcp/resources/code_file_resource.py +209 -209
  39. tree_sitter_analyzer/mcp/server.py +408 -333
  40. tree_sitter_analyzer/mcp/tools/__init__.py +30 -30
  41. tree_sitter_analyzer/mcp/tools/analyze_scale_tool.py +673 -654
  42. tree_sitter_analyzer/mcp/tools/analyze_scale_tool_cli_compatible.py +247 -247
  43. tree_sitter_analyzer/mcp/tools/base_tool.py +54 -54
  44. tree_sitter_analyzer/mcp/tools/read_partial_tool.py +308 -300
  45. tree_sitter_analyzer/mcp/tools/table_format_tool.py +379 -362
  46. tree_sitter_analyzer/mcp/tools/universal_analyze_tool.py +559 -543
  47. tree_sitter_analyzer/mcp/utils/__init__.py +107 -107
  48. tree_sitter_analyzer/mcp/utils/error_handler.py +549 -549
  49. tree_sitter_analyzer/output_manager.py +253 -253
  50. tree_sitter_analyzer/plugins/__init__.py +280 -280
  51. tree_sitter_analyzer/plugins/base.py +529 -529
  52. tree_sitter_analyzer/plugins/manager.py +379 -379
  53. tree_sitter_analyzer/project_detector.py +317 -0
  54. tree_sitter_analyzer/queries/__init__.py +26 -26
  55. tree_sitter_analyzer/queries/java.py +391 -391
  56. tree_sitter_analyzer/queries/javascript.py +148 -148
  57. tree_sitter_analyzer/queries/python.py +285 -285
  58. tree_sitter_analyzer/queries/typescript.py +229 -229
  59. tree_sitter_analyzer/query_loader.py +257 -257
  60. tree_sitter_analyzer/security/__init__.py +22 -0
  61. tree_sitter_analyzer/security/boundary_manager.py +237 -0
  62. tree_sitter_analyzer/security/regex_checker.py +292 -0
  63. tree_sitter_analyzer/security/validator.py +241 -0
  64. tree_sitter_analyzer/table_formatter.py +652 -589
  65. tree_sitter_analyzer/utils.py +277 -277
  66. {tree_sitter_analyzer-0.7.0.dist-info → tree_sitter_analyzer-0.8.1.dist-info}/METADATA +27 -1
  67. tree_sitter_analyzer-0.8.1.dist-info/RECORD +77 -0
  68. tree_sitter_analyzer-0.7.0.dist-info/RECORD +0 -72
  69. {tree_sitter_analyzer-0.7.0.dist-info → tree_sitter_analyzer-0.8.1.dist-info}/WHEEL +0 -0
  70. {tree_sitter_analyzer-0.7.0.dist-info → tree_sitter_analyzer-0.8.1.dist-info}/entry_points.txt +0 -0
@@ -1,654 +1,673 @@
1
- #!/usr/bin/env python3
2
- """
3
- Analyze Code Scale MCP Tool
4
-
5
- This tool provides code scale analysis including metrics about
6
- complexity, size, and structure through the MCP protocol.
7
- Enhanced for LLM-friendly analysis workflow.
8
- """
9
-
10
- import re
11
- from pathlib import Path
12
- from typing import Any
13
-
14
- from ...core.analysis_engine import AnalysisRequest, get_analysis_engine
15
- from ...language_detector import detect_language_from_file
16
- from ...utils import setup_logger
17
-
18
- # Set up logging
19
- logger = setup_logger(__name__)
20
-
21
-
22
- class AnalyzeScaleTool:
23
- """
24
- MCP Tool for analyzing code scale and complexity metrics.
25
-
26
- This tool integrates with existing analyzer components to provide
27
- comprehensive code analysis through the MCP protocol, optimized
28
- for LLM workflow efficiency.
29
- """
30
-
31
- def __init__(self) -> None:
32
- """Initialize the analyze scale tool."""
33
- # Use unified analysis engine instead of deprecated AdvancedAnalyzer
34
- self.analysis_engine = get_analysis_engine()
35
- logger.info("AnalyzeScaleTool initialized")
36
-
37
- def _calculate_file_metrics(self, file_path: str) -> dict[str, Any]:
38
- """
39
- Calculate basic file metrics including line counts and estimated token count.
40
-
41
- Args:
42
- file_path: Path to the file to analyze
43
-
44
- Returns:
45
- Dictionary containing file metrics
46
- """
47
- try:
48
- with open(file_path, encoding="utf-8") as f:
49
- content = f.read()
50
-
51
- lines = content.split("\n")
52
- total_lines = len(lines)
53
-
54
- # Count different types of lines
55
- code_lines = 0
56
- comment_lines = 0
57
- blank_lines = 0
58
-
59
- for line in lines:
60
- stripped = line.strip()
61
- if not stripped:
62
- blank_lines += 1
63
- elif (
64
- stripped.startswith("//")
65
- or stripped.startswith("/*")
66
- or stripped.startswith("*")
67
- ):
68
- comment_lines += 1
69
- else:
70
- code_lines += 1
71
-
72
- # Estimate token count (rough approximation)
73
- # Split by common delimiters and count non-empty tokens
74
- tokens = re.findall(r"\b\w+\b|[^\w\s]", content)
75
- estimated_tokens = len([t for t in tokens if t.strip()])
76
-
77
- # Calculate file size
78
- file_size = len(content.encode("utf-8"))
79
-
80
- return {
81
- "total_lines": total_lines,
82
- "code_lines": code_lines,
83
- "comment_lines": comment_lines,
84
- "blank_lines": blank_lines,
85
- "estimated_tokens": estimated_tokens,
86
- "file_size_bytes": file_size,
87
- "file_size_kb": round(file_size / 1024, 2),
88
- }
89
- except Exception as e:
90
- logger.error(f"Error calculating file metrics for {file_path}: {e}")
91
- return {
92
- "total_lines": 0,
93
- "code_lines": 0,
94
- "comment_lines": 0,
95
- "blank_lines": 0,
96
- "estimated_tokens": 0,
97
- "file_size_bytes": 0,
98
- "file_size_kb": 0,
99
- }
100
-
101
- def _extract_structural_overview(self, analysis_result: Any) -> dict[str, Any]:
102
- """
103
- Extract structural overview with position information for LLM guidance.
104
-
105
- Args:
106
- analysis_result: Result from AdvancedAnalyzer
107
-
108
- Returns:
109
- Dictionary containing structural overview
110
- """
111
- overview: dict[str, Any] = {
112
- "classes": [],
113
- "methods": [],
114
- "fields": [],
115
- "imports": [],
116
- "complexity_hotspots": [],
117
- }
118
-
119
- # Extract class information with position from unified analysis engine
120
- classes = [
121
- e for e in analysis_result.elements if e.__class__.__name__ == "Class"
122
- ]
123
- for cls in classes:
124
- class_info = {
125
- "name": cls.name,
126
- "type": cls.class_type,
127
- "start_line": cls.start_line,
128
- "end_line": cls.end_line,
129
- "line_span": cls.end_line - cls.start_line + 1,
130
- "visibility": cls.visibility,
131
- "extends": cls.extends_class,
132
- "implements": cls.implements_interfaces,
133
- "annotations": [ann.name for ann in cls.annotations],
134
- }
135
- overview["classes"].append(class_info)
136
-
137
- # Extract method information with position and complexity from unified analysis engine
138
- methods = [
139
- e for e in analysis_result.elements if e.__class__.__name__ == "Function"
140
- ]
141
- for method in methods:
142
- method_info = {
143
- "name": method.name,
144
- "start_line": method.start_line,
145
- "end_line": method.end_line,
146
- "line_span": method.end_line - method.start_line + 1,
147
- "visibility": method.visibility,
148
- "return_type": method.return_type,
149
- "parameter_count": len(method.parameters),
150
- "complexity": method.complexity_score,
151
- "is_constructor": method.is_constructor,
152
- "is_static": method.is_static,
153
- "annotations": [ann.name for ann in method.annotations],
154
- }
155
- overview["methods"].append(method_info)
156
-
157
- # Track complexity hotspots
158
- if method.complexity_score > 10: # High complexity threshold
159
- overview["complexity_hotspots"].append(
160
- {
161
- "type": "method",
162
- "name": method.name,
163
- "complexity": method.complexity_score,
164
- "start_line": method.start_line,
165
- "end_line": method.end_line,
166
- }
167
- )
168
-
169
- # Extract field information with position
170
- # Extract field information from unified analysis engine
171
- fields = [
172
- e for e in analysis_result.elements if e.__class__.__name__ == "Variable"
173
- ]
174
- for field in fields:
175
- field_info = {
176
- "name": field.name,
177
- "type": field.field_type,
178
- "start_line": field.start_line,
179
- "end_line": field.end_line,
180
- "visibility": field.visibility,
181
- "is_static": field.is_static,
182
- "is_final": field.is_final,
183
- "annotations": [ann.name for ann in field.annotations],
184
- }
185
- overview["fields"].append(field_info)
186
-
187
- # Extract import information
188
- # Extract import information from unified analysis engine
189
- imports = [
190
- e for e in analysis_result.elements if e.__class__.__name__ == "Import"
191
- ]
192
- for imp in imports:
193
- import_info = {
194
- "name": imp.imported_name,
195
- "statement": imp.import_statement,
196
- "line": imp.line_number,
197
- "is_static": imp.is_static,
198
- "is_wildcard": imp.is_wildcard,
199
- }
200
- overview["imports"].append(import_info)
201
-
202
- return overview
203
-
204
- def _generate_llm_guidance(
205
- self, file_metrics: dict[str, Any], structural_overview: dict[str, Any]
206
- ) -> dict[str, Any]:
207
- """
208
- Generate guidance for LLM on how to efficiently analyze this file.
209
-
210
- Args:
211
- file_metrics: Basic file metrics
212
- structural_overview: Structural overview of the code
213
-
214
- Returns:
215
- Dictionary containing LLM guidance
216
- """
217
- guidance: dict[str, Any] = {
218
- "analysis_strategy": "",
219
- "recommended_tools": [],
220
- "key_areas": [],
221
- "complexity_assessment": "",
222
- "size_category": "",
223
- }
224
-
225
- total_lines = file_metrics["total_lines"]
226
- # estimated_tokens = file_metrics["estimated_tokens"] # Not used currently
227
-
228
- # Determine size category
229
- if total_lines < 100:
230
- guidance["size_category"] = "small"
231
- guidance["analysis_strategy"] = (
232
- "This is a small file that can be analyzed in full detail."
233
- )
234
- elif total_lines < 500:
235
- guidance["size_category"] = "medium"
236
- guidance["analysis_strategy"] = (
237
- "This is a medium-sized file. Consider focusing on key classes and methods."
238
- )
239
- elif total_lines < 1500:
240
- guidance["size_category"] = "large"
241
- guidance["analysis_strategy"] = (
242
- "This is a large file. Use targeted analysis with read_code_partial."
243
- )
244
- else:
245
- guidance["size_category"] = "very_large"
246
- guidance["analysis_strategy"] = (
247
- "This is a very large file. Strongly recommend using structural analysis first, then targeted deep-dives."
248
- )
249
-
250
- # Recommend tools based on file size and complexity
251
- if total_lines > 200:
252
- guidance["recommended_tools"].append("read_code_partial")
253
-
254
- if len(structural_overview["complexity_hotspots"]) > 0:
255
- guidance["recommended_tools"].append("format_table")
256
- guidance["complexity_assessment"] = (
257
- f"Found {len(structural_overview['complexity_hotspots'])} complexity hotspots"
258
- )
259
- else:
260
- guidance["complexity_assessment"] = (
261
- "No significant complexity hotspots detected"
262
- )
263
-
264
- # Identify key areas for analysis
265
- if len(structural_overview["classes"]) > 1:
266
- guidance["key_areas"].append(
267
- "Multiple classes - consider analyzing class relationships"
268
- )
269
-
270
- if len(structural_overview["methods"]) > 20:
271
- guidance["key_areas"].append(
272
- "Many methods - focus on public interfaces and high-complexity methods"
273
- )
274
-
275
- if len(structural_overview["imports"]) > 10:
276
- guidance["key_areas"].append("Many imports - consider dependency analysis")
277
-
278
- return guidance
279
-
280
- def get_tool_schema(self) -> dict[str, Any]:
281
- """
282
- Get the MCP tool schema for analyze_code_scale.
283
-
284
- Returns:
285
- Dictionary containing the tool schema
286
- """
287
- return {
288
- "type": "object",
289
- "properties": {
290
- "file_path": {
291
- "type": "string",
292
- "description": "Path to the code file to analyze",
293
- },
294
- "language": {
295
- "type": "string",
296
- "description": "Programming language (optional, auto-detected if not specified)",
297
- },
298
- "include_complexity": {
299
- "type": "boolean",
300
- "description": "Include complexity metrics in the analysis",
301
- "default": True,
302
- },
303
- "include_details": {
304
- "type": "boolean",
305
- "description": "Include detailed element information",
306
- "default": False,
307
- },
308
- "include_guidance": {
309
- "type": "boolean",
310
- "description": "Include LLM analysis guidance",
311
- "default": True,
312
- },
313
- },
314
- "required": ["file_path"],
315
- "additionalProperties": False,
316
- }
317
-
318
- async def execute(self, arguments: dict[str, Any]) -> dict[str, Any]:
319
- """
320
- Execute the analyze_code_scale tool.
321
-
322
- Args:
323
- arguments: Tool arguments containing file_path and optional parameters
324
-
325
- Returns:
326
- Dictionary containing enhanced analysis results optimized for LLM workflow
327
-
328
- Raises:
329
- ValueError: If required arguments are missing or invalid
330
- FileNotFoundError: If the specified file doesn't exist
331
- """
332
- # Validate required arguments
333
- if "file_path" not in arguments:
334
- raise ValueError("file_path is required")
335
-
336
- file_path = arguments["file_path"]
337
- language = arguments.get("language")
338
- # include_complexity = arguments.get("include_complexity", True) # Not used currently
339
- include_details = arguments.get("include_details", False)
340
- include_guidance = arguments.get("include_guidance", True)
341
-
342
- # Validate file exists
343
- if not Path(file_path).exists():
344
- raise FileNotFoundError(f"File not found: {file_path}")
345
-
346
- # Detect language if not specified
347
- if not language:
348
- language = detect_language_from_file(file_path)
349
- if language == "unknown":
350
- raise ValueError(f"Could not detect language for file: {file_path}")
351
-
352
- logger.info(f"Analyzing code scale for {file_path} (language: {language})")
353
-
354
- try:
355
- # Use performance monitoring with proper context manager
356
- from ...mcp.utils import get_performance_monitor
357
-
358
- with get_performance_monitor().measure_operation(
359
- "analyze_code_scale_enhanced"
360
- ):
361
- # Calculate basic file metrics
362
- file_metrics = self._calculate_file_metrics(file_path)
363
-
364
- # Use appropriate analyzer based on language
365
- if language == "java":
366
- # Use AdvancedAnalyzer for comprehensive analysis
367
- # Use unified analysis engine instead of deprecated advanced_analyzer
368
- request = AnalysisRequest(
369
- file_path=file_path,
370
- language=language,
371
- include_complexity=True,
372
- include_details=True,
373
- )
374
- analysis_result = await self.analysis_engine.analyze(request)
375
- if analysis_result is None:
376
- raise RuntimeError(f"Failed to analyze file: {file_path}")
377
- # Extract structural overview
378
- structural_overview = self._extract_structural_overview(
379
- analysis_result
380
- )
381
- else:
382
- # Use universal analysis_engine for other languages
383
- request = AnalysisRequest(
384
- file_path=file_path,
385
- language=language,
386
- include_details=include_details,
387
- )
388
- universal_result = await self.analysis_engine.analyze(request)
389
- if not universal_result or not universal_result.success:
390
- error_msg = (
391
- universal_result.error_message
392
- if universal_result
393
- else "Unknown error"
394
- )
395
- raise RuntimeError(
396
- f"Failed to analyze file with universal engine: {error_msg}"
397
- )
398
-
399
- # Adapt the result to a compatible structure for report generation
400
- # This part needs careful implementation based on universal_result structure
401
- analysis_result = None # Placeholder
402
- structural_overview = {} # Placeholder
403
-
404
- # Generate LLM guidance
405
- llm_guidance = None
406
- if include_guidance:
407
- llm_guidance = self._generate_llm_guidance(
408
- file_metrics, structural_overview
409
- )
410
-
411
- # Build enhanced result structure
412
- result = {
413
- "file_path": file_path,
414
- "language": language,
415
- "file_metrics": file_metrics,
416
- "summary": {
417
- "classes": len(
418
- [
419
- e
420
- for e in (
421
- analysis_result.elements if analysis_result else []
422
- )
423
- if e.__class__.__name__ == "Class"
424
- ]
425
- ),
426
- "methods": len(
427
- [
428
- e
429
- for e in (
430
- analysis_result.elements if analysis_result else []
431
- )
432
- if e.__class__.__name__ == "Function"
433
- ]
434
- ),
435
- "fields": len(
436
- [
437
- e
438
- for e in (
439
- analysis_result.elements if analysis_result else []
440
- )
441
- if e.__class__.__name__ == "Variable"
442
- ]
443
- ),
444
- "imports": len(
445
- [
446
- e
447
- for e in (
448
- analysis_result.elements if analysis_result else []
449
- )
450
- if e.__class__.__name__ == "Import"
451
- ]
452
- ),
453
- "annotations": len(
454
- getattr(analysis_result, "annotations", [])
455
- if analysis_result
456
- else []
457
- ),
458
- "package": (
459
- analysis_result.package.name
460
- if analysis_result and analysis_result.package
461
- else None
462
- ),
463
- },
464
- "structural_overview": structural_overview,
465
- }
466
-
467
- if include_guidance:
468
- result["llm_guidance"] = llm_guidance
469
-
470
- # Add detailed information if requested (backward compatibility)
471
- if include_details:
472
- result["detailed_analysis"] = {
473
- "statistics": (
474
- analysis_result.get_statistics() if analysis_result else {}
475
- ),
476
- "classes": [
477
- {
478
- "name": cls.name,
479
- "type": getattr(cls, "class_type", "unknown"),
480
- "visibility": getattr(cls, "visibility", "unknown"),
481
- "extends": getattr(cls, "extends_class", None),
482
- "implements": getattr(cls, "implements_interfaces", []),
483
- "annotations": [
484
- getattr(ann, "name", str(ann))
485
- for ann in getattr(cls, "annotations", [])
486
- ],
487
- "lines": f"{cls.start_line}-{cls.end_line}",
488
- }
489
- for cls in [
490
- e
491
- for e in (
492
- analysis_result.elements if analysis_result else []
493
- )
494
- if e.__class__.__name__ == "Class"
495
- ]
496
- ],
497
- "methods": [
498
- {
499
- "name": method.name,
500
- "file_path": getattr(method, "file_path", file_path),
501
- "visibility": getattr(method, "visibility", "unknown"),
502
- "return_type": getattr(
503
- method, "return_type", "unknown"
504
- ),
505
- "parameters": len(getattr(method, "parameters", [])),
506
- "annotations": [
507
- getattr(ann, "name", str(ann))
508
- for ann in getattr(method, "annotations", [])
509
- ],
510
- "is_constructor": getattr(
511
- method, "is_constructor", False
512
- ),
513
- "is_static": getattr(method, "is_static", False),
514
- "complexity": getattr(method, "complexity_score", 0),
515
- "lines": f"{method.start_line}-{method.end_line}",
516
- }
517
- for method in [
518
- e
519
- for e in (
520
- analysis_result.elements if analysis_result else []
521
- )
522
- if e.__class__.__name__ == "Function"
523
- ]
524
- ],
525
- "fields": [
526
- {
527
- "name": field.name,
528
- "type": getattr(field, "field_type", "unknown"),
529
- "file_path": getattr(field, "file_path", file_path),
530
- "visibility": getattr(field, "visibility", "unknown"),
531
- "is_static": getattr(field, "is_static", False),
532
- "is_final": getattr(field, "is_final", False),
533
- "annotations": [
534
- getattr(ann, "name", str(ann))
535
- for ann in getattr(field, "annotations", [])
536
- ],
537
- "lines": f"{field.start_line}-{field.end_line}",
538
- }
539
- for field in [
540
- e
541
- for e in (
542
- analysis_result.elements if analysis_result else []
543
- )
544
- if e.__class__.__name__ == "Variable"
545
- ]
546
- ],
547
- }
548
-
549
- # Count elements by type
550
- classes_count = len(
551
- [
552
- e
553
- for e in (analysis_result.elements if analysis_result else [])
554
- if e.__class__.__name__ == "Class"
555
- ]
556
- )
557
- methods_count = len(
558
- [
559
- e
560
- for e in (analysis_result.elements if analysis_result else [])
561
- if e.__class__.__name__ == "Function"
562
- ]
563
- )
564
-
565
- logger.info(
566
- f"Successfully analyzed {file_path}: {classes_count} classes, "
567
- f"{methods_count} methods, {file_metrics['total_lines']} lines, "
568
- f"~{file_metrics['estimated_tokens']} tokens"
569
- )
570
-
571
- return result
572
-
573
- except Exception as e:
574
- logger.error(f"Error analyzing {file_path}: {e}")
575
- raise
576
-
577
- def validate_arguments(self, arguments: dict[str, Any]) -> bool:
578
- """
579
- Validate tool arguments against the schema.
580
-
581
- Args:
582
- arguments: Arguments to validate
583
-
584
- Returns:
585
- True if arguments are valid
586
-
587
- Raises:
588
- ValueError: If arguments are invalid
589
- """
590
- schema = self.get_tool_schema()
591
- required_fields = schema.get("required", [])
592
-
593
- # Check required fields
594
- for field in required_fields:
595
- if field not in arguments:
596
- raise ValueError(f"Required field '{field}' is missing")
597
-
598
- # Validate file_path
599
- if "file_path" in arguments:
600
- file_path = arguments["file_path"]
601
- if not isinstance(file_path, str):
602
- raise ValueError("file_path must be a string")
603
- if not file_path.strip():
604
- raise ValueError("file_path cannot be empty")
605
-
606
- # Validate optional fields
607
- if "language" in arguments:
608
- language = arguments["language"]
609
- if not isinstance(language, str):
610
- raise ValueError("language must be a string")
611
-
612
- if "include_complexity" in arguments:
613
- include_complexity = arguments["include_complexity"]
614
- if not isinstance(include_complexity, bool):
615
- raise ValueError("include_complexity must be a boolean")
616
-
617
- if "include_details" in arguments:
618
- include_details = arguments["include_details"]
619
- if not isinstance(include_details, bool):
620
- raise ValueError("include_details must be a boolean")
621
-
622
- if "include_guidance" in arguments:
623
- include_guidance = arguments["include_guidance"]
624
- if not isinstance(include_guidance, bool):
625
- raise ValueError("include_guidance must be a boolean")
626
-
627
- return True
628
-
629
- def get_tool_definition(self) -> Any:
630
- """
631
- Get the MCP tool definition for analyze_code_scale.
632
-
633
- Returns:
634
- Tool definition object compatible with MCP server
635
- """
636
- try:
637
- from mcp.types import Tool
638
-
639
- return Tool(
640
- name="analyze_code_scale",
641
- description="Analyze code scale, complexity, and structure metrics with LLM-optimized guidance for efficient large file analysis",
642
- inputSchema=self.get_tool_schema(),
643
- )
644
- except ImportError:
645
- # Fallback for when MCP is not available
646
- return {
647
- "name": "analyze_code_scale",
648
- "description": "Analyze code scale, complexity, and structure metrics with LLM-optimized guidance for efficient large file analysis",
649
- "inputSchema": self.get_tool_schema(),
650
- }
651
-
652
-
653
- # Tool instance for easy access
654
- analyze_scale_tool = AnalyzeScaleTool()
1
+ #!/usr/bin/env python3
2
+ """
3
+ Analyze Code Scale MCP Tool
4
+
5
+ This tool provides code scale analysis including metrics about
6
+ complexity, size, and structure through the MCP protocol.
7
+ Enhanced for LLM-friendly analysis workflow.
8
+ """
9
+
10
+ import re
11
+ from pathlib import Path
12
+ from typing import Any
13
+
14
+ from ...core.analysis_engine import AnalysisRequest, get_analysis_engine
15
+ from ...language_detector import detect_language_from_file
16
+ from ...security import SecurityValidator
17
+ from ...utils import setup_logger
18
+
19
+ # Set up logging
20
+ logger = setup_logger(__name__)
21
+
22
+
23
+ class AnalyzeScaleTool:
24
+ """
25
+ MCP Tool for analyzing code scale and complexity metrics.
26
+
27
+ This tool integrates with existing analyzer components to provide
28
+ comprehensive code analysis through the MCP protocol, optimized
29
+ for LLM workflow efficiency.
30
+ """
31
+
32
+ def __init__(self, project_root: str = None) -> None:
33
+ """Initialize the analyze scale tool."""
34
+ # Use unified analysis engine instead of deprecated AdvancedAnalyzer
35
+ self.project_root = project_root
36
+ self.analysis_engine = get_analysis_engine(project_root)
37
+ self.security_validator = SecurityValidator(project_root)
38
+ logger.info("AnalyzeScaleTool initialized with security validation")
39
+
40
+ def _calculate_file_metrics(self, file_path: str) -> dict[str, Any]:
41
+ """
42
+ Calculate basic file metrics including line counts and estimated token count.
43
+
44
+ Args:
45
+ file_path: Path to the file to analyze
46
+
47
+ Returns:
48
+ Dictionary containing file metrics
49
+ """
50
+ try:
51
+ with open(file_path, encoding="utf-8") as f:
52
+ content = f.read()
53
+
54
+ lines = content.split("\n")
55
+ total_lines = len(lines)
56
+
57
+ # Count different types of lines
58
+ code_lines = 0
59
+ comment_lines = 0
60
+ blank_lines = 0
61
+
62
+ for line in lines:
63
+ stripped = line.strip()
64
+ if not stripped:
65
+ blank_lines += 1
66
+ elif (
67
+ stripped.startswith("//")
68
+ or stripped.startswith("/*")
69
+ or stripped.startswith("*")
70
+ ):
71
+ comment_lines += 1
72
+ else:
73
+ code_lines += 1
74
+
75
+ # Estimate token count (rough approximation)
76
+ # Split by common delimiters and count non-empty tokens
77
+ tokens = re.findall(r"\b\w+\b|[^\w\s]", content)
78
+ estimated_tokens = len([t for t in tokens if t.strip()])
79
+
80
+ # Calculate file size
81
+ file_size = len(content.encode("utf-8"))
82
+
83
+ return {
84
+ "total_lines": total_lines,
85
+ "code_lines": code_lines,
86
+ "comment_lines": comment_lines,
87
+ "blank_lines": blank_lines,
88
+ "estimated_tokens": estimated_tokens,
89
+ "file_size_bytes": file_size,
90
+ "file_size_kb": round(file_size / 1024, 2),
91
+ }
92
+ except Exception as e:
93
+ logger.error(f"Error calculating file metrics for {file_path}: {e}")
94
+ return {
95
+ "total_lines": 0,
96
+ "code_lines": 0,
97
+ "comment_lines": 0,
98
+ "blank_lines": 0,
99
+ "estimated_tokens": 0,
100
+ "file_size_bytes": 0,
101
+ "file_size_kb": 0,
102
+ }
103
+
104
+ def _extract_structural_overview(self, analysis_result: Any) -> dict[str, Any]:
105
+ """
106
+ Extract structural overview with position information for LLM guidance.
107
+
108
+ Args:
109
+ analysis_result: Result from AdvancedAnalyzer
110
+
111
+ Returns:
112
+ Dictionary containing structural overview
113
+ """
114
+ overview: dict[str, Any] = {
115
+ "classes": [],
116
+ "methods": [],
117
+ "fields": [],
118
+ "imports": [],
119
+ "complexity_hotspots": [],
120
+ }
121
+
122
+ # Extract class information with position from unified analysis engine
123
+ classes = [
124
+ e for e in analysis_result.elements if e.__class__.__name__ == "Class"
125
+ ]
126
+ for cls in classes:
127
+ class_info = {
128
+ "name": cls.name,
129
+ "type": cls.class_type,
130
+ "start_line": cls.start_line,
131
+ "end_line": cls.end_line,
132
+ "line_span": cls.end_line - cls.start_line + 1,
133
+ "visibility": cls.visibility,
134
+ "extends": cls.extends_class,
135
+ "implements": cls.implements_interfaces,
136
+ "annotations": [ann.name for ann in cls.annotations],
137
+ }
138
+ overview["classes"].append(class_info)
139
+
140
+ # Extract method information with position and complexity from unified analysis engine
141
+ methods = [
142
+ e for e in analysis_result.elements if e.__class__.__name__ == "Function"
143
+ ]
144
+ for method in methods:
145
+ method_info = {
146
+ "name": method.name,
147
+ "start_line": method.start_line,
148
+ "end_line": method.end_line,
149
+ "line_span": method.end_line - method.start_line + 1,
150
+ "visibility": method.visibility,
151
+ "return_type": method.return_type,
152
+ "parameter_count": len(method.parameters),
153
+ "complexity": method.complexity_score,
154
+ "is_constructor": method.is_constructor,
155
+ "is_static": method.is_static,
156
+ "annotations": [ann.name for ann in method.annotations],
157
+ }
158
+ overview["methods"].append(method_info)
159
+
160
+ # Track complexity hotspots
161
+ if method.complexity_score > 10: # High complexity threshold
162
+ overview["complexity_hotspots"].append(
163
+ {
164
+ "type": "method",
165
+ "name": method.name,
166
+ "complexity": method.complexity_score,
167
+ "start_line": method.start_line,
168
+ "end_line": method.end_line,
169
+ }
170
+ )
171
+
172
+ # Extract field information with position
173
+ # Extract field information from unified analysis engine
174
+ fields = [
175
+ e for e in analysis_result.elements if e.__class__.__name__ == "Variable"
176
+ ]
177
+ for field in fields:
178
+ field_info = {
179
+ "name": field.name,
180
+ "type": field.field_type,
181
+ "start_line": field.start_line,
182
+ "end_line": field.end_line,
183
+ "visibility": field.visibility,
184
+ "is_static": field.is_static,
185
+ "is_final": field.is_final,
186
+ "annotations": [ann.name for ann in field.annotations],
187
+ }
188
+ overview["fields"].append(field_info)
189
+
190
+ # Extract import information
191
+ # Extract import information from unified analysis engine
192
+ imports = [
193
+ e for e in analysis_result.elements if e.__class__.__name__ == "Import"
194
+ ]
195
+ for imp in imports:
196
+ import_info = {
197
+ "name": imp.imported_name,
198
+ "statement": imp.import_statement,
199
+ "line": imp.line_number,
200
+ "is_static": imp.is_static,
201
+ "is_wildcard": imp.is_wildcard,
202
+ }
203
+ overview["imports"].append(import_info)
204
+
205
+ return overview
206
+
207
+ def _generate_llm_guidance(
208
+ self, file_metrics: dict[str, Any], structural_overview: dict[str, Any]
209
+ ) -> dict[str, Any]:
210
+ """
211
+ Generate guidance for LLM on how to efficiently analyze this file.
212
+
213
+ Args:
214
+ file_metrics: Basic file metrics
215
+ structural_overview: Structural overview of the code
216
+
217
+ Returns:
218
+ Dictionary containing LLM guidance
219
+ """
220
+ guidance: dict[str, Any] = {
221
+ "analysis_strategy": "",
222
+ "recommended_tools": [],
223
+ "key_areas": [],
224
+ "complexity_assessment": "",
225
+ "size_category": "",
226
+ }
227
+
228
+ total_lines = file_metrics["total_lines"]
229
+ # estimated_tokens = file_metrics["estimated_tokens"] # Not used currently
230
+
231
+ # Determine size category
232
+ if total_lines < 100:
233
+ guidance["size_category"] = "small"
234
+ guidance["analysis_strategy"] = (
235
+ "This is a small file that can be analyzed in full detail."
236
+ )
237
+ elif total_lines < 500:
238
+ guidance["size_category"] = "medium"
239
+ guidance["analysis_strategy"] = (
240
+ "This is a medium-sized file. Consider focusing on key classes and methods."
241
+ )
242
+ elif total_lines < 1500:
243
+ guidance["size_category"] = "large"
244
+ guidance["analysis_strategy"] = (
245
+ "This is a large file. Use targeted analysis with read_code_partial."
246
+ )
247
+ else:
248
+ guidance["size_category"] = "very_large"
249
+ guidance["analysis_strategy"] = (
250
+ "This is a very large file. Strongly recommend using structural analysis first, then targeted deep-dives."
251
+ )
252
+
253
+ # Recommend tools based on file size and complexity
254
+ if total_lines > 200:
255
+ guidance["recommended_tools"].append("read_code_partial")
256
+
257
+ # Ensure all required fields exist
258
+ required_fields = ["complexity_hotspots", "classes", "methods", "fields", "imports"]
259
+ for field in required_fields:
260
+ if field not in structural_overview:
261
+ structural_overview[field] = []
262
+
263
+ if len(structural_overview["complexity_hotspots"]) > 0:
264
+ guidance["recommended_tools"].append("format_table")
265
+ guidance["complexity_assessment"] = (
266
+ f"Found {len(structural_overview['complexity_hotspots'])} complexity hotspots"
267
+ )
268
+ else:
269
+ guidance["complexity_assessment"] = (
270
+ "No significant complexity hotspots detected"
271
+ )
272
+
273
+ # Identify key areas for analysis
274
+ if len(structural_overview["classes"]) > 1:
275
+ guidance["key_areas"].append(
276
+ "Multiple classes - consider analyzing class relationships"
277
+ )
278
+
279
+ if len(structural_overview["methods"]) > 20:
280
+ guidance["key_areas"].append(
281
+ "Many methods - focus on public interfaces and high-complexity methods"
282
+ )
283
+
284
+ if len(structural_overview["imports"]) > 10:
285
+ guidance["key_areas"].append("Many imports - consider dependency analysis")
286
+
287
+ return guidance
288
+
289
+ def get_tool_schema(self) -> dict[str, Any]:
290
+ """
291
+ Get the MCP tool schema for analyze_code_scale.
292
+
293
+ Returns:
294
+ Dictionary containing the tool schema
295
+ """
296
+ return {
297
+ "type": "object",
298
+ "properties": {
299
+ "file_path": {
300
+ "type": "string",
301
+ "description": "Path to the code file to analyze",
302
+ },
303
+ "language": {
304
+ "type": "string",
305
+ "description": "Programming language (optional, auto-detected if not specified)",
306
+ },
307
+ "include_complexity": {
308
+ "type": "boolean",
309
+ "description": "Include complexity metrics in the analysis",
310
+ "default": True,
311
+ },
312
+ "include_details": {
313
+ "type": "boolean",
314
+ "description": "Include detailed element information",
315
+ "default": False,
316
+ },
317
+ "include_guidance": {
318
+ "type": "boolean",
319
+ "description": "Include LLM analysis guidance",
320
+ "default": True,
321
+ },
322
+ },
323
+ "required": ["file_path"],
324
+ "additionalProperties": False,
325
+ }
326
+
327
+ async def execute(self, arguments: dict[str, Any]) -> dict[str, Any]:
328
+ """
329
+ Execute the analyze_code_scale tool.
330
+
331
+ Args:
332
+ arguments: Tool arguments containing file_path and optional parameters
333
+
334
+ Returns:
335
+ Dictionary containing enhanced analysis results optimized for LLM workflow
336
+
337
+ Raises:
338
+ ValueError: If required arguments are missing or invalid
339
+ FileNotFoundError: If the specified file doesn't exist
340
+ """
341
+ # Validate required arguments
342
+ if "file_path" not in arguments:
343
+ raise ValueError("file_path is required")
344
+
345
+ file_path = arguments["file_path"]
346
+ language = arguments.get("language")
347
+ # include_complexity = arguments.get("include_complexity", True) # Not used currently
348
+ include_details = arguments.get("include_details", False)
349
+ include_guidance = arguments.get("include_guidance", True)
350
+
351
+ # Security validation
352
+ is_valid, error_msg = self.security_validator.validate_file_path(file_path)
353
+ if not is_valid:
354
+ logger.warning(f"Security validation failed for file path: {file_path} - {error_msg}")
355
+ raise ValueError(f"Invalid file path: {error_msg}")
356
+
357
+ # Sanitize inputs
358
+ if language:
359
+ language = self.security_validator.sanitize_input(language, max_length=50)
360
+
361
+ # Validate file exists
362
+ if not Path(file_path).exists():
363
+ raise FileNotFoundError(f"File not found: {file_path}")
364
+
365
+ # Detect language if not specified
366
+ if not language:
367
+ language = detect_language_from_file(file_path)
368
+ if language == "unknown":
369
+ raise ValueError(f"Could not detect language for file: {file_path}")
370
+
371
+ logger.info(f"Analyzing code scale for {file_path} (language: {language})")
372
+
373
+ try:
374
+ # Use performance monitoring with proper context manager
375
+ from ...mcp.utils import get_performance_monitor
376
+
377
+ with get_performance_monitor().measure_operation(
378
+ "analyze_code_scale_enhanced"
379
+ ):
380
+ # Calculate basic file metrics
381
+ file_metrics = self._calculate_file_metrics(file_path)
382
+
383
+ # Use appropriate analyzer based on language
384
+ if language == "java":
385
+ # Use AdvancedAnalyzer for comprehensive analysis
386
+ # Use unified analysis engine instead of deprecated advanced_analyzer
387
+ request = AnalysisRequest(
388
+ file_path=file_path,
389
+ language=language,
390
+ include_complexity=True,
391
+ include_details=True,
392
+ )
393
+ analysis_result = await self.analysis_engine.analyze(request)
394
+ if analysis_result is None:
395
+ raise RuntimeError(f"Failed to analyze file: {file_path}")
396
+ # Extract structural overview
397
+ structural_overview = self._extract_structural_overview(
398
+ analysis_result
399
+ )
400
+ else:
401
+ # Use universal analysis_engine for other languages
402
+ request = AnalysisRequest(
403
+ file_path=file_path,
404
+ language=language,
405
+ include_details=include_details,
406
+ )
407
+ universal_result = await self.analysis_engine.analyze(request)
408
+ if not universal_result or not universal_result.success:
409
+ error_msg = (
410
+ universal_result.error_message
411
+ if universal_result
412
+ else "Unknown error"
413
+ )
414
+ raise RuntimeError(
415
+ f"Failed to analyze file with universal engine: {error_msg}"
416
+ )
417
+
418
+ # Adapt the result to a compatible structure for report generation
419
+ # This part needs careful implementation based on universal_result structure
420
+ analysis_result = None # Placeholder
421
+ structural_overview = {} # Placeholder
422
+
423
+ # Generate LLM guidance
424
+ llm_guidance = None
425
+ if include_guidance:
426
+ llm_guidance = self._generate_llm_guidance(
427
+ file_metrics, structural_overview
428
+ )
429
+
430
+ # Build enhanced result structure
431
+ result = {
432
+ "file_path": file_path,
433
+ "language": language,
434
+ "file_metrics": file_metrics,
435
+ "summary": {
436
+ "classes": len(
437
+ [
438
+ e
439
+ for e in (
440
+ analysis_result.elements if analysis_result else []
441
+ )
442
+ if e.__class__.__name__ == "Class"
443
+ ]
444
+ ),
445
+ "methods": len(
446
+ [
447
+ e
448
+ for e in (
449
+ analysis_result.elements if analysis_result else []
450
+ )
451
+ if e.__class__.__name__ == "Function"
452
+ ]
453
+ ),
454
+ "fields": len(
455
+ [
456
+ e
457
+ for e in (
458
+ analysis_result.elements if analysis_result else []
459
+ )
460
+ if e.__class__.__name__ == "Variable"
461
+ ]
462
+ ),
463
+ "imports": len(
464
+ [
465
+ e
466
+ for e in (
467
+ analysis_result.elements if analysis_result else []
468
+ )
469
+ if e.__class__.__name__ == "Import"
470
+ ]
471
+ ),
472
+ "annotations": len(
473
+ getattr(analysis_result, "annotations", [])
474
+ if analysis_result
475
+ else []
476
+ ),
477
+ "package": (
478
+ analysis_result.package.name
479
+ if analysis_result and analysis_result.package
480
+ else None
481
+ ),
482
+ },
483
+ "structural_overview": structural_overview,
484
+ }
485
+
486
+ if include_guidance:
487
+ result["llm_guidance"] = llm_guidance
488
+
489
+ # Add detailed information if requested (backward compatibility)
490
+ if include_details:
491
+ result["detailed_analysis"] = {
492
+ "statistics": (
493
+ analysis_result.get_statistics() if analysis_result else {}
494
+ ),
495
+ "classes": [
496
+ {
497
+ "name": cls.name,
498
+ "type": getattr(cls, "class_type", "unknown"),
499
+ "visibility": getattr(cls, "visibility", "unknown"),
500
+ "extends": getattr(cls, "extends_class", None),
501
+ "implements": getattr(cls, "implements_interfaces", []),
502
+ "annotations": [
503
+ getattr(ann, "name", str(ann))
504
+ for ann in getattr(cls, "annotations", [])
505
+ ],
506
+ "lines": f"{cls.start_line}-{cls.end_line}",
507
+ }
508
+ for cls in [
509
+ e
510
+ for e in (
511
+ analysis_result.elements if analysis_result else []
512
+ )
513
+ if e.__class__.__name__ == "Class"
514
+ ]
515
+ ],
516
+ "methods": [
517
+ {
518
+ "name": method.name,
519
+ "file_path": getattr(method, "file_path", file_path),
520
+ "visibility": getattr(method, "visibility", "unknown"),
521
+ "return_type": getattr(
522
+ method, "return_type", "unknown"
523
+ ),
524
+ "parameters": len(getattr(method, "parameters", [])),
525
+ "annotations": [
526
+ getattr(ann, "name", str(ann))
527
+ for ann in getattr(method, "annotations", [])
528
+ ],
529
+ "is_constructor": getattr(
530
+ method, "is_constructor", False
531
+ ),
532
+ "is_static": getattr(method, "is_static", False),
533
+ "complexity": getattr(method, "complexity_score", 0),
534
+ "lines": f"{method.start_line}-{method.end_line}",
535
+ }
536
+ for method in [
537
+ e
538
+ for e in (
539
+ analysis_result.elements if analysis_result else []
540
+ )
541
+ if e.__class__.__name__ == "Function"
542
+ ]
543
+ ],
544
+ "fields": [
545
+ {
546
+ "name": field.name,
547
+ "type": getattr(field, "field_type", "unknown"),
548
+ "file_path": getattr(field, "file_path", file_path),
549
+ "visibility": getattr(field, "visibility", "unknown"),
550
+ "is_static": getattr(field, "is_static", False),
551
+ "is_final": getattr(field, "is_final", False),
552
+ "annotations": [
553
+ getattr(ann, "name", str(ann))
554
+ for ann in getattr(field, "annotations", [])
555
+ ],
556
+ "lines": f"{field.start_line}-{field.end_line}",
557
+ }
558
+ for field in [
559
+ e
560
+ for e in (
561
+ analysis_result.elements if analysis_result else []
562
+ )
563
+ if e.__class__.__name__ == "Variable"
564
+ ]
565
+ ],
566
+ }
567
+
568
+ # Count elements by type
569
+ classes_count = len(
570
+ [
571
+ e
572
+ for e in (analysis_result.elements if analysis_result else [])
573
+ if e.__class__.__name__ == "Class"
574
+ ]
575
+ )
576
+ methods_count = len(
577
+ [
578
+ e
579
+ for e in (analysis_result.elements if analysis_result else [])
580
+ if e.__class__.__name__ == "Function"
581
+ ]
582
+ )
583
+
584
+ logger.info(
585
+ f"Successfully analyzed {file_path}: {classes_count} classes, "
586
+ f"{methods_count} methods, {file_metrics['total_lines']} lines, "
587
+ f"~{file_metrics['estimated_tokens']} tokens"
588
+ )
589
+
590
+ return result
591
+
592
+ except Exception as e:
593
+ logger.error(f"Error analyzing {file_path}: {e}")
594
+ raise
595
+
596
+ def validate_arguments(self, arguments: dict[str, Any]) -> bool:
597
+ """
598
+ Validate tool arguments against the schema.
599
+
600
+ Args:
601
+ arguments: Arguments to validate
602
+
603
+ Returns:
604
+ True if arguments are valid
605
+
606
+ Raises:
607
+ ValueError: If arguments are invalid
608
+ """
609
+ schema = self.get_tool_schema()
610
+ required_fields = schema.get("required", [])
611
+
612
+ # Check required fields
613
+ for field in required_fields:
614
+ if field not in arguments:
615
+ raise ValueError(f"Required field '{field}' is missing")
616
+
617
+ # Validate file_path
618
+ if "file_path" in arguments:
619
+ file_path = arguments["file_path"]
620
+ if not isinstance(file_path, str):
621
+ raise ValueError("file_path must be a string")
622
+ if not file_path.strip():
623
+ raise ValueError("file_path cannot be empty")
624
+
625
+ # Validate optional fields
626
+ if "language" in arguments:
627
+ language = arguments["language"]
628
+ if not isinstance(language, str):
629
+ raise ValueError("language must be a string")
630
+
631
+ if "include_complexity" in arguments:
632
+ include_complexity = arguments["include_complexity"]
633
+ if not isinstance(include_complexity, bool):
634
+ raise ValueError("include_complexity must be a boolean")
635
+
636
+ if "include_details" in arguments:
637
+ include_details = arguments["include_details"]
638
+ if not isinstance(include_details, bool):
639
+ raise ValueError("include_details must be a boolean")
640
+
641
+ if "include_guidance" in arguments:
642
+ include_guidance = arguments["include_guidance"]
643
+ if not isinstance(include_guidance, bool):
644
+ raise ValueError("include_guidance must be a boolean")
645
+
646
+ return True
647
+
648
+ def get_tool_definition(self) -> Any:
649
+ """
650
+ Get the MCP tool definition for analyze_code_scale.
651
+
652
+ Returns:
653
+ Tool definition object compatible with MCP server
654
+ """
655
+ try:
656
+ from mcp.types import Tool
657
+
658
+ return Tool(
659
+ name="analyze_code_scale",
660
+ description="Analyze code scale, complexity, and structure metrics with LLM-optimized guidance for efficient large file analysis",
661
+ inputSchema=self.get_tool_schema(),
662
+ )
663
+ except ImportError:
664
+ # Fallback for when MCP is not available
665
+ return {
666
+ "name": "analyze_code_scale",
667
+ "description": "Analyze code scale, complexity, and structure metrics with LLM-optimized guidance for efficient large file analysis",
668
+ "inputSchema": self.get_tool_schema(),
669
+ }
670
+
671
+
672
+ # Tool instance for easy access
673
+ analyze_scale_tool = AnalyzeScaleTool()