Skip to main content

Agent Shell

Agent Shell is a light weight abstraction for executing a cli coding agent headlessly and returning the output that can be used programatically as a unified contract

Features

  • One unified contract — the same execute, stream, health_check, and list_models API across every agent; swap the backend without changing consuming code.
  • Six CLI agents — Claude Code, OpenCode, Copilot CLI, Codex, Pi, and Cursor behind a common adapter protocol.
  • Execute or stream — get one AgentResponse (raises AgentExecutionError on a failed run), or async-iterate normalized StreamEvents with optional thinking/reasoning.
  • Session resumption — continue any conversation by passing back its session_id.
  • Normalized cost & tokens — consistent cost and output_tokens (reasoning included) regardless of how each CLI reports them.
  • Model discovery — retrieve the exact account/workspace-aware model strings accepted by each CLI, without inference calls, SDK dependencies, or static catalogs.
  • Health checks — confirm an agent + model combination actually works before you rely on it, read from the event stream rather than unreliable exit codes.
  • Portable tool control — one canonical allow/deny vocabulary (bash, edit, read, web_search, web_fetch) translated to each CLI's own tool names.
  • Unified MCP management — register, remove, and list MCP servers across agents through a single API.
  • Async & dependency-free — pure asyncio, zero runtime dependencies, Python 3.12+.

Installation

uv add agent-shell-py

or with pip:

pip install agent-shell-py

Agent skills

Skill_Banner

The repository includes reusable skills that teach coding agents how to use AgentShell:

  • invoking-cli-agents — invoke, stream, resume, and restrict CLI agents.
  • delegating-code-review — delegate an independent code review through AgentShell.

Install them interactively with the Vercel Skills CLI:

npx skills add ScottRBK/agent-shell

Or install both skills globally for every coding agent supported by AgentShell:

npx skills add ScottRBK/agent-shell --global \
  --skill '*' \
  --agent claude-code opencode github-copilot codex pi cursor \
  --yes

Install only the core AgentShell skill with:

npx skills add ScottRBK/agent-shell --skill invoking-cli-agents

The skills provide agent instructions. Install agent-shell-py and the chosen coding-agent CLIs separately.

Examples

Execute

from agent_shell.shell import AgentShell
from agent_shell.models.agent import AgentType

shell = AgentShell(agent_type=AgentType.CLAUDE_CODE)

response = await shell.execute(
    cwd="/path/to/project",
    prompt="Can you tell me about this project?",
    allowed_tools=["Read", "Glob", "Grep"],
    model="sonnet",
)

print(response.response)
print(f"Cost: ${response.cost:.4f}")
print(f"Output tokens: {response.output_tokens}")  # billed output, reasoning included
print(f"Session: {response.session_id}")

# Resume the conversation using the session_id
follow_up = await shell.execute(
    cwd="/path/to/project",
    prompt="Now refactor the auth module based on your findings",
    allowed_tools=["Read", "Edit", "Bash"],
    model="sonnet",
    session_id=response.session_id,
)

output_tokens is a cost measure: the billed output-token count, which includes reasoning tokens (they are billed at the output rate). It is reported consistently across all adapters.

Failure handling

execute() raises AgentExecutionError instead of returning when a run failed — an error event was emitted, the terminal result had content == "error", or no terminal result arrived at all. str(e) is the bare reason; the exception also carries whatever partial response/cost/session_id/duration/output_tokens the run produced before failing.

from agent_shell.models.agent import AgentExecutionError

try:
    response = await shell.execute(cwd="/path/to/project", prompt="Fix the failing test")
except AgentExecutionError as e:
    print(f"run failed: {e}")   # e.g. "500 model name=qwen3.6-27b-8Q failed to load"

Stream

from agent_shell.shell import AgentShell
from agent_shell.models.agent import AgentType

shell = AgentShell(agent_type=AgentType.CLAUDE_CODE)

async for event in shell.stream(
    cwd="/path/to/project",
    prompt="Refactor the auth module",
    allowed_tools=["Read", "Edit", "Bash"],
    model="sonnet",
    effort="high",
    include_thinking=True,
):
    if event.type == "system":
        print(f"Session: {event.session_id}")
    else:
        print(f"[{event.type}] {event.content}")

Model discovery

Ask the selected CLI which model strings it currently advertises, then pass one back unchanged. Discovery sends no inference prompt and has no model-token cost.

shell = AgentShell(agent_type=AgentType.CLAUDE_CODE)

models = await shell.list_models(cwd="/path/to/project")
selected_model = models[0]

response = await shell.execute(
    cwd="/path/to/project",
    prompt="Review this project",
    model=selected_model,
)

"Available" means advertised as selectable for the current harness, account, and workspace. It does not prove quota, entitlement, credentials, or provider health. The harness's order and aliases such as auto and default are preserved. A genuine empty catalog returns []; discovery failures are raised instead of being mistaken for an empty catalog.

See the agent parameter comparison for each harness's underlying discovery mechanism.

Health check

Verify an agent + model combination actually works before relying on it. It sends a trivial prompt and reports whether a real response came back — catching bad model names, missing credentials, and billing/quota failures. Exit codes alone are unreliable (some CLIs exit 0 on failure), so the verdict is read from the normalized event stream.

shell = AgentShell(agent_type=AgentType.CLAUDE_CODE)

result = await shell.health_check(cwd="/path/to/project", model="haiku")
if not result.healthy:
    print(f"unavailable: {result.exception}")

Restricting tools (disallowed_tools)

Pass a deny-list of tools that the agent must not use. Use the canonical vocabulary {bash, edit, read, web_search, web_fetch} and Agent Shell translates it to each CLI's own tool names — callers don't need to know the per-harness vocabulary:

shell = AgentShell(agent_type=AgentType.CLAUDE_CODE)

response = await shell.execute(
    cwd="/path/to/project",
    prompt="Audit this code but don't run anything or touch the network",
    disallowed_tools=["bash", "web_search", "web_fetch"],
)
  • edit covers write/edit/notebook-edit (it fans out on harnesses that split them).
  • Any name outside the canonical set passes through verbatim (e.g. an MCP tool mcp__server__tool, or a harness-specific name like Write, or Copilot's view).
  • Deny takes precedence over auto-approve on every backend that supports it.
  • Where a backend cannot enforce a deny, the adapter emits a UserWarning listing the ignored tools rather than failing silently. Coverage varies: Claude and OpenCode enforce all five canonical names; Copilot enforces only bash/edit canonically (use a verbatim name for its other tools); Codex can only deny web_search; Cursor cannot enforce any per-call deny (its tool policy lives in .cursor/cli.json).
  • Denying edit or read is best-effort: a model can still modify or read files through the shell, so also deny bash when you need a hard file boundary.

OpenCode

from agent_shell.shell import AgentShell
from agent_shell.models.agent import AgentType

shell = AgentShell(agent_type=AgentType.OPENCODE)

response = await shell.execute(
    cwd="/path/to/project",
    prompt="Can you tell me about this project?",
    model="anthropic/claude-sonnet-4-5",
)

print(response.response)
print(f"Session: {response.session_id}")

# Resume the conversation using the session_id
follow_up = await shell.execute(
    cwd="/path/to/project",
    prompt="Now refactor the auth module based on your findings",
    model="anthropic/claude-sonnet-4-5",
    session_id=response.session_id,
)

Note: For OpenCode, allowed_tools and effort are ignored — the adapter maps neither to a CLI flag nor to opencode.json. To restrict an OpenCode agent, use disallowed_tools (see Restricting tools): it is enforced via a per-run OPENCODE_PERMISSION environment variable and holds even under auto-approve. Keep auto_approve=True (the default) — with auto_approve=False, opencode run auto-rejects permission prompts non-interactively and can silently abort the run.

Cursor

from agent_shell.shell import AgentShell
from agent_shell.models.agent import AgentType

shell = AgentShell(agent_type=AgentType.CURSOR)

response = await shell.execute(
    cwd="/path/to/project",
    prompt="Can you tell me about this project?",
)

print(response.response)
print(f"Session: {response.session_id}")

Note: Cursor runs headlessly via cursor-agent --print --output-format stream-json and requires workspace trust, which the adapter always passes (--trust). With auto_approve=True (the default) it also passes --force so tools auto-run; otherwise tools are auto-rejected but the run still completes. allowed_tools, effort, and disallowed_tools are ignored — Cursor exposes no per-call tool policy or effort flag (tool policy lives in .cursor/cli.json), so each emits a UserWarning. On a Free plan only model=None/"auto" works. MCP servers are declared in .cursor/mcp.json; the add/remove/list MCP methods raise NotImplementedError.

MCP Servers

Register MCP servers for any supported agent through a unified API. All adapters use user-scope configuration so registrations persist across the agent's execute/stream calls.

from agent_shell.shell import AgentShell
from agent_shell.models.agent import AgentType, MCPServerSpec, MCPServerType

shell = AgentShell(agent_type=AgentType.CLAUDE_CODE)

# Register a stdio MCP server (e.g. forgetful) before running an eval
await shell.add_mcp_server(MCPServerSpec(
    name="forgetful",
    type=MCPServerType.STDIO,
    command="uvx",
    args=["forgetful-ai"],
    env={"FORGETFUL_API_KEY": "..."},
))

response = await shell.execute(
    cwd="/path/to/project",
    prompt="Recall any prior decisions about the auth module",
)

# Optional cleanup
await shell.remove_mcp_server("forgetful")

For HTTP transport, pass url and headers instead of command/args/env:

await shell.add_mcp_server(MCPServerSpec(
    name="remote",
    type=MCPServerType.HTTP,
    url="https://example.com/mcp",
    headers={"Authorization": "Bearer ..."},
))

add_mcp_server overwrites an existing server with the same name. remove_mcp_server warns rather than raises when the named server is not found. list_mcp_servers() works for Claude Code, OpenCode, Copilot CLI, and Codex. Claude Code reads user-scope entries directly from ~/.claude.json, so listing does not launch configured servers for health checks. MCP is not supported for Pi or Cursor — neither CLI exposes an add/remove subcommand, so all three MCP methods raise NotImplementedError.

Logging

Agent Shell uses Python's standard logging module. Configure the agent_shell logger to capture tool calls, session IDs, costs, and errors:

import logging

logging.getLogger("agent_shell").setLevel(logging.INFO)
logging.getLogger("agent_shell").addHandler(logging.StreamHandler())

Set to DEBUG for raw JSON events and full command arguments.

Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

agent_shell_py-0.2.3.tar.gz (1.9 MB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

agent_shell_py-0.2.3-py3-none-any.whl (52.2 kB view details)

Uploaded Python 3

File details

Details for the file agent_shell_py-0.2.3.tar.gz.

File metadata

  • Download URL: agent_shell_py-0.2.3.tar.gz
  • Upload date:
  • Size: 1.9 MB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/7.0.0 CPython/3.13.14

File hashes

Hashes for agent_shell_py-0.2.3.tar.gz
Algorithm Hash digest
SHA256 d83acb5942f672db9ec324da4baa79019a8594cf8d5a949e84295749c5e98195
MD5 d0a62e53d6a1362617f227bf6122d3d1
BLAKE2b-256 7ec149e7d50e6c9c54f4a805f96590ff1144d3bf439049544691ad0485648b51

See more details on using hashes here.

Provenance

The following attestation bundles were made for agent_shell_py-0.2.3.tar.gz:

Publisher: publish.yml on ScottRBK/agent-shell

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file agent_shell_py-0.2.3-py3-none-any.whl.

File metadata

  • Download URL: agent_shell_py-0.2.3-py3-none-any.whl
  • Upload date:
  • Size: 52.2 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/7.0.0 CPython/3.13.14

File hashes

Hashes for agent_shell_py-0.2.3-py3-none-any.whl
Algorithm Hash digest
SHA256 24f2a10066329d3631b000018cfd353d6be0d47cc261648d90409b202d513fd4
MD5 056e011460ce8d5a669d5eaa0d5b9874
BLAKE2b-256 0d858482aae0a0e3e3d4e0f8902285a84e65f704e95e033a227f36e9300ea29a

See more details on using hashes here.

Provenance

The following attestation bundles were made for agent_shell_py-0.2.3-py3-none-any.whl:

Publisher: publish.yml on ScottRBK/agent-shell

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

Release history Release notifications | RSS feed

0.4.0

2 files

0.3.2

2 files

0.3.1

2 files

0.3.0

2 files

0.2.5

2 files

0.2.4

2 files

This release

0.2.3 This release

2 files

0.2.2

2 files

0.2.1

2 files

0.2.0

2 files

0.1.17

2 files

0.1.16

2 files

0.1.15

2 files

0.1.14

2 files

0.1.13

2 files

0.1.12

2 files

0.1.11

2 files

0.1.10

2 files

0.1.9

2 files

0.1.8

2 files

0.1.7

2 files

0.1.5

2 files

0.1.4

2 files

0.1.3

2 files

0.1.0

2 files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page