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.",
Behavior4/5

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

With no annotations provided, the description carries the full burden and does an excellent job disclosing key behavioral traits: safety mechanisms (strict allowlist, blocked dangerous patterns), platform specifics (Windows CMD/PowerShell), and examples of allowed commands. It doesn't cover error handling or output format, but provides substantial operational context.

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 appropriately sized and front-loaded with the core purpose and safety constraints, followed by specific examples. Every sentence adds value, though the list of allowed commands could be slightly more concise.

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

Completeness4/5

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

For a tool with no annotations and no output schema, the description provides excellent context about safety constraints, allowed commands, and usage examples. It doesn't describe the return format or error behavior, but covers most essential operational aspects given the complexity.

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 fully documents all three parameters. The description adds no additional parameter information beyond what's in the schema, meeting the baseline expectation when schema coverage is complete.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/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 specific verbs ('executes') and resources ('Windows CMD or PowerShell command on the local machine'), and distinguishes it from siblings by focusing on safe command execution rather than code execution, document search, or GitHub operations.

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

Usage Guidelines5/5

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

It explicitly defines when to use this tool ('to run git status, dir, npm install, tsc --noEmit, etc.') and provides clear alternatives by naming sibling tools (code_executor, doc_search, github_repo_reader), though it doesn't explicitly state when not to use it beyond the allowlist constraints.

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

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