Skip to main content

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:

uv tool install agent-host-mcp

Or install with pip in your Python environment:

pip install agent-host-mcp

Start the server:

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:

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

Keep the file private, then start the server:

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:

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.

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

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:

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:

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 apply to MCP tools only; HTTP uploads and browser knowledge sign-in still use 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 execute(string, path="~") One host-wide FIFO queue in a persistent Screen; each call returns the worker runtime_id and job task_id. Python state remains separate per directory.
Run a shell script 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 run(path, prompt, session_id=None, 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 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.

execute defaults to the server account’s home directory. run requires an existing working directory. Use create_path to create an absolute directory and its missing parents first.

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. run uses your saved Codex login and configured defaults for new sessions. A saved session must be closed in its current Codex client before resuming it here.

For a quick request, use run or execute directly. Structured engineering uses architecture_design to maintain only .agents/ARCHITECTURE.md, build_roadmap to manage numbered .agents/roadmaps/roadmap-###.md plans, and coding to plan and execute every task in one selected roadmap. coding creates numbered .agents/tasks/task-###.md records and uses the same runtime queue, dependencies, session serialization, polling, cancellation, and retry behavior as 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 run or 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. A concurrent submission fails with the agent name and asks the client to submit it later. Omit agent_id for the simpler project/session behavior.

The structured files have one fixed layout:

<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. 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 result includes top-level tool and runtime_id fields so clients can identify whether the ID belongs to run or coding. Execution results include tool="execute", the persistent execute runtime_id, and their task_id.

Collect a long-running result

Codex run and coding return runtime_id, a UUIDv4 run ID. Save it and call poll_runtime(runtime_id) to check output and status at any time. 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; status 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 resume_run(runtime_id, prompt) 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. list_runtime shows queued runs and active capacity. cancel_runtime(runtime_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 poll_runtime. Idle pooled Screens do not consume run capacity. Terminal results retain saved model/depth metadata when available.

run is deliberately generic and passes the client prompt unchanged. 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; resume_run restores the coding method around the retry instruction.

execute returns the persistent worker runtime_id and per-job task_id. Save the task ID and call poll_execution(task_id) to check its result. list_executions shows the persistent worker, active task, and FIFO positions. cancel_execution(task_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.

For example, start a cell:

{"string":"6 * 7"}

Then call poll_execution with the returned task ID:

{"task_id":"returned-task-id"}

Use poll_runtime(runtime_id) for run/coding status and poll_execution(task_id) for execute status. Agent Fleet tools manage roles; polling uses the job ID saved at submission. Omitting the ID starts new work. Polling never reruns the original task. Inspect the returned status and error fields; when a result contains its own status, check that too.

A gateway timeout or disconnected client leaves accepted work running. Use the saved runtime or task ID to check it again. Polling returns captured 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, delete_session, 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_list_pages, wiki_search, and wiki_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. delete_session 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 twenty-eight 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 five classes below group tools by the work you want to do.

System

Manage sessions, models, usage, deletion, and upload 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.
update_session Set a client-managed description; blank text clears it.
list_models Discover supported models and reasoning depths.
token_count Inspect recorded host/session usage and cache-hit ratios; retired usage appears in others.
delete_session Delete a session only after its current knowledge is saved and verified.
get_upload_skill Get instructions for authenticated HTTP file uploads.

Work

Choose run for intelligent, model-driven Codex work or execute for deterministic Python/shell work without a model. The other Work tools inspect, retry, list, or cancel those jobs.

Tool Use it to
run Schedule Codex work, optionally gated by runtime dependencies, and return UUIDv4 runtime_id.
resume_run Retry a failed or interrupted Codex run under the same runtime_id with a new prompt.
poll_runtime / list_runtime Stream/poll run output and list retained run IDs, paths, sessions, and capacity.
cancel_runtime Safely cancel by runtime_id; force=true also cancels its queued/blocked dependent chain, never independent runs.
execute Queue Python cells or prefixed shell scripts and return tool, worker runtime_id, and job task_id.
poll_execution / list_executions Inspect one execution or list the queued/running execution state.
cancel_execution Cancel queued/running work by task_id; 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.
coding Plan and execute one complete roadmap through the step-coding and review loop in one runtime lane.
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_list_pages Browse knowledge topic pages with pagination.
wiki_search Find relevant knowledge sections.
wiki_read Read selected sections and their source provenance.

Agent fleet

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

Tool Use it to
create_agent Create a private agent workspace with role documents and a host guide; return its agent ID.
retire_agent Move an active workspace into the private archive without overwriting.
restore_agent Move a retired workspace back into the active fleet without overwriting.

Agent Fleet uses this fixed host layout:

~/.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>/...

create_agent accepts optional name, complete soul text, and complete instructions text. Null text creates starter documents. Its flat result returns tool, agent_id, status, and the active absolute path. Save 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.

Pass the returned agent_id to run or 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 run or coding submissions are also refused while it is busy; submit them again after the current runtime becomes terminal. When an agent is busy, check existing work with poll_runtime using your known runtime_id.

To transfer a local file, read get_upload_skill first. Uploads use a separate HTTP POST /upload with the same Bearer token, 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.

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:

uv tool upgrade agent-host-mcp

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

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.

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.

Metadata

Release files for agent-host-mcp 0.2.1

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Built distribution (wheel)

Table of built distributions (wheels) for agent-host-mcp 0.2.1
File Interpreter ABI Platform Actions
agent_host_mcp-0.2.1-py3-none-any.whl Python 3 none any Details for agent_host_mcp-0.2.1-py3-none-any.whl

Release files / agent_host_mcp-0.2.1-py3-none-any.whl

Download URL agent_host_mcp-0.2.1-py3-none-any.whl
Size 176.5 kB
Tags Python 3
SHA-256 checksum
How to use checksums
1027674b654ce258c12b00170fa179b19bdcaf32014c80d184a84cc4a5680a71
BLAKE2b-256 checksum
How to use checksums
b1912e652fb6a3d349b8b3d95e35f43f4fcc3654ed205715e3b5aef33b85a275
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via uv/0.11.18 {"installer":{"name":"uv","version":"0.11.18","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"22.04","id":"jammy","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}

Security for agent-host-mcp 0.2.1

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

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