Skip to main content
Glama
carloshpdoc

memorydetective

Find every reference to a Swift symbol

swiftFindSymbolReferences

Queries SourceKit-LSP to find all references to a Swift symbol across a project, returning callsites and captures with code snippets. An index store is needed for cross-file results.

Instructions

[mg.code] Locates the symbol's declaration in filePath, then asks SourceKit-LSP for textDocument/references. Returns every callsite + capture across the project, with a snippet of each line. Requires an IndexStoreDB at <projectRoot>/.build/index/store for cross-file references — build it with swift build -Xswiftc -index-store-path -Xswiftc <projectRoot>/.build/index/store. The result includes a needsIndex: true hint when the index is missing.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
symbolNameYesName of the Swift symbol to find references for.
filePathYesPath to a Swift file where the symbol is declared. The LSP query needs a position; we locate it in this file via a regex pre-scan.
projectRootNoOverride the project root. Default discovers the nearest Package.swift / .xcodeproj / .xcworkspace.
includeDeclarationNoInclude the declaration site itself in the result set.

Implementation Reference

  • Main handler function: resolves file path, locates symbol declaration via regex pre-scan, acquires SourceKit-LSP client, calls lspReferences to find all references, attaches code snippets, and returns results with a needsIndex hint when no references found.
    export async function swiftFindSymbolReferences(
      input: SwiftFindSymbolReferencesInput,
    ): Promise<SwiftFindSymbolReferencesResult> {
      const file = resolvePath(input.filePath);
      if (!existsSync(file)) {
        throw new Error(`File not found: ${file}`);
      }
      const root = input.projectRoot
        ? resolvePath(input.projectRoot)
        : projectRootFor(file);
    
      const pos = findSymbolDeclaration(file, input.symbolName);
      if (!pos) {
        return {
          ok: true,
          symbolName: input.symbolName,
          totalReferences: 0,
          references: [],
        };
      }
    
      const client = await acquireClient(root);
      const refs = await lspReferences(
        client,
        file,
        pos.line,
        pos.character,
        input.includeDeclaration ?? true,
      );
    
      const refsWithSnippets = refs.map((r) => ({
        ...r,
        snippet: snippetAt(r.filePath, r.line),
      }));
    
      return {
        ok: true,
        symbolName: input.symbolName,
        totalReferences: refs.length,
        references: refsWithSnippets,
        needsIndex: refs.length === 0 ? true : undefined,
      };
    }
  • Zod schema defining the tool's input: symbolName (required), filePath (required), projectRoot (optional), includeDeclaration (optional, default true).
    export const swiftFindSymbolReferencesSchema = z.object({
      symbolName: z
        .string()
        .min(1)
        .describe("Name of the Swift symbol to find references for."),
      filePath: z
        .string()
        .min(1)
        .describe(
          "Path to a Swift file where the symbol is declared. The LSP query needs a position; we locate it in this file via a regex pre-scan.",
        ),
      projectRoot: z
        .string()
        .optional()
        .describe(
          "Override the project root. Default discovers the nearest Package.swift / .xcodeproj / .xcworkspace.",
        ),
      includeDeclaration: z
        .boolean()
        .default(true)
        .describe("Include the declaration site itself in the result set."),
    });
  • src/index.ts:441-453 (registration)
    MCP server registration of the tool with name 'swiftFindSymbolReferences', title, description, input schema, and async handler that delegates to the main handler function.
    server.registerTool(
      "swiftFindSymbolReferences",
      {
        title: "Find every reference to a Swift symbol",
        description:
          "[mg.code] Locates the symbol's declaration in `filePath`, then asks SourceKit-LSP for `textDocument/references`. Returns every callsite + capture across the project, with a snippet of each line. **Requires an IndexStoreDB** at `<projectRoot>/.build/index/store` for cross-file references — build it with `swift build -Xswiftc -index-store-path -Xswiftc <projectRoot>/.build/index/store`. The result includes a `needsIndex: true` hint when the index is missing.",
        inputSchema: swiftFindSymbolReferencesSchema.shape,
      },
      async (input) => {
        const result = await swiftFindSymbolReferences(input);
        return { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] };
      },
    );
  • Re-export aggregator for the swift tools module, making swiftFindSymbolReferences and its schema available from a single import point.
    export {
      swiftFindSymbolReferences,
      swiftFindSymbolReferencesSchema,
      type SwiftFindSymbolReferencesInput,
      type SwiftFindSymbolReferencesResult,
    } from "./findSymbolReferences.js";
  • Helper function that finds a symbol's declaration position in a file using regex pre-scan. First tries declaration keywords (class, struct, etc.), then falls back to any word match. Returns 0-based LSP positions.
    export function findSymbolDeclaration(
      filePath: string,
      symbolName: string,
    ): SymbolPosition | null {
      const text = readFileSync(filePath, "utf8");
      const lines = text.split(/\r?\n/);
    
      const declRe = new RegExp(
        `\\b(?:class|struct|enum|protocol|func|var|let|actor|extension)\\s+${escapeRegex(symbolName)}\\b`,
      );
      for (let i = 0; i < lines.length; i++) {
        const m = lines[i].match(declRe);
        if (m) {
          const ch = lines[i].indexOf(symbolName, m.index ?? 0);
          if (ch >= 0) {
            return { line: i, character: ch, matchedText: lines[i] };
          }
        }
      }
    
      const wordRe = new RegExp(`\\b${escapeRegex(symbolName)}\\b`);
      for (let i = 0; i < lines.length; i++) {
        const m = lines[i].match(wordRe);
        if (m) {
          return {
            line: i,
            character: m.index ?? 0,
            matchedText: lines[i],
          };
        }
      }
      return null;
    }
    
    export function escapeRegex(s: string): string {
      return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
    }
    
    /** Extract a few lines of context around `line` for snippet display. */
    export function snippetAt(filePath: string, line: number, padding = 1): string {
      try {
        const text = readFileSync(filePath, "utf8");
        const lines = text.split(/\r?\n/);
        const start = Math.max(0, line - padding);
        const end = Math.min(lines.length - 1, line + padding);
        return lines.slice(start, end + 1).join("\n");
      } catch {
        return "";
      }
    }
Behavior4/5

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

With no annotations provided, the description carries full burden. It discloses the internal workflow (locating declaration via regex pre-scan, using SourceKit-LSP for references), the output content (callsites+captures with snippets), and a special hint (`needsIndex: true`) when the index is missing. This is transparent and honest about limitations, though rate limits or potential errors are not mentioned.

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

Conciseness4/5

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

The description is a single paragraph but is well-structured: it starts with the core action, then explains the mechanism, then the output, then the requirement. Every sentence adds value. It could be slightly improved by breaking into bullet points for readability, but it remains concise and front-loaded.

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

Completeness4/5

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

Given the tool's complexity and no output schema, the description covers purpose, mechanism, output content (callsites, captures, snippets), and a prerequisite (IndexStoreDB). It appropriately hints at missing index via `needsIndex`. Missing details like error handling or performance impact, but overall complete for most use cases.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters4/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

The input schema has 100% coverage with descriptions for all 4 parameters. The description adds meaning beyond the schema by explaining why `filePath` is needed (to get a position for the LSP query), the role of `projectRoot` (with auto-discovery), and the effect of `includeDeclaration`. This enriches the semantic 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 tool's purpose: 'Locates the symbol's declaration in `filePath`, then asks SourceKit-LSP for `textDocument/references`. Returns every callsite + capture across the project, with a snippet of each line.' It uses a specific verb ('find') and resource ('symbol references'), and distinguishes from siblings like `swiftGetSymbolDefinition` by focusing on references rather than just the definition.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines4/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description provides clear context for when to use this tool and includes a critical prerequisite: requiring an IndexStoreDB for cross-file references. It explains how to build the index. However, it does not explicitly mention when not to use it (e.g., for single-file searches) or direct to alternatives like `swiftGetSymbolDefinition`. Still, the guidance is strong.

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/carloshpdoc/memorydetective'

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