Skip to main content
Glama
lolpack

MCP Pyrefly Autotype Server

by lolpack

get_project_context

Retrieve project-wide type information to enhance type inference accuracy for Python code analysis and annotation.

Instructions

Get project-wide type information for better type inference

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
project_pathYesPath to the project directory

Implementation Reference

  • Core handler implementing get_project_context: walks project directory to find Python files, checks Pyrefly compatibility by running pyrefly check command, and compiles project context.
    async def get_project_context(self, project_path: str) -> Dict[str, Any]:
        """Get project-wide type information using Pyrefly."""
        context: Dict[str, Any] = {
            "project_path": project_path,
            "python_files": [],
            "pyrefly_compatible": False,
            "analysis_summary": {}
        }
        
        try:
            # Check if Pyrefly can analyze this project
            pyrefly_check = await self.run_pyrefly_command([
                "uv", "run", "pyrefly", "check", project_path
            ])
            
            context["pyrefly_compatible"] = pyrefly_check["success"]
            
            # Collect Python files
            for root, dirs, files in os.walk(project_path):
                dirs[:] = [d for d in dirs if not d.startswith('.') and d not in ['__pycache__', 'node_modules']]
                
                for file in files:
                    if file.endswith('.py'):
                        file_path = os.path.join(root, file)
                        context["python_files"].append(file_path)
            
            if pyrefly_check["success"]:
                context["analysis_summary"] = {
                    "output": pyrefly_check["stdout"],
                    "total_files": len(context["python_files"])
                }
        
        except Exception as e:
            context["error"] = str(e)
        
        return context
  • Registers the 'get_project_context' tool in the MCP server's list_tools, including its description and input schema requiring 'project_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"],
        },
    ),
  • MCP tool dispatch handler for 'get_project_context': validates input, calls PyreflyAnalyzer.get_project_context, and returns formatted text response.
        elif name == "get_project_context":
            project_path = arguments.get("project_path")
            
            if not project_path:
                raise ValueError("Missing project_path argument")
            
            if not os.path.exists(project_path):
                raise ValueError(f"Project path not found: {project_path}")
            
            context = await pyrefly_analyzer.get_project_context(project_path)
            
            result_text = f"""Project Context for {project_path}:
    
    Python files found: {len(context.get('python_files', []))}
    Pyrefly compatible: {context.get('pyrefly_compatible', False)}
    
    Analysis summary:
    {context.get('analysis_summary', {}).get('output', 'No analysis available')}
    
    Files:
    {chr(10).join(f"  - {file}" for file in context.get('python_files', [])[:20])}
    {"  ... and more" if len(context.get('python_files', [])) > 20 else ""}"""
            
            return [types.TextContent(type="text", text=result_text)]
  • Helper method used by get_project_context to execute the 'pyrefly check' command and capture its output for compatibility check.
    async def run_pyrefly_command(self, cmd: List[str], timeout: int = 60) -> Dict[str, Any]:
        """Run a Pyrefly command and return the results."""
        try:
            result = subprocess.run(
                cmd, 
                capture_output=True, 
                text=True, 
                timeout=timeout
            )
            
            return {
                "success": result.returncode == 0,
                "stdout": result.stdout,
                "stderr": result.stderr,
                "returncode": result.returncode
            }
        except subprocess.TimeoutExpired:
            return {
                "success": False,
                "error": f"Pyrefly execution timed out after {timeout}s"
            }
        except Exception as e:
            return {
                "success": False,
                "error": str(e)
            }
Behavior2/5

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

No annotations are provided, so the description carries full burden for behavioral disclosure. The description mentions 'type inference' but doesn't specify what the tool returns (e.g., a summary, structured data, or raw output), whether it's read-only or has side effects, or any performance considerations. It lacks details on behavior beyond the basic purpose.

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

Conciseness4/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's appropriately sized for a simple tool with one parameter, though it could be slightly more informative without losing conciseness. The structure is front-loaded with the core function.

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. It doesn't explain what the tool returns (e.g., a data structure, success status, or error messages), which is critical for a tool focused on 'type information'. For a tool with no structured output documentation, the description should compensate more by detailing expected results or usage context.

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?

The input schema has 100% description coverage, with the parameter 'project_path' clearly documented as 'Path to the project directory'. The description adds no additional meaning beyond this, as it doesn't elaborate on parameter usage or constraints. With high schema coverage, the baseline score of 3 is appropriate since the schema handles the parameter documentation adequately.

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

Purpose3/5

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

The description states the tool 'Get project-wide type information for better type inference', which provides a clear verb ('Get') and resource ('project-wide type information'). However, it doesn't specifically distinguish this from sibling tools like 'analyze_python_file' or 'type_check_file' that also deal with type-related operations. The purpose is understandable but lacks sibling differentiation.

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

Usage Guidelines2/5

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

The description provides no guidance on when to use this tool versus alternatives. It doesn't mention when this tool is appropriate (e.g., for initial project setup, batch analysis) or when to prefer sibling tools like 'analyze_python_file' for file-specific analysis. There's no explicit or implied context for usage decisions.

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