Skip to main content
Glama
deepsuthar496

Remote Command MCP Server

execute_remote_command

Execute shell commands on remote host machines across different operating systems, automatically handling platform-specific differences between Windows and Unix-like systems.

Instructions

Execute a command on the host machine

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
commandYesCommand to execute
cwdNoWorking directory for command execution

Implementation Reference

  • Handler for CallToolRequestSchema that specifically handles 'execute_remote_command': validates args, sanitizes/normalizes command, executes it, and returns stdout/stderr or error.
    this.server.setRequestHandler(CallToolRequestSchema, async (request) => {
      if (request.params.name !== 'execute_remote_command') {
        throw new McpError(
          ErrorCode.MethodNotFound,
          `Unknown tool: ${request.params.name}`
        );
      }
    
      if (!isValidExecArgs(request.params.arguments)) {
        throw new McpError(
          ErrorCode.InvalidParams,
          'Invalid command execution arguments'
        );
      }
    
      try {
        // Sanitize and normalize the command
        const sanitizedCmd = sanitizeCommand(request.params.arguments.command);
        const normalizedCmd = normalizeCommand(sanitizedCmd);
    
        const { stdout, stderr } = await this.executeCommand(
          normalizedCmd,
          request.params.arguments.cwd
        );
    
        // Combine stdout and stderr in the response
        const output = [];
        
        if (stdout.trim()) {
          output.push(stdout.trim());
        }
        
        if (stderr.trim()) {
          output.push('STDERR:', stderr.trim());
        }
    
        return {
          content: [
            {
              type: 'text',
              text: output.join('\n') || 'Command completed successfully (no output)',
            },
          ],
        };
      } catch (error: any) {
        // Enhanced error handling with more details
        const errorMessage = [
          'Command execution error:',
          `Command: ${request.params.arguments.command}`,
          `Error: ${error?.message || 'Unknown error'}`
        ];
    
        console.error('Command failed:', error);  // Debug log
    
        return {
          content: [
            {
              type: 'text',
              text: errorMessage.join('\n'),
            },
          ],
          isError: true,
        };
      }
    });
  • Input schema definition for the execute_remote_command tool, specifying command (required) and optional cwd.
    inputSchema: {
      type: 'object',
      properties: {
        command: {
          type: 'string',
          description: 'Command to execute',
        },
        cwd: {
          type: 'string',
          description: 'Working directory for command execution',
        },
      },
      required: ['command'],
    },
  • src/index.ts:148-169 (registration)
    Registration of the execute_remote_command tool in the ListTools response.
    this.server.setRequestHandler(ListToolsRequestSchema, async () => ({
      tools: [
        {
          name: 'execute_remote_command',
          description: 'Execute a command on the host machine',
          inputSchema: {
            type: 'object',
            properties: {
              command: {
                type: 'string',
                description: 'Command to execute',
              },
              cwd: {
                type: 'string',
                description: 'Working directory for command execution',
              },
            },
            required: ['command'],
          },
        },
      ],
    }));
  • Core helper method that executes the sanitized command using exec or spawn, handles pipes, timeouts, stdout/stderr capture, cross-platform.
    private executeCommand(command: string, cwd?: string): Promise<{ stdout: string; stderr: string }> {
      return new Promise((resolve, reject) => {
        let timeout: NodeJS.Timeout | null = null;
    
        // Set timeout
        timeout = setTimeout(() => {
          reject(new Error(`Command timed out after ${COMMAND_TIMEOUT/1000} seconds`));
        }, COMMAND_TIMEOUT);
    
        // Use exec for commands with pipes, spawn for simple commands
        if (command.includes('|')) {
          execPromise(command, {
            cwd,
            shell: isWindows ? 'cmd.exe' : '/bin/sh',
            timeout: COMMAND_TIMEOUT,
            windowsHide: true
          }).then(({ stdout, stderr }) => {
            if (timeout) clearTimeout(timeout);
            resolve({ stdout, stderr });
          }).catch((error) => {
            if (timeout) clearTimeout(timeout);
            reject(error);
          });
        } else {
          const shell = isWindows ? 'cmd.exe' : '/bin/sh';
          const args = isWindows ? ['/c', command] : ['-c', command];
          
          console.error(`Executing command: ${command} (${shell} ${args.join(' ')})`);  // Debug log
    
          const child = spawn(shell, args, {
            cwd,
            shell: true,
            windowsHide: true
          });
    
          let stdout = '';
          let stderr = '';
    
          child.stdout.on('data', (data) => {
            stdout += data.toString();
          });
    
          child.stderr.on('data', (data) => {
            stderr += data.toString();
          });
    
          child.on('error', (error) => {
            if (timeout) clearTimeout(timeout);
            reject(error);
          });
    
          child.on('close', (code) => {
            if (timeout) clearTimeout(timeout);
            if (code === 0 || stdout.length > 0) { // Consider command successful if there's output even with non-zero exit code
              resolve({ stdout, stderr });
            } else {
              reject(new Error(`Command failed with exit code ${code}${stderr ? ': ' + stderr : ''}`));
            }
          });
        }
      });
  • Helper to sanitize the command by removing null bytes, semicolons (unix), and || operators to prevent injection.
    const sanitizeCommand = (command: string): string => {
      // Remove any null bytes that could be used for command injection
      command = command.replace(/\0/g, '');
      
      // Only remove malicious command chaining while preserving pipes
      if (isWindows) {
        command = command.replace(/\|\|/g, '');  // Remove OR operator but keep pipes
      } else {
        command = command.replace(/;/g, '').replace(/\|\|/g, '');  // Remove semicolon and OR operator
      }
      
      return command;
    };
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. It mentions execution but doesn't describe permissions required, whether commands run asynchronously, timeout behavior, error handling, or output format. For a potentially dangerous remote execution tool, this is a significant gap.

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 states the core functionality without unnecessary words. It's appropriately sized and front-loaded with the essential information.

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 tool that executes remote commands with no annotations and no output schema, the description is insufficient. It doesn't address critical aspects like security implications, execution environment, error conditions, or what the tool returns. The combination of high-risk functionality and minimal description creates significant gaps.

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 both parameters (command and cwd) adequately. The description doesn't add any additional meaning about parameter usage beyond what's in the schema, meeting the baseline 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 ('execute') and target ('command on the host machine'), providing a specific verb+resource combination. It doesn't need to differentiate from siblings since none exist, but it could be more specific about what types of commands or hosts are supported.

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?

No guidance is provided on when to use this tool versus alternatives or what prerequisites might be needed. The description states what it does but offers no context about appropriate use cases, security considerations, or limitations.

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/deepsuthar496/Remote-Command-MCP'

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