Skip to main content
Glama

find_references

Read-onlyIdempotent

Locate where symbols are referenced in code to track usage across projects and identify dependencies.

Instructions

어디서 쓰|참조|사용처|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

  • Main execution logic for the 'find_references' tool. Handles TypeScript semantic references via ts-morph LanguageService, fallback identifier search across project files, and string-based search in Python files. Returns formatted list of definitions and usages.
    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 annotations for the 'find_references' tool.
    export const findReferencesDefinition: ToolDefinition = {
      name: 'find_references',
      description: '어디서 쓰|참조|사용처|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'],
        readOnlyHint: true,
        destructiveHint: false,
        idempotentHint: true,
        openWorldHint: false
      }
    };
  • src/index.ts:179-179 (registration)
    Maps the tool name 'find_references' to its handler function `findReferences` in the `toolHandlers` object, enabling dynamic dispatch during tool calls.
    'find_references': findReferences,
  • src/index.ts:112-112 (registration)
    Adds the tool definition to the `tools` array, making it discoverable via the ListTools MCP request.
    findReferencesDefinition,
  • Helper function to determine if a node represents a symbol definition (used in fallback search).
    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 provide readOnlyHint=true, openWorldHint=false, idempotentHint=true, and destructiveHint=false, indicating a safe, deterministic read operation. The description doesn't add behavioral details beyond this, such as rate limits or output format, but it doesn't contradict the annotations either.

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 a disorganized list of keywords ('어디서 쓰|참조|사용처|find usage|references|where used') followed by a phrase ('Find symbol references'). It lacks proper sentence structure and front-loading, making it inefficient and unclear despite its 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 tool's complexity (finding references in code) and lack of output schema, the description is inadequate. It doesn't explain what 'references' means in this context, the return format, or how it differs from similar tools. Annotations cover safety, but more context is needed for effective use.

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%, with clear descriptions for all 4 parameters. The description adds no parameter-specific information beyond what the schema provides, so it meets the baseline score of 3 without compensating or enhancing the schema details.

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

Purpose3/5

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

The description states the tool finds symbol references, which is a clear purpose, but it's presented as a list of keywords ('어디서 쓰|참조|사용처|find usage|references|where used') rather than a coherent sentence. It doesn't distinguish this from sibling tools like 'find_symbol' or 'analyze_dependency_graph', leaving ambiguity about its specific scope.

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 description is a keyword list with no context, prerequisites, or exclusions. Sibling tools like 'find_symbol' or 'analyze_dependency_graph' might overlap, but no comparison is made.

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/su-record/hi-ai'

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