Skip to main content
Glama
lolpack

MCP Pyrefly Autotype Server

by lolpack

analyze_python_file

Analyze Python files to identify missing type annotations, helping improve code documentation and type safety.

Instructions

Analyze a Python file for missing type annotations

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
file_pathYesPath to the Python file to analyze
detailedNoInclude detailed analysis information

Implementation Reference

  • The handler logic within the call_tool function that processes calls to 'analyze_python_file', validates input, runs the analysis via PyreflyAnalyzer, and returns formatted results.
        if name == "analyze_python_file":
            file_path = arguments.get("file_path")
            detailed = arguments.get("detailed", False)
            
            if not file_path:
                raise ValueError("Missing file_path argument")
            
            if not os.path.exists(file_path):
                raise ValueError(f"File not found: {file_path}")
            
            analysis = await pyrefly_analyzer.analyze_file(file_path)
            
            if detailed:
                result_text = f"""Detailed Pyrefly Analysis for {file_path}:
    
    Functions needing types ({len(analysis.get('functions_needing_types', []))}):
    {chr(10).join(f"  - {func}" for func in analysis.get('functions_needing_types', []))}
    
    Variables needing types ({len(analysis.get('variables_needing_types', []))}):
    {chr(10).join(f"  - {var}" for var in analysis.get('variables_needing_types', []))}
    
    Suggested types:
    {chr(10).join(f"  - {name}: {type_hint}" for name, type_hint in analysis.get('suggested_types', {}).items())}
    
    Pyrefly Output:
    {analysis.get('pyrefly_output', 'No output available')}"""
            else:
                result_text = f"""Pyrefly Analysis for {file_path}:
    Functions needing types: {len(analysis.get('functions_needing_types', []))}
    Variables needing types: {len(analysis.get('variables_needing_types', []))}"""
            
            return [types.TextContent(type="text", text=result_text)]
  • Schema definition for the 'analyze_python_file' tool, including input parameters file_path (required) and detailed (optional boolean).
    types.Tool(
        name="analyze_python_file",
        description="Analyze a Python file for missing type annotations",
        inputSchema={
            "type": "object",
            "properties": {
                "file_path": {
                    "type": "string",
                    "description": "Path to the Python file to analyze"
                },
                "detailed": {
                    "type": "boolean", 
                    "description": "Include detailed analysis information",
                    "default": False
                }
            },
            "required": ["file_path"],
        },
    ),
  • Registration of the 'analyze_python_file' tool via the MCP server.list_tools() handler, which lists all available tools including this one.
    @server.list_tools()
    async def handle_list_tools() -> list[types.Tool]:
        """
        List available tools for Python type analysis and modification.
        """
        return [
            types.Tool(
                name="analyze_python_file",
                description="Analyze a Python file for missing type annotations",
                inputSchema={
                    "type": "object",
                    "properties": {
                        "file_path": {
                            "type": "string",
                            "description": "Path to the Python file to analyze"
                        },
                        "detailed": {
                            "type": "boolean", 
                            "description": "Include detailed analysis information",
                            "default": False
                        }
                    },
                    "required": ["file_path"],
                },
            ),
            types.Tool(
                name="add_types_to_file",
                description="Add type annotations to a Python file using Pyrefly",
                inputSchema={
                    "type": "object",
                    "properties": {
                        "file_path": {
                            "type": "string",
                            "description": "Path to the Python file to add types to"
                        },
                        "backup": {
                            "type": "boolean",
                            "description": "Create a backup of the original file",
                            "default": True
                        },
                        "aggressive": {
                            "type": "boolean",
                            "description": "Use aggressive type inference",
                            "default": False
                        },
                        "safe_mode": {
                            "type": "boolean",
                            "description": "Use safe mode for type inference",
                            "default": True
                        }
                    },
                    "required": ["file_path"],
                },
            ),
            types.Tool(
                name="type_check_file",
                description="Run type checking on a Python file using Pyrefly",
                inputSchema={
                    "type": "object",
                    "properties": {
                        "file_path": {
                            "type": "string",
                            "description": "Path to the Python file to type check"
                        }
                    },
                    "required": ["file_path"],
                },
            ),
            types.Tool(
                name="get_project_context",
                description="Get project-wide type information for better type inference",
                inputSchema={
                    "type": "object",
                    "properties": {
                        "project_path": {
                            "type": "string",
                            "description": "Path to the project directory"
                        }
                    },
                    "required": ["project_path"],
                },
            ),
        ]
  • Helper method in PyreflyAnalyzer class that runs the pyrefly autotype command on the file, parses the output, and returns structured analysis data used by the tool handler.
    async def analyze_file(self, file_path: str) -> Dict[str, Any]:
        """Analyze a Python file using Pyrefly's analysis capabilities."""
        try:
            # Use Pyrefly to analyze the file
            result = await self.run_pyrefly_command([
                "uv", "run", "pyrefly", "autotype", file_path
            ])
            
            if result["success"]:
                # Parse Pyrefly's output for analysis information
                analysis = self._parse_pyrefly_analysis(result["stdout"], file_path)
                return analysis
            else:
                return {
                    "error": result.get("error", result.get("stderr", "Unknown error")),
                    "file_path": file_path
                }
                
        except Exception as e:
            return {"error": str(e), "file_path": file_path}
Behavior2/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

No annotations are provided, so the description carries the full burden of behavioral disclosure. It states the action ('analyze') but does not describe what the analysis entails (e.g., static analysis, runtime checks), output format, error handling, or performance considerations. This leaves significant gaps in understanding the tool's behavior.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is a single, efficient sentence that directly states the tool's purpose without unnecessary words. It is front-loaded with the core action and resource, making it easy to understand at a glance.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness2/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given the lack of annotations and output schema, the description is incomplete for a tool that performs analysis. It does not explain what the analysis returns (e.g., a list of missing annotations, statistics, or recommendations), how results are structured, or any behavioral traits like error conditions. This leaves the agent with insufficient context for effective use.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters3/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema description coverage is 100%, with clear descriptions for both parameters ('file_path' and 'detailed'). The description does not add any additional meaning beyond what the schema provides, such as explaining how 'detailed' affects the analysis output. Baseline 3 is appropriate as the schema handles parameter documentation adequately.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the specific verb ('analyze') and resource ('Python file') with a precise purpose ('for missing type annotations'). It effectively distinguishes from sibling tools like 'add_types_to_file' (which modifies files), 'get_project_context' (which retrieves context), and 'type_check_file' (which checks types rather than analyzing for missing ones).

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines3/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description implies usage by specifying the analysis target ('Python file for missing type annotations'), but it does not explicitly state when to use this tool versus alternatives like 'type_check_file' or 'add_types_to_file'. No guidance is provided on prerequisites, exclusions, or specific scenarios for selection.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Install Server

Other Tools

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/lolpack/mcp-pyrefly-autotype'

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