Skip to main content
Glama
MrGNSS

Desktop Commander MCP

execute_command

Execute terminal commands with timeout control, allowing commands to run in background if they exceed the timeout duration.

Instructions

Execute a terminal command with timeout. Command will continue running in background if it doesn't complete within timeout.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
commandYes
timeout_msNo

Implementation Reference

  • The primary handler function for the 'execute_command' MCP tool. It validates input arguments using the schema, checks if the command is allowed, executes the command via the terminal manager with optional timeout, and returns a formatted response including PID and initial output.
    export async function executeCommand(args: unknown) {
      const parsed = ExecuteCommandArgsSchema.safeParse(args);
      if (!parsed.success) {
        throw new Error(`Invalid arguments for execute_command: ${parsed.error}`);
      }
    
      if (!commandManager.validateCommand(parsed.data.command)) {
        throw new Error(`Command not allowed: ${parsed.data.command}`);
      }
    
      const result = await terminalManager.executeCommand(
        parsed.data.command,
        parsed.data.timeout_ms
      );
    
      return {
        content: [{
          type: "text",
          text: `Command started with PID ${result.pid}\nInitial output:\n${result.output}${
            result.isBlocked ? '\nCommand is still running. Use read_output to get more output.' : ''
          }`
        }],
      };
    }
  • Zod schema defining the input parameters for the execute_command tool: required 'command' string and optional 'timeout_ms' number.
    export const ExecuteCommandArgsSchema = z.object({
      command: z.string(),
      timeout_ms: z.number().optional(),
    });
  • src/server.ts:61-65 (registration)
    Tool registration in the MCP server's ListTools response, specifying name, description, and input schema for execute_command.
      name: "execute_command",
      description:
        "Execute a terminal command with timeout. Command will continue running in background if it doesn't complete within timeout.",
      inputSchema: zodToJsonSchema(ExecuteCommandArgsSchema),
    },
  • src/server.ts:216-219 (registration)
    Dispatch logic in the MCP server's CallToolRequest handler that routes 'execute_command' calls to the executeCommand function after parsing arguments.
    case "execute_command": {
      const parsed = ExecuteCommandArgsSchema.parse(args);
      return executeCommand(parsed);
    }
  • Low-level helper in TerminalManager that spawns the shell process for the command, handles stdout/stderr streaming, timeout blocking, and exit handling. Called by the main handler.
    async executeCommand(command: string, timeoutMs: number = DEFAULT_COMMAND_TIMEOUT): Promise<CommandExecutionResult> {
      const process = spawn(command, [], { shell: true });
      let output = '';
      
      // Ensure process.pid is defined before proceeding
      if (!process.pid) {
        throw new Error('Failed to get process ID');
      }
      
      const session: TerminalSession = {
        pid: process.pid,
        process,
        lastOutput: '',
        isBlocked: false,
        startTime: new Date()
      };
      
      this.sessions.set(process.pid, session);
    
      return new Promise((resolve) => {
        process.stdout.on('data', (data) => {
          const text = data.toString();
          output += text;
          session.lastOutput += text;
        });
    
        process.stderr.on('data', (data) => {
          const text = data.toString();
          output += text;
          session.lastOutput += text;
        });
    
        setTimeout(() => {
          session.isBlocked = true;
          resolve({
            pid: process.pid!,
            output,
            isBlocked: true
          });
        }, timeoutMs);
    
        process.on('exit', (code) => {
          if (process.pid) {
            // Store completed session before removing active session
            this.completedSessions.set(process.pid, {
              pid: process.pid,
              output: output + session.lastOutput, // Combine all output
              exitCode: code,
              startTime: session.startTime,
              endTime: new Date()
            });
            
            // Keep only last 100 completed sessions
            if (this.completedSessions.size > 100) {
              const oldestKey = Array.from(this.completedSessions.keys())[0];
              this.completedSessions.delete(oldestKey);
            }
            
            this.sessions.delete(process.pid);
          }
          resolve({
            pid: process.pid!,
            output,
            isBlocked: false
          });
        });
      });
    }
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 mentions that commands run in the background if they exceed the timeout, which adds some context. However, it fails to address critical aspects like permission requirements, side effects (e.g., file modifications), error handling, or output format, leaving significant gaps for a tool that executes terminal commands.

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 and front-loaded, stating the core purpose in the first sentence. The second sentence adds important behavioral context without unnecessary elaboration. While efficient, it could be slightly improved by integrating parameter details, but it avoids redundancy and 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 of executing terminal commands, no annotations, and no output schema, the description is incomplete. It lacks details on security implications, execution environment, return values, or error cases. For a potentially dangerous tool with 2 parameters, this minimal description leaves too many unknowns for safe and effective use.

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

Parameters2/5

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

The schema description coverage is 0%, so the description must compensate for undocumented parameters. It only mentions 'timeout' generically without explaining the 'timeout_ms' parameter's unit (milliseconds) or the 'command' parameter's format (e.g., shell syntax). This adds minimal value beyond the schema, failing to adequately clarify parameter meanings and 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: 'Execute a terminal command with timeout.' It specifies the verb ('execute') and resource ('terminal command'), making it easy to understand what the tool does. However, it doesn't explicitly differentiate from sibling tools like 'block_command' or 'force_terminate', which prevents a perfect score.

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?

The description provides no guidance on when to use this tool versus alternatives. It doesn't mention prerequisites, appropriate contexts, or when to choose other tools like 'force_terminate' for stopping commands or 'read_output' for checking results. This lack of comparative guidance limits its utility for an AI agent.

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/MrGNSS/ClaudeDesktopCommander'

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