Skip to main content
Glama
dylan-gluck

MCP Background Job Server

by dylan-gluck

execute_command

Run shell commands as background jobs to handle long-running processes asynchronously, returning a job ID for monitoring and management.

Instructions

Execute a command as a background job and return job ID.

Args: command: Shell command to execute in the background

Returns: ExecuteOutput containing the job ID (UUID) of the started job

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
commandYesShell command to execute

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault
job_idYesUUID v4 job identifier

Implementation Reference

  • MCP tool handler for execute_command. Validates input, calls JobManager.execute_command, handles errors, returns ExecuteOutput with job_id.
    @mcp.tool()
    async def execute_command(
        command: str = Field(..., description="Shell command to execute"),
    ) -> ExecuteOutput:
        """Execute a command as a background job and return job ID.
    
        Args:
            command: Shell command to execute in the background
    
        Returns:
            ExecuteOutput containing the job ID (UUID) of the started job
        """
        try:
            job_manager = get_job_manager()
            job_id = await job_manager.execute_command(command)
            return ExecuteOutput(job_id=job_id)
        except ValueError as e:
            raise ToolError(f"Invalid command: {str(e)}")
        except RuntimeError as e:
            if "Maximum concurrent jobs limit" in str(e):
                raise ToolError(f"Job limit reached: {str(e)}")
            else:
                raise ToolError(f"Failed to start job: {str(e)}")
        except Exception as e:
            logger.error(f"Error executing command '{command}': {e}")
            raise ToolError(f"Failed to execute command: {str(e)}")
  • Core JobManager method implementing the command execution logic: security validation, job limits check, job creation, process startup, and storage.
    async def execute_command(self, command: str) -> str:
        """Execute command as background job, return job_id.
    
        Args:
            command: Shell command to execute
    
        Returns:
            UUID v4 job identifier
    
        Raises:
            RuntimeError: If maximum concurrent jobs limit is reached
            ValueError: If command is empty or invalid
        """
        if not command or not command.strip():
            raise ValueError("Command cannot be empty")
    
        # Validate command security
        self._validate_command_security(command.strip())
    
        # Check job limit
        running_jobs = sum(
            1 for job in self._jobs.values() if job.status == JobStatus.RUNNING
        )
        if running_jobs >= self.config.max_concurrent_jobs:
            raise RuntimeError(
                f"Maximum concurrent jobs limit ({self.config.max_concurrent_jobs}) reached"
            )
    
        # Generate unique job ID
        job_id = str(uuid.uuid4())
    
        # Create job record
        job = BackgroundJob(
            job_id=job_id,
            command=command.strip(),
            status=JobStatus.RUNNING,
            started=datetime.now(timezone.utc),
        )
    
        # Create process wrapper
        process_wrapper = ProcessWrapper(
            job_id=job_id,
            command=command.strip(),
            max_output_size=self.config.max_output_size_bytes,
        )
    
        try:
            # Start the process
            await process_wrapper.start()
    
            # Update job with process info
            job.pid = process_wrapper.get_pid()
    
            # Store job and process
            self._jobs[job_id] = job
            self._processes[job_id] = process_wrapper
    
            logger.info(f"Started job {job_id}: {command.strip()}")
            return job_id
    
        except Exception as e:
            logger.error(f"Failed to start job {job_id}: {e}")
            # Clean up on failure
            try:
                process_wrapper.cleanup()
            except Exception:
                pass
            raise
  • Pydantic model for the output schema of the execute_command tool, containing the job_id.
    class ExecuteOutput(BaseModel):
        """Output from execute tool."""
    
        job_id: str = Field(..., description="UUID v4 job identifier")
  • FastMCP @mcp.tool() decorator registering the execute_command function as an MCP tool.
    @mcp.tool()
  • Pydantic model defining the input schema for execute_command (though used inline in tool).
    class ExecuteInput(BaseModel):
        """Input for execute tool."""
    
        command: str = Field(..., description="Shell command to execute")
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. It discloses key behavioral traits: execution as a background job and return of a job ID, but lacks details on permissions, rate limits, error handling, or job lifecycle implications. It adequately covers the core operation but misses advanced context.

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 with the core purpose in the first sentence, followed by structured Args and Returns sections. Every sentence adds value without redundancy, making it highly efficient and well-organized.

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?

Given the tool's moderate complexity (background execution), no annotations, and an output schema (ExecuteOutput), the description is mostly complete. It covers purpose, parameters, and returns, but could benefit from more behavioral context like security implications or job management links.

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

Parameters4/5

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

The description adds minimal semantics beyond the schema (which has 100% coverage), noting the command is a 'Shell command to execute in the background,' slightly reinforcing the schema's description. With only one parameter, the baseline is high, but it doesn't provide format examples or constraints.

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 specific action ('Execute a command as a background job') and resource ('command'), distinguishing it from sibling tools like get_job_output or kill_job by focusing on job initiation rather than monitoring or termination.

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

Usage Guidelines4/5

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

The description implies usage for starting background jobs, with context from sibling tools suggesting alternatives for job monitoring (get_job_status, tail_job_output) and management (kill_job, interact_with_job). However, it lacks explicit guidance on when to use this versus other job-related tools or prerequisites.

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/dylan-gluck/mcp-background-job'

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