Skip to main content
Glama

find_references

Locate all usages of a specific symbol within a project to analyze code dependencies and understand how functions, variables, or classes are referenced across files.

Instructions

where used|references|usages|find usage|references|where used - Find symbol references

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
symbolNameYesName of the symbol to find references for
filePathNoFile path where the symbol is defined
lineNoLine number of the symbol definition
projectPathYesProject directory path

Implementation Reference

  • Core handler function for the 'find_references' tool. Uses TypeScript Language Service for precise references at position, scans Python files for occurrences, and performs fallback identifier search across project TypeScript files using ts-morph. Collects references with definition detection.
    export async function findReferences(args: {
      symbolName: string;
      filePath?: string;
      line?: number;
      projectPath: string;
    }): Promise<ToolResult> {
      const { symbolName, filePath, line, projectPath } = args;
      
      try {
        // Use cached project for performance
        const projectCache = ProjectCache.getInstance();
        const project = projectCache.getOrCreate(projectPath);
    
        const allReferences: ReferenceInfo[] = [];
    
        // Check for Python files
        const glob = await import('glob');
        const pythonFiles = glob.globSync(path.join(projectPath, '**/*.py'), {
          ignore: ['**/node_modules/**', '**/.git/**', '**/venv/**', '**/__pycache__/**']
        });
    
        // Parse Python files for references
        for (const pyFile of pythonFiles) {
          try {
            const content = await readFile(pyFile, 'utf-8');
            const lines = content.split('\n');
    
            lines.forEach((line, index) => {
              if (line.includes(symbolName)) {
                const column = line.indexOf(symbolName);
                allReferences.push({
                  filePath: pyFile,
                  line: index + 1,
                  column: column,
                  text: line.trim().substring(0, 100),
                  isDefinition: /^(def|class)\s/.test(line.trim())
                });
              }
            });
          } catch (error) {
            console.error(`Error parsing Python file ${pyFile}:`, error);
          }
        }
        
        // If specific file and line provided, use precise reference finding
        if (filePath && line) {
          const sourceFile = project.getSourceFile(filePath);
          if (sourceFile) {
            const position = sourceFile.compilerNode.getPositionOfLineAndCharacter(line - 1, 0);
            const node = sourceFile.getDescendantAtPos(position);
            
            if (node) {
              const symbol = node.getSymbol();
              if (symbol) {
                const references = project.getLanguageService().findReferencesAtPosition(sourceFile, position);
                
                if (references) {
                  for (const ref of references) {
                    for (const reference of ref.getReferences()) {
                      const refSourceFile = reference.getSourceFile();
                      const refNode = reference.getNode();
                      const start = refNode.getStartLinePos();
                      const pos = refSourceFile.getLineAndColumnAtPos(start);
                      
                      allReferences.push({
                        filePath: refSourceFile.getFilePath(),
                        line: pos.line,
                        column: pos.column,
                        text: refNode.getParent()?.getText().substring(0, 100) || refNode.getText(),
                        isDefinition: reference.isDefinition() || false
                      });
                    }
                  }
                }
              }
            }
          }
        } else {
          // Fallback: search by name across all files
          for (const sourceFile of project.getSourceFiles()) {
            const filePath = sourceFile.getFilePath();
            
            // Skip node_modules and other irrelevant paths
            if (filePath.includes('node_modules') || filePath.includes('.git')) {
              continue;
            }
            
            // Find all identifiers matching the symbol name
            sourceFile.forEachDescendant((node) => {
              if (Node.isIdentifier(node) && node.getText() === symbolName) {
                const start = node.getStartLinePos();
                const pos = sourceFile.getLineAndColumnAtPos(start);
                const parent = node.getParent();
                
                // Determine if this is a definition
                const isDefinition = isSymbolDefinition(node);
                
                allReferences.push({
                  filePath: filePath,
                  line: pos.line,
                  column: pos.column,
                  text: parent?.getText().substring(0, 100) || node.getText(),
                  isDefinition
                });
              }
            });
          }
        }
        
        const definitions = allReferences.filter(r => r.isDefinition);
        const usages = allReferences.filter(r => !r.isDefinition);
    
        return {
          content: [{
            type: 'text',
            text: `Found ${allReferences.length} references (${definitions.length} defs, ${usages.length} uses):\n${allReferences.slice(0, 20).map(r =>
              `${r.isDefinition ? 'DEF' : 'USE'}: ${r.filePath}:${r.line}`
            ).join('\n')}`
          }]
        };
      } catch (error) {
        return {
          content: [{ 
            type: 'text', 
            text: `Error finding references: ${error instanceof Error ? error.message : 'Unknown error'}` 
          }]
        };
      }
    }
  • ToolDefinition object defining the input schema, description, and metadata for the 'find_references' tool.
    export const findReferencesDefinition: ToolDefinition = {
      name: 'find_references',
      description: 'where used|references|usages|find usage|references|where used - Find symbol references',
      inputSchema: {
        type: 'object',
        properties: {
          symbolName: { type: 'string', description: 'Name of the symbol to find references for' },
          filePath: { type: 'string', description: 'File path where the symbol is defined' },
          line: { type: 'number', description: 'Line number of the symbol definition' },
          projectPath: { type: 'string', description: 'Project directory path' }
        },
        required: ['symbolName', 'projectPath']
      },
      annotations: {
        title: 'Find References',
        audience: ['user', 'assistant']
      }
    };
  • src/index.ts:612-613 (registration)
    Tool handler registration in the central executeToolCall switch statement that dispatches calls to findReferences based on tool name.
    case 'find_references':
      return await findReferences(args as any) as CallToolResult;
  • src/index.ts:110-110 (registration)
    Inclusion of the tool definition in the tools array used for ListTools MCP protocol endpoint.
    findReferencesDefinition,
  • Helper function to determine if an identifier node represents a symbol definition based on parent node types.
    function isSymbolDefinition(node: Node): boolean {
      const parent = node.getParent();
      if (!parent) return false;
      
      // Check if this is a declaration
      return Node.isFunctionDeclaration(parent) ||
             Node.isClassDeclaration(parent) ||
             Node.isInterfaceDeclaration(parent) ||
             Node.isTypeAliasDeclaration(parent) ||
             Node.isVariableDeclaration(parent) ||
             Node.isMethodDeclaration(parent) ||
             Node.isPropertyDeclaration(parent) ||
             Node.isParameterDeclaration(parent);
    }
Behavior3/5

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

Annotations only provide a title ('Find References'), so the description carries the burden of behavioral disclosure. It implies a read-only search operation ('find'), which aligns with no destructive hints, but doesn't add context like rate limits, authentication needs, or what 'references' entails (e.g., exact matches, partial matches, scope). It's minimal but not contradictory.

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

Conciseness2/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is poorly structured and repetitive, with redundant synonyms ('where used|references|usages|find usage|references|where used') and a final phrase that restates the idea. It's not front-loaded with clear information, and the repetition adds no value, making it inefficient rather than concise.

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 no annotations beyond title, no output schema, and a 4-parameter tool, the description is incomplete. It doesn't explain what 'references' means in output, how results are returned, or any behavioral nuances. For a tool that likely returns complex data (references in a codebase), this leaves significant gaps for an AI agent.

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 description coverage is 100%, so the schema already documents all four parameters (symbolName, filePath, line, projectPath) with clear descriptions. The description adds no meaning beyond this, such as explaining how parameters interact or providing examples. Baseline 3 is appropriate as the schema does the heavy lifting.

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

Purpose2/5

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

The description is a tautology that restates the tool name with synonyms ('where used|references|usages|find usage|references|where used'), then repeats 'Find symbol references' which is essentially the tool name. It doesn't specify what type of symbol (code symbol, data symbol, etc.) or what context (codebase, documentation, etc.), making it vague rather than specific.

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 is provided on when to use this tool versus alternatives. The sibling tools include 'find_symbol', which might be related for locating definitions, but the description doesn't mention this or any other context for usage. It lacks explicit when/when-not statements or named alternatives.

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/ssdeanx/ssd-ai'

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