Skip to main content
Glama
davidkim9

Container Exec MCP Server

by davidkim9

exec

Execute commands inside Docker containers to manage processes, run scripts, or perform administrative tasks within isolated environments.

Instructions

Execute a command in a Docker container

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
container_idYesContainer ID or name
commandYesCommand to execute in the container
stdinNoInput to send to the command via stdin
working_dirNoWorking directory for the command/home/ubuntu/workspace
userNoUser to run the command as
envNoEnvironment variables (format: KEY=value)
timeoutNoCommand timeout in seconds

Implementation Reference

  • The main handler function for the 'exec' tool. It executes the Docker command using the helper function, handles timeout, formats stdout/stderr/exit code output, and returns as text content or error message.
    async function handler(params: z.infer<typeof inputSchema>, context: ToolContext): Promise<CallToolResult> {
      const { container_id, command, stdin, working_dir, user, env, timeout } = params;
      const { docker } = context;
    
      try {
        const result = await Promise.race([
          executeDockerCommand(docker, container_id, command, stdin, working_dir, user, env),
          new Promise<never>((_, reject) =>
            setTimeout(() => reject(new Error('Command timeout')), timeout * 1000)
          )
        ]);
    
        let output = '';
        if (result.stdout) {
          output += `STDOUT:\n${result.stdout}\n`;
        }
        if (result.stderr) {
          output += `STDERR:\n${result.stderr}\n`;
        }
        output += `Exit Code: ${result.exitCode}`;
    
        return {
          content: [{
            type: 'text',
            text: output
          }]
        };
      } catch (error) {
        return {
          content: [{
            type: 'text',
            text: `Execution error: ${error instanceof Error ? error.message : 'Unknown error'}`
          }]
        };
      }
  • Zod input schema defining the parameters for the 'exec' tool: container_id, command, stdin, working_dir, user, env, timeout.
    const inputSchema = z.object({
      container_id: z.string().describe('Container ID or name'),
      command: z.string().describe('Command to execute in the container'),
      stdin: z.string().optional().describe('Input to send to the command via stdin'),
      working_dir: z.string().optional().default('/home/ubuntu/workspace').describe('Working directory for the command'),
      user: z.string().optional().describe('User to run the command as'),
      env: z.array(z.string()).optional().describe('Environment variables (format: KEY=value)'),
      timeout: z.number().optional().default(30).describe('Command timeout in seconds')
    });
  • Helper function that performs the actual Docker exec operation: creates exec instance, starts stream, parses multiplexed stdout/stderr, handles stdin, retrieves exit code.
    async function executeDockerCommand(
      docker: any,
      containerId: string,
      command: string,
      stdin?: string,
      workingDir?: string,
      user?: string,
      env?: string[]
    ): Promise<{ stdout: string; stderr: string; exitCode: number | null }> {
      try {
        const container = docker.getContainer(containerId);
    
        // Check if container is running
        const info = await container.inspect();
        if (!info.State.Running) {
          throw new Error(`Container '${containerId}' is not running`);
        }
    
        // Create exec instance
        const exec = await container.exec({
          Cmd: ['/bin/bash', '-c', command],
          AttachStdin: !!stdin,
          AttachStdout: true,
          AttachStderr: true,
          Tty: false,
          WorkingDir: workingDir,
          User: user,
          Env: env
        });
    
        // Start execution
        const stream = await exec.start({
          Detach: false,
          Tty: false,
          stdin: !!stdin
        });
    
        let stdout = '';
        let stderr = '';
    
        // Handle stdin if provided
        if (stdin) {
          const stdinStream = new Readable();
          stdinStream.push(stdin);
          stdinStream.push(null); // End the stream
          stdinStream.pipe(stream);
        }
    
        // Docker multiplexes stdout/stderr in a special format
        const parseDockerStream = (data: Buffer): { stdout: string; stderr: string } => {
          let stdout = '';
          let stderr = '';
          let offset = 0;
    
          while (offset < data.length) {
            if (offset + 8 > data.length) break;
    
            const streamType = data[offset];
            const size = data.readUInt32BE(offset + 4);
    
            if (offset + 8 + size > data.length) break;
    
            const chunk = data.slice(offset + 8, offset + 8 + size).toString();
    
            if (streamType === 1) {
              stdout += chunk;
            } else if (streamType === 2) {
              stderr += chunk;
            }
    
            offset += 8 + size;
          }
    
          return { stdout, stderr };
        };
    
        // Collect all data
        const chunks: Buffer[] = [];
        stream.on('data', (chunk: Buffer) => {
          chunks.push(chunk);
        });
    
        // Wait for completion
        await new Promise((resolve, reject) => {
          stream.on('end', resolve);
          stream.on('error', reject);
        });
    
        // Parse the collected data
        const allData = Buffer.concat(chunks);
        const parsed = parseDockerStream(allData);
        stdout = parsed.stdout;
        stderr = parsed.stderr;
    
        // Get exit code
        const execInfo = await exec.inspect();
    
        return {
          stdout,
          stderr,
          exitCode: execInfo.ExitCode
        };
    
      } catch (error) {
        throw error;
      }
    }
  • The 'execCommand' tool is registered in the AVAILABLE_TOOLS array, which provides all Docker container management tools.
    export const AVAILABLE_TOOLS: ToolDefinition[] = [
      execCommand,
      listContainers,
      getContainerInfo
    ];
  • Export of the 'execCommand' ToolDefinition, including name, description, inputSchema, and handler references.
    export const execCommand: ToolDefinition = {
      name: 'exec',
      description: 'Execute a command in a Docker container',
      inputSchema,
      handler
    };
Behavior2/5

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

With no annotations provided, the description carries full burden for behavioral disclosure. It states the tool executes commands but doesn't mention critical behaviors: whether this is a read/write operation, what permissions are needed, if commands run as root by default, what happens on timeout, or how output/errors are returned. For a command execution tool with zero annotation coverage, this leaves significant gaps.

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 a single, clear sentence with zero wasted words. It's appropriately sized for a tool with comprehensive schema documentation and gets straight to the point without unnecessary elaboration.

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?

For a command execution tool with 7 parameters, no annotations, and no output schema, the description is incomplete. It doesn't explain what the tool returns (stdout/stderr/exit code), error conditions, security implications, or interaction patterns. The combination of mutation capability and lack of behavioral context makes this inadequate.

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 all 7 parameters thoroughly. The description adds no additional parameter semantics beyond what's in the schema. Baseline 3 is appropriate when the schema does the heavy lifting for parameter documentation.

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') and target resource ('a command in a Docker container'), providing a specific verb+resource combination. However, it doesn't explicitly distinguish this from sibling tools like get_container_info or list_containers, which are read-only operations versus this execution tool.

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 (e.g., container must be running), when not to use it (e.g., for simple container inspection), or how it differs from sibling tools like get_container_info for container metadata.

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/davidkim9/container-exec-mcp'

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