Skip to main content
Glama

find_references

Locate all references to a TypeScript/JavaScript symbol in your codebase by specifying the root directory, file path, line number, and symbol name.

Instructions

Find all references to a TypeScript/JavaScript symbol across the codebase

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
filePathYesFile path containing the symbol (relative to root)
lineYesLine number (1-based) or string to match in the line
rootYesRoot directory for resolving relative paths
symbolNameYesName of the symbol to find references for

Implementation Reference

  • Main handler function that executes the LSP references tool logic, formats output, and handles errors.
    execute: async (args: z.infer<typeof schema>) => {
      const result = await findReferencesWithLSP(args, client);
      if (result.isOk()) {
        const messages = [result.value.message];
    
        if (result.value.references.length > 0) {
          messages.push(
            result.value.references
              .map(
                (ref) =>
                  `\n${ref.relativePath}:${ref.line}:${ref.column}\n${ref.preview}`,
              )
              .join("\n"),
          );
        }
    
        return messages.join("\n\n");
      } else {
        throw new Error(result.error);
      }
    },
  • Zod schema defining input parameters for the find references tool.
    const schema = z.object({
      root: z.string().describe("Root directory for resolving relative paths"),
      relativePath: z
        .string()
        .describe("File path containing the symbol (relative to root)"),
      line: z
        .union([z.number(), z.string()])
        .describe("Line number (1-based) or string to match in the line"),
      column: z
        .number()
        .optional()
        .describe("Character position in the line (0-based)"),
      symbolName: z.string().describe("Name of the symbol to find references for"),
    });
  • Registration of the references tool in the createLSPTools factory function.
    createReferencesTool(client),
  • Core helper function that performs LSP findReferences operation, validates input, reads files, processes locations.
    async function findReferencesWithLSP(
      request: FindReferencesRequest,
      client: LSPClient,
    ): Promise<Result<FindReferencesSuccess, string>> {
      try {
        if (!client) {
          return err("LSP client not available");
        }
    
        // Read file content with metadata
        let fileContent: string;
        let fileUri: string;
        try {
          const result = readFileWithMetadata(request.root, request.relativePath);
          fileContent = result.fileContent;
          fileUri = result.fileUri;
        } catch (error) {
          const context: ErrorContext = {
            operation: "find references",
            filePath: request.relativePath,
            language: "lsp",
          };
          return err(formatError(error, context));
        }
    
        // Validate line and symbol
        let targetLine: number;
        let symbolPosition: number;
        try {
          const result = validateLineAndSymbol(
            fileContent,
            request.line,
            request.symbolName,
            request.relativePath,
          );
          targetLine = result.lineIndex;
          symbolPosition = result.symbolIndex;
        } catch (error) {
          const context: ErrorContext = {
            operation: "symbol validation",
            filePath: request.relativePath,
            symbolName: request.symbolName,
            details: { line: request.line },
          };
          return err(formatError(error, context));
        }
    
        // Open document in LSP
        client.openDocument(fileUri, fileContent);
    
        // Give LSP server time to process the document
        await new Promise<void>((resolve) => setTimeout(resolve, 1000));
        // Find references
        const locations = await client.findReferences(fileUri, {
          line: targetLine,
          character: symbolPosition,
        });
    
        // Convert LSP locations to our Reference format
        const references: Reference[] = [];
    
        for (const location of locations) {
          const refPath = location.uri?.replace("file://", "") || "";
          let refContent: string;
          try {
            refContent = readFileSync(refPath, "utf-8");
          } catch (error) {
            // Skip references in files we can't read
            continue;
          }
          const refLines = refContent.split("\n");
    
          // Get the text at the reference location
          const startLine = location.range.start.line;
          const startCol = location.range.start.character;
          const endCol = location.range.end.character;
          const refLineText = refLines[startLine] || "";
          const text = refLineText.substring(startCol, endCol);
    
          // Create preview with context
          const prevLine = startLine > 0 ? refLines[startLine - 1] : "";
          const nextLine =
            startLine < refLines.length - 1 ? refLines[startLine + 1] : "";
          const preview = [
            prevLine && `${startLine}: ${prevLine}`,
            `${startLine + 1}: ${refLineText}`,
            nextLine && `${startLine + 2}: ${nextLine}`,
          ]
            .filter(Boolean)
            .join("\n");
    
          references.push({
            relativePath: path.relative(request.root, refPath),
            line: startLine + 1, // Convert to 1-based
            column: startCol + 1, // Convert to 1-based
            text,
            preview,
          });
        }
    
        return ok({
          message: `Found ${references.length} reference${
            references.length === 1 ? "" : "s"
          } to "${request.symbolName}"`,
          references,
        });
      } catch (error) {
        const context: ErrorContext = {
          operation: "find references",
          filePath: request.relativePath,
          symbolName: request.symbolName,
          language: "lsp",
        };
        return err(formatError(error, context));
      }
    }
  • Capability-based filtering for the find_references tool, disabling if no referencesProvider.
    if (name === "find_references" && !capabilities.referencesProvider) {
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. It states the action ('find all references') but doesn't disclose behavioral traits like whether this is a read-only operation (implied by 'find'), performance considerations (e.g., might be slow for large codebases), error handling, or output format. For a tool with 4 required parameters and no annotations, this is a significant gap in transparency.

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 TypeScript/JavaScript symbol across the codebase'). There is zero waste or redundancy, making it highly concise and well-structured for quick understanding.

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 (4 required parameters, no annotations, no output schema), the description is incomplete. It doesn't explain what 'references' means in this context (e.g., includes imports, calls, etc.), how results are returned, or any limitations. For a tool that likely returns structured data about code references, more context is needed to guide the agent effectively.

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 fully documents all 4 parameters (filePath, line, root, symbolName). The description adds no additional parameter semantics beyond what's in the schema, such as explaining how 'line' interacts with 'symbolName' or format examples. With high schema coverage, the baseline score of 3 is appropriate as the description doesn't compensate but doesn't need to heavily.

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 verb ('find') and resource ('references to a TypeScript/JavaScript symbol') with scope ('across the codebase'). It distinguishes from siblings like 'get_definitions' or 'get_symbols_in_scope' by focusing on references rather than definitions or scope-limited symbols. However, it doesn't explicitly differentiate from tools like 'get_type_at_symbol' which might overlap in some contexts.

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 like 'get_definitions' or 'get_symbols_in_scope'. It doesn't mention prerequisites (e.g., needing a codebase root) or exclusions (e.g., not for finding definitions). The context is implied but not explicit, leaving the agent to infer usage from the name and description alone.

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/mizchi/typescript-mcp'

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