Skip to content

shell

code_context_agent.tools.shell

Unified shell command executor.

This module provides a secure, bounded shell command execution utility shared across all tool modules.

CommandResult

Bases: TypedDict

Result of a shell command execution.

ToolResult

Bases: FrozenModel

Standardized result structure for tool responses.

Provides a consistent JSON serialization pattern for tool outputs.

Example

result = ToolResult(status="success", data={"count": 42}) return result.to_json() '{"status": "success", "data": {"count": 42}}'

result = ToolResult.error("File not found") return result.to_json() '{"status": "error", "error": "File not found"}'

to_json

to_json()

Serialize to JSON string, omitting None values.

Source code in src/code_context_agent/tools/shell.py
def to_json(self) -> str:
    """Serialize to JSON string, omitting None values."""
    d: dict[str, Any] = {"status": self.status}
    if self.data:
        d.update(self.data)
    if self.error_message:
        d["error"] = self.error_message
    return json.dumps(d)

success classmethod

success(**data)

Create a success result with data.

Source code in src/code_context_agent/tools/shell.py
@classmethod
def success(cls, **data: Any) -> ToolResult:
    """Create a success result with data."""
    return cls(status="success", data=data if data else None)

error classmethod

error(message, **extra)

Create an error result.

Source code in src/code_context_agent/tools/shell.py
@classmethod
def error(cls, message: str, **extra: Any) -> ToolResult:
    """Create an error result."""
    return cls(status="error", error_message=message, data=extra if extra else None)

run_command

run_command(
    cmd,
    cwd=None,
    timeout=120,
    max_output=100000,
    input_data=None,
)

Run shell command with bounds.

Uses shell=False with shlex parsing for security. For commands requiring shell features (pipes, redirects), pass a list like ["sh", "-c", "cmd"].

Parameters:

Name Type Description Default
cmd str | list[str]

Command string or list of arguments.

required
cwd str | None

Working directory.

None
timeout int

Maximum execution time in seconds.

120
max_output int

Maximum characters to capture.

100000
input_data str | None

Optional string to send to stdin.

None

Returns:

Type Description
CommandResult

Dict with status, stdout, stderr, return_code, and truncated flag.

Source code in src/code_context_agent/tools/shell.py
def run_command(
    cmd: str | list[str],
    cwd: str | None = None,
    timeout: int = 120,
    max_output: int = 100_000,
    input_data: str | None = None,
) -> CommandResult:
    """Run shell command with bounds.

    Uses shell=False with shlex parsing for security. For commands requiring
    shell features (pipes, redirects), pass a list like ["sh", "-c", "cmd"].

    Args:
        cmd: Command string or list of arguments.
        cwd: Working directory.
        timeout: Maximum execution time in seconds.
        max_output: Maximum characters to capture.
        input_data: Optional string to send to stdin.

    Returns:
        Dict with status, stdout, stderr, return_code, and truncated flag.
    """
    # Convert string to list safely using ternary for clarity
    cmd_list = shlex.split(cmd) if isinstance(cmd, str) else cmd

    try:
        result = subprocess.run(
            cmd_list,
            cwd=cwd,
            capture_output=True,
            text=True,
            timeout=timeout,
            input=input_data,
        )

        stdout = result.stdout[:max_output]
        truncated = len(result.stdout) > max_output

        if truncated:
            stdout += f"\n... (truncated, {len(result.stdout)} total chars)"

        return {
            "status": "success" if result.returncode == 0 else "error",
            "stdout": stdout,
            "stderr": result.stderr[:10000],
            "return_code": result.returncode,
            "truncated": truncated,
        }
    except subprocess.TimeoutExpired:
        return {
            "status": "error",
            "stdout": "",
            "stderr": f"Command timed out after {timeout}s",
            "return_code": -1,
            "truncated": False,
        }
    except (subprocess.SubprocessError, OSError) as e:
        return {
            "status": "error",
            "stdout": "",
            "stderr": str(e),
            "return_code": -1,
            "truncated": False,
        }