Skip to main content
Glama
alxspiker

Windows Command Line MCP Server

execute_command

Execute Windows commands like 'dir' or 'echo' and retrieve their output through a secure MCP server interface.

Instructions

Execute a Windows command and return its output. Only commands in the allowed list can be executed. This tool should be used for running simple commands like 'dir', 'echo', etc.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
commandYesThe command to execute
workingDirNoWorking directory for the command
timeoutNoTimeout in milliseconds

Implementation Reference

  • The core handler logic for the 'execute_command' tool. It performs security checks to block dangerous commands, constructs the shell command using cmd.exe on Windows, sets execution options, calls the executeCommand helper, and returns stdout or an error.
    async ({ command, workingDir, timeout }) => {
      try {
        // Security check: Ensure only allowed commands are executed
        const commandLower = command.toLowerCase();
        
        // Block potentially dangerous commands
        const dangerousPatterns = [
          'net user', 'net localgroup', 'netsh', 'format', 'rd /s', 'rmdir /s', 
          'del /f', 'reg delete', 'shutdown', 'taskkill', 'sc delete', 'bcdedit',
          'cacls', 'icacls', 'takeown', 'diskpart', 'cipher /w', 'schtasks /create',
          'rm -rf', 'sudo', 'chmod', 'chown', 'passwd', 'mkfs', 'dd'
        ];
        
        // Check for dangerous patterns
        if (dangerousPatterns.some(pattern => commandLower.includes(pattern.toLowerCase()))) {
          return {
            isError: true,
            content: [
              {
                type: "text",
                text: "Command contains potentially dangerous operations and cannot be executed.",
              },
            ],
          };
        }
        
        const options: any = { timeout };
        if (workingDir) {
          options.cwd = workingDir;
        }
        
        let cmdToExecute;
        if (isWindows) {
          cmdToExecute = `cmd.exe /c ${command}`;
        } else {
          // For non-Windows, try to execute the command directly
          cmdToExecute = command;
        }
        
        const stdout = executeCommand(cmdToExecute, options);
        return {
          content: [
            {
              type: "text",
              text: stdout.toString() || 'Command executed successfully (no output)',
            },
          ],
        };
      } catch (error) {
        return {
          isError: true,
          content: [
            {
              type: "text",
              text: `Error executing command: ${error}`,
            },
          ],
        };
      }
    }
  • Input schema using Zod for the 'execute_command' tool, defining parameters: command (required string), workingDir (optional string), timeout (optional number with default).
    {
      command: z.string().describe("The command to execute"),
      workingDir: z.string().optional().describe("Working directory for the command"),
      timeout: z.number().default(30000).describe("Timeout in milliseconds"),
    },
  • index.ts:446-514 (registration)
    MCP server registration of the 'execute_command' tool, including the tool name, description, input schema, and inline handler function.
    server.tool(
      "execute_command",
      "Execute a Windows command and return its output. Only commands in the allowed list can be executed. This tool should be used for running simple commands like 'dir', 'echo', etc.",
      {
        command: z.string().describe("The command to execute"),
        workingDir: z.string().optional().describe("Working directory for the command"),
        timeout: z.number().default(30000).describe("Timeout in milliseconds"),
      },
      async ({ command, workingDir, timeout }) => {
        try {
          // Security check: Ensure only allowed commands are executed
          const commandLower = command.toLowerCase();
          
          // Block potentially dangerous commands
          const dangerousPatterns = [
            'net user', 'net localgroup', 'netsh', 'format', 'rd /s', 'rmdir /s', 
            'del /f', 'reg delete', 'shutdown', 'taskkill', 'sc delete', 'bcdedit',
            'cacls', 'icacls', 'takeown', 'diskpart', 'cipher /w', 'schtasks /create',
            'rm -rf', 'sudo', 'chmod', 'chown', 'passwd', 'mkfs', 'dd'
          ];
          
          // Check for dangerous patterns
          if (dangerousPatterns.some(pattern => commandLower.includes(pattern.toLowerCase()))) {
            return {
              isError: true,
              content: [
                {
                  type: "text",
                  text: "Command contains potentially dangerous operations and cannot be executed.",
                },
              ],
            };
          }
          
          const options: any = { timeout };
          if (workingDir) {
            options.cwd = workingDir;
          }
          
          let cmdToExecute;
          if (isWindows) {
            cmdToExecute = `cmd.exe /c ${command}`;
          } else {
            // For non-Windows, try to execute the command directly
            cmdToExecute = command;
          }
          
          const stdout = executeCommand(cmdToExecute, options);
          return {
            content: [
              {
                type: "text",
                text: stdout.toString() || 'Command executed successfully (no output)',
              },
            ],
          };
        } catch (error) {
          return {
            isError: true,
            content: [
              {
                type: "text",
                text: `Error executing command: ${error}`,
              },
            ],
          };
        }
      }
    );
  • Supporting helper function executeCommand that performs the actual command execution using Node.js execSync, with platform-specific handling (direct exec on Windows, modified fallback on other platforms).
    function executeCommand(command: string, options: any = {}) {
      if (isWindows) {
        return execSync(command, options);
      } else {
        // Log warning for non-Windows environments
        console.error(`Warning: Running in a non-Windows environment (${platform()}). Windows commands may not work.`);
        
        // For testing purposes on non-Windows platforms
        try {
          // For Linux/MacOS, we'll strip cmd.exe and powershell.exe references
          let modifiedCmd = command;
          
          // Replace cmd.exe /c with empty string
          modifiedCmd = modifiedCmd.replace(/cmd\.exe\s+\/c\s+/i, '');
          
          // Replace powershell.exe -Command with empty string or a compatible command
          modifiedCmd = modifiedCmd.replace(/powershell\.exe\s+-Command\s+("|')/i, '');
          
          // Remove trailing quotes if we removed powershell -Command
          if (modifiedCmd !== command) {
            modifiedCmd = modifiedCmd.replace(/("|')$/, '');
          }
          
          console.error(`Attempting to execute modified command: ${modifiedCmd}`);
          return execSync(modifiedCmd, options);
        } catch (error) {
          console.error(`Error executing modified command: ${error}`);
          return Buffer.from(`This tool requires a Windows environment. Current platform: ${platform()}`);
        }
      }
    }
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 of behavioral disclosure. It mentions the allowed-list constraint and suggests simple commands, but lacks critical details: it doesn't specify security implications (e.g., permissions required), error handling, output format, or potential side effects (e.g., whether commands can modify the system). For a command execution tool with zero annotation coverage, this is inadequate.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness4/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is concise (two sentences) and front-loaded with the core purpose. The second sentence adds useful constraints and examples, but could be slightly more structured (e.g., separating constraints from examples). Overall, it's efficient with minimal waste.

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 complexity (command execution with security implications), lack of annotations, and no output schema, the description is incomplete. It mentions an allowed list and simple commands but omits critical context: what the output looks like, error conditions, safety warnings, or how to check allowed commands (via 'list_allowed_commands'). This leaves significant gaps for an AI agent to use it correctly.

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 three parameters ('command', 'workingDir', 'timeout') with descriptions. The description adds no additional parameter semantics beyond what's in the schema, such as examples of allowed commands or timeout behavior. Baseline is 3 when schema coverage is high and no extra param info is provided.

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: 'Execute a Windows command and return its output.' It specifies the verb ('execute'), resource ('Windows command'), and outcome ('return its output'). However, it doesn't explicitly differentiate from sibling tools like 'execute_powershell' or 'list_allowed_commands', which would be needed for a score of 5.

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 description provides some usage context: 'Only commands in the allowed list can be executed' and 'This tool should be used for running simple commands like 'dir', 'echo', etc.' This implies when to use it (for simple commands) and hints at constraints, but it doesn't explicitly state when NOT to use it or name alternatives (e.g., use 'execute_powershell' for PowerShell scripts), so it falls short of explicit guidance.

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/alxspiker/Windows-Command-Line-MCP-Server'

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