> ## Documentation Index
> Fetch the complete documentation index at: https://docs.agentuse.io/llms.txt
> Use this file to discover all available pages before exploring further.

# Environment Variables

> Environment variables used by AgentUse

## API Configuration

These environment variables are required for authenticating with AI providers.

<ParamField path="ANTHROPIC_API_KEY" type="string">
  API key for Anthropic Claude models.

  ```bash theme={"system"}
  export ANTHROPIC_API_KEY="sk-ant-api03-..."
  ```

  You can also use the OAuth configuration flow:

  ```bash theme={"system"}
  agentuse auth login anthropic
  ```
</ParamField>

<ParamField path="ANTHROPIC_REFRESH_TOKEN" type="string">
  OAuth refresh token for Anthropic. Alternative to `ANTHROPIC_API_KEY`.

  Useful for Docker/container deployments where you want to use OAuth instead of API keys.

  ```bash theme={"system"}
  export ANTHROPIC_REFRESH_TOKEN="your-refresh-token"
  ```

  To get your refresh token:

  1. Run `agentuse auth login anthropic` locally
  2. Extract from `~/.local/share/agentuse/auth.json`

  The token is automatically refreshed when expired and stored in memory.
</ParamField>

<ParamField path="OPENAI_API_KEY" type="string">
  API key for OpenAI GPT models.

  ```bash theme={"system"}
  export OPENAI_API_KEY="sk-proj-..."
  ```
</ParamField>

<ParamField path="OPENROUTER_API_KEY" type="string">
  API key for OpenRouter service.

  ```bash theme={"system"}
  export OPENROUTER_API_KEY="sk-or-v1-..."
  ```
</ParamField>

<ParamField path="OPENCODE_GO_API_KEY" type="string">
  API key for OpenCode Go open coding models.

  ```bash theme={"system"}
  export OPENCODE_GO_API_KEY="..."
  ```
</ParamField>

<ParamField path="OPENCODE_GO_BASE_URL" type="string">
  Optional base URL override for OpenCode Go. Defaults to `https://opencode.ai/zen/go/v1`.

  ```bash theme={"system"}
  export OPENCODE_GO_BASE_URL="https://opencode.ai/zen/go/v1"
  ```
</ParamField>

<ParamField path="AWS_ACCESS_KEY_ID" type="string">
  AWS access key ID for Amazon Bedrock authentication (SigV4). Used together with `AWS_SECRET_ACCESS_KEY` and `AWS_REGION`.

  ```bash theme={"system"}
  export AWS_ACCESS_KEY_ID="AKIA..."
  ```
</ParamField>

<ParamField path="AWS_SECRET_ACCESS_KEY" type="string">
  AWS secret access key for Amazon Bedrock authentication (SigV4).

  ```bash theme={"system"}
  export AWS_SECRET_ACCESS_KEY="..."
  ```
</ParamField>

<ParamField path="AWS_REGION" type="string">
  AWS region for Amazon Bedrock API calls (e.g. `us-east-1`). Falls back to `AWS_DEFAULT_REGION` if unset. Required when using Bedrock.

  ```bash theme={"system"}
  export AWS_REGION="us-east-1"
  ```
</ParamField>

<ParamField path="AWS_SESSION_TOKEN" type="string">
  Optional AWS session token for temporary credentials (e.g. STS / assumed roles) when using Amazon Bedrock.

  ```bash theme={"system"}
  export AWS_SESSION_TOKEN="..."
  ```
</ParamField>

<ParamField path="AWS_BEARER_TOKEN_BEDROCK" type="string">
  Bedrock API key (Bearer token). When set, used instead of AWS SigV4 authentication.

  ```bash theme={"system"}
  export AWS_BEARER_TOKEN_BEDROCK="..."
  ```
</ParamField>

<ParamField path="AWS_PROFILE" type="string">
  AWS named profile from `~/.aws/credentials` / `~/.aws/config`. Used when no static keys or Bearer token are set: the SDK credential provider chain resolves SSO cache, assumed roles, instance metadata, etc.

  ```bash theme={"system"}
  export AWS_REGION=eu-west-1
  export AWS_PROFILE=my-bedrock-profile
  ```
</ParamField>

## Custom API Key Suffixes

You can use multiple API keys by adding suffixes:

```bash theme={"system"}
# For development environment
export ANTHROPIC_API_KEY_DEV="sk-ant-api03-dev..."
export OPENAI_API_KEY_DEV="sk-proj-dev..."

# For production environment  
export ANTHROPIC_API_KEY_PROD="sk-ant-api03-prod..."
export OPENAI_API_KEY_PROD="sk-proj-prod..."
```

Then reference them in your agent:

```yaml theme={"system"}
---
model: anthropic:claude-sonnet-5:dev  # Uses ANTHROPIC_API_KEY_DEV
---
```

## Serve Mode

<ParamField path="AGENTUSE_API_KEY" type="string">
  API key for authenticating requests to the serve mode HTTP server.
  Required when binding to exposed hosts (not `127.0.0.1` or `localhost`).

  ```bash theme={"system"}
  export AGENTUSE_API_KEY="your-secret-key"
  agentuse serve --host 0.0.0.0
  ```

  Clients authenticate via Bearer token:

  ```bash theme={"system"}
  curl -X POST http://server:12233/api/run \
    -H "Authorization: Bearer your-secret-key" \
    -d '{"agent": "my-agent.agentuse"}'
  ```
</ParamField>

## Approval Gates

<ParamField path="SLACK_BOT_TOKEN" type="string">
  Slack bot token used to post and update channel messages when `channels.slack` listens for `approval`, `completion`, or `failure`. The app needs the `chat:write` bot scope, and the bot must be in the target channel unless you also grant `chat:write.public` for public channels.

  ```bash theme={"system"}
  export SLACK_BOT_TOKEN="xoxb-..."
  ```
</ParamField>

<ParamField path="SLACK_APP_TOKEN" type="string">
  Optional Slack app-level token used for Socket Mode approval actions in Slack. Web approval pages and channel-only Slack messages do not require this token. If set, the app-level token needs `connections:write`; plain thread-reply comments also require Slack message event subscriptions and the relevant channel history scopes.

  ```bash theme={"system"}
  export SLACK_APP_TOKEN="xapp-..."
  ```
</ParamField>

<ParamField path="SLACK_APPROVAL_CHANNEL" type="string">
  Default Slack channel id for Slack channels. Agents can override this with `channels.slack.channel_id`.

  ```bash theme={"system"}
  export SLACK_APPROVAL_CHANNEL="C0123456789"
  ```
</ParamField>

<ParamField path="AGENTUSE_RESUME_PUBLIC_URL" type="string">
  Fallback public base URL used to build approval review links. Prefer `agentuse serve --public-url ...` or `serve.publicUrl` for hosted deployments.

  ```bash theme={"system"}
  export AGENTUSE_RESUME_PUBLIC_URL="https://agentuse.mycompany.com"
  ```
</ParamField>

## Behavior Control

<ParamField path="MAX_STEPS" type="number">
  Override the maximum number of conversation steps (LLM generation cycles) an agent can take.
  Default: 100

  ```bash theme={"system"}
  export MAX_STEPS="200"
  ```

  **Precedence:** This environment variable overrides the `maxSteps` value in agent YAML files.

  This prevents infinite loops and controls cost by limiting the number of LLM calls. Each step typically involves an LLM generation with potential tool calls.

  <Note>
    The default was reduced from 1000 to 100 for better cost protection. Most agents complete successfully within 100 steps.
  </Note>
</ParamField>

## Mock Mode (Testing)

Mock all tool outputs with the LLM instead of executing them. Mirror the `--mock` flags on
`agentuse run`; see [Testing with Mocked Tools](/reference/cli-commands#testing-with-mocked-tools).

<ParamField path="AGENTUSE_MOCK_MODE" type="boolean">
  `1` to mock all tool outputs (no real bash/filesystem/MCP/store side effects). Same as `--mock`. Requires `AGENTUSE_MOCK_MODEL`.
</ParamField>

<ParamField path="AGENTUSE_MOCK_MODEL" type="string" required>
  Model that generates mock outputs. **Required** whenever mock mode is on (same as `--mock-model`). Not defaulted to the agent's model on purpose: mock fires an LLM call per tool result, and running that on the agent's premium, rate-limited token caused opaque `429`s.

  Use the **lowest-end model you can reach** here: mocking only fabricates a plausible tool result, not real reasoning, so a small fast model is plenty and keeps cost and rate-limit pressure low. Good picks: `anthropic:claude-haiku-4-5`, `openai:gpt-5.4-nano`, or `openrouter:deepseek/deepseek-v4-flash`.

  Set it for one run with `--mock-model`, or as a global default in the shell, `~/.agentuse/.env`, or the [`env` block of `~/.agentuse/config.json`](/reference/configuration-files#global-env-defaults). `--mock-model` overrides whichever source supplies it.
</ParamField>

<ParamField path="AGENTUSE_MOCK_APPROVAL" type="boolean">
  `1` to also mock the `await_human` approval gate instead of suspending. Same as `--mock-approval`.
</ParamField>

## Context Management

<ParamField path="CONTEXT_COMPACTION" type="boolean">
  Enable or disable automatic context compaction when approaching model limits.
  Default: true (enabled)

  ```bash theme={"system"}
  # Disable context compaction
  export CONTEXT_COMPACTION="false"
  ```

  When enabled, AgentUse automatically compacts older messages when context approaches the model's token limit.
</ParamField>

<ParamField path="COMPACTION_THRESHOLD" type="number">
  Percentage of context limit to trigger compaction.
  Default: 0.7 (70%)

  ```bash theme={"system"}
  export COMPACTION_THRESHOLD="0.8"  # Trigger at 80%
  ```

  Must be a decimal between 0 and 1.
</ParamField>

<ParamField path="COMPACTION_KEEP_RECENT" type="number">
  Number of recent messages to preserve during compaction.
  Default: 3

  ```bash theme={"system"}
  export COMPACTION_KEEP_RECENT="5"  # Keep last 5 messages
  ```

  These messages are never compacted to maintain conversation flow.
</ParamField>

<ParamField path="APPROVAL_COMPACTION_MIN_TOKENS" type="number">
  Minimum active-context size that triggers opportunistic compaction at an approval gate.
  Default: 64000

  ```bash theme={"system"}
  export APPROVAL_COMPACTION_MIN_TOKENS="32000"
  ```

  This is separate from `COMPACTION_THRESHOLD`: a 64k-token context may be far
  below a large model's window, but still expensive to resend after a human
  approval pause. Set to `0` to disable approval-boundary compaction while
  keeping normal model-limit compaction enabled.
</ParamField>

<ParamField path="STEP_COMPACTION_MIN_TOKENS" type="number">
  Minimum active-context size that triggers opportunistic compaction between LLM
  steps after the first tool call.
  Default: 64000

  ```bash theme={"system"}
  export STEP_COMPACTION_MIN_TOKENS="128000"
  ```

  This enables split-turn compaction for long autonomous runs: older context can
  be summarized before the next model call even when the full model window is not
  close to exhausted. Set to `0` to disable step-boundary compaction while
  keeping approval-boundary and model-limit compaction enabled.
</ParamField>

## Tool Output

Large tool results are re-sent to the model on every subsequent step, so a single oversized output (a big diff, a verbose log, a huge file) inflates input tokens for the rest of the run. These variables cap how much of any one tool result reaches the model. When session storage is available, truncated `bash` output keeps the full stdout/stderr stream as a session-local tool output artifact; runner-level truncation of other tool results also saves the full raw result and adds a reference to the bounded preview. Defaults match historical behavior, so you only need to set them to tune.

<ParamField path="AGENTUSE_TOOL_MAX_OUTPUT_BYTES" type="number">
  Maximum size (in characters) of a single model-facing tool result, also used by the built-in `bash` stream cap. Output over this limit is truncated to a head + tail slice, dropping the middle, with a marker noting how much was omitted.
  Default: 30720 (30KB)

  ```bash theme={"system"}
  export AGENTUSE_TOOL_MAX_OUTPUT_BYTES="61440"  # 60KB
  ```
</ParamField>

<ParamField path="AGENTUSE_TOOL_OUTPUT_HEAD_RATIO" type="number">
  Fraction of `AGENTUSE_TOOL_MAX_OUTPUT_BYTES` kept as the head when truncating; the remainder is kept as the tail. Errors and context often appear early, while the most recent output appears at the end, so both ends are preserved.
  Default: 0.4 (40% head / 60% tail)

  ```bash theme={"system"}
  export AGENTUSE_TOOL_OUTPUT_HEAD_RATIO="0.5"  # even split
  ```

  Must be a decimal between 0 and 1.
</ParamField>

<ParamField path="AGENTUSE_TOOL_MAX_LINES" type="number">
  Default number of lines `read_file` returns when no explicit `limit` is given (and the truncation cap for file reads).
  Default: 2000

  ```bash theme={"system"}
  export AGENTUSE_TOOL_MAX_LINES="5000"
  ```
</ParamField>

<ParamField path="AGENTUSE_TOOL_MAX_LINE_LENGTH" type="number">
  Per-line character cap for `read_file` output. Longer lines are truncated with a `... (truncated)` suffix.
  Default: 2000

  ```bash theme={"system"}
  export AGENTUSE_TOOL_MAX_LINE_LENGTH="4000"
  ```
</ParamField>

<Note>
  Prefer not generating bloat in the first place over raising these caps. For example, use `git diff --stat` instead of a full `git diff` of high-churn files. Truncation is a safety net, not a substitute for asking the tool for less.
</Note>

## Logging and Debug

<ParamField path="LOG_LEVEL" type="string">
  Set the logging level for AgentUse output.
  Default: INFO

  ```bash theme={"system"}
  export LOG_LEVEL="DEBUG"  # Available: DEBUG, INFO, WARN, ERROR
  ```

  Controls which messages are displayed during execution.
</ParamField>

<ParamField path="DEBUG" type="boolean">
  Enable debug logging and verbose output.
  Default: false

  ```bash theme={"system"}
  export DEBUG="true"   # or DEBUG="1"
  ```

  Shows detailed execution information, tool calls, and internal state.
</ParamField>

## Telemetry

<ParamField path="AGENTUSE_TELEMETRY_DISABLED" type="boolean">
  Disable anonymous telemetry collection. No prompts, code, or file paths are ever collected.
  Default: false (telemetry enabled)

  ```bash theme={"system"}
  export AGENTUSE_TELEMETRY_DISABLED=true
  ```
</ParamField>

## Storage

<ParamField path="XDG_DATA_HOME" type="string">
  Override the default data directory for session logs and project data.
  Default: `~/.local/share`

  ```bash theme={"system"}
  export XDG_DATA_HOME="/custom/data/path"
  ```

  Session logs are stored at `$XDG_DATA_HOME/agentuse/project/{git-hash}/session/`.

  See [Session Logs](/guides/session-logs) for more details.
</ParamField>

## Development Variables

<ParamField path="NODE_TLS_REJECT_UNAUTHORIZED" type="string">
  For local development with self-signed certificates (HTTPS testing).

  ```bash theme={"system"}
  # Only for development - allows self-signed certs
  export NODE_TLS_REJECT_UNAUTHORIZED="0"
  ```

  <Warning>
    Never use this in production. It disables SSL certificate verification.
  </Warning>
</ParamField>

## MCP Server Environment Variables

<Info>
  **Security by Design**: AgentUse intentionally prevents hardcoding secrets in `.agentuse` files. All sensitive values must come from environment variables, keeping your secrets secure and out of version control.
</Info>

### The Security Model

MCP servers can access environment variables through two fields:

* **`requiredEnvVars`**: Variables that MUST exist or the agent fails immediately
* **`allowedEnvVars`**: Variables that are passed through if they exist (optional)

```yaml theme={"system"}
---
model: anthropic:claude-sonnet-5
mcpServers:
  notion:
    command: "pnpx"
    args: ["-y", "@notionhq/notion-mcp-server"]
    requiredEnvVars:
      - NOTION_API_KEY        # Fails immediately if missing
    allowedEnvVars:
      - NOTION_DEBUG_MODE     # Optional, warns if missing
      - NOTION_WORKSPACE_ID   # Optional, warns if missing
---
```

### Why This Design?

1. **No Secrets in Code**: `.agentuse` files are often committed to version control
2. **Clear Requirements**: Developers know exactly what env vars are needed
3. **Early Failure**: Missing required vars fail fast with clear error messages
4. **Security Allowlist**: Only explicitly allowed vars are passed to MCP servers

### Setting Environment Variables

<Tabs>
  <Tab title="Option 1: .env File (Recommended)">
    Create a `.env` file in your project root:

    ```bash theme={"system"}
    # .env
    NOTION_API_KEY=secret_abc123
    GITHUB_TOKEN=ghp_xyz789
    OPENAI_API_KEY=sk-proj-...
    ```

    AgentUse automatically loads `.env` files from the project root (detected via `.git/`, `.agentuse/`, or `package.json`).

    **Override Options:**

    ```bash theme={"system"}
    # Use a specific .env file
    agentuse run agent.agentuse --env-file .env.production

    # Run from a different directory
    agentuse run agent.agentuse -C /path/to/project
    ```

    <Warning>
      Add `.env` to your `.gitignore` to prevent committing secrets!
    </Warning>
  </Tab>

  <Tab title="Option 2: Shell Export">
    Export variables in your shell session:

    ```bash theme={"system"}
    export NOTION_API_KEY="secret_abc123"
    export GITHUB_TOKEN="ghp_xyz789"

    # Then run your agent
    agentuse run my-agent.agentuse
    ```

    For permanent setup, add to `~/.zshrc` or `~/.bashrc`:

    ```bash theme={"system"}
    # ~/.zshrc
    export NOTION_API_KEY="secret_abc123"
    export GITHUB_TOKEN="ghp_xyz789"
    ```
  </Tab>

  <Tab title="Option 3: Inline Command">
    Pass variables directly when running:

    ```bash theme={"system"}
    NOTION_API_KEY="secret_abc123" agentuse run my-agent.agentuse
    ```

    Useful for CI/CD or one-time runs.
  </Tab>

  <Tab title="Option 4: Secret Managers">
    For production, use secret managers:

    ```bash theme={"system"}
    # AWS Secrets Manager
    export NOTION_API_KEY=$(aws secretsmanager get-secret-value \
      --secret-id notion-api-key --query SecretString --output text)

    # 1Password CLI
    export NOTION_API_KEY=$(op read "op://vault/notion/api-key")

    # HashiCorp Vault
    export NOTION_API_KEY=$(vault kv get -field=api_key secret/notion)
    ```
  </Tab>
</Tabs>

### Error Messages

AgentUse provides clear, actionable error messages:

```bash theme={"system"}
# Missing required variable
Error: Missing required environment variables for MCP server 'notion': NOTION_API_KEY
Please set these in your .env file or export them in your shell.

# Missing optional variable (warning only)
[WARN] Optional environment variable 'NOTION_DEBUG_MODE' not set for server 'notion'

# Connection failure with hint
Failed to connect to MCP server 'github'
Note: The following optional environment variables are not set: GITHUB_TOKEN
If this server requires these variables, please set them in your .env file.
```

### Complete Example

```yaml theme={"system"}
---
model: anthropic:claude-sonnet-5
mcpServers:
  # API-based service requiring authentication
  notion:
    command: "pnpx"
    args: ["-y", "@notionhq/notion-mcp-server"]
    requiredEnvVars:
      - NOTION_API_KEY    # Must be set or fails
    allowedEnvVars:
      - NOTION_DEBUG      # Optional debug flag
      
  # Database connection
  postgres:
    command: "pnpx"
    args: ["-y", "@modelcontextprotocol/server-postgresql"]
    requiredEnvVars:
      - DATABASE_URL      # Required connection string
    allowedEnvVars:
      - PG_STATEMENT_TIMEOUT  # Optional timeout
      - PG_POOL_SIZE          # Optional pool config
      
  # Local filesystem (no auth needed)
  filesystem:
    command: "pnpx"
    args: ["-y", "@modelcontextprotocol/server-filesystem", "./data"]
    # No env vars needed for local filesystem
---
```

With `.env` file:

```bash theme={"system"}
# Required vars (agent won't start without these)
NOTION_API_KEY=secret_abc123
DATABASE_URL=postgresql://user:pass@localhost/mydb

# Optional vars (agent works without these)
NOTION_DEBUG=true
PG_POOL_SIZE=20
```

## Using .env Files

For a full overview of user-facing configuration files and directories, see [Configuration Files](/reference/configuration-files).

AgentUse automatically loads `.env` files if present in your project directory:

```bash theme={"system"}
# .env
ANTHROPIC_API_KEY=sk-ant-api03-...
OPENAI_API_KEY=sk-proj-...
OPENROUTER_API_KEY=sk-or-v1-...
OPENCODE_GO_API_KEY=...
GITHUB_TOKEN=ghp_...
DATABASE_URL=postgresql://user:pass@localhost/db

# Behavior control
MAX_STEPS=500

# Context management
CONTEXT_COMPACTION=true
COMPACTION_THRESHOLD=0.7
COMPACTION_KEEP_RECENT=3
APPROVAL_COMPACTION_MIN_TOKENS=64000
STEP_COMPACTION_MIN_TOKENS=64000

# Logging and debug
LOG_LEVEL=INFO
DEBUG=false

# Telemetry (opt-out)
AGENTUSE_TELEMETRY_DISABLED=false
```

<Note>
  Never commit `.env` files to version control. Add them to `.gitignore`.
</Note>

## Priority Order

Environment variables are loaded in this order (later overrides earlier):

1. System environment variables
2. `.env` file in current directory
3. Command-line environment variables

Example:

```bash theme={"system"}
# This overrides any existing MAX_STEPS value
MAX_STEPS=100 agentuse run agent.agentuse
```

## Security Best Practices

### Store Secrets Securely

Never hardcode API keys in agent files:

```yaml theme={"system"}
# ❌ Bad - Would be insecure (but AgentUse doesn't allow this)
mcpServers:
  github:
    env:
      GITHUB_TOKEN: "ghp_actualTokenHere"  # Not supported by design!

# ✅ Good - Use environment variable allowlist
mcpServers:
  github:
    command: "pnpx"
    args: ["-y", "@modelcontextprotocol/server-github"]
    requiredEnvVars:
      - GITHUB_TOKEN  # Must be in .env or shell environment
```

### Use .gitignore

Always exclude sensitive files:

```gitignore theme={"system"}
# Environment files
.env
.env.local
.env.*.local

# API keys
*.key
*.pem
```

### Validate Required Variables

For MCP servers that require specific environment variables, they will fail with clear error messages if the variables are not set.

## Troubleshooting

<AccordionGroup>
  <Accordion title="API key not found">
    Verify the environment variable is set:

    ```bash theme={"system"}
    echo $ANTHROPIC_API_KEY
    ```

    If empty, set it:

    ```bash theme={"system"}
    export ANTHROPIC_API_KEY="your-key-here"
    ```

    Or use the auth command:

    ```bash theme={"system"}
    agentuse auth login
    ```
  </Accordion>

  <Accordion title="Wrong API key being used">
    Check which key is being used:

    ```bash theme={"system"}
    agentuse auth list
    ```

    The tool prioritizes OAuth tokens over API keys for Anthropic.
  </Accordion>

  <Accordion title="MAX_STEPS not working">
    Ensure you're setting it before running the agent:

    ```bash theme={"system"}
    export MAX_STEPS=100
    agentuse run agent.agentuse

    # Or inline:
    MAX_STEPS=100 agentuse run agent.agentuse
    ```
  </Accordion>
</AccordionGroup>

## Next Steps

<CardGroup cols={2}>
  <Card title="Model Configuration" icon="key" href="/guides/model-configuration">
    Set up model providers and API keys
  </Card>

  <Card title="MCP Configuration" icon="plug" href="/reference/agent-syntax#mcp-servers">
    Configure MCP servers
  </Card>
</CardGroup>
