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)
            }

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