# Harnesses & sign-in

> Index of all pages: https://anywhere.so/llms.txt

Anywhere never couples to an agent framework or SDK. Install whichever CLI, runtime, or library you want in `build`, run it in a `[[trigger]]`, and authenticate with either encrypted API keys or an interactive CLI sign-in stored on the worker's persistent disk.

## An optional pattern for unattended agents

Any command that exits works out of the box, and you can opt into any of the small output conventions in [Runs & conventions](/docs/runs-and-artifacts). For unattended coding and ops agents, one pattern that works reliably in practice is five explicit steps:

**prepare -> run the agent -> check -> leave a note -> exit**

1. **Prepare:** Read any webhook `stdin` payload and verify required secrets or sign-in before invoking a model. If anything is missing, write the fix to `$ANYWHERE_RUN_DIR/note` and exit non-zero.
2. **Run the agent:** Pass inputs cleanly, constrain tools when processing untrusted external data, and close `stdin` (`</dev/null`) when calling interactive-capable CLIs after saving a webhook body.
3. **Check:** Verify the expected deliverable exists and parses. Coding agents can exit `0` even when they wrote nothing, so your wrapper script should decide the final exit code.
4. **Leave a note:** Write a concise one-line summary to `$ANYWHERE_RUN_DIR/note`.
5. **Exit:** Return `0` on verified success, non-zero otherwise.

## Claude Code (`claude -p`)

Install Claude Code in `build`:

```toml
build = "npm i -g @anthropic-ai/claude-code"
```

### API key vs. interactive subscription sign-in

- **API key:** Store `ANTHROPIC_API_KEY` as a secret (`anywhere secrets set --worker NAME ANTHROPIC_API_KEY`).
- **Interactive sign-in on the worker's disk:** Deploy the worker first, then open a real terminal with `anywhere exec -t` and sign in once with `CLAUDE_CONFIG_DIR` pointing inside `/app/data`:

```sh
anywhere exec -t triage -- env CLAUDE_CONFIG_DIR=/app/data/claude claude auth login
anywhere exec triage -- env CLAUDE_CONFIG_DIR=/app/data/claude claude auth status --text
```

Then start Claude in your run script with `CLAUDE_CONFIG_DIR=/app/data/claude`. Do not also set `ANTHROPIC_API_KEY` on the same worker, because `claude -p` always prefers the API key when present.

### Webhook stdin, transcripts & running safely inside gVisor

- **Redirect stdin on webhook runs:** If a webhook wrapper saves `stdin` to a file first (for example `cat > payload.json`), pass `</dev/null` to `claude -p` so Claude never blocks waiting on standard input.
- **Optional transcript artifact:** Pass `--output-format stream-json --verbose` and write the scrubbed JSON-lines stream to `$ANYWHERE_RUN_DIR/artifacts/transcript.jsonl` if you want a full inspectable audit trail in the portal.
- **Trusted internal tasks:** Export `IS_SANDBOX=1` before running `claude -p "$(cat prompt.md)" --dangerously-skip-permissions </dev/null`. The worker's gVisor sandbox is the boundary.
- **Untrusted external inputs** (errors, GitHub issues, webhook bodies): Fetch external inputs in your shell or Python prepare step, `unset` unused tokens and API secrets before launching Claude, restrict tools (`--tools "Read,Grep,Glob,Write" --permission-mode dontAsk`), and render your HTML report from the structured data Claude writes.

## Codex (`codex exec`)

Install Codex in `build`:

```toml
build = "npm i -g @openai/codex"
```

Codex's inner sandbox cannot nest inside gVisor, so run it with `--dangerously-bypass-approvals-and-sandbox`. In webhook runs where your wrapper reads `stdin` first, pass `</dev/null`. To capture an optional JSON-lines transcript safely, stream `--json` to a file outside `artifacts/` first, then scrub any secrets and bound its size before writing `$ANYWHERE_RUN_DIR/artifacts/transcript.jsonl` (so a large raw stream never blows the 10 MiB artifact cap):

```sh
codex exec \
  --dangerously-bypass-approvals-and-sandbox \
  --skip-git-repo-check \
  --json \
  -o "$ANYWHERE_RUN_DIR/artifacts/answer.md" \
  "$(cat prompt.md)" \
  </dev/null > "$ANYWHERE_RUN_DIR/codex.jsonl"

# Optional: scrub secrets and bound size before copying into artifacts/
python3 /app/transcript.py "$ANYWHERE_RUN_DIR/codex.jsonl" \
  "$ANYWHERE_RUN_DIR/artifacts/transcript.jsonl"
```

- **API key:** Set `CODEX_API_KEY` via `anywhere secrets set --worker NAME CODEX_API_KEY`.
- **ChatGPT subscription sign-in:** Enable device code login in your ChatGPT security settings, set `cli_auth_credentials_store = "file"` in `/app/data/codex/config.toml`, and run:

```sh
anywhere exec -t my-worker -- env CODEX_HOME=/app/data/codex codex login --device-auth
```

## OpenCode, OpenRouter & custom harnesses

Any Linux binary, runtime, or agent SDK works on the Ubuntu base image (Node.js, Python, and `apt` are preinstalled):

- **OpenCode & other CLIs:** Install in `build`, keep config/auth under `/app/data/`, and invoke non-interactively in `[[trigger]]`.
- **TypeScript / AI SDKs:** Run `build = "npm ci && npm run build"` and `run = "node dist/agent.js"`, reading `OPENROUTER_API_KEY`, `ANTHROPIC_API_KEY`, or `OPENAI_API_KEY` from secrets.
- **Python:** Create a virtualenv in `build` (`python3 -m venv /app/.venv && /app/.venv/bin/pip install -r requirements.txt`) and invoke `/app/.venv/bin/python agent.py`. Keep `.venv/` in `.gitignore` so deploys don't upload local binaries.
- **Go, Rust, or plain scripts:** Compile in `build` (or install toolchains via `apt`) and run the binary directly in `[[trigger]]`.
- **Open models:** Point your harness or script at OpenRouter (`OPENROUTER_API_KEY`) to run DeepSeek, Qwen, or other low-cost models on high-frequency schedules.

## Tools, APIs & MCP servers

A worker's agent can connect to tools in three ways:

- **Local stdio MCP servers:** Install the MCP server package in `build` and configure your harness (for example `.mcp.json` or CLI flags) to spawn it over stdio during the run.
- **Local `127.0.0.1` HTTP MCP servers:** Start a local HTTP MCP server inside your run script on any loopback port except `7682` (reserved for `/_anywhere/done`), pass its `http://127.0.0.1:<port>` URL to your harness, and stop it in a `trap` on exit.
- **Remote HTTPS MCP servers & external APIs:** Connect shared remote MCP servers once per workspace with `anywhere connections` (recommended) or reach public internet APIs over outbound IPv4 TCP and DNS (every port except mail's `25`, `465`, and `587`).

Nothing calls into a worker from outside except its secret webhook URLs. See the [MCP agent recipe](/docs/recipes#agent-with-local-and-remote-mcp-servers-mcp-agent) for a working layout.

### Authenticating remote MCP servers

Pick the auth path that matches the remote MCP server:

1. **Workspace MCP connections (`anywhere connections` — recommended for all remote MCP servers):** Connect a remote MCP server once in your personal or team workspace and share it with all workers or selected workers. Raw OAuth tokens and API keys stay encrypted in Postgres—never on worker disks—and Anywhere's proxy handles automatic OAuth sign-in, serialized token refresh, live scope updates, and instant revocation without restarting workers:

   ```sh
   # Automatic OAuth (prints a single browser approval link)
   anywhere connections add notion https://mcp.notion.com/mcp --scope selected --workers triage

   # Encrypted API key or custom header (omit --value-stdin to paste in the browser instead)
   printf %s "$LINEAR_API_KEY" | anywhere connections add linear https://mcp.linear.app/mcp \
     --auth static --header Authorization --prefix Bearer --value-stdin --scope all

   # Custom OAuth app (for providers that require a registered client ID; callback URL comes from `anywhere connections list`)
   anywhere connections add slack https://mcp.slack.com/mcp \
     --auth oauth-custom --client-id "$CLIENT_ID" --scopes "channels:read"

   # Verify without waking any worker
   anywhere connections test notion
   ```

   You can also add, test, scope, reconnect, or remove connections in the portal under your workspace menu's **Connections** page.

   Every run of a worker with at least one scoped active connection automatically receives `ANYWHERE_MCP_URL`, `ANYWHERE_MCP_TOKEN`, and `ANYWHERE_MCP_CONNECTIONS` (builds never receive them). Point any harness at `${ANYWHERE_MCP_URL}/<name>` with `Authorization: Bearer ${ANYWHERE_MCP_TOKEN}`—no platform SDK required:

   **Claude Code (`mcp.json`):**

   ```json
   {
     "mcpServers": {
       "linear": {
         "type": "http",
         "url": "${ANYWHERE_MCP_URL}/linear",
         "headers": {
           "Authorization": "Bearer ${ANYWHERE_MCP_TOKEN}"
         }
       }
     }
   }
   ```

   Invoke with `claude -p "$(cat prompt.md)" --mcp-config mcp.json --strict-mcp-config </dev/null`. If your run wrapper filters environment variables, allowlist `ANYWHERE_MCP_URL`, `ANYWHERE_MCP_TOKEN`, and `ANYWHERE_MCP_CONNECTIONS`.

   **Codex (`codex exec`):**

   ```sh
   codex exec --dangerously-bypass-approvals-and-sandbox --skip-git-repo-check \
     -c "mcp_servers.linear.url=\"${ANYWHERE_MCP_URL}/linear\"" \
     -c 'mcp_servers.linear.bearer_token_env_var="ANYWHERE_MCP_TOKEN"' \
     "$(cat prompt.md)" </dev/null
   ```

   **OpenCode (`opencode.json` — set `"oauth": false` so OpenCode sends the bearer header directly):**

   ```json
   {
     "mcp": {
       "linear": {
         "type": "remote",
         "url": "{env:ANYWHERE_MCP_URL}/linear",
         "oauth": false,
         "headers": {
           "Authorization": "Bearer {env:ANYWHERE_MCP_TOKEN}"
         }
       }
     }
   }
   ```

   **Python (`mcp`) and TypeScript (`@modelcontextprotocol/sdk`):**

   ```python
   import os
   from mcp import ClientSession
   from mcp.client.streamable_http import streamablehttp_client

   url = f"{os.environ['ANYWHERE_MCP_URL']}/linear"
   headers = {"Authorization": f"Bearer {os.environ['ANYWHERE_MCP_TOKEN']}"}
   async with streamablehttp_client(url, headers=headers) as (read, write, _):
       async with ClientSession(read, write) as session:
           await session.initialize()
           result = await session.call_tool("list_issues", {"limit": 10})
   ```

   ```ts
   import { Client } from "@modelcontextprotocol/sdk/client/index.js";
   import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";

   const client = new Client({ name: "worker", version: "1.0.0" });
   await client.connect(
     new StreamableHTTPClientTransport(
       new URL(`${process.env.ANYWHERE_MCP_URL}/linear`),
       {
         requestInit: {
           headers: {
             Authorization: `Bearer ${process.env.ANYWHERE_MCP_TOKEN}`,
           },
         },
       },
     ),
   );
   ```

   Inside a run, `GET $ANYWHERE_MCP_URL` with `Authorization: Bearer $ANYWHERE_MCP_TOKEN` returns JSON listing the worker's scoped connections and their statuses. For interactive debugging inside `anywhere exec`, run `anywhere connections env --worker NAME` to mint a 15-minute token; keep `ANYWHERE_MCP_TOKEN` out of logs, transcripts, and artifacts.

2. **Per-worker `anywhere secrets`:** Use `anywhere secrets set --worker NAME` for non-MCP credentials (`ANTHROPIC_API_KEY`, `CODEX_API_KEY`, database URLs) or as a direct fallback when a remote server cannot be proxied.
3. **Interactive sign-in inside `anywhere exec -t`:** Use for CLI harness subscriptions (`claude auth login`, `codex login --device-auth`) or rare local/stdio tools that must authenticate inside the sandbox.

**Do not copy active OAuth credential files from your laptop into a worker** (such as `~/.claude/.credentials.json` or `~/.codex/.credentials.json`). Under OAuth 2.1 refresh-token rotation, whichever machine refreshes first invalidates the shared refresh token and revokes both sessions. If an upstream connection later expires and refresh fails, Anywhere's proxy marks the connection `needs_reauth` and returns HTTP `401` (`connection_needs_reauth`); verify in your run script that required MCP calls succeeded rather than relying on exit code `0` alone, and reconnect via the portal or `anywhere connections reconnect NAME`.

## Interactive terminals (`anywhere exec -t`)

Pass `-t` before the worker name whenever you need a real TTY (signing into a CLI, inspecting files interactively, or running `bash`):

```sh
anywhere exec -t triage -- bash
```

Keys (`Ctrl-C`, `Ctrl-D`), window resizing, and exit codes pass through directly. For scripted or agent-run commands without a terminal, omit `-t`:

```sh
anywhere exec triage -- ls -la /app/data
```
