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