Skip to main content
Glama

move_function

Relocate a function from one file to another using Language Server Protocol refactoring to reorganize code structure.

Instructions

Move a function to a different file using LSP refactoring

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
sourceFileYesSource file containing the function
targetFileYesTarget file to move the function to
functionNameYesName of the function to move
lineYesLine number where the function is located
characterNoCharacter position where the function starts
languageNoProgramming languagetypescript

Implementation Reference

  • Main handler function that executes the move_function tool: extracts function from source, removes it, adds to target, updates imports using LSP and file ops.
    export async function moveFunction(args: MoveFunctionArgs, clientManager: LSPClientManager) {
      const { sourceFile, targetFile, functionName, line, character: _character = 0, language = 'typescript' } = args;
      const workspaceRoot = findWorkspaceRoot(sourceFile);
    
      try {
        const client = await clientManager.getOrCreateLSPClient(language, workspaceRoot);
    
        // Open both files
        const sourceContent = await fs.readFile(sourceFile, 'utf-8');
        const targetContent = await fs.readFile(targetFile, 'utf-8').catch(() => '');
    
        await clientManager.sendLSPNotification(client, 'textDocument/didOpen', {
          textDocument: {
            uri: `file://${sourceFile}`,
            languageId: language,
            version: 1,
            text: sourceContent,
          },
        });
    
        await clientManager.sendLSPNotification(client, 'textDocument/didOpen', {
          textDocument: {
            uri: `file://${targetFile}`,
            languageId: language,
            version: 1,
            text: targetContent,
          },
        });
    
        // Find the function definition
        const functionText = extractFunctionFromContent(sourceContent, functionName, line);
    
        if (!functionText) {
          throw new Error(`Function ${functionName} not found at line ${line}`);
        }
    
        // Remove from source file
        const updatedSourceContent = removeFunctionFromContent(sourceContent, functionName, line);
    
        // Add to target file
        const updatedTargetContent = targetContent + '\n\n' + functionText;
    
        // Write the changes
        await fs.writeFile(sourceFile, updatedSourceContent);
        await fs.writeFile(targetFile, updatedTargetContent);
    
        // Update imports/exports as needed
        await updateImportsForMovedFunction(sourceFile, targetFile, functionName, language);
    
        return {
          content: [
            {
              type: 'text',
              text: `Successfully moved function '${functionName}' from ${sourceFile} to ${targetFile}`,
            },
          ],
        };
      } catch (error) {
        throw new Error(`Failed to move function: ${error instanceof Error ? error.message : String(error)}`);
      }
    }
  • TypeScript interface defining the input arguments for the move_function tool.
    export interface MoveFunctionArgs {
      sourceFile: string;
      targetFile: string;
      functionName: string;
      line: number;
      character?: number;
      language?: string;
    }
  • src/server.ts:67-101 (registration)
    Tool object registration in the listTools response, including name, description, and input schema.
      name: 'move_function',
      description: 'Move a function to a different file using LSP refactoring',
      inputSchema: {
        type: 'object',
        properties: {
          sourceFile: {
            type: 'string',
            description: 'Source file containing the function',
          },
          targetFile: {
            type: 'string',
            description: 'Target file to move the function to',
          },
          functionName: {
            type: 'string',
            description: 'Name of the function to move',
          },
          line: {
            type: 'number',
            description: 'Line number where the function is located',
          },
          character: {
            type: 'number',
            description: 'Character position where the function starts',
            default: 0,
          },
          language: {
            type: 'string',
            description: 'Programming language',
            default: 'typescript',
          },
        },
        required: ['sourceFile', 'targetFile', 'functionName', 'line'],
      },
    },
  • src/server.ts:214-215 (registration)
    Dispatch to the moveFunction handler in the callTool request switch statement.
    case 'move_function':
      return await moveFunction(args as unknown as MoveFunctionArgs, this.clientManager);
  • Helper utility to remove the function from source content by matching braces and name, used in moveFunction handler.
    export function removeFunctionFromContent(content: string, functionName: string, line: number): string {
      const lines = content.split('\n');
      const startIndex = line - 1;
    
      let braceCount = 0;
      let inFunction = false;
      let endIndex = startIndex;
    
      for (let i = startIndex; i < lines.length; i++) {
        const currentLine = lines[i];
    
        if (!inFunction && currentLine.includes(functionName)) {
          inFunction = true;
        }
    
        if (inFunction) {
          braceCount += (currentLine.match(/{/g) || []).length;
          braceCount -= (currentLine.match(/}/g) || []).length;
    
          if (braceCount === 0 && inFunction) {
            endIndex = i;
            break;
          }
        }
      }
    
      lines.splice(startIndex, endIndex - startIndex + 1);
      return lines.join('\n');
    }
Behavior2/5

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

With no annotations provided, the description carries full burden for behavioral disclosure. While 'move' implies mutation and 'LSP refactoring' suggests editor integration, it doesn't address critical behaviors: whether this operation is reversible, what happens to imports/references, if it requires specific permissions, or what the output looks like. For a mutation tool with zero annotation coverage, this is insufficient.

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 with zero wasted words. It's front-loaded with the core action and includes the implementation mechanism. Every element earns its place without redundancy or unnecessary elaboration.

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 mutation tool with 6 parameters, no annotations, and no output schema, the description is incomplete. It doesn't explain what happens after the move, how errors are handled, or what the agent should expect as a result. The combination of mutation complexity and lack of structured metadata requires more descriptive context than provided.

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 all parameters are documented in the schema. The description adds no additional parameter semantics beyond what the schema provides (like explaining why both line and character are needed for precise location). The baseline of 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 ('Move a function') and mechanism ('using LSP refactoring'), distinguishing it from siblings like extract_function (which creates new functions) and rename_symbol (which renames within the same file). It precisely identifies both the resource (function) and destination (different file).

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 extract_function or rename_symbol. It doesn't mention prerequisites, constraints, or typical scenarios for moving functions versus other refactoring operations, leaving the agent to infer usage context from the tool name 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

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