Skip to main content
Glama

codebase_graph_query

Query code dependency graphs to see a file's imports and dependents, enabling understanding of codebase structure and impact analysis.

Instructions

Query the code dependency graph for a specific file. Returns what the file imports and what files depend on it.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
projectPathNoAbsolute path to the project directory.
filePathYesRelative path of the file to query (e.g. 'src/index.ts').

Implementation Reference

  • src/index.ts:190-203 (registration)
    Tool registration for 'codebase_graph_query' using the MCP server.tool() method. Defines the name, description, and Zod schema (projectPath optional, filePath required). The handler delegates to handleGraphTool('codebase_graph_query', args).
    server.tool(
      "codebase_graph_query",
      "Query the code dependency graph for a specific file. Returns what the file imports and what files depend on it.",
      {
        projectPath: z
          .string()
          .describe("Absolute path to the project directory.")
          .optional(),
        filePath: z.string().describe("Relative path of the file to query (e.g. 'src/index.ts')."),
      },
      async (args) => ({
        content: [{ type: "text", text: await handleGraphTool("codebase_graph_query", args) }],
      }),
    );
  • The handleGraphTool function dispatches to the 'codebase_graph_query' case (lines 78-105). It retrieves the graph via getOrBuildGraph, calls getFileDependencies(graph, filePath), and formats output showing imports (→) and dependents (←).
    export async function handleGraphTool(
      name: string,
      args: Record<string, unknown>,
    ): Promise<string> {
      const projectPath = path.resolve((args.projectPath as string) || process.cwd());
    
      // Auto-start watcher on any graph interaction (fire-and-forget)
      ensureWatcherStarted(projectPath);
    
      switch (name) {
        case "codebase_graph_build": {
          const resolved = path.resolve(projectPath);
    
          // Concurrency guard: if already building, show progress
          if (isGraphBuildInProgress(resolved)) {
            const progress = getGraphBuildProgress(resolved);
            const lines = [
              `⚠ Graph build already in progress for: ${resolved}`,
            ];
            if (progress) {
              const elapsed = ((Date.now() - progress.startedAt) / 1000).toFixed(0);
              const pct = progress.filesTotal > 0
                ? ` (${Math.round((progress.filesProcessed / progress.filesTotal) * 100)}%)`
                : "";
              lines.push(`Phase: ${progress.phase}`);
              lines.push(`Progress: ${progress.filesProcessed}/${progress.filesTotal} files${pct}`);
              lines.push(`Elapsed: ${elapsed}s`);
            }
            lines.push("", "Call codebase_graph_status to check progress.");
            return lines.join("\n");
          }
    
          // Fire-and-forget: start graph build in the background
          const extraExts = mergeExtraExtensions(args.extraExtensions as string | undefined);
          rebuildGraph(resolved, extraExts.size > 0 ? extraExts : undefined)
            .then((graph) => {
              logger.info("Background graph build completed", {
                projectPath: resolved,
                nodes: graph.nodes.length,
                edges: graph.edges.length,
              });
            })
            .catch((err) => {
              const message = err instanceof Error ? err.message : String(err);
              logger.error("Background graph build failed", { projectPath: resolved, error: message });
            });
    
          return [
            `Graph build started in the background for: ${resolved}`,
            "",
            "IMPORTANT: The graph is now building asynchronously.",
            "Call codebase_graph_status to check progress. Keep calling it periodically until the build completes.",
            "Once complete, you can use codebase_graph_query, codebase_graph_stats, etc. to explore the graph.",
          ].join("\n");
        }
    
        case "codebase_graph_query": {
          const filePath = args.filePath as string;
          const graph = await getOrBuildGraph(projectPath);
          const deps = getFileDependencies(graph, filePath);
    
          const lines = [`Dependencies for: ${filePath}\n`];
    
          if (deps.imports.length === 0 && deps.importedBy.length === 0) {
            lines.push("No dependency information found for this file.");
            lines.push("Make sure codebase_graph_build has been run and the file path is relative.");
          } else {
            if (deps.imports.length > 0) {
              lines.push(`Imports (${deps.imports.length}):`);
              for (const imp of deps.imports) {
                lines.push(`  → ${imp}`);
              }
            }
    
            if (deps.importedBy.length > 0) {
              lines.push(`\nImported by (${deps.importedBy.length}):`);
              for (const dep of deps.importedBy) {
                lines.push(`  ← ${dep}`);
              }
            }
          }
    
          return lines.join("\n");
        }
  • getFileDependencies helper: looks up a CodeGraph node by relativePath and returns its 'imports' (what the file imports) and 'importedBy' (what files depend on it).
    export function getFileDependencies(graph: CodeGraph, relativePath: string): {
      imports: string[];
      importedBy: string[];
    } {
      const node = graph.nodes.find((n) => n.relativePath === relativePath);
      if (!node) {
        return { imports: [], importedBy: [] };
      }
      return {
        imports: node.dependencies,
        importedBy: node.dependents,
      };
    }
  • CodeGraphNode type definition used by the graph: contains 'dependencies' (what this file imports) and 'dependents' (files that import this file).
    export interface CodeGraphNode {
      filePath: string;
      relativePath: string;
      imports: string[];
      exports: string[];
      dependencies: string[];
      dependents: string[];
    }
  • Re-exports getFileDependencies from graph-analysis.ts so it can be imported by the graph-tools handler.
    // Re-export analysis functions for external consumers
    export { findCircularDependencies, generateMermaidDiagram, getFileDependencies, getGraphStats } from "./graph-analysis.js";
Behavior2/5

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

No annotations are provided, and the description does not disclose behavioral traits such as whether the graph must exist, error handling for missing files, or performance implications. The description covers only basic input/output.

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, front-loaded sentence that conveys the essential information without extraneous words. It is concise and well-structured.

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

Completeness3/5

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

For a simple 2-parameter tool with no output schema, the description is adequate but could be more complete by mentioning that the graph must be built beforehand or what happens if the file is not found.

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 coverage is 100% with clear parameter descriptions. The description adds no additional parameter information beyond what's in the schema, so it meets the baseline but does not enhance understanding.

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 verb ('Query') and resource ('code dependency graph for a specific file'), and specifies the output ('what the file imports and what files depend on it'). It distinguishes itself from siblings like codebase_graph_build and codebase_graph_circular by focusing on querying an existing graph.

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?

No guidance on when to use this tool versus alternatives. There is no mention of prerequisites (e.g., graph must be built first) or scenarios where other tools like codebase_impact or codebase_graph_circular might be more appropriate.

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/giancarloerra/SocratiCode'

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