Skip to main content
Glama
saksham0712

MCP Complete Implementation Guide

by saksham0712

execute_command

Execute system commands directly from the MCP server to automate tasks, run scripts, and perform system operations with specified working directories.

Instructions

Execute a system command (use with caution)

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
commandYesThe command to execute
cwdNoWorking directory for the command

Implementation Reference

  • Primary MCP handler for execute_command tool. Executes shell commands using subprocess.run, captures stdout/stderr, formats output, and returns as TextContent. Includes timeout and cwd support.
    async def execute_command(self, command: str, cwd: Optional[str] = None) -> list[types.TextContent]:
        """Execute system command"""
        try:
            result = subprocess.run(
                command,
                shell=True,
                capture_output=True,
                text=True,
                cwd=cwd or Path.cwd(),
                timeout=30,
            )
            
            output = f"Command: {command}\nOutput:\n{result.stdout}"
            if result.stderr:
                output += f"\nErrors:\n{result.stderr}"
            
            return [types.TextContent(type="text", text=output)]
        except Exception as error:
            raise Exception(f"Command execution failed: {str(error)}")
  • Primary MCP handler for execute_command tool in JavaScript server. Uses child_process.exec to run commands, captures output, formats response, supports cwd.
    async executeCommand(command, cwd = process.cwd()) {
      const { exec } = require('child_process');
      const { promisify } = require('util');
      const execAsync = promisify(exec);
    
      try {
        const { stdout, stderr } = await execAsync(command, { cwd });
        return {
          content: [
            {
              type: 'text',
              text: `Command: ${command}\nOutput:\n${stdout}${stderr ? `\nErrors:\n${stderr}` : ''}`,
            },
          ],
        };
      } catch (error) {
        throw new Error(`Command execution failed: ${error.message}`);
      }
    }
  • server.py:126-143 (registration)
    Registration of execute_command tool in Python MCP server's list_tools handler, including input schema definition.
    types.Tool(
        name="execute_command",
        description="Execute a system command (use with caution)",
        inputSchema={
            "type": "object",
            "properties": {
                "command": {
                    "type": "string",
                    "description": "The command to execute",
                },
                "cwd": {
                    "type": "string",
                    "description": "Working directory for the command",
                },
            },
            "required": ["command"],
        },
    ),
  • server.js:99-115 (registration)
    Registration of execute_command tool in JavaScript MCP server's list_tools response, including input schema.
      name: 'execute_command',
      description: 'Execute a system command (use with caution)',
      inputSchema: {
        type: 'object',
        properties: {
          command: {
            type: 'string',
            description: 'The command to execute',
          },
          cwd: {
            type: 'string',
            description: 'Working directory for the command',
          },
        },
        required: ['command'],
      },
    },
  • Handler implementation in ChatGPT proxy server for execute_command, used when bridging OpenAI tools to local execution.
    case 'execute_command':
      const { stdout, stderr } = await execAsync(args.command, { cwd: args.cwd || process.cwd() });
      return { success: true, stdout, stderr, command: args.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/saksham0712/MCP'

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