Skip to main content
Glama

proc_sudo

Execute commands with sudo privileges on remote servers via SSH to perform administrative tasks securely.

Instructions

Executes a command with sudo privileges

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
sessionIdYesSSH session ID
commandYesCommand to execute with sudo
passwordNoSudo password
cwdNoWorking directory

Implementation Reference

  • The `execSudo` function handles the execution of commands with sudo privileges, including path/password handling and sudo-specific error checks.
    export async function execSudo(
      sessionId: string,
      command: string,
      password?: string,
      cwd?: string,
      timeoutMs?: number
    ): Promise<ExecResult> {
      logger.debug('Executing sudo command', { sessionId, command, cwd, timeoutMs });
    
      const session = sessionManager.getSession(sessionId);
      if (!session) {
        throw new Error(`Session ${sessionId} not found or expired`);
      }
    
      const osInfo = await sessionManager.getOSInfo(sessionId);
    
      if (osInfo.platform === 'windows') {
        throw createSudoError(
          'Sudo is not supported on Windows hosts',
          'Use an elevated session instead of sudo commands'
        );
      }
    
      const timer = createTimer();
    
      try {
        const fullCommand = buildSudoCommand(command, osInfo, password, cwd);
    
        // Execute with optional timeout
        let result;
        if (timeoutMs) {
          result = await Promise.race([
            session.ssh.execCommand(fullCommand),
            new Promise<never>((_, reject) =>
              setTimeout(() => reject(createTimeoutError(
                `Sudo command timed out after ${timeoutMs}ms`,
                'Increase timeout or optimize the command'
              )), timeoutMs)
            )
          ]);
        } else {
          result = await session.ssh.execCommand(fullCommand);
        }
    
        // Check if sudo failed due to password issues
        if (result.code !== 0 && result.stderr) {
          const stderrLower = result.stderr.toLowerCase();
          if (stderrLower.includes('password') ||
            stderrLower.includes('authentication') ||
            stderrLower.includes('sorry')) {
            throw createSudoError(
              'Sudo authentication failed',
              'Provide a valid sudo password or ensure NOPASSWD is configured'
            );
          }
        }
    
        const execResult: ExecResult = {
          code: result.code || 0,
          stdout: result.stdout || '',
          stderr: result.stderr || '',
          durationMs: timer.elapsed()
        };
    
        logger.debug('Sudo command execution completed', {
          sessionId,
          code: execResult.code,
          durationMs: execResult.durationMs
        });
    
        return execResult;
    
      } catch (error) {
        if ((error as any)?.code === ErrorCode.ETIMEOUT) {
          throw error;
        }
        if (error instanceof Error && error.message.includes('sudo')) {
          throw error;
        }
    
        logger.error('Sudo command execution failed', { sessionId, command, error });
        throw wrapError(error, ErrorCode.ENOSUDO, 'Failed to execute sudo command on remote system');
      }
    }
  • src/mcp.ts:417-424 (registration)
    Registration of the 'proc_sudo' tool handler within the MCP server's request handler switch statement.
    case 'proc_sudo': {
      const params = SudoSchema.parse(args);
      const result = await execSudo(params.sessionId, params.command, params.password, params.cwd, params.timeoutMs);
      // Add safety warning (never blocks, only warns)
      const resultWithWarning = addSafetyWarningToResult(params.command, result);
      logger.info('Sudo command executed', { sessionId: params.sessionId, command: redactSensitiveData(params.command) });
      return { content: [{ type: 'text', text: JSON.stringify(resultWithWarning, null, 2) }] };
    }
  • Definition of the 'proc_sudo' tool's input schema in the MCP server.
      name: 'proc_sudo',
      description: 'Executes a command with sudo privileges',
      inputSchema: {
        type: 'object',
        properties: {
          sessionId: { type: 'string', description: 'SSH session ID' },
          command: { type: 'string', description: 'Command to execute with sudo' },
          password: { type: 'string', description: 'Sudo password' },
          cwd: { type: 'string', description: 'Working directory' }
        },
        required: ['sessionId', 'command']
      }
    },

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