Skip to main content
Glama

rename_symbol

Rename TypeScript symbols (variables, functions, classes) across the entire codebase by specifying the root directory, file path, line, old name, and new name for consistent refactoring.

Instructions

Rename a TypeScript symbol (variable, function, class, etc.) 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
newNameYesNew name for the symbol
oldNameYesCurrent name of the symbol
rootYesRoot directory for resolving relative paths

Implementation Reference

  • Zod input schema defining parameters for the rename_symbol tool: root, relativePath, optional line, textTarget, newName.
    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")
        .optional(),
      textTarget: z.string().describe("Symbol to rename"),
      newName: z.string().describe("New name for the symbol"),
    });
  • The core tool handler for lsp_rename_symbol (referred to as rename_symbol in docs/filters). Defines the tool with name, description, schema, and execute function that performs the rename via LSP and formats the output showing changed files.
    export function createRenameSymbolTool(
      client: LSPClient,
    ): McpToolDef<typeof schema> {
      return {
        name: "lsp_rename_symbol",
        description:
          "Rename a symbol across the codebase using LSP. Requires exact position or text target in the specified line.",
        schema,
        execute: async (args) => {
          const result = await handleRenameSymbol(args, client);
          if (result.isErr()) {
            throw new Error(result.error);
          }
    
          // Format output
          const { message, changedFiles } = result.value;
          const output = [message, "", "Changes:"];
    
          for (const file of changedFiles) {
            const relativePath = path.relative(args.root, file.filePath);
            output.push(`  ${relativePath}:`);
    
            for (const change of file.changes) {
              output.push(
                `    Line ${change.line}: "${change.oldText}" → "${change.newText}"`,
              );
            }
          }
    
          return output.join("\n");
        },
      };
    }
  • Registration of the rename_symbol tool (as lsp_rename_symbol) within the array of all LSP tools returned by createLSPTools.
    export function createLSPTools(client: LSPClient): McpToolDef<any>[] {
      return [
        createHoverTool(client),
        createReferencesTool(client),
        createDefinitionsTool(client),
        createDiagnosticsTool(client),
        createRenameSymbolTool(client),
        createDocumentSymbolsTool(client),
        createCompletionTool(client),
        createSignatureHelpTool(client),
        createFormatDocumentTool(client),
        createWorkspaceSymbolsTool(client),
        createCodeActionsTool(client),
        createCheckCapabilitiesTool(client),
        createDeleteSymbolTool(client),
      ];
  • Core helper function that orchestrates the rename operation, dispatching to line-specific or text-search-based rename logic.
    async function handleRenameSymbol(
      request: RenameSymbolRequest,
      client: LSPClient,
    ): Promise<Result<RenameSymbolSuccess, string>> {
      try {
        if (request.line !== undefined) {
          return performRenameWithLine(request, client);
        } else {
          return performRenameWithoutLine(request, client);
        }
      } catch (error) {
        return err(error instanceof Error ? error.message : String(error));
      }
    }
  • Key helper implementing the LSP rename at specific position: opens project files, performs LSP rename request, applies WorkspaceEdit changes to files, returns success with changed files details.
    async function performRenameAtPosition(
      request: RenameSymbolRequest,
      fileUri: string,
      fileContent: string,
      targetLine: number,
      symbolPosition: number,
      client: LSPClient,
    ): Promise<Result<RenameSymbolSuccess, string>> {
      try {
        if (!client) {
          return err("LSP client not available");
        }
    
        // Open all TypeScript/JavaScript files in the project to ensure LSP knows about them
        const projectFiles = await findProjectFiles(request.root);
        for (const file of projectFiles) {
          if (file !== path.resolve(request.root, request.relativePath)) {
            try {
              const content = readFileSync(file, "utf-8");
              client.openDocument(`file://${file}`, content);
            } catch (e) {
              debug(`[lspRenameSymbol] Failed to open file: ${file}`, e);
            }
          }
        }
    
        // Open the target document
        client.openDocument(fileUri, fileContent);
        await new Promise<void>((resolve) => setTimeout(resolve, 1000));
    
        const position: Position = {
          line: targetLine,
          character: symbolPosition,
        };
    
        // Optional: Check if rename is possible at this position
        try {
          const prepareResult = await client.prepareRename(fileUri, position);
    
          if (prepareResult === null) {
            return err(
              `Cannot rename symbol at line ${targetLine + 1}, column ${
                symbolPosition + 1
              }`,
            );
          }
        } catch {
          // Some LSP servers don't support prepareRename, continue with rename
        }
    
        // Perform rename
        let workspaceEdit: WorkspaceEdit | null = null;
    
        try {
          // Use the client's rename method which handles errors properly
          workspaceEdit = await client.rename(fileUri, position, request.newName);
        } catch (error: any) {
          // Check if LSP doesn't support rename (e.g., TypeScript Native Preview)
          if (
            error.code === -32601 ||
            error.message?.includes("Unhandled method") ||
            error.message?.includes("Method not found")
          ) {
            return err("LSP server doesn't support rename operation");
          }
          // Re-throw other errors
          throw error;
        }
    
        if (!workspaceEdit) {
          // LSP returned null, try TypeScript tool as fallback
          return err("No changes from LSP rename operation");
        }
    
        // Debug: Log the workspace edit
        debug(
          "[lspRenameSymbol] WorkspaceEdit from LSP:",
          JSON.stringify(workspaceEdit, null, 2),
        );
    
        // Apply changes and format result
        const result = await applyWorkspaceEdit(request.root, workspaceEdit);
    
        // Close all opened documents
        client.closeDocument(fileUri);
        for (const file of projectFiles) {
          if (file !== path.resolve(request.root, request.relativePath)) {
            try {
              client.closeDocument(`file://${file}`);
            } catch (e) {
              // Ignore close errors
            }
          }
        }
    
        return ok(result);
      } catch (error) {
        return err(error instanceof Error ? error.message : String(error));
      }
    }
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 mentions renaming 'across the codebase,' implying a refactoring operation, but lacks details on permissions, side effects, error handling, or response format. For a mutation tool with zero annotation coverage, this is a significant gap in behavioral disclosure.

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 without unnecessary words. Every part of the sentence earns its place by specifying the action, target, scope, and examples.

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?

For a complex mutation tool with no annotations and no output schema, the description is incomplete. It lacks details on behavioral traits, error conditions, and return values, which are critical for an agent to use the tool effectively in a codebase context.

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 five parameters. The description adds no additional parameter semantics beyond what the schema provides, such as format examples or constraints. Baseline 3 is appropriate when the schema does the heavy lifting.

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 specific action ('Rename') and target ('TypeScript symbol'), specifying the scope ('across the codebase') and listing examples of symbol types (variable, function, class, etc.). This distinguishes it from siblings like 'delete_symbol' or 'find_references' by focusing on renaming rather than deletion or querying.

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 'delete_symbol' or 'find_references', nor does it mention prerequisites or exclusions. It simply states what the tool does without contextual usage information.

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