Skip to main content
Glama
abdessamad-elamrani

MalwareAnalyzerMCP

shell_command

Execute terminal commands for malware analysis with configurable timeout and background execution capabilities.

Instructions

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

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
commandYesThe command to execute in the terminal
timeout_msNoOptional timeout in milliseconds (default: 30000)

Implementation Reference

  • Core handler function that spawns the shell command using child_process.spawn with shell: true, captures stdout/stderr output, handles timeout by marking as blocked, tracks process in sessions map, and resolves with pid, output, and blocked status.
    async shellCommand(command, timeoutMs = DEF_TIMEOUT) {
      const process = spawn(command, [], { shell: true });
      let output = '';
      
      // Ensure process.pid is defined before proceeding
      if (!process.pid) {
        return {
          pid: -1,  // Use -1 to indicate an error state
          output: 'Error: Failed to get process ID. The command could not be executed.',
          isBlocked: false
        };
      }
      
      // Create a session object to track this process
      const session = {
        pid: process.pid,
        process,
        lastOutput: '',
        isBlocked: false,
        startTime: new Date()
      };
      
      this.sessions.set(process.pid, session);
    
      return new Promise((resolve) => {
        // Handle standard output
        process.stdout.on('data', (data) => {
          const text = data.toString();
          output += text;
          session.lastOutput += text;
        });
    
        // Handle error output
        process.stderr.on('data', (data) => {
          const text = data.toString();
          output += text;
          session.lastOutput += text;
        });
    
        // Set timeout to mark process as blocked if it exceeds timeoutMs
        setTimeout(() => {
          session.isBlocked = true;
          resolve({
            pid: process.pid,
            output,
            isBlocked: true
          });
        }, timeoutMs);
    
        // Handle process completion
        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 50 completed sessions
            if (this.completedSessions.size > 50) {
              const oldestKey = Array.from(this.completedSessions.keys())[0];
              this.completedSessions.delete(oldestKey);
            }
            
            this.sessions.delete(process.pid);
          }
          
          resolve({
            pid: process.pid,
            output,
            isBlocked: false
          });
        });
      });
    }
  • MCP tool call handler for 'shell_command' in the main server request handler. Validates arguments, calls terminalManager.shellCommand, and returns JSON result or error.
    case 'shell_command':
      try {
        // Type-check and validate arguments
        if (!args || typeof args.command !== 'string') {
          return {
            content: [{ type: "text", text: "Error: Invalid command parameter" }],
            isError: true,
          };
        }
        
        console.error(`Executing command: ${args.command}`);
        const result = await terminalManager.shellCommand(
          args.command, 
          typeof args.timeout_ms === 'number' ? args.timeout_ms : undefined
        );
        console.error(`Command executed with PID: ${result.pid}, blocked: ${result.isBlocked}`);
        return {
          content: [{ type: "text", text: JSON.stringify(result) }],
        };
      } catch (error) {
        console.error('Error executing command:', error);
        return {
          content: [{ type: "text", text: `Error: ${error instanceof Error ? error.message : String(error)}` }],
          isError: true,
        };
      }
  • Zod schema defining input parameters for shell_command tool: command (required string) and timeout_ms (optional number).
    const shellCommandSchema = z.object({
      command: z.string().min(1).describe("The command to execute in the terminal"),
      timeout_ms: z.number().optional().describe("Optional timeout in milliseconds (default: 30000)")
    });
  • serverMCP.js:101-104 (registration)
    Registration of the shell_command tool in the ListToolsRequestSchema handler, including name, description, and inputSchema converted from Zod schema.
      name: 'shell_command',
      description: 'Execute a command in the terminal with timeout. Command will continue running in background if it doesn\'t complete within timeout.',
      inputSchema: zodToJsonSchema(shellCommandSchema),
    },
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 of behavioral disclosure. It adds context about timeout handling and background execution, which are useful behavioral traits. However, it lacks details on permissions, error handling, or output format, leaving gaps in transparency for a potentially risky 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 front-loaded and concise, consisting of two sentences that directly convey the core functionality and a key behavioral trait (timeout and background execution). Every sentence earns its place without unnecessary details, making it efficient and well-structured.

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 complexity of executing shell commands (potentially risky with no annotations or output schema), the description is moderately complete. It covers the basic action and timeout behavior but lacks information on security implications, error responses, or how to handle output, which are important for such a tool.

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 both parameters ('command' and 'timeout_ms') adequately. The description implies timeout behavior but does not add significant meaning beyond what the schema provides, such as default values or usage examples, meeting the baseline for high coverage.

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 action ('execute a command in the terminal') and the resource ('command'), making the purpose evident. However, it does not explicitly differentiate from sibling tools like 'read_output' or 'file', which might also involve terminal operations, so it lacks sibling differentiation.

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 such as 'read_output' or other siblings. It mentions a timeout feature but does not specify scenarios where this tool is preferred or when it should be avoided, leaving usage context unclear.

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/abdessamad-elamrani/MalwareAnalyzerMCP'

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