Metadata-Version: 2.5
Name: agent-host-mcp
Version: 0.2.5
Summary: Connect Codex sessions, remote execution, and project knowledge to MCP clients.
Requires-Python: >=3.11
Requires-Dist: jsonschema<5,>=4.20
Requires-Dist: mcp<2,>=1.30
Requires-Dist: python-dotenv<2,>=1
Requires-Dist: python-multipart<1,>=0.0.33
Requires-Dist: pyyaml<7,>=6
Description-Content-Type: text/markdown

# Agent Host MCP

**Turn your agent on the host into an MCP server.**

Agent Host MCP lets your assistant work with the development environment on your
Linux machine. Read project files, execute Python or shell commands, ask a remote
Codex agent to carry out a task, and reuse knowledge from past sessions—all
through one MCP connection.

Use it when your code lives on a remote host and you want your assistant to
inspect that environment directly instead of copying files and terminal output
into a conversation.

## What you can do

- **Understand a project:** read contributor guidance, inspect files, and find
  saved Codex sessions.
- **Get work done:** run notebook-style Python cells or shell scripts, or delegate
  a task to Codex in a new or existing session.
- **Keep useful context:** build topic knowledge from sessions, then browse the
  knowledge wiki or search it from your assistant.
- **Manage the host workflow:** transfer files, label sessions, and inspect
  recorded token usage.

## Quick start

### 1. Start Agent Host MCP on your host

You need a **Linux host** with Python **3.11+** and GNU Screen. For knowledge browsing and
retrieval, also install Git, Node.js **22.22.0+** and npm. Run the server as the account
whose Codex sessions you want to use, with that account’s existing Codex login.
Install Codex CLI **0.167.1+** separately and ensure `codex` is on that account’s
PATH. Agent Host MCP reuses it; installing this package does not download a
second Codex runtime.
Set `CODEX_HOME` if its configuration lives outside `~/.codex`.

Install with uv:

```sh
uv tool install agent-host-mcp
```

Or install with pip in your Python environment:

```sh
pip install agent-host-mcp
```

Start the server:

```sh
agent-host-mcp --host 0.0.0.0 --port 7081 --api_key YOUR_MCP_TOKEN
```

Replace `YOUR_MCP_TOKEN` with a long, random secret and use the same value in your
client. This key protects the MCP server; it is **not** an OpenAI API key. Codex
uses its own existing login.

### Use a configuration file instead

Save these values in `config.toml`:

```toml
host = "0.0.0.0"
port = 7081
api_key = "YOUR_MCP_TOKEN"
concurrent = 10
```

Keep the file private, then start the server:

```sh
chmod 600 config.toml
agent-host-mcp -f config.toml
```

`concurrent` limits simultaneous managed Codex runs (1–1000, default 10); the
persistent execute worker does not consume a slot. JSON files with the same
fields are also supported. CLI flags override
file settings, so you can change the port without editing the file:

```sh
agent-host-mcp -f config.toml --port 7082
```

`--api-key` is an alias for `--api_key`; `--config` is an alias for `-f`.
Without explicit settings, the host is `127.0.0.1` and the port is `7081`.
If no API key is supplied by flag or file, the server uses `MCP_TOKEN` from the
environment, then `.env` in its working directory.

The pinned knowledge-wiki renderer is installed automatically on first knowledge
access and reused afterward. That first request needs npm registry access and
may take longer; no extra setup command is required.

### 2. Add it to your Codex client

OAuth browser sign-in is available by default. Keep the same server configuration
with `host`, `port`, and `api_key`; no additional OAuth setting is required.
The login page uses your existing MCP token to approve each client.

The service can continue using HTTP behind your HTTPS gateway. Forward `/mcp`,
`/.well-known/*`, `/register`, `/authorize`, `/token`, `/revoke`, and `/oauth/*`
through that gateway. Preserve the original external `Host` header when forwarding
requests: OAuth uses that hostname for discovery and login URLs. A gateway that
replaces it with a backend hostname must be configured to preserve it.

Use one public base address for the website and every client connection: open
`https://YOUR_HOST/` in your browser and configure the connector with
`https://YOUR_HOST/mcp`. The website shows the MCP address to copy. If the gateway
cannot preserve the external Host, set `public_url = "https://YOUR_HOST"` in the
server configuration. This also sets the origin used by OAuth and shared-file links.

On your client machine, register the server and sign in:

```sh
codex mcp add remotecodex --url https://YOUR_HOST/mcp
codex mcp login remotecodex
```

Enter your server MCP token and select **Sign in to allow access**, or **Cancel**.
Approval grants access to all MCP tools, including host execution and session
deletion. The client receives its own credentials; it does not receive your MCP
token. Compatible clients renew access automatically for up to 30 days before
requiring sign-in again. Changing the server MCP token invalidates existing OAuth
connections. Sign in separately for each hostname you use.
Direct HTTP OAuth is supported only on localhost for development.

**Alternatively, connect with the server token.** On the machine where you use Codex, set `MCP_TOKEN` to your server’s token. For
example, in Bash you can enter it without placing its value in shell history:

```bash
read -rsp 'Agent Host MCP token: ' MCP_TOKEN
export MCP_TOKEN
printf '\n'
```

Register the server, replacing `https://YOUR_HOST` with your server’s HTTPS URL:

```sh
codex mcp add remotecodex \
  --url https://YOUR_HOST/mcp \
  --bearer-token-env-var MCP_TOKEN
```

Start your Codex client from an environment where `MCP_TOKEN` is available.
Other MCP clients can use **Streamable HTTP** at `/mcp` with OAuth or
`Authorization: Bearer <MCP_TOKEN>`. OAuth credentials also authorize `/event` and `/file`. The legacy `/upload` route
and browser knowledge sign-in still require the server MCP token.

### 3. Ask your assistant to use it

Try requests such as:

> Use remotecodex to read my project’s contributor guidance and summarize it.
>
> Run a Python cell that calculates 6 * 7 on the remote host.
>
> Start a new Codex session in my project and ask it to investigate the failing tests.
>
> Search my saved knowledge for deployment hints.

Replace “my project directory” with the actual host path. The client discovers
available tools and their parameters through `tools/list`.

Session discovery returns `result`, `total`, and `next_offset` in one JSON response.
Start with `list_sessions({})`, then pass the returned `next_offset` as `offset`
until it is null. When `next_offset` is non-null, do not call offset 0 again—that
would repeat the first page. Use a smaller `limit` if your client cuts off long
responses. Pages are ordered by session ID, not guaranteed chronological age;
concurrent session changes can shift offsets.

## Choose the right execution tool

| Task | Tool | What to expect |
| --- | --- | --- |
| Run code directly | `command(action="execute", code=..., path="~")` | One host-wide FIFO queue in a persistent Screen; each call returns the worker `runtime_id` and job `action_id`. Python state remains separate per directory. |
| Run a shell script | `command(action="execute")` with a cell beginning with `!` or `%` | The whole remaining cell runs through `/bin/sh` in the chosen directory. |
| Send a generic prompt to Codex | `handoff_task(action="run", path=..., prompt=..., model=..., depth=..., agent_id=None)` | Without an agent, use a project session. With an agent, continue that role and its private session across projects. Returns a UUIDv4 `runtime_id`. |
| Implement a project roadmap | `handoff_task(action="coding", path=..., roadmap=..., agent_id=None)` | Plans all roadmap work into `.agents/tasks`, executes and reviews it in one runtime lane, optionally as a persistent Agent Fleet role. |

`command(action="execute")` defaults to the server account’s home directory. `handoff_task(action="run")` requires an
existing working directory. Use `create_path` to create an absolute directory
and its missing parents first.

`command(action="execute")` uses the server’s installed Python packages and normal account
permissions; it is not a security sandbox. Python variables last until the runtime
worker Screen restarts. Shell environment/directory changes do not carry over to later
cells. `handoff_task(action="run")` uses your saved Codex login. Choose a supported model and depth with
`list_models`, then provide both explicitly; omitted, null and blank values are
rejected before submission. Use action="get" with the saved runtime_id to reconnect; no original prompt or settings are needed. Explicit run settings
override agent and saved-session defaults for that turn, preserving session identity.
Ask for a new session’s focus and pass `description`; use `session(action="update")` to
change an existing focus. A saved session must be closed in its current Codex
client before resuming it here.

For a quick request, use `handoff_task(action="run")` or `command(action="execute")` directly. Structured engineering uses
`architecture_design` to maintain only `.agents/ARCHITECTURE.md`, `build_roadmap`
to manage numbered `.agents/roadmaps/roadmap-###.md` plans, and `handoff_task(action="coding")` to plan
and execute every task in one selected roadmap. `handoff_task(action="coding")` creates numbered
`.agents/tasks/task-###.md` records and uses the same runtime queue,
dependencies, session serialization, polling, cancellation, and retry behavior as
`handoff_task(action="run")`. Prefer existing `make` test/build targets. Run a deploy target only when
deployment is explicitly authorized; use `update_make` only when reusable
automation genuinely needs to change.

Supplying an active Agent Fleet `agent_id` to `handoff_task(action="run")` or `handoff_task(action="coding")` switches from a
project-owned session to that persistent role. Any supplied `session_id` is
ignored. Codex starts in the agent's private workspace, automatically reads its
role files, and receives the selected project path as another writable workspace.
One agent can own only one starting/running turn across all projects. Additional
submissions are accepted with their own `runtime_id` and automatically depend on
the agent's latest unfinished runtime. Explicit dependencies are preserved. Omit
`agent_id` for the simpler project/session behavior.

### Delegate to another agent

Choose an active recipient with `list_agents`, choose a supported model/depth
with `list_models`, then call `handoff_task`:

```json
{
  "action": "run",
  "agent_id": "recipient-agent-uuid",
  "path": "/srv/projects/example",
  "prompt": "Review the API changes. Report findings with file references.",
  "model": "model-from-list_models",
  "depth": "supported-depth",
  "dependencies": []
}
```

Replace the recipient and model/depth placeholders with discovered values.
For action="run", path/prompt/model/depth are required. agent_id selects a recipient; dependencies default to no explicit prerequisites.
Use an existing project directory. Include the task,
relevant context, and acceptance criteria in the prompt.

Handoff creates a new runtime in the recipient's private session, with write
access to its private workspace and the selected project. It preserves the
submitting task and its session; it does not transfer a conversation or
automatically copy its history. Busy recipients accept work into their existing
queue. The newest unfinished recipient runtime is added as a dependency, alongside
any explicit prerequisites. Independent eligible agents can continue in parallel.

Save `id`/`result.runtime_id`; `result.tool` is `handoff_task`. Follow the response
followup and call `handoff_task(action="get", runtime_id="<saved ID>")` for progress and cursor replay.
Use `handoff_task(action="cancel")` for explicit cancellation or `handoff_task(action="resume")` to retry a failed
or interrupted handoff under the same ID. Each handoff call creates new work;
do not repeat it to check progress or blindly retry after a lost response.
If the task needs the submitting run's completed output, include that runtime ID
in dependencies and let the submitting run finish. Dependencies start work only
after success. Restricted local agents can use action="run" with agent_id, plus get/list. Coding, cancel and resume require owner/OAuth access.

### Structured project files

The structured files have one fixed layout:

```text
<project>/
├── Makefile
└── .agents/
    ├── ARCHITECTURE.md
    ├── roadmaps/roadmap-###.md
    └── tasks/task-###.md
```

`architecture_design(path)` reads the architecture; supply complete `content` to create or replace it
and optionally pass the prior `expected_sha256` to reject concurrent changes.
`build_roadmap(path)` lists plans. Supply `content` without `roadmap` to allocate the
next number, an exact `roadmap-###.md` without content to read it, or both to
replace that plan; named updates also accept `expected_sha256`. `handoff_task(action="coding")` requires
`path` and the exact roadmap filename. Use optional `prompt` for additional
context, `session_id` to continue a saved conversation, and `dependencies` to
schedule the work. It reads the architecture and roadmap, plans numbered task
records, implements them step by step, and loops through
architecture/roadmap review and repair until aligned or blocked. Save its returned
`runtime_id` and coordinator `task_path`, then use the normal runtime monitoring tools.
Every runtime response includes `id` and puts `tool`/`runtime_id` inside `result` so clients
can identify the controlling tool. Codex submissions use tool="handoff_task"; roadmap_path identifies structured coding work. Execution results include
`tool="command"`, the persistent execute `runtime_id`, and their `action_id`.

### Codex task actions

Call `handoff_task` with an explicit action:

| Action | Inputs and behavior |
| --- | --- |
| `run` | Required path, prompt, model and depth; submits generic work. |
| `coding` | Required path and roadmap; plans, implements, tests and reviews one roadmap. Optional model/depth override inheritance. |
| `get` | Required runtime_id; optional cursor_id and interval_seconds=10 (0–30). Reads status/events without submitting work. |
| `list` | No task inputs; returns capacity and retained runtime records. |
| `cancel` | Required runtime_id; force=false protects pending dependents, true cancels their pending chain too. |
| `resume` | Required runtime_id and retry prompt; retries only failed/interrupted work with saved settings. |

Submission actions accept optional agent_id, session_id, description and dependencies.
With agent_id, Codex cwd is the private agent workspace and the project path is an
additional writable directory. The agent session takes precedence over session_id.
Without agent_id, Codex uses the project cwd and its selected or new session.
No caller session is transferred and no caller dependency is inferred.
Get/list/cancel/resume reject project settings and submission inputs. Only get takes
cursor/window controls; only cancel takes force. Existing runtime IDs and cursors
remain valid. The old run/handoff/coding/get_runtime/list_runtime/cancel_runtime/
resume_run tool registrations are removed without aliases; refresh discovery.

### Collect a long-running result

Codex `handoff_task(action="run")` and `handoff_task(action="coding")` return **`runtime_id`**, a UUIDv4 run ID. Save it and
call `handoff_task(action="get", runtime_id="<saved ID>")` to check output and status at any time.
Use the response `id` as the runtime ID. To replay Codex JSON events, call
`handoff_task(action="get", runtime_id="<saved ID>", cursor_id=None, interval_seconds=10)`.
Its `result` includes original event objects in `events`, plus `next_cursor_id`
and `has_more`. Pass `next_cursor_id` as the next call's `cursor_id`. Repeating a
cursor replays retained events without rerunning Codex. Each page contains at
most 100 events and 60 KiB of serialized event payloads.

Events retain Codex's types and fields, including `thread.started`,
`item.completed`, and `turn.completed`. A running snapshot collects original
event objects inside JSON result pages for 10 seconds by default, with a maximum of 30 seconds.
Queued and finished snapshots
return normal JSON immediately with their retained event page inside `result`.
Set `interval_seconds=0` for an immediate snapshot, or a shorter window up to 30.
If the window ends while work continues, status stays `running`; the followup
names the runtime and exact next poll call. Ending a poll never stops Codex.
When caught up, keep the returned cursor and poll again while work is running.
After terminal status, drain pages until `has_more=false`.

The private journal retains up to 4 MiB of payloads and 4,096 events per runtime.
`events_truncated=true` reports missing older events or an event too large for a
page; oversized events are skipped rather than modified. Cursors belong to one
runtime journal and remain valid across retries and server restarts while that
runtime is retained. Older runs without captured events report
`event_replay_available=false`; their status and captured Screen output remain
available. Journals expire with retained runtime results.

Screens are created lazily up to `concurrent` and returned idle to a reusable pool when
Codex exits. When active capacity is full, the accepted run is
queued FIFO and still returns its runtime ID immediately; result includes its queue
position. Optional `dependencies` keeps it queued until those runtime IDs complete
successfully. An unsuccessful dependency pauses downstream runs in visible `blocked`
state without starting Codex, while independent eligible runs continue. Use
the same explicit saved `session_id` for several accepted runs to create a serial
lane: if dependencies are omitted or empty, each new run automatically depends on
the newest unfinished run for that session. If dependencies are supplied explicitly,
they must include that newest same-session predecessor. Different sessions can still
run in parallel. Use
`handoff_task(action="resume", runtime_id="<saved ID>", prompt="<retry instruction>")` to retry a failed or interrupted prerequisite under
the same run ID. Dependents remain paused during the retry and become eligible only
after it succeeds. Independent runs
execute in parallel up to `concurrent`, so clients can submit a dynamic dependency graph.
`handoff_task(action="list")` shows queued
runs and active capacity. `handoff_task(action="cancel", runtime_id="<saved ID>")` refuses by default when queued
or blocked downstream runs depend on the target. Pass `force=true` to cancel the target
and all of those transitive dependents; independent runs remain untouched. Cancellation
retains status, does not delete saved Codex sessions, and cannot undo host side effects. The saved
Codex conversation’s `session_id` is separate. While live, runtime status includes
the exact Screen attach command. A terminal runtime remains attachable while its pool
slot stays idle; the next lease clears the terminal and scrollback, transfers attachment
to the new runtime, and leaves the earlier result available through `handoff_task(action="get")`.
Idle pooled Screens do not consume run capacity. Terminal results retain saved
model/depth metadata when available.

`handoff_task(action="run")` is generic and preserves your prompt inside shared-skill discovery guidance. `handoff_task(action="coding")`
constructs the structured model instruction itself: read the global architecture
and selected roadmap, plan every executable item into numbered task records,
implement all tasks with focused behavioral tests, run full regression through
`make`, review against architecture and roadmap, review the coding diff, and loop
through repairs until every gate passes or a concrete blocker is recorded. The
lane then stops; it never selects another roadmap. A failed/interrupted coding
runtime keeps its coordinator and task records; `handoff_task(action="resume")` restores the coding
method around the retry instruction.

`command(action="execute")` returns the persistent worker **`runtime_id`** and per-job **`action_id`**.
Save the action ID and call `command(action="get", action_id="<saved ID>")` to check its result.
`command(action="list")` shows the persistent worker, active task,
and FIFO positions. `command(action="cancel", action_id="<saved ID>")` removes queued work without running it. Cancelling
the running task stops and replaces the worker Screen, resets all in-memory notebook
namespaces, and cannot undo host side effects already produced. Disconnecting alone
does not cancel accepted tasks.

Only `action` is always required. `code` is required for execute and omitted for
other actions. Get/cancel requires `action_id`; list takes neither code nor an ID.
Path applies only to execute. Get accepts `cursor_id` and `interval_seconds=10`
(0–30); queued/terminal reads return immediately. Follow `next_cursor_id` for
lifecycle replay; completed output is in `result.result`. A list uses
`active_action_id`, `queued` entries with `action_id`, and `queue_depth`.

For example, start a cell:

```json
{"action":"execute","code":"6 * 7"}
```

Then call `command(action="get")` with the returned action ID:

```json
{"action":"get","action_id":"returned-command-id"}
```

Use `handoff_task(action="get", runtime_id="<saved ID>")` for `handoff_task(action="run")`/`handoff_task(action="coding")` status and
`command(action="get", action_id="<saved ID>")` for `command(action="execute")` status. Agent Fleet tools manage roles;
polling uses the job ID saved at submission. command get/cancel requires action_id;
only action="execute" submits new command work.
Polling never reruns the original task. Normal tool responses use the same five
top-level fields: `status`, `followup`, `result`, `id`, and `timestamp`.
`result` contains the tool-specific data. Async `id` is a runtime ID for Codex,
an action ID for commands or knowledge/deletion/make jobs; synchronous
calls use null. `timestamp` is UTC response time, separate from job/agent dates.
For example, creating a directory returns:

```json
{
  "status": "completed",
  "followup": "Completed. Directory is ready. Use the returned path with handoff_task(action=\"run\") for intelligent work or action=\"coding\" for a selected roadmap.",
  "result": {"path": "/srv/projects/example"},
  "id": null,
  "timestamp": "2026-11-17T13:00:00Z"
}
```

`status` describes the tool call or the job being monitored:

| Status | Meaning |
| --- | --- |
| `completed` | The operation finished successfully, including a read or list. |
| `failed` | The operation or job failed; read `followup` and any retained result. |
| `queued` | Accepted and waiting to start. |
| `running` | Starting or executing. |
| `blocked` | Waiting for a failed or interrupted dependency to be resolved. |
| `cancelled` | Explicitly cancelled. |
| `interrupted` | Stopped before a verified result; inspect side effects before retrying. |

Every response also includes a top-level `followup` with the next step. For async
work it names the polling tool and exact runtime/task ID; action-based work gives
the reconnect call with its original selectors and `action_id`. Follow that call
instead of submitting the job again. Runtime replay followups include the next
cursor, including when a terminal job still has event pages to drain. A completed
and fully replayed job says no further polling is needed. Pagination followups
give the next offset while preserving the requested filters and page size.

Tool-call errors, including invalid inputs, return `status: "failed"` with the
explanation and next step in `followup`, and null `result`/`id`. Failed async jobs
retain their IDs and result data. Python exceptions and nonzero shell exits are
reported as failed execution jobs; their results retain tracebacks or exit codes.
A list response can be `completed` while individual listed jobs are
`running` or `queued`. Agent lifecycle uses `agent_state: "active"` or
`"retired"`, separate from tool status. The `list_agents` input named `status`
remains a lifecycle filter. When a result contains its own outcome, inspect that
too, such as per-session knowledge results.

A gateway timeout or disconnected client leaves accepted work running. Use the
saved runtime or task ID to check it again. Runtime polling returns captured Codex
events, Screen output, and status; it is not a live stream of model tokens. Managed Codex and execute Screens
survive an HTTP server restart and are reconciled without replay; a lost active Screen/task is
reported interrupted. Completed results are retained for up to 24 hours, subject
to bounded retention. `build_knowledge`, `session(action="delete")`, and nonempty `make`
target execution retain the separate reconnectable `action_id` protocol; those
server-owned actions are interrupted by server shutdown and never auto-rerun.

## Build and use your knowledge

Ask your assistant to call `list_models`, choose a supported model and depth,
then call `build_knowledge`. Supply `session_id` to target one session, or omit it
for an incremental batch. A temporary Codex session distills useful context into
notes, then the knowledge wiki turns those notes into browsable pages. Unchanged
context is reused. If publishing the knowledge fails, retry the build; saved notes
are reused without repeating successful extraction.

Browse the results at **`/knowledge`** and sign in with your MCP token. The
knowledge-wiki page and `wiki(action="list")`, `wiki(action="search")`, and `wiki(action="read")` tools use the
same saved knowledge. Viewing or searching it does not call a model. Browser
visualization needs access to the wiki renderer's pinned external library/font CDNs.

Use your gateway’s HTTPS address for browser sign-in. The service can use HTTP
behind that gateway; it does not need its own SSL certificate. Direct loopback
HTTP access is supported for local development.

While the server runs, it also checks for new or changed session context every
30 minutes. When idle, it runs a daily maintenance pass that still skips unchanged
context. Builds use your Codex login and can make model calls.

**Session retirement:** knowledge builds may delete sessions whose working
directories have been removed, after saving their notes and verifying the
completed wiki pages. A failed knowledge build keeps the affected sessions.
Sessions with existing working directories are preserved by automatic builds.
`session(action="delete")` explicitly deletes a selected session, including one whose
working directory exists, only after its current knowledge is verified. Active or changed sessions, and sessions with remaining descendants, are kept.

## Available tools

The server exposes eighteen tools through **progressive tool discovery**.
Your MCP client calls `tools/list` for the authoritative catalog, chooses the
relevant workflow class first, and follows related tools as needed. The six
classes below group tools by the work you want to do.

### System

Manage sessions, models, usage, deletion, and file transfer/sharing guidance.

| Tool | Use it to |
| --- | --- |
| `list_sessions` | Find saved sessions in pages: `limit` defaults to 20 (maximum 100); pass `next_offset` as `offset` to continue. |
| `session` | Update session focus with action="update", or delete after verified knowledge with action="delete". Deletion progress uses its action_id and the same session_id. |
| `list_models` | Discover supported models and reasoning depths. |
| `token_count` | Inspect recorded host/session usage and cache-hit ratios; retired usage appears in `others`. |
| `get_file_transfer_skill` | Read instructions for HTTP file uploads, direct downloads, and sharing. |
| `get_file_download_url` | Create a full, expiring sharing URL for an absolute host file path. |

### Work

Choose `handoff_task(action="run")` for intelligent, model-driven Codex work or `command(action="execute")` for
deterministic Python/shell work without a model. Use `handoff_task` get/list/cancel/resume actions to manage accepted Codex tasks.

| Tool | Use it to |
| --- | --- |
| `handoff_task` | Intelligent Codex work: actions run/coding submit; get/list inspect; cancel/resume control. Optional agent_id selects a private agent session with project write access. |
| `command` | Manage deterministic Python/shell work: `action="execute"` with `code`, `"get"`/`"cancel"` with `action_id`, or `"list"` for the queue. Running cancellation resets notebook namespaces. |

### Coding

Use architecture- and roadmap-driven intelligent coding, with deterministic
project path and Makefile support.

| Tool | Use it to |
| --- | --- |
| `architecture_design` | Read, create, or conflict-safely update only `.agents/ARCHITECTURE.md`. |
| `build_roadmap` | List, read, create, or update only numbered `.agents/roadmaps/roadmap-###.md` plans. |
| `create_path` | Create an absolute host directory and missing parents. |
| `make` | Read Makefile or run one validated target with reconnectable results. |
| `update_make` | Atomically replace the complete Makefile without execution. |

### Knowledge and wiki

Build reusable session knowledge and retrieve its wiki pages.

| Tool | Use it to |
| --- | --- |
| `build_knowledge` | Extract reusable knowledge from changed or selected sessions; may retire missing-directory sessions. |
| `wiki` | Read-only knowledge retrieval: action="list" paginates topics, "search" finds refs, and "read" retrieves exact sections. |

### Agent fleet

Create and manage private, durable agent workspaces without starting model turns.

| Tool | Use it to |
| --- | --- |
| `list_agents` | Find active or retired roles in pages; use `next_offset` to continue. |
| `agent` | Create, update, retire or restore a private role through its action selector. Returns tool="agent" and agent_state; existing IDs and saved sessions are preserved. |

Call `list_agents(status="active", limit=20, offset=0)` to discover available
roles. Use `status="retired"` for archived roles or `status="all"` for both.
Results contain agent IDs, names, model/depth overrides, `agent_state`, workspace paths, and
timestamps. `total` counts all agents matching the filter. Pass each non-null
`next_offset` as the next `offset`, keeping the same status and limit, until it
is null. Results are sorted by agent ID, not by age; concurrent roster changes
can shift pages. Job progress is separate: use `handoff_task(action="list")` or
`handoff_task(action="get", runtime_id="<saved ID>")` with a known runtime ID.

Agent Fleet uses this fixed host layout:

```text
~/.agent-host-mcp/
├── agents.json
├── agents/<agent_id>/
│   ├── AGENTS.md
│   ├── SOUL.md
│   ├── INSTRUCTIONS.md
│   ├── AGENT_HOST_MCP_SKILL.md
│   └── session.json        # created when Codex announces the first session
└── archived/<agent_id>/...
```

Use `list_agents` to discover roles and `agent` for lifecycle changes:

| Action | Required inputs | Editable inputs |
| --- | --- | --- |
| `create` | action only | name, model, depth, soul, instructions |
| `update` | action and agent_id | name, model, depth, agents_md, soul, instructions |
| `retire` | action and agent_id | None |
| `restore` | action and agent_id | None |

For example, call `agent` with:

```json
{"action":"create","name":"Reviewer"}
```

Save `result.agent_id`. To change that role later:

```json
{"action":"update","agent_id":"<existing agent UUID>","instructions":"Review API changes and report findings."}
```

Creation generates the ID and initial AGENTS.md; supplying agent_id or agents_md
for create is rejected. Retire/restore rejects editable inputs. Create calls are
non-idempotent: after an uncertain response, inspect list_agents rather than
blindly repeating creation. Updates and lifecycle changes never start Codex.
All lifecycle results use tool="agent", agent_state and the standard envelope,
with null top-level id because they are synchronous. The four previous lifecycle
tool registrations are removed without aliases; existing agents need no migration.
The restricted local-agent token can list roles but cannot call agent; lifecycle
changes require owner Bearer or MCP OAuth.

`agent(action="create")` accepts optional `name`, `model`, `depth`, complete `soul` text, and
complete `instructions` text. Use `list_models` to choose a supported model/depth
pair. Null model/depth inherit the saved session's settings, or host defaults for
a new session. Role settings override saved settings for coding and other inherited turns.
For `handoff_task(action="run")`, the required explicit model/depth override both role and saved settings,
including a resumed session. Unsupported settings fail at execution rather than
silently selecting a different model. Null role text creates starter documents.
The envelope returns `status: "completed"`; the agent's `tool`, `agent_id`, `agent_state: "active"`,
and absolute `path` inside `result`. Save `result.agent_id` for
retirement/restoration. Repeating a retire or restore request is safe when the
agent is already in that state; neither overwrites an occupied destination. The
roster and workspace are private server-account state; preserve `~/.agent-host-mcp` in host
backups. `AGENT_HOST_MCP_HOME` may set a different absolute fleet root.
Each new workspace also receives the packaged `AGENT_HOST_MCP_SKILL.md` guide;
generated AGENTS.md directs the role to its file-layout, state, class, and ID
conventions before project work begins.

Use `agent(action="update", agent_id="<existing ID>", ...)` to change any combination of `name`, `model`,
`depth`, `agents_md`, `soul`, and `instructions`. The last three replace the complete
contents of `AGENTS.md`, `SOUL.md`, and `INSTRUCTIONS.md`. Omitted or null fields
stay unchanged. Empty strings clear optional settings or document content.
Changing the display name does not rewrite custom role documents automatically.

Updates work for active or retired agents, but are refused while a running Codex
turn holds the agent's execution lock. Settings take effect on its next turn;
clearing an override returns to saved session settings or host defaults. The agent
ID, workspace path, timestamps, saved session binding, and packaged host guide
are server-managed. Use `agent(action="retire")` and `agent(action="restore")` for lifecycle changes.

Pass the returned `agent_id` to `handoff_task(action="run")` or `handoff_task(action="coding")` for role-based work across
multiple projects. The first session announcement saves its Codex session in the
private workspace; later turns resume that session regardless of project path.
The runtime result includes both `agent_id` and the effective `session_id`.
Retirement is refused while that agent has a turn in progress.
New `handoff_task(action="run")` or `handoff_task(action="coding")` submissions queue while the agent is busy, in submission
order across projects. Use each returned `runtime_id` with `handoff_task(action="get")`; its JSON response
returns `queued` immediately while waiting, and its `followup` gives the
next polling call. Retried jobs can replay events from earlier attempts even
while queued. A failed prerequisite blocks
later work until a successful `handoff_task(action="resume")` retry. Independent agents can continue
in parallel.

To transfer a local file, read `get_file_transfer_skill` first. Uploads use a separate
HTTP `POST /upload` with the server MCP master Bearer token (not an OAuth token or cookie), the actual file bytes, and a
client-selected absolute destination directory. Missing parents are created;
existing files are never overwritten. The file limit is 100 MiB. Native MCP auth
does not automatically expose the credential to an agent’s separate HTTP client.

### Skills

Use `add_skill` for both Markdown skills and Git collections. Supply exactly one mode:

```json
{"name":"review-api","introduction":"Review API contracts.","content":"# Review API\nCheck behavior against the architecture."}
```

```json
{"git_url":"https://example.com/team/skills.git"}
```

Markdown requires name/introduction/content together and returns synchronously;
identical retries are safe and differing existing content is never replaced.
Git import takes git_url alone, clones privately and queues Codex integration.
Mixed or incomplete inputs fail before publication/staging. Save its runtime_id,
then use handoff_task get/cancel/resume; no original URL is needed for polling.
Never blindly retry uncertain Git admission. Both modes return tool="add_skill";
Git jobs created before consolidation retain valid IDs and retry workflows.

The shared library has this layout:

```text
~/.agent-host-mcp/agents/skills/
├── SKILL.md
└── <skill-name>/
    ├── SKILL.md
    └── references/, scripts/, assets/    # when the skill needs them
```

`AGENT_HOST_MCP_HOME` changes the host root. The root `SKILL.md` contains short
introductions and links. Codex runs and agent roles are instructed to read that
index first, then load only the relevant skill and resources. Retiring an agent
does not remove this shared library. It does not modify your global Codex setup.

For example, call `add_skill` with:

```json
{"name":"review-python","introduction":"Review Python changes for correctness.","content":"# Review Python\nInspect behavior and report actionable findings with file references."}
```

Names use lowercase letters, digits, and hyphens, up to 63 characters.
Introductions are one line, up to 500 characters. Supply a Markdown body or a
complete `SKILL.md`; missing name/description frontmatter is generated. Complete
frontmatter must use the same name. Existing skills are preserved: identical
retries succeed, while different content under an existing name is rejected.

For a repository, supply an HTTPS or SSH Git URL to `add_skill(git_url=...)`. It returns
`tool="add_skill"` and `runtime_id` immediately. Git clone and Codex integration
run through the normal queue and require host Git access and Codex login. Use
`handoff_task(action="get", runtime_id="<saved ID>")` for progress, `handoff_task(action="cancel")` to stop it, or
`handoff_task(action="resume")` to retry a failed/interrupted import. Use host Git/SSH credentials
rather than putting passwords in URLs.

Imports are staged privately. Codex prepares the relevant skills and supporting
files, then the host validates and publishes them together with index entries.
Existing skills are never replaced. Failed imports keep their staging files for
retry. Cloning times out after 60 seconds; publication rejects symlinks and limits
each skill to 1,000 files and 50 MiB, with a 1 MiB limit for `SKILL.md`.
Only import repositories you trust; adding a skill does not run its scripts.

### Recorded token usage

Token usage is recorded session usage, not an exact billing report. Cached and
reasoning counters are subsets, and `cache_hit_ratio` is cached input divided by
input; unknown coverage is reported.

## Access and upgrades

The landing page at `/` is public. MCP calls, uploads and knowledge content
require authentication. Signing in to the knowledge browser does not authorize
MCP calls or uploads. Connect only clients you trust with the host account’s access.

Credential precedence is CLI `--api_key`, configuration `api_key`, exported
`MCP_TOKEN`, then `.env`. Restart the server after changing its settings.

Keep your server configuration, Codex login and saved sessions when upgrading.
Preserve `~/.agent-mcp` for knowledge, `~/.agent-cmp` for action/session data,
and `~/.agent-host-mcp` for agent workspaces and the roster.
If you customized `CODEX_HOME`, `AGENT_MCP_DB`, or `AGENT_HOST_MCP_HOME`, back up
those locations too.

Upgrade an installation managed by uv:

```sh
uv tool upgrade agent-host-mcp
```

For a pip installation, use the same Python environment as the server:

```sh
pip install --upgrade agent-host-mcp
```

Restart the server through your usual process or service manager after upgrading.
Wait for active work to finish before restarting.

Refresh your client’s MCP connection after installation to discover updated tools.
The website footer and the `X-Agent-Host-MCP-Version` HTTP response header identify
the running server; MCP initialization reports the same version. If they differ,
check that the browser and connector use the same host and gateway backend.
An error mentioning `link_id` or an eligible linked account requires selecting or
reconnecting that account in the client's connector settings. A working website
does not establish the client's account connection, and a server update cannot
refresh that connection or its cached tool list automatically.

## Check your setup

Open the host’s `/` page, or ask your connected assistant to call `list_models`
and `list_sessions`. These discovery tools do not submit model turns or delete
sessions. Open `/knowledge` to sign in and browse saved knowledge.

| Symptom | What to check |
| --- | --- |
| Unauthorized or startup token error | Match the server’s token and the client’s `MCP_TOKEN` environment variable. |
| Port 7081 is already in use | Stop the intended previous process yourself, or choose another `--port`. |
| External session has an active writer | Managed same-session runs queue automatically; for an IDE, CLI or other unmanaged owner, close it normally before resuming, or omit the ID to create a separate session. |
| Knowledge wiki unavailable | Check Git, Node.js/npm, npm registry access on first use, and browser CDN access. |
| Client still shows old tools | Refresh/reconnect the client after restarting the updated server; a new conversation alone may not refresh its cache. |
| Public gateway cannot be reached | Check gateway routing and any IP allowlist separately from the local server. |

## HTTP event replay and file transfer

MCP tools always return JSON envelopes, including when a progress token is supplied.
`handoff_task(action="get")` and `command(action="get")` share the event reader used by the separate HTTP
`GET /event?id=...&cursor_id=...&interval_seconds=10` route. This route is not an MCP
tool. Use a Codex runtime ID or a command **action ID**, not the command worker ID.
Queued and terminal jobs return JSON; running jobs use SSE for up to 10 seconds
by default (0–30 allowed; zero returns JSON). SSE `event` data preserves Codex
objects, `cursor` checkpoints provide `next_cursor_id`, and a final `status` event
contains the normal envelope. Reconnect with the last checkpoint; duplicate replay
is safe. Drain `has_more` pages even after completion. Execute events describe
queued, running and terminal lifecycle; completed output is in the job result,
not incremental stdout. Disconnecting does not cancel work.

`POST /file` accepts the same multipart `path` and `file` fields and 100 MiB limit
as `/upload`: `path` must be an absolute destination directory. Missing parents
are created and existing files are never overwritten. `GET /file?path=...`
downloads a regular file using its absolute host path; send `path` through your
HTTP client's query-parameter encoder. Relative paths, dot traversal, symlink
components, directories and devices are rejected. Downloads are attachments with
no caching; file contents can change if another process edits the file.

Both `/event` and `/file` accept the same OAuth access tokens as `/mcp`, or the
server MCP Bearer token. Browser cookies cannot authorize them. OAuth file access
has the server account's filesystem permissions. Keep credentials out of URLs.
Gateways must forward `/event` and `/file` explicitly if these routes are needed.

## Restricted local-agent access

The server generates a separate credential at
`~/.agent-host-mcp/internal-token` (or `<AGENT_HOST_MCP_HOME>/internal-token`).
The directory is private and the file is readable only by its owner. Local agents
may read this file to configure Bearer authentication for `/mcp`; never copy its
contents into prompts or logs. This credential exposes three tools: `wiki`, `list_agents`, and `handoff_task`. Only the run/get/list
actions are permitted on `handoff_task`; coding/cancel/resume require full access.
Other tool calls and all file/event HTTP routes are denied. The owner or calling
agent must supply a known supported model/depth pair for restricted-agent run
calls, since this credential does not expose list_models. Missing session focus
updates and failed/interrupted runtime retries must also be handed to an owner
or full-access client; this credential cannot call session action="update" or handoff_task action="resume". `handoff_task(action="run")` can modify host
project workspaces, so share this credential only with trusted local agents.
It survives restarts; to rotate it, remove the private file and restart the service
so a new credential is generated. Existing processes retain their loaded credential
until restart. The owner token and OAuth access retain the full tool catalog.

## Share a file with an expiring link

Create a download link with `POST /share-file`, authenticated with the server
MCP Bearer token or the same OAuth access token used for `/mcp`. Send JSON:

```json
{"path":"/absolute/host/path/report.pdf","expires_seconds":600}
```

`path` is an existing absolute host file path; upload client-local files through
`POST /file` first. Relative paths, dot traversal, symlinks, directories and devices
are rejected. `expires_seconds` defaults to 600 (10 minutes); allowed values are
integers from 1 to 86400 (24 hours). Cookies and the restricted local-agent token
cannot create links.

The JSON envelope's `result` contains `file_id`, `filename`, `url`, `expires_at`,
`size` and `sha256`. The stored object uses an opaque file ID; the download
filename adds the safe source extension, for example `<file-id>.pdf` or
`<file-id>.tar.gz`. The original host path is absent from the URL. The server copies the file
into its private local object store, so later edits or deletion of the source do
not change shared bytes. This feature uses host storage; no external object-storage
account or bucket is required.

Anyone holding `url` can use HTTP GET to download that object, repeatedly until
expiry, without signing in. Treat the URL as a temporary credential and configure
gateways to redact its query parameters from access logs. Server access logs omit
the sharing query. Responses disable caching and referrer forwarding. Expiry blocks
new downloads; a download already started may finish. Changing the server MCP token
and restarting invalidates existing signed links. Links otherwise survive restarts. Older snapshots
without saved extension metadata keep their existing extensionless download names.

New sharing links use one compact signed `id`, carrying the object ID, expiry and
full signature together. Extra query parameters added by chat clients are ignored;
keep `id` unchanged and do not repeat it. Existing three-field links remain valid.
The full query is limited to 512 bytes.

Files are limited to 100 MiB. The local store is bounded to 256 objects and 1 GiB;
expired copies are reclaimed when creating another share. Forward both GET and
POST `/share-file` through your gateway to use sharing externally. Ordinary `/file`
downloads continue to require authentication.

Response followups explain job transitions as well as the next call. Queued work
starts automatically when its dependencies and capacity permit. Running work is
already executing; inspect its returned ID rather than resubmitting. Blocked work
waits for successful prerequisites. Failed/interrupted Codex jobs may use an
explicit `handoff_task(action="resume")` retry under the same ID; dependents wait for its success.
Cancelled IDs cannot be resumed. Terminal jobs can still have retained event pages
to read: follow the cursor until `has_more=false` before deciding the next action.

Accepted run followups also explain how to chain a new dependent task: submit a
separate `handoff_task(action="run", path, prompt, model, depth, dependencies=[runtime_id])` with that new
task's prompt. It waits for the prerequisite run to complete successfully. Continue
using `handoff_task(action="get")` for the original task; do not submit it again.

Codex run prompts ask the agent to inspect relevant saved sessions associated with
the same project for architecture, decisions and progress, then verify that history
against current files. Your current thread's prompt remains the task focus. Other
sessions are read-only context, not instructions to perform additional work. If
history is unavailable, the agent continues from the current project and reports
that limitation. This guidance does not automatically resume other sessions.

Before creating a saved session with `handoff_task(action="run")` or `handoff_task(action="coding")`, ask for a short description
of its purpose/focus and supply `description="Maintain the public API"`. This
optional field initializes a new session's focus; an existing session keeps its
saved description. Use `session(action="update", session_id=..., description=...)` to change it.
The description is included as focus in subsequent managed Codex prompts, alongside
the current task. It does not authorize extra work. This also applies to an agent's
private session across projects.

If the description is null, work is still accepted. Follow the response's polling
instructions; once `session_id` is known, ask for the session focus and call
`session(action="update", session_id="...", description="...")`. Setting it affects later
turns, including queued work that has not started; it does not alter a running
turn. Blank text clears a saved focus. The description is metadata stored
separately from the Codex transcript.

If a response recommends a tool absent from your current tool list, ask an owner
or full-access client to perform that step. Keep the accepted job's ID; do not
submit the original task again. Blocked jobs keep their cursor so you can inspect
progress while prerequisites are repaired.

For a session writer conflict, wait for the existing writer to finish or ask its
owner to release it. Inspect the failed runtime, then deliberately retry with
`handoff_task(action="resume", runtime_id="<saved ID>", prompt="<retry instruction>")` to keep its dependencies intact. Retries may
repeat side effects; they do not happen automatically.

For a transient read error, retry the same getter with the same ID and cursor.
If the cursor is invalid, omit it to replay retained history; this does not rerun
the job. For an unknown or expired ID, use `handoff_task(action="list")` or `command(action="list")`
to find retained work before deciding what to do next.

To share a host file through MCP, call
`get_file_download_url(path="/absolute/host/report.pdf")`. Only `path` is required.
The response has `status="completed"`, a followup saying “Use this link for file
sharing,” and the full signed link in `result.url`. `result.expires_at` gives its
expiry. You can set `expires_seconds` from 1 to 86400; the default is 600 seconds.
No polling is needed.

The tool copies the file into a private sharing store (100 MiB per file). The
public URL uses a compact signed ID. The download filename uses the opaque
file ID plus a safe file extension, without the host path or original basename. Anyone holding the URL can download that snapshot until
expiry without your MCP credential. Share it only with intended recipients.
Owner Bearer or MCP OAuth is required to create a link; restricted local-agent
credentials cannot. Repeated calls create separate snapshots, so avoid blind
retries after an uncertain response. After expiry, request a new link if needed.

`get_file_transfer_skill` replaces the previous `get_upload_skill` tool name.
Refresh your MCP client's tool catalog to discover the current names.

When hosted by systemd, managed Screens run detached with `-dmS` in independent
systemd user scopes. Restarting the HTTP service leaves those Screens and their
Codex/Python workers running; the server reconnects through saved state without
replaying jobs. You can inspect a Screen using its returned attachment command
even while HTTP is unavailable. Runtime cancellation still stops its worker
scope, including descendants.

For a systemd deployment, install GNU Screen and `systemd-run`, enable lingering
for the service account (`sudo loginctl enable-linger SERVICE_USER`), and ensure
that account's systemd user manager is running. Its private bus must exist at
`/run/user/UID/bus`. A managed launch fails explicitly if isolation is unavailable;
it does not silently launch a worker that will die with HTTP. Standalone launches
keep ordinary detached Screen behavior and do not require a systemd user manager.

This applies to newly launched workers. Before the first upgrade from an older
version, let existing managed work finish: older Screens still belong to the
HTTP service group. Server-owned knowledge/deletion/Make actions remain tied to
HTTP and can be interrupted by a restart.



## Progressive tool usage

Tool descriptions are short. Every tool accepts `flag`, which defaults to null.
Use `flag="-h"` to read usage without starting work or changing host state. Omit
execution arguments when asking for help:

```json
{"name":"handoff_task","arguments":{"flag":"-h"}}
```

For action tools, select an action to get its parameters, required inputs,
defaults, examples and side effects:

```json
{"name":"handoff_task","arguments":{"action":"run","flag":"-h"}}
```

```json
{"name":"handoff_task","arguments":{"action":"get","flag":"-h"}}
```

The first describes submission; the second describes replay using a saved
runtime ID. `command`, `agent`, `session` and `wiki` likewise provide different
usage for each action. `make` accepts a target as its action. Help does not need
execution inputs such as a prompt, code or runtime ID. Tool and action permissions
still apply; restricted clients cannot use help to access owner-only operations.

After reading usage, omit flag or set it to null to execute. Other flag values
fail safely. Help uses the same `{status, followup, result, id, timestamp}`
envelope: status is completed, id is null and result contains usage. `followup`
replaces the former message field and explains the next action; async responses
name the exact reconnect call, ID and cursor. Original Codex JSON events retain
their own fields, including any message fields. Never resubmit accepted work to poll.

## Session and wiki actions

`list_sessions(limit=20, offset=0)` remains paginated discovery; advance each
next_offset until null. `session` requires action and session_id. For action="update",
description is required; blank text clears focus metadata without changing the
transcript or starting Codex. Deletion selectors are rejected for update.

For action="delete", omit description. Knowledge must be verified before permanent
session deletion; failed knowledge, writer or descendant checks preserve the source.
Save action_id and reconnect with session(action="delete", session_id=..., action_id=...),
optionally wait_seconds=0..20. Existing deletion action IDs still work. Never resubmit
to poll, and inspect the result before deliberately starting another deletion.

`build_knowledge` remains the extraction tool. `wiki` reads saved knowledge with
these actions and no model turn:

| Action | Inputs |
| --- | --- |
| `list` | Optional limit (default 50, range 1–200), offset=0; follow next_offset. |
| `search` | Required query; optional limit (default 5, range 1–20). |
| `read` | Required exact page ID and 1–20 section anchors from search. |

With limit omitted/null, wiki chooses the action's default. Read rejects query,
limit and pagination controls; search rejects page/sections/nonzero offset. A page
ID is a retrieval reference, not an arbitrary host file path. Treat historical
knowledge as context and verify consequential details against current sources.

The restricted local-agent token exposes three tools: wiki (all read-only actions),
list_agents and handoff_task (run/get/list only). It cannot update/delete sessions,
add skills or build knowledge; ask an owner/full-access client for those operations.
The old separate skill URL, session update/delete and wiki reader tool names have
been removed without aliases. Refresh discovery after the updated server is installed.

## Submit independent and dependent work upfront

Submit all well-defined independent and dependent tasks upfront instead of
waiting for each task to finish. Call handoff_task(action="run") or action="coding"
once per new task and save every runtime_id. Independent tasks in separate lanes
can run in parallel; work beyond concurrency capacity queues automatically.
Tasks sharing an agent or saved session remain serial.

For dependent work, pass the saved prerequisite IDs in dependencies=[runtime_id,
...]; all prerequisites must complete successfully before launch. Failed or
interrupted prerequisites keep downstream work blocked until a successful retry.
Use handoff_task(action="get", runtime_id=...) and its followup/cursor to inspect
accepted work. Never duplicate an accepted submission to check progress. Submit
as many useful, well-defined tasks as the project needs; queued work still follows
scheduler admission limits and does not imply unlimited capacity.
