Skip to main content
Glama

find_references

Locate all references to a symbol in your codebase using Language Server Protocol integration. Specify file, line, and character position to identify the symbol and find where it's used throughout the project.

Instructions

Find all references to a symbol using LSP

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
fileYesFile containing the symbol
lineYesLine number of the symbol
characterNoCharacter position of the symbol
languageNoProgramming languagetypescript

Implementation Reference

  • The main handler function that executes the 'find_references' tool. It uses LSP to find references to a symbol at a given position by opening workspace files and sending a textDocument/references request.
    export async function findReferences(args: FindReferencesArgs, clientManager: LSPClientManager) {
      const { file, line, character = 0, language = 'typescript' } = args;
      const workspaceRoot = findWorkspaceRoot(file);
    
      try {
        const client = await clientManager.getOrCreateLSPClient(language, workspaceRoot);
    
        // Open all files in the workspace to enable cross-file reference finding
        const { glob } = await import('glob');
    
        // Determine file extension based on language
        const extensions = {
          typescript: '**/*.{ts,tsx}',
          javascript: '**/*.{js,jsx}',
          python: '**/*.py',
        };
    
        const pattern = extensions[language as keyof typeof extensions] || '**/*.ts';
        const workspaceFiles = await glob(pattern, {
          cwd: workspaceRoot,
          absolute: true,
          ignore: ['**/node_modules/**', '**/dist/**', '**/.git/**'],
        });
    
        // Open all files in the workspace
        for (const filePath of workspaceFiles) {
          try {
            const fileContent = await fs.readFile(filePath, 'utf-8');
            await clientManager.sendLSPNotification(client, 'textDocument/didOpen', {
              textDocument: {
                uri: `file://${filePath}`,
                languageId: language,
                version: 1,
                text: fileContent,
              },
            });
          } catch (_error) {
            // Skip files that can't be read
            continue;
          }
        }
    
        const referencesResponse = await clientManager.sendLSPRequest(client, 'textDocument/references', {
          textDocument: { uri: `file://${file}` },
          position: { line: line - 1, character },
          context: { includeDeclaration: true },
        });
    
        const references = Array.isArray(referencesResponse) ? (referencesResponse as LSPLocation[]) : [];
    
        const formattedReferences = references.map((ref: LSPLocation) => ({
          file: ref.uri.replace('file://', ''),
          line: ref.range.start.line + 1,
          character: ref.range.start.character,
        }));
    
        return {
          references: formattedReferences,
          count: formattedReferences.length,
          content: [
            {
              type: 'text',
              text: `Found ${formattedReferences.length} references:\n${formattedReferences
                .map((ref: { file: string; line: number; character: number }) => `${ref.file}:${ref.line}:${ref.character}`)
                .join('\n')}`,
            },
          ],
        };
      } catch (error) {
        throw new Error(`Failed to find references: ${error instanceof Error ? error.message : String(error)}`);
      }
    }
  • src/server.ts:143-170 (registration)
    Registers the 'find_references' tool in the MCP server's tool list, including name, description, and input schema.
    {
      name: 'find_references',
      description: 'Find all references to a symbol using LSP',
      inputSchema: {
        type: 'object',
        properties: {
          file: {
            type: 'string',
            description: 'File containing the symbol',
          },
          line: {
            type: 'number',
            description: 'Line number of the symbol',
          },
          character: {
            type: 'number',
            description: 'Character position of the symbol',
            default: 0,
          },
          language: {
            type: 'string',
            description: 'Programming language',
            default: 'typescript',
          },
        },
        required: ['file', 'line'],
      },
    },
  • src/server.ts:218-219 (registration)
    Handles incoming calls to the 'find_references' tool by dispatching to the findReferences handler function.
    case 'find_references':
      return await findReferences(args as unknown as FindReferencesArgs, this.clientManager);
  • TypeScript interface defining the input arguments for the 'find_references' tool, used for type safety in the handler and server.
    export interface FindReferencesArgs {
      file: string;
      line: number;
      character?: number;
      language?: string;
    }
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 mentions using LSP, which hints at language-aware analysis, but doesn't describe key traits like whether it's read-only (implied by 'find'), performance considerations (e.g., speed, network usage), error handling, or output format. For a tool with 4 parameters and no annotation coverage, 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.

Conciseness5/5

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

The description is a single, efficient sentence that front-loads the core purpose ('Find all references to a symbol') and adds technical context ('using LSP'). There is no wasted verbiage or redundancy, making it highly concise and well-structured for quick comprehension.

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 (4 parameters, no annotations, no output schema), the description is incomplete. It lacks details on behavioral aspects (e.g., read-only nature, potential side effects), output expectations (what 'references' look like), and usage context relative to siblings. Without annotations or output schema, the description should compensate more to provide a complete understanding, which it does not.

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 parameters (file, line, character, language) with descriptions and defaults. The description adds no additional meaning beyond what the schema provides, such as clarifying how parameters interact (e.g., file-path format, line/character indexing) or usage examples. Baseline 3 is appropriate as the schema handles the heavy lifting.

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 action ('Find all references') and the resource ('to a symbol'), specifying it uses LSP (Language Server Protocol). It distinguishes from siblings like 'rename_symbol' or 'move_function' by focusing on reference discovery rather than modification. However, it doesn't explicitly contrast with sibling tools beyond the general purpose difference.

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 explicit guidance on when to use this tool versus alternatives is provided. The description implies usage for locating symbol references via LSP, but it doesn't specify scenarios (e.g., code navigation vs. refactoring), prerequisites, or when not to use it (e.g., for non-symbol elements). Sibling tools like 'extract_function' or 'rename_symbol' suggest related contexts, but no comparative advice is given.

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/sminnee/lsp-mcp'

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