Skip to main content
Glama

ensure_lines_in_file

Manages specific lines in remote files by adding or removing them as needed, ensuring configuration consistency across SSH-connected servers.

Instructions

Ensures specific lines are present or absent in a file

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
sessionIdYesSSH session ID
pathYesFile path
linesYesLines to manage
stateYesDesired state

Implementation Reference

  • The handler function `ensureLinesInFile` which verifies existence of lines in a file and appends them if they are missing.
    export async function ensureLinesInFile(
      sessionId: string,
      filePath: string,
      lines: string[],
      createIfMissing: boolean = true,
      sudoPassword?: string
    ): Promise<LinesInFileResult> {
      logger.debug('Ensuring lines in file', { sessionId, filePath, lineCount: lines.length });
    
      try {
        const osInfo = await sessionManager.getOSInfo(sessionId);
        let fileContent = '';
        let fileExists = false;
    
        // Check if file exists and read its content
        if (await pathExists(sessionId, filePath)) {
          fileExists = true;
          fileContent = await readFile(sessionId, filePath);
        } else if (!createIfMissing) {
          throw createFilesystemError(
            `File ${filePath} does not exist and createIfMissing is false`
          );
        }
    
        // Check which lines are missing
        const existingLines = fileContent.split('\n');
        const missingLines: string[] = [];
    
        for (const line of lines) {
          if (!existingLines.includes(line)) {
            missingLines.push(line);
          }
        }
    
        if (missingLines.length === 0) {
          logger.info('All lines already exist in file', { sessionId, filePath });
          return {
            ok: true,
            added: 0
          };
        }
    
        // Add missing lines
        const newContent = fileExists
          ? fileContent + '\n' + missingLines.join('\n')
          : missingLines.join('\n');
    
        // Write file (may need sudo)
        try {
          await writeFile(sessionId, filePath, newContent);
        } catch (error) {
          if (sudoPassword) {
            // Try with sudo by writing to temp file and moving
            const tempDir = resolveRemoteTempDir(osInfo);
            const baseTempDir = tempDir.replace(/\/+$/, '');
            const tempFile = `${baseTempDir}/ssh-mcp-${Date.now()}.tmp`;
            await writeFile(sessionId, tempFile, newContent);
    
            const moveResult = await execSudo(
              sessionId,
              `mv ${tempFile} ${filePath}`,
              sudoPassword
            );
    
            if (moveResult.code !== 0) {
              throw createFilesystemError(
                `Failed to move temporary file to ${filePath}`,
                'Check file permissions and sudo access'
              );
            }
          } else {
            throw error;
          }
        }
    
        logger.info('Lines added to file successfully', {
          sessionId,
          filePath,
          added: missingLines.length
        });
    
        return {
          ok: true,
          added: missingLines.length
        };
    
      } catch (error) {
        logger.error('Failed to ensure lines in file', { sessionId, filePath, error });
        throw 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 states the tool ensures lines are present or absent, implying mutation, but doesn't disclose critical behaviors like whether it creates files if missing, handles duplicates, requires specific permissions, or provides error messages. This leaves significant gaps for a mutation tool.

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 waste—it directly states the tool's function without unnecessary words. It's appropriately sized and front-loaded, making it easy to parse quickly.

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 tool's complexity (mutation with 4 parameters) and lack of annotations or output schema, the description is insufficient. It doesn't explain return values, error conditions, or behavioral details like file creation or line matching, leaving the agent with incomplete context for safe invocation.

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 parameters (sessionId, path, lines, state) with descriptions and enum values. The description adds no additional meaning beyond what the schema provides, such as explaining how 'lines' are matched or what 'state' entails operationally.

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 tool's purpose with a specific verb ('ensures') and resource ('lines in a file'), and distinguishes it from sibling tools like fs_write or fs_read by focusing on line-level management. However, it doesn't explicitly differentiate from all siblings (e.g., patch_apply might also modify files).

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 fs_write for general file writing or patch_apply for patching. It mentions the tool's function but offers no context about prerequisites, typical use cases, or exclusions.

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