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 };
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. It hints at caution but doesn't specify what risks are involved (e.g., destructive effects, permission requirements, or rate limits). This leaves significant gaps in understanding the tool's behavior beyond the basic action.

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 with just one sentence, front-loaded with the core action and a cautionary note. Every word earns its place, making it efficient and easy to parse without unnecessary elaboration.

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 (executing system commands can be high-risk), lack of annotations, and no output schema, the description is incomplete. It doesn't cover return values, error handling, security implications, or detailed behavioral traits, leaving the agent with insufficient context for safe and effective use.

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?

The input schema has 100% description coverage, clearly documenting the 'command' and 'cwd' parameters. The description adds no additional parameter details beyond what the schema provides, so it meets the baseline of 3 for high schema coverage without compensating with extra semantic value.

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 verb ('execute') and resource ('system command'), making the purpose understandable. However, it doesn't differentiate from siblings like 'get_system_info' or 'list_directory' which might also involve system operations, leaving some ambiguity about when to choose this specific tool.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines3/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The phrase 'use with caution' implies this tool should be used carefully, suggesting it might have risks or side effects. However, it doesn't provide explicit guidance on when to use it versus alternatives like 'get_system_info' for safe queries, nor does it specify prerequisites or exclusions, leaving usage context somewhat vague.

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/saksham0712/MCP'

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