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)
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 tool 'Get[s] the call graph' but doesn't explain what a 'call graph' entails, whether it's read-only or has side effects, or any performance or permission considerations. For a tool with no annotations, this leaves significant gaps in understanding its behavior.

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 well-structured with clear sections for purpose, arguments, and returns, and it's front-loaded with the main purpose. It's concise with no wasted sentences, though the parameter descriptions could be more detailed without sacrificing brevity.

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 complexity of analyzing function call graphs, no annotations, no output schema, and low schema description coverage (0%), the description is incomplete. It lacks details on the return format, error handling, or behavioral traits, making it inadequate for a tool with 3 parameters and no structured support.

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 description includes an 'Args' section that lists and briefly describes the three parameters, adding meaning beyond the input schema, which has 0% description coverage. However, the descriptions are minimal (e.g., 'Path to the file containing the function') and don't provide detailed semantics like format examples or constraints, so it partially compensates but not fully.

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

Purpose4/5

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

The description clearly states the tool's purpose: 'Get the call graph for a specific function.' This specifies the verb ('Get') and resource ('call graph'), making it easy to understand what the tool does. However, it doesn't differentiate from sibling tools like 'analyze_dependencies' or 'analyze_change_impact,' which might have overlapping functionality, so it doesn't reach the highest score.

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 sibling tools like 'analyze_dependencies' or 'analyze_change_impact,' nor does it specify prerequisites or exclusions. The only implied context is analyzing functions, but this is insufficient for effective tool 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

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