Skip to main content
Glama

execute_command

Execute system commands and retrieve their output, supporting persistent shell sessions or new instances for isolated operations.

Instructions

Execute a command and return its output. Commands run in a persistent shell session by default. Use newSession: true to run in a new shell instance.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
commandYes
newSessionNo

Implementation Reference

  • Main handler logic for the 'execute_command' tool. Parses input arguments using the schema, determines whether to use a new shell session or the persistent shell, spawns the process, captures stdout/stderr, handles output markers for persistent sessions, and resolves with the command output and error status.
    if (name === "execute_command") {
        const parsed = ExecuteCommandArgsSchema.safeParse(args);
        if (!parsed.success) {
            throw new Error(`Invalid arguments for execute_command: ${parsed.error}`);
        }
    
        return new Promise((resolve) => {
            const useNewSession = parsed.data.newSession || false;
            const isWindows = platform() === 'win32';
            
            if (useNewSession) {
                const cmdProcess = spawn(isWindows ? 'cmd' : '/bin/sh', [], {
                    windowsHide: true,
                });
    
                let output = '';
                let errorOutput = '';
    
                cmdProcess.stdout.on('data', (data) => {
                    output += data.toString();
                });
    
                cmdProcess.stderr.on('data', (data) => {
                    errorOutput += data.toString();
                });
    
                cmdProcess.on('error', (error) => {
                    resolve({
                        content: [{ 
                            type: "text", 
                            text: `Failed to execute command: ${error.message}`
                        }],
                        isError: true,
                    });
                });
    
                cmdProcess.stdin.write(parsed.data.command + '\n');
                cmdProcess.stdin.end();
    
                cmdProcess.on('close', (code) => {
                    const finalOutput = output + (errorOutput ? `\nErrors:\n${errorOutput}` : '');
                    resolve({
                        content: [{ 
                            type: "text", 
                            text: finalOutput || `Command completed with code ${code}`
                        }],
                        isError: code !== 0,
                    });
                });
            } else {
                if (!persistentCmd) {
                    initializePersistentCmd();
                }
    
                if (!persistentCmd) {
                    throw new Error("Failed to initialize persistent CMD session");
                }
    
                let output = '';
                let errorOutput = '';
                let commandComplete = false;
    
                const outputMarker = `__CMD_OUTPUT_${Date.now()}__`;
                const markerCommand = isWindows ? `echo ${outputMarker}` : `echo "${outputMarker}"`;
    
                const dataHandler = (data: Buffer) => {
                    const str = data.toString();
                    if (str.includes(outputMarker)) {
                        commandComplete = true;
                        return;
                    }
                    if (!commandComplete) {
                        output += str;
                    }
                };
    
                const errorHandler = (data: Buffer) => {
                    errorOutput += data.toString();
                };
    
                persistentCmd.stdout?.on('data', dataHandler);
                persistentCmd.stderr?.on('data', errorHandler);
    
                persistentCmd.stdin?.write(parsed.data.command + '\n' + markerCommand + '\n');
    
                const checkInterval = setInterval(() => {
                    if (commandComplete) {
                        clearInterval(checkInterval);
                        persistentCmd?.stdout?.removeListener('data', dataHandler);
                        persistentCmd?.stderr?.removeListener('data', errorHandler);
    
                        const finalOutput = output + (errorOutput ? `\nErrors:\n${errorOutput}` : '');
                        resolve({
                            content: [{ 
                                type: "text", 
                                text: finalOutput || "Command completed"
                            }],
                            isError: false,
                        });
                    }
                }, 50);
    
                setTimeout(() => {
                    if (!commandComplete) {
                        clearInterval(checkInterval);
                        persistentCmd?.stdout?.removeListener('data', dataHandler);
                        persistentCmd?.stderr?.removeListener('data', errorHandler);
                        resolve({
                            content: [{ 
                                type: "text", 
                                text: "Command timed out"
                            }],
                            isError: true,
                        });
                    }
                }, 30000);
            }
        });
  • Zod schema defining the input parameters for the execute_command tool: 'command' (required string) and 'newSession' (optional boolean). Used for validation and JSON schema generation.
    const ExecuteCommandArgsSchema = z.object({
        command: z.string(),
        newSession: z.boolean().optional(),
    });
  • src/index.ts:163-168 (registration)
    Tool registration in the ListToolsRequestSchema handler. Specifies the tool name, description, and input schema for the MCP server.
        name: "execute_command",
        description: "Execute a command and return its output. " +
            "Commands run in a persistent shell session by default. " +
            "Use newSession: true to run in a new shell instance.",
        inputSchema: zodToJsonSchema(ExecuteCommandArgsSchema),
    },
  • Helper function to initialize the persistent shell process (cmd.exe on Windows or /bin/sh on Unix), used by the execute_command handler for non-newSession executions. Handles process events and error cleanup.
    function initializePersistentCmd() {
        const isWindows = platform() === 'win32';
        if (persistentCmd) return;
    
        const shell = isWindows ? 
            join(process.env.SystemRoot || 'C:\\Windows', 'System32', 'cmd.exe') : 
            '/bin/sh';
    
        persistentCmd = spawn(isWindows ? 'cmd.exe' : '/bin/sh', [], {
            windowsHide: true,
            shell: true  // This ensures proper path resolution
        });
    
        persistentCmd.on('error', (error) => {
            console.error('Error in persistent CMD:', error);
            persistentCmd = null;
        });
    
        persistentCmd.on('exit', () => {
            persistentCmd = null;
        });
    }
Behavior3/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

With no annotations provided, the description carries the full burden. It discloses that commands run in a persistent shell session by default and can be run in a new instance, which is useful behavioral context. However, it lacks details on permissions, security implications, error handling, or output format, which are important for a command execution tool.

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 appropriately sized and front-loaded, with two clear sentences that efficiently convey key information without waste. Each sentence earns its place by explaining the core function and a critical parameter behavior.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness3/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given the tool's complexity (command execution with potential security and behavioral implications), no annotations, no output schema, and 0% schema coverage, the description is incomplete. It covers the basic operation and session behavior but lacks details on permissions, error handling, output structure, or safety warnings, which are crucial for such a tool.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters4/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema description coverage is 0%, so the description must compensate. It adds meaning by explaining the 'newSession' parameter's effect (running in a new shell instance vs. default persistent session) and implies 'command' is the input to execute. It doesn't detail the 'command' parameter's format or constraints, but provides enough context for basic usage.

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 with a specific verb ('Execute') and resource ('a command'), and specifies it returns output. However, it doesn't explicitly differentiate from the sibling 'execute_ssh_command' tool, which likely has a different context or target.

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

Usage Guidelines4/5

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

The description provides clear context about when to use the 'newSession' parameter (to run in a new shell instance vs. the default persistent session). It doesn't explicitly mention when to use this tool versus the sibling 'execute_ssh_command' or other alternatives, which is a minor gap.

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/PhialsBasement/CMD-MCP-Server'

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