# ag-bash [Health: Active]

**Category:** 🖥️ Command Line  
**Repository:** https://github.com/sairam0424/ag-bash  
**GitHub Stars:** 1  
**npm Downloads (last month):** 262  
**Views:** 1  
**Installs:** 0  
**Upvotes:** 0  
**Directory Page:** https://allmcps.com/mcp/ag-bash

## Description
Sandboxed AI-native bash with 70 agentic tools: run_bash, code edit/diff, WASM Python/JS.

## Tools
Capabilities this server exposes over MCP:

- **run_bash** — Run a bash script in a persistent sandboxed environment. State (cwd, variables, functions) persists between calls.
- **get_state** — Retrieve the current state of the shell (CWD and Environment Variables).
- **snapshot** — Capture a complete binary snapshot of the current shell state (filesystem + environment).
- **restore** — Restore the shell to a previously captured state via a snapshot.
- **create_delta** — Create a differential delta between a base snapshot and current state for efficient sync.
- **apply_delta** — Apply a differential delta to the current shell state.
- **fork_speculate** — Fork-speculation: copy-on-write branch the sandbox into N isolated children, run a candidate script sequence in each branch in parallel, and report each branch's output + exit code so you can pick a winner. Branch mutations (env, cwd, files) are invisible to the persistent shell and to each other. Optionally pass keepWinner to commit exactly one winning branch's scripts onto the persistent shell; otherwise the persistent shell is left untouched (all branches discarded).
- **search_tools** — Discover which agentic tools are available for a free-text task description (Code Mode). Returns the best-matching tools by relevance so an agent can pick a tool without pre-loading the full catalog.
- **add_todo** — Add a new todo item.
- **ag_browser_cdp** — Call a raw Chrome DevTools Protocol method (browser-harness escape hatch).
- **ag_browser_click** — Click at screen coordinates in the current browser tab (browser-harness).
- **ag_browser_goto** — Navigate the current browser tab to a URL (browser-harness).
- **ag_browser_js** — Evaluate a JavaScript expression in the current browser tab (browser-harness).
- **ag_browser_page_info** — Return current tab metadata: url, title, viewport and scroll sizes (browser-harness).
- **ag_browser_press** — Press a key in the current browser tab (browser-harness).
- **ag_browser_screenshot** — Capture a PNG screenshot of the current browser tab (browser-harness).
- **ag_browser_type** — Insert text into the currently focused element (browser-harness).
- **ag_browser_wait_for_element** — Wait for an element matching a CSS selector to appear (browser-harness).
- **ag_convert** — Convert documents (PDF, Docx, Xlsx) and images to Markdown with AI-powered visual intelligence and OCR.
- **ag_edit** — Advanced line-based file editor. Supports multiple non-contiguous edits in a single call and protects against stale writes using content hashes.
- **ag_explain** — Parse and explain a shell command string, showing its structure and components.
- **ag_find_files** — Find files by name or glob pattern recursively.
- **ag_find_symbol** — Search for symbols (functions, variables, classes) by name or pattern across the workspace.
- **ag_grep** — High-performance recursive pattern search within files.
- **ag_hover** — Get semantic information about a symbol at a specific line and character position.
- **ag_lsp** — Advanced code intelligence: goToDefinition, findReferences, hover, etc.
- **ag_multi_edit** — Apply multiple non-contiguous text replacements to a file in a single operation.
- **ag_todo** — Manage project tasks and todos. Support for listing, adding, updating, and removing tasks.
- **ag_web_fetch** — Fetch the content of a web page and convert it to clean markdown. Results are cached for 15 minutes.
- **ag_web_search** — Search the web for current information, documentation, and answers.
- **agent_memory_read** — Read a memory entry for an agent type.
- **agent_memory_write** — Write a memory entry for an agent type.
- **analyze_code** — Perform semantic analysis on a source file.
- **check_destructive** — Check if a command contains destructive patterns (rm -rf, DROP TABLE, git reset --hard, etc.). Returns warning or null.
- **check_environment** — Get diagnostics about the sandboxed environment.
- **close_session** — Terminate a persistent session and release its resources.
- **cron_create** — Schedule a recurring or one-shot prompt using a cron expression.
- **cron_delete** — Delete a scheduled cron job.
- **cron_list** — List all scheduled cron jobs.
- **diff_files** — Generate a unified diff between two files.
- **edit_file** — Apply a text patch to a file (simple find and replace).
- **enter_worktree** — Create and enter an isolated virtual worktree for independent development.
- **exit_worktree** — Exit the active worktree and restore the original working directory.
- **explain_command** — Parse and explain a shell command.
- **find_files** — Search for files by name or glob pattern.
- **find_symbols** — Search for symbols (functions, variables) across the workspace.
- **get_definition** — Find the definition of a symbol.
- **get_references** — Find all references to a function or variable.
- **git_audit_log** — Get the git operations audit log, optionally filtered to destructive operations only.
- **git_track** — Record and classify a git operation. Returns classification (safe/mutating/destructive) and audit entry.
- **glob_files** — Fast glob pattern matching over the filesystem. Returns matching file paths sorted by name or mtime.
- **grep_search** — Search for a text pattern across multiple files.
- **help_builtin** — Get detailed help for a shell builtin command.
- **hover_info** — Get information about a symbol at a specific position.
- **index_workspace** — Trigger a full scan and indexing of all supported files in the workspace.
- **list_dir** — List contents of a directory.
- **list_mcp_tools** — List all tools available via connected MCP servers.
- **list_todos** — List all todo items.
- **plan_enter** — Enter plan mode to design an approach before making changes.
- **plan_exit** — Exit plan mode and return to execution mode.
- **query_json** — Run a jq query against a JSON file or string.
- **read_file** — Read the contents of a file from the virtual filesystem.
- **run_command** — Execute a shell command in the sandbox.
- **run_js** — Execute JavaScript code in the sandbox. For persistent state, use run_js_session.
- **run_js_session** — Execute JavaScript code in a persistent session (stateful REPL). Maintains variables and modules between calls.
- **run_python** — Execute Python code in the sandbox. For persistent state, use run_python_session.
- **run_python_session** — Execute Python code in a persistent session (stateful REPL). Maintains variables and imports between calls.
- **search_tools** — Search for available tools by keyword, or select by exact name with 'select:Name1,Name2'.
- **send_message** — Send a message from one agent to another.
- **sync_mcp_tools** — Synchronize and register all MCP tools into the central toolbox.
- **task_create** — Create a new tracked task with subject, description, owner, and progress text.
- **task_get** — Get full details of a specific task by ID.
- **task_list** — List all tracked tasks, optionally filtered by status or owner.
- **task_stop** — Stop (fail) a running task.
- **task_update** — Update a task's status, subject, description, owner, or dependencies.
- **team_create** — Create a new agent team for coordinated multi-agent work.
- **team_delete** — Delete an agent team.
- **update_todo** — Update the status of a todo item.
- **write_file** — Create or overwrite a file in the virtual filesystem.

## Claude Desktop Quick Installation
Install path detected from listing signals. Uses `npx` (confidence: high):

```json
"mcpServers": {
  "ag-bash": {
    "command": "npx",
    "args": ["-y","@ag-bash/mcp-server"]
  }
}
```

## Documentation & README

# Ag-Bash: The AI-Native Shell Monorepo

[![NPM Version](https://img.shields.io/npm/v/@ag-bash/bash.svg)](https://www.npmjs.com/package/@ag-bash/bash)
[![License](https://img.shields.io/badge/license-Apache--2.0-blue.svg)](https://github.com/sairam0424/ag-bash/blob/main/LICENSE)
[![Quality](https://github.com/sairam0424/ag-bash/actions/workflows/quality.yml/badge.svg?branch=main)](https://github.com/sairam0424/ag-bash/actions/workflows/quality.yml)
[![Tests](https://github.com/sairam0424/ag-bash/actions/workflows/tests.yml/badge.svg?branch=main)](https://github.com/sairam0424/ag-bash/actions/workflows/tests.yml)
[![CodeQL](https://github.com/sairam0424/ag-bash/actions/workflows/codeql.yml/badge.svg?branch=main)](https://github.com/sairam0424/ag-bash/actions/workflows/codeql.yml)
[![Bench](https://github.com/sairam0424/ag-bash/actions/workflows/bench.yml/badge.svg?branch=main)](https://github.com/sairam0424/ag-bash/actions/workflows/bench.yml)

Ag-Bash is a production-grade, sandboxed Bash environment designed specifically for AI agents. It provides a virtualized Unix-like experience entirely in-process, featuring an in-memory filesystem, integrated runtimes for Python and JavaScript, and full support for modern agentic protocols.

## 🏗️ Monorepo Architecture

This repository is organized into a modular monorepo to support independent versioning and consumption of core engine components and protocol adapters.

| Package | Version | Description |
| :--- | :--- | :--- |
| [`@ag-bash/bash`](https://github.com/sairam0424/ag-bash/blob/HEAD/packages/bash) | [![npm](https://img.shields.io/npm/v/@ag-bash/bash.svg)](https://www.npmjs.com/package/@ag-bash/bash) | **Core Engine**: The virtual shell, filesystem, and sandboxed runtimes. |
| [`@ag-bash/mcp-server`](https://github.com/sairam0424/ag-bash/blob/HEAD/packages/mcp-server) | [![npm](https://img.shields.io/npm/v/@ag-bash/mcp-server.svg)](https://www.npmjs.com/package/@ag-bash/mcp-server) | **MCP Server**: A standalone Model Context Protocol server for seamless agent integration. |
| [`@ag-bash/agent-bridge`](https://github.com/sairam0424/ag-bash/blob/HEAD/packages/agent-bridge) | [![npm](https://img.shields.io/npm/v/@ag-bash/agent-bridge.svg)](https://www.npmjs.com/package/@ag-bash/agent-bridge) | **Agent Bridge**: Terminal UI bridge for AI agent communication. |

---

## What's New in v6.0.0

| Feature | Description |
| :--- | :--- |
| **ExecutionPipeline** | The composable 6-stage pipeline (normalize, parse, transform, sandbox, interpret, persist) is now the sole execution engine. The legacy monolith path has been removed. |
| **Fork-Speculation** | `bash.fork()` creates isolated copy-on-write branches; `bash.speculate()` runs N candidates in parallel and keeps the winner. Core moat for agentic workflows. |
| **Observations at Source** | Every command produces typed `Observation` objects with `code` and `confidence` fields, surfacing issues without blocking execution. |
| **True Streaming** | `bash.execStream()` yields stdout/stderr chunks via AsyncGenerator as statements produce output, byte-identical to buffered exec. |
| **RunLoop v2** | Extended with `mode`, `healer`, and `memory` configuration. AgentMemory now persists across sessions. |
| **MCP 2025-06-18** | Protocol bumped to latest spec with back-compat preserved for 2024-11-05 clients. Code Mode slice for structured output. |
| **Destructive Detection** | AST-based gate detects `rm -rf /`, fork bombs, and decode-pipe-to-shell patterns structurally. Default policy: WARN. |
| **OTEL at Exec Level** | Optional `AgBashTracer` wraps each `exec()` call in an OpenTelemetry span. Zero overhead when `@opentelemetry/api` is absent. |

---

## Installation & Distribution

**Requires Node.js >=20.6.0.** For full ESM-hook security hardening, Node.js >=23.5 is recommended.

Ag-Bash ships across multiple channels (current version **6.0.4**, synchronized across all npm packages):

### npm library

```bash
# Core engine (recommended)
npm i @ag-bash/bash

# With the standalone MCP server
npm install @ag-bash/mcp-server
```

**Subpath imports** for tree-shaking and targeted use:

```typescript
import { Bash, createShell } from "@ag-bash/bash";
import { RunLoop } from "@ag-bash/bash/agent-runtime";
import { createTestBash } from "@ag-bash/bash/testing";
```

### MCP server (npx / MCP Registry)

The MCP server exposes 70 tools over stdio. Add it to Claude Code in one command (no global install needed):

```bash
claude mcp add ag-bash -- npx -y @ag-bash/mcp-server
# or run it directly
npx @ag-bash/mcp-server
```

It is also published to the [MCP Registry](https://registry.modelcontextprotocol.io) as `io.github.sairam0424/ag-bash`.

> A submission to the Docker MCP Catalog (`docker/mcp-registry`) is currently in review.

### Claude Code plugin

```text
/plugin marketplace add sairam0424/ag-bash
/plugin install ag-bash@ag-bash
```

### Homebrew (macOS)

```bash
brew tap sairam0424/tap
brew install ag-bash
```

This also installs the `ag-shell` and `ag-bash-mcp` binaries.

---

## 🚀 Quick Start

### For Developers (Library)

If you are building an application and want to embed a sandboxed shell:

```bash
npm install @ag-bash/bash
```

```typescript
import { Bash, createShell } from "@ag-bash/bash";

// Quick instantiation
const bash = new Bash();
const result = await bash.exec('echo "Hello Ag-Bash"');
console.log(result.stdout); // "Hello Ag-Bash\n"

// Or use createShell for full configuration
const shell = createShell({ filesystem: "overlay", cwd: "/workspace" });
await shell.exec("ls -la");
```

### 2. Standalone CLI & Shell (Global)

For human-in-the-loop debugging and interactive use, install the Ag-Bash suite globally.

#### Via Homebrew (macOS)

```bash
brew tap sairam0424/tap
brew install ag-bash
```

This installs the `ag-bash`, `ag-shell`, and `ag-bash-mcp` binaries.

#### Via NPM (Cross-platform)

```bash
npm install -g @ag-bash/bash @ag-bash/mcp-server
```

---

### For AI Agents (MCP)

To provide a bash environment to your agent (e.g., in Claude Code, Claude Desktop, or Cursor), register the MCP server via `npx` — no global install required:

```bash
claude mcp add ag-bash -- npx -y @ag-bash/mcp-server
```

Or add the server to your MCP configuration manually:

```json
{
  "mcpServers": {
    "ag-bash": {
      "command": "npx",
      "args": ["-y", "@ag-bash/mcp-server"]
    }
  }
}
```

---

## 🛡️ Key Features

- **v6.0 Architecture**: ExecutionPipeline as sole engine, fork-speculation, observations-at-source, true streaming, OTEL tracing, destructive-detection gate.
- **v6.0 RunLoop**: Autonomous LLM execution loop with observation forwarding, AgenticHealer self-correction, AgentMemory persistence, plan-mode write-gating, and BudgetManager stopping conditions.
- **v3.0 DI** *(Breaking)*: Dependency Injection via `ServiceContainer`, restructured `BashOptions` API with grouped sub-objects, and zero singletons.
- **FNV-1a ASTCache**: Non-cryptographic hashing with true LRU eviction for high-frequency script execution.
- **Pipeline Early Termination**: Static AST analysis detects `head -N` patterns and truncates upstream output.
- **Type-Safe Core**: Eliminated `any` types from core services, interpreter, and error hierarchy (`unknown` throughout).
- **Hardened MCP Server**: Sanitized JSON-RPC error messages (path stripping, length cap), zero console leakage from library code.
- **Project V-Next**: (v2.5.0+) Unified Permission Architecture, Real JSON-RPC MCP Client (Stdio/HTTP), and multi-step Planning Mode.
- **Nexus Prime Suite**: (v2.0.0+) Intelligent semantic analysis (`ag-hover`, `ag-explain`), symbol discovery, and persistent project management.
- **Agentic Healer 2.0**: (v2.4.0+) Tool-aware recovery loop with multi-keyword semantic scoring for automated remediation.
- **High-Fidelity Observability**: (v2.4.0+) EventEmitter-driven tool tracking with `tool:start`, `tool:progress`, and `tool:end` hooks.
- **Tree-sitter AST Parser**: High-fidelity shell parsing for complex scripts and security analysis.
- **Virtual Filesystem**: Choose between `InMemoryFs`, `OverlayFs` (COW), or `ReadWriteFs`.
- **Integrated Runtimes**: Out-of-the-box support for `jq`, `sqlite3`, `python3` (WASM), and `js-exec` (QuickJS).
- **Protocol First**: Full Model Context Protocol (MCP) support with persistent session state.
- **Defense in Depth**: Robust sandbox prevents prototype pollution and unauthorized filesystem access.
- **No Dependencies**: The core engine is lightweight and runs in Node.js or the Browser.

## 📖 Documentation

- **[User Guide](https://github.com/sairam0424/ag-bash/blob/HEAD/docs/user-guide.md)**: Narrative introduction to Ag-Bash, installation, and core concepts.
- **[Command Registry](https://github.com/sairam0424/ag-bash/blob/HEAD/docs/COMMAND_REGISTRY.md)**: Categorized reference for all 110+ supported tools.
- **[Technical Architecture](https://github.com/sairam0424/ag-bash/blob/HEAD/docs/ARCHITECTURE.md)**: Deep dive into the Nexus engine, performance, and resource accounting.
- **[Shell Engine Deep-Dive](https://github.com/sairam0424/ag-bash/blob/HEAD/packages/bash/README.md)**: Technical guide for filesystem options and custom commands.
- **[MCP Server Configuration](https://github.com/sairam0424/ag-bash/blob/HEAD/packages/mcp-server/README.md)**: Agentic integration patterns and configuration.
- **[Security & Threat Model](https://github.com/sairam0424/ag-bash/blob/HEAD/THREAT_MODEL.md)**: Detailed breakdown of the sandbox architecture.

## Version History

| Version | Codename | Highlights |
| :--- | :--- | :--- |
| **v6.0** | *Pipeline* | ExecutionPipeline default, fork-speculation, streaming, OTEL, destructive gate, Node >=20.6 |
| **v5.0** | *Hardened* | Lazy ServiceContainer, defense-in-depth default ON, SSRF prevention, ASTCache 64-bit FNV-1a |
| **v4.1** | *Runtime* | Introduced Agent RunLoop, Trap signal handlers, Self-Healing recovery, and OpenTelemetry spans (default/extended in v6.0) |
| **v3.0** | *Breaking Redesign* | ServiceContainer DI, new `BashOptions` grouped API, zero singletons |
| **v2.x** | *Nexus Prime* | Agentic tools (`ag-hover`, `ag-explain`), MCP integration, Planning Mode |
| **v1.x** | *Genesis* | Initial release, core interpreter, in-memory filesystem, basic builtins |

See the [CHANGELOG](https://github.com/sairam0424/ag-bash/blob/HEAD/CHANGELOG.md) for detailed release notes.

---

## 📜 License

Apache-2.0

