Skip to main content
Glama

get_function_call_graph

Generate a function call graph to analyze dependencies and relationships in Python code by specifying the file path and function name, with optional repository context.

Instructions

Get the call graph for a specific function.

Args: file_path: Path to the file containing the function function_name: Name of the function to analyze repo_path: Optional repository path (uses active repository if not specified)

Returns: Information about the function's call graph

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
file_pathYes
function_nameYes
repo_pathNo

Implementation Reference

  • The core handler function for the 'get_function_call_graph' tool, decorated with @mcp.tool(). It determines the repository, enriches the code graph for the specified function, handles errors, and formats the output using a helper function.
    @mcp.tool()
    def get_function_call_graph(file_path: str, function_name: str, repo_path: str = None) -> str:
        """Get the call graph for a specific function.
    
        Args:
            file_path: Path to the file containing the function
            function_name: Name of the function to analyze
            repo_path: Optional repository path (uses active repository if not specified)
    
        Returns:
            Information about the function's call graph
        """
        global _code_graphs, _active_repo
        
        # Determine which repository to use
        target_repo = repo_path
        if target_repo:
            target_repo = os.path.abspath(target_repo)
            if target_repo not in _code_graphs:
                return f"Error: Repository '{repo_path}' not initialized"
        else:
            if _active_repo is None:
                return "Error: No active repository. Please initialize a graph first."
            target_repo = _active_repo
        
        code_graph = _code_graphs[target_repo]
    
        try:
            # Resolve relative paths to absolute
            if not os.path.isabs(file_path):
                file_path = os.path.join(target_repo, file_path)
    
            # Get enrichment result
            enrichment = code_graph.enrich(file_path, function_name)
    
            if enrichment.errors:
                error_messages = [str(error) for error in enrichment.errors]
                return f"Errors retrieving call graph:\n" + "\n".join(error_messages)
    
            if not enrichment.result:
                return f"Function '{function_name}' not found in '{file_path}'"
    
            # Format the result for better readability
            result = format_enrichment_result(file_path, function_name, enrichment.result)
            return result
    
        except Exception as e:
            return f"Error retrieving call graph: {str(e)}"
  • Helper function used by the handler to format the enrichment result from CodeGraph.enrich into a readable markdown string with function info, direct calls, callers, and full JSON subgraph.
    def format_enrichment_result(
        file_path: str, function_name: str, subgraph: Dict[str, Any]
    ) -> str:
        """Format the enrichment result for better readability"""
        # Find the entry point node key
        entrypoint_keys = [k for k in subgraph.keys() if k.endswith(function_name)]
        if not entrypoint_keys:
            return f"Error: Entry point function {function_name} not found in subgraph"
    
        entrypoint_key = entrypoint_keys[0]
        entrypoint_node = subgraph[entrypoint_key]
    
        # Extract direct callees
        direct_callees = entrypoint_node.get("callees", [])
        direct_callee_names = [path.split(".")[-1] for path in direct_callees]
    
        # Get callers (functions that call this function)
        # This requires iterating through all nodes in the graph
        callers = []
        for node_key, node in subgraph.items():
            if node_key == entrypoint_key:
                continue
            if entrypoint_key in node.get("callees", []):
                callers.append(node_key)
    
        caller_names = [path.split(".")[-1] for path in callers]
    
        # Format the result
        result = [
            f"## Function Call Graph for '{function_name}' in {file_path}",
            "",
            "### Function Information",
            f"- Full path: {entrypoint_key}",
            f"- Filepath: {entrypoint_node.get('filepath', 'Unknown')}",
            f"- Line number: {entrypoint_node.get('lineno', 'Unknown')}",
            "",
            "### Direct Function Calls",
        ]
    
        if direct_callee_names:
            for name in direct_callee_names:
                result.append(f"- {name}")
        else:
            result.append("- No direct function calls found")
    
        result.extend(
            [
                "",
                "### Called By",
            ]
        )
    
        if caller_names:
            for name in caller_names:
                result.append(f"- {name}")
        else:
            result.append("- Not called by any other functions in the analyzed code")
    
        result.extend(
            [
                "",
                "### Full Call Graph (JSON)",
                "```json",
                json.dumps(subgraph, indent=2),
                "```",
            ]
        )
    
        return "\n".join(result)
Install Server

Other Tools

Related 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/mattmorgis/nuanced-mcp'

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