Skip to main content
Glama
pathakkhhimanshu

AI Dev Assistant

terminal_commander

Execute allowlisted Windows CMD or PowerShell commands for development tasks like git operations, npm installs, and directory management with built-in security protections.

Instructions

Executes a safe Windows CMD or PowerShell command on the local machine. Protected by a strict allowlist — only pre-approved commands are permitted. Dangerous patterns (rm -rf, del /s, format, shutdown, registry edits, etc.) are blocked even if the base command is allowed. Allowed commands include: dir, git, node, npm, python, tsc, docker, ipconfig, and more. Use this to run git status, dir, npm install, tsc --noEmit, etc.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
commandYesThe full command to execute. Examples: 'git status', 'dir C:\Projects', 'npm run build', 'ipconfig /all'
working_directoryNoOptional: Absolute path to set as the working directory before executing. Windows example: C:\Users\YourName\Projects\my-repo
use_powershellNoIf true, runs the command via PowerShell instead of CMD. Default: false (uses CMD on Windows, /bin/sh on others).

Implementation Reference

  • The handler for the terminal_commander tool, responsible for command validation, shell spawning, and output formatting.
    async handler(args: {
      command: string;
      working_directory?: string;
      use_powershell?: boolean;
    }): Promise<string> {
      const { command, working_directory, use_powershell = false } = args;
    
      // ── Validation ──────────────────────────────────────────────────────────
      const validation = validateCommand(command);
      if (!validation.allowed) {
        return (
          `## ❌ Command Blocked\n\n` +
          `**Command:** \`${command}\`\n\n` +
          `**Reason:** ${validation.reason}\n\n` +
          `_If this command should be allowed, add it to the \`SAFE_COMMANDS_ALLOWLIST\` in \`src/tools/terminalCommander.ts\`._`
        );
      }
    
      // ── Working directory validation ─────────────────────────────────────────
      let cwd: string | undefined;
      if (working_directory) {
        cwd = path.resolve(working_directory);
        const fs = await import("fs");
        if (!fs.existsSync(cwd)) {
          return `ERROR: Working directory does not exist: ${cwd}`;
        }
      }
    
      // ── Spawn ────────────────────────────────────────────────────────────────
      const isWindows = process.platform === "win32";
      let shell: string;
      let shellArgs: string[];
    
      if (use_powershell) {
        shell = isWindows ? "powershell.exe" : "pwsh";
        shellArgs = ["-NonInteractive", "-Command", command];
      } else {
        shell = isWindows ? "cmd.exe" : "/bin/sh";
        shellArgs = isWindows ? ["/c", command] : ["-c", command];
      }
    
      const startTime = Date.now();
    
      const result = await new Promise<CommandResult>((resolve) => {
        const proc = spawn(shell, shellArgs, {
          cwd,
          windowsHide: true,
          env: process.env,
        });
    
        let stdout = "";
        let stderr = "";
        let timedOut = false;
    
        const killTimer = setTimeout(() => {
          timedOut = true;
          proc.kill("SIGKILL");
        }, TIMEOUT_MS);
    
        proc.stdout.on("data", (chunk: Buffer) => {
          stdout += chunk.toString();
          if (stdout.length > MAX_OUTPUT_BYTES) {
            stdout = stdout.slice(0, MAX_OUTPUT_BYTES) + "\n[OUTPUT TRUNCATED]";
            proc.kill("SIGKILL");
          }
        });
    
        proc.stderr.on("data", (chunk: Buffer) => {
          stderr += chunk.toString();
        });
    
        proc.on("close", (exitCode) => {
          clearTimeout(killTimer);
          resolve({
            command,
            workingDirectory: cwd ?? process.cwd(),
            stdout: stdout.trimEnd(),
            stderr: stderr.trimEnd(),
            exitCode,
            executionTimeMs: Date.now() - startTime,
            timedOut,
          });
        });
    
        proc.on("error", (err) => {
          clearTimeout(killTimer);
          resolve({
            command,
            workingDirectory: cwd ?? process.cwd(),
            stdout: "",
            stderr: `Failed to spawn shell: ${err.message}`,
            exitCode: -1,
            executionTimeMs: Date.now() - startTime,
            timedOut: false,
          });
        });
      });
    
      // ── Format output ────────────────────────────────────────────────────────
      const status = result.exitCode === 0 ? "✅ Success" : `⚠️ Exit Code ${result.exitCode}`;
      const lines: string[] = [
        `## Terminal Commander`,
        `**Command:** \`${result.command}\``,
        `**CWD:** ${result.workingDirectory}`,
        `**Shell:** ${use_powershell ? "PowerShell" : "CMD"}  |  **Status:** ${status}  |  **Time:** ${result.executionTimeMs}ms`,
      ];
    
      if (result.timedOut) {
        lines.push(`\n⏱️ **TIMED OUT** after ${TIMEOUT_MS / 1000} seconds.`);
      }
    
      if (result.stdout) {
        lines.push(`\n### Output\n\`\`\`\n${result.stdout}\n\`\`\``);
      } else {
        lines.push(`\n### Output\n*(empty)*`);
      }
    
      if (result.stderr) {
        lines.push(`\n### Stderr\n\`\`\`\n${result.stderr}\n\`\`\``);
      }
    
      return lines.join("\n");
    },
  • Tool registration for "terminal_commander" including metadata and schema.
    export function terminalCommanderTool() {
      return {
        name: "terminal_commander",
        description:
          "Executes a safe Windows CMD or PowerShell command on the local machine. " +
          "Protected by a strict allowlist — only pre-approved commands are permitted. " +
          "Dangerous patterns (rm -rf, del /s, format, shutdown, registry edits, etc.) are blocked even if the base command is allowed. " +
          "Allowed commands include: dir, git, node, npm, python, tsc, docker, ipconfig, and more. " +
          "Use this to run `git status`, `dir`, `npm install`, `tsc --noEmit`, etc.",

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

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