Skip to main content
Glama

analyze_code

Read-onlyIdempotent

Analyze code for structural issues like long methods, large classes, and duplicate code, then receive specific refactoring suggestions to improve maintainability.

Instructions

Analyze code for smells and suggest refactorings.

Detects code smells like long methods, large classes, feature envy, and suggests appropriate refactorings to address them.

Note: This feature requires backend support. Returns backend_supported: false for backends that don't implement analysis yet.

Args: path: File or directory path to analyze smells: Optional list of smell types to check for (e.g., ['long-method', 'large-class', 'feature-envy'])

Returns: TOON-formatted string with analysis results.

Supported smell types (when backend supports analysis): - long-method: Method exceeds line threshold - large-class: Class has too many responsibilities - feature-envy: Method uses another class's data excessively - data-clumps: Same data items appear together repeatedly - primitive-obsession: Overuse of primitives instead of objects - duplicate-code: Similar code in multiple locations

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
pathYes
smellsNo

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault
resultYes

Implementation Reference

  • The core handler function `analyze_code` that executes the code analysis logic by interacting with language-specific adapters.
    async def analyze_code(params: AnalyzeCodeInput) -> str:
        """Analyze code for smells and suggest refactorings.
    
        Detects code smells like long methods, large classes, feature envy,
        and suggests appropriate refactorings to address them.
    
        Note: This feature requires backend support. Returns backend_supported: false
        for backends that don't implement analysis yet.
    
        Args:
            params: Input parameters including path and optional smell filter
    
        Returns:
            TOON-formatted string with analysis results
        """
        # Detect language from path
        language = detect_language(params.path)
        if language is None:
            return encode_toon({
                "status": "error",
                "error": f"Could not detect language from path: {params.path}",
                "hint": "Ensure the path has a recognized file extension (.py, .rb, .java, .go)",
            })
    
        # Get adapter for the language
        adapter = get_adapter(language)
        if adapter is None:
            return encode_toon({
                "status": "error",
                "error": f"No backend available for language: {language}",
                "hint": f"Install the {language} refactoring backend",
            })
    
        # Check if analysis is supported
        if not adapter.supports_analysis():
            return encode_toon({
                "analysis": {
                    "path": params.path,
                    "language": language,
                    "backend_supported": False,
                },
                "smells": [],
                "note": "Code smell analysis is not yet implemented for this backend. "
                        "This feature will be available in a future release.",
            })
    
        # Run analysis
        result = await adapter.analyze_code(
            path=params.path,
            smells=params.smells,
        )
    
        # Format response
        response: dict[str, Any] = {
            "analysis": {
                "path": result.path,
                "language": result.language,
                "backend_supported": result.backend_supported,
            }
        }
    
        if result.smells:
            response["smells"] = [
                {
                    "type": s.smell_type,
                    "location": s.location,
                    "severity": s.severity.value,
                    "suggested_refactoring": s.suggested_refactoring,
                    "details": s.details,
                }
                for s in result.smells
            ]
        else:
            response["smells"] = []
    
        return encode_toon(response)
  • The Pydantic model `AnalyzeCodeInput` defining the input schema for the `analyze_code` tool.
    class AnalyzeCodeInput(BaseModel):
        """Input for analyzing code."""
    
        model_config = ConfigDict(str_strip_whitespace=True)
    
        path: str = Field(
            ...,
            description="File or directory path to analyze (e.g., 'src/order.py')",
            min_length=1,
        )
        smells: list[str] | None = Field(
            default=None,
            description="Optional list of smell types to check for (e.g., ['long-method', 'large-class'])",
        )
  • The MCP tool registration for `analyze_code` in the main server module.
    @mcp.tool(
        name="analyze_code",
        annotations={
            "title": "Analyze Code for Smells",
            "readOnlyHint": True,
            "destructiveHint": False,
            "idempotentHint": True,
            "openWorldHint": False,
        },
    )
    async def analyze_code(
        path: str,
        smells: Optional[List[str]] = None,
    ) -> str:
        """Analyze code for smells and suggest refactorings.
    
        Detects code smells like long methods, large classes, feature envy,
        and suggests appropriate refactorings to address them.
    
        Note: This feature requires backend support. Returns backend_supported: false
        for backends that don't implement analysis yet.
    
        Args:
            path: File or directory path to analyze
            smells: Optional list of smell types to check for
                (e.g., ['long-method', 'large-class', 'feature-envy'])
    
        Returns:
            TOON-formatted string with analysis results.
    
        Supported smell types (when backend supports analysis):
            - long-method: Method exceeds line threshold
            - large-class: Class has too many responsibilities
            - feature-envy: Method uses another class's data excessively
            - data-clumps: Same data items appear together repeatedly
            - primitive-obsession: Overuse of primitives instead of objects
            - duplicate-code: Similar code in multiple locations
        """
        input_params = AnalyzeCodeInput(path=path, smells=smells)
        return await _analyze_code(input_params)

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/marshally/mcp-refactoring'

If you have feedback or need assistance with the MCP directory API, please join our Discord server