Skip to main content
Glama

patch_apply

Apply unified diff patches to files on remote servers via SSH to modify configurations, fix bugs, or update code without manual editing.

Instructions

Applies a patch to a file

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
sessionIdYesSSH session ID
pathYesFile path to patch
patchYesPatch content (unified diff format)

Implementation Reference

  • The `applyPatch` function handles the logic for applying a unified diff patch to a remote file. It performs a dry run first and handles temporary file cleanup.
    export async function applyPatch(
      sessionId: string,
      filePath: string,
      diff: string,
      sudoPassword?: string
    ): Promise<PatchResult> {
      logger.debug('Applying patch to file', { sessionId, filePath });
    
      try {
        const osInfo = await sessionManager.getOSInfo(sessionId);
        // Check if patch command is available
        const hasPatch = await commandExists(sessionId, 'patch');
        if (!hasPatch) {
          throw createPatchError(
            'patch command not found on remote system',
            'Install patch utility or apply changes manually'
          );
        }
    
        // Write patch to temporary file
        const tempDir = resolveRemoteTempDir(osInfo);
        const baseTempDir = tempDir.replace(/\/+$/, '');
        const tempPatchFile = `${baseTempDir}/ssh-mcp-patch-${Date.now()}.patch`;
        await writeFile(sessionId, tempPatchFile, diff);
    
        try {
          // Test patch first (dry run)
          const testResult = await execCommand(
            sessionId,
            `patch --dry-run -p0 ${filePath} < ${tempPatchFile}`
          );
    
          if (testResult.code !== 0) {
            throw createPatchError(
              'Patch would fail to apply',
              `Patch test failed: ${testResult.stderr}`
            );
          }
    
          // Apply patch
          const applyCommand = `patch -p0 ${filePath} < ${tempPatchFile}`;
          let result;
    
          if (sudoPassword) {
            result = await execSudo(sessionId, applyCommand, sudoPassword);
          } else {
            result = await execCommand(sessionId, applyCommand);
          }
    
          const patchResult: PatchResult = {
            ok: result.code === 0,
            changed: result.code === 0
          };
    
          if (result.code === 0) {
            logger.info('Patch applied successfully', { sessionId, filePath });
          } else {
            logger.error('Patch application failed', {
              sessionId,
              filePath,
              code: result.code,
              stderr: result.stderr
            });
          }
    
          return patchResult;
    
        } finally {
          // Clean up temporary patch file
          try {
            const cleanupCommand = osInfo.platform === 'windows'
              ? `Remove-Item -Path ${tempPatchFile} -Force -ErrorAction SilentlyContinue`
              : `rm -f ${tempPatchFile}`;
            await execCommand(sessionId, cleanupCommand);
          } catch (error) {
            logger.warn('Failed to clean up temporary patch file', { tempPatchFile, error });
          }
        }
    
      } catch (error) {
        logger.error('Failed to apply patch', { sessionId, filePath, error });
        throw error;
      }
    }
  • Schema definition for the "patch_apply" tool inputs.
    export const PatchApplySchema = z.object({
      sessionId: z.string().min(1),
      path: z.string().min(1),
      diff: z.string(),
      sudoPassword: z.string().optional()
    });
  • src/mcp.ts:496-501 (registration)
    Tool handler registration for "patch_apply" in `src/mcp.ts`.
    case 'patch_apply': {
      const params = PatchApplySchema.parse(args);
      const result = await applyPatch(params.sessionId, params.path, params.diff, params.sudoPassword);
      logger.info('Patch applied', { sessionId: params.sessionId, path: params.path });
      return { content: [{ type: 'text', text: JSON.stringify(result, null, 2) }] };
    }
Behavior2/5

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

With no annotations provided, the description carries the full burden of behavioral disclosure but does very little. It states the action but doesn't cover critical aspects like whether this is a destructive operation (likely yes, as it modifies files), error handling, permissions needed, or what happens on success/failure. This is inadequate for a mutation tool with zero annotation coverage.

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 extremely concise—a single sentence with zero waste. It's front-loaded with the core action and target, making it easy to parse quickly, though this brevity contributes to gaps in other dimensions.

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 of applying patches (a mutation operation) with no annotations and no output schema, the description is incomplete. It lacks details on behavior, outcomes, error cases, and integration with sibling tools (e.g., SSH sessions), making it insufficient for safe and effective use by an AI agent.

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 three parameters (sessionId, path, patch) with clear descriptions. The description adds no additional meaning beyond what's in the schema, such as explaining patch format constraints or path requirements, resulting in the baseline score for high schema coverage.

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 ('applies a patch') and the target ('to a file'), providing a specific verb+resource combination. However, it doesn't differentiate from sibling tools like 'fs_write' or 'ensure_lines_in_file' that might also modify files, missing the opportunity to clarify its unique role in applying patch content specifically.

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 offers no guidance on when to use this tool versus alternatives. It doesn't mention prerequisites (e.g., needing an SSH session from 'ssh_open_session'), exclusions, or comparisons to siblings like 'fs_write' for general file modifications, leaving usage context entirely implicit.

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/oaslananka/mcp-ssh-tool'

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