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

# Claude Code

> How to connect Claude Code with the TrueFoundry AI Gateway.

This guide provides instructions for integrating [Claude Code](https://docs.anthropic.com/en/docs/claude-code) with the TrueFoundry AI Gateway.

<Note>
  This page covers the **Claude Code CLI** and the **VS Code extension**, which use `ANTHROPIC_BASE_URL` and environment variables in `settings.json`. For the other two Claude surfaces, see the overview below — **[Claude Desktop](/docs/ai-gateway/claude-desktop)** (Cowork on third-party inference) and **claude.ai** (the web app).
</Note>

<Tip>
  Want to guardrail Claude Code's **prompts and tool calls** (not just model requests)? See **[Guardrails using Claude Code Hooks](/docs/ai-gateway/claude-code-hooks)** — it uses Claude Code hooks to block or rewrite dangerous actions in the client.
</Tip>

## The Claude surfaces you can govern

TrueFoundry can put every Claude surface — not just the CLI — behind the AI Gateway, with fleet-wide enforcement via MDM where the tool supports it:

| Surface                         | How it routes to the AI Gateway                                                                          |        MDM-enforceable        | Guide                                                                                                                       |
| ------------------------------- | -------------------------------------------------------------------------------------------------------- | :---------------------------: | --------------------------------------------------------------------------------------------------------------------------- |
| **Claude Code (CLI + VS Code)** | `ANTHROPIC_BASE_URL` in `managed-settings.json`                                                          | Yes (macOS · Linux · Windows) | This page                                                                                                                   |
| **Claude Desktop (Cowork 3P)**  | `com.anthropic.claudefordesktop` managed preferences                                                     |     Yes (macOS · Windows)     | [Claude Desktop](/docs/ai-gateway/claude-desktop)                                                                           |
| **claude.ai (web app)**         | On-device interception with [aitori](https://github.com/truefoundry/aitori) — no endpoint setting exists |        Deployed via MDM       | [Govern all AI traffic](/docs/ai-gateway/govern-traffic-through-ai-gateway#method-b-aitori-the-open-source-on-device-agent) |

**Claude Code and Claude Desktop** are configured by the same tool: TrueFoundry ships the **[`tfy-local-ai-setup`](https://github.com/truefoundry/tfy-local-ai-setup)** binary, deployed over MDM, which runs the device-login flow, writes the managed config (with a fresh gateway token in the `X-TFY-API-KEY` header), immutably locks it, and refreshes on a schedule. Prebuilt binaries for all platforms live on the [releases page](https://github.com/truefoundry/tfy-local-ai-setup/releases). One run configures whichever tools are installed — pass `--claude-code`, `--claude-desktop`, and `--codex`, or omit all three to auto-detect. See [Enterprise security with MDM](/docs/ai-gateway/mcp/enterprise-security-claude) for the full deployment scripts.

**claude.ai** has no endpoint setting — the web app calls Anthropic's backend directly — so it can't be pointed at a gateway the way the CLI or Desktop can. To govern it, TrueFoundry ships **[aitori](https://github.com/truefoundry/aitori)**, an open-source (Apache-2.0) on-device agent that runs as the machine's HTTPS proxy, decrypts an allowlist of AI hosts, and reroutes their model and MCP calls through the AI Gateway. Try it on one machine:

```bash theme={"dark"}
# Install (macOS / Linux)
curl -fsSL https://raw.githubusercontent.com/truefoundry/aitori/main/install.sh | sh

# Govern this machine and open the live view at http://127.0.0.1:9100
sudo aitori up --ui \
  --gateway-url "https://gateway.truefoundry.ai/api/llm/ai-proxy/" \
  --token-file ~/.aitori/tf_token

# Revert the system proxy when you're done
sudo aitori down
```

Claude (Code, Desktop, web) and ChatGPT are covered by built-in profiles, so there are no rules to write to get started. Because claude.ai calls Anthropic's backend server-side, you get guardrails and audit on the visible content but **not** token-level cost tracking. Full setup, config-file rollout, and the fleet story are in [Govern all AI traffic through the AI Gateway](/docs/ai-gateway/govern-traffic-through-ai-gateway).

## What is Claude Code?

Claude Code is Anthropic's agentic coding tool that lives in your terminal, understands your codebase, and helps you code faster through natural language commands. It serves as an intelligent pair programming partner that can read, analyze, and work with your entire project structure.

## Model Configuration

Claude Code supports model aliases (`opus`, `sonnet`, `haiku`, `opusplan`) that provide convenient shortcuts for different use cases. When integrating with TrueFoundry, you can configure these aliases to use your specific TrueFoundry models through environment variables.

<Note>
  Model aliases allow you to switch between different Claude models during your coding session using simple commands like `/model opus` or `/model sonnet`.
</Note>

## Prerequisites

Before integrating Claude Code with TrueFoundry, ensure you have:

1. **TrueFoundry Account**: Create a [TrueFoundry account](https://www.truefoundry.com/register) and follow the instructions in our [Gateway Quick Start Guide](https://docs.truefoundry.com/gateway/quick-start)
2. **Claude Code Installation**: Install Claude Code following the [official documentation](https://docs.anthropic.com/en/docs/claude-code)
3. Configure models in TrueFoundry for each provider you want to use

## Integrate TrueFoundry with Claude Code

Claude Code uses a settings.json file for configuration. You'll need to modify the environment variables to route requests through TrueFoundry.

First, get the base URL and model name from your TrueFoundry AI Gateway playground using the unified code snippet:

<Frame>
  <img src="https://mintcdn.com/truefoundry/n3EuZuJ0K8wBFp1G/images/new-code-snippet.png?fit=max&auto=format&n=n3EuZuJ0K8wBFp1G&q=85&s=3634c2dc8c3565fd77ab896d3fd07ed9" alt="TrueFoundry playground showing unified code snippet with base URL and model name" width="2940" height="1664" data-path="images/new-code-snippet.png" />
</Frame>

Claude Code can be configured either globally or per project by editing the settings file:

* Global: `~/.claude/settings.json`
* Project-specific: `.claude/settings.json` in your project directory

```json lines theme={"dark"}
{
  "env": {
    "ANTHROPIC_BASE_URL": "{GATEWAY_BASE_URL}",
    "ANTHROPIC_AUTH_TOKEN": "your-truefoundry-api-key",
    "ANTHROPIC_MODEL": "claude-code/claude-sonnet",
    "ANTHROPIC_DEFAULT_OPUS_MODEL": "claude-code/claude-opus",
    "ANTHROPIC_DEFAULT_SONNET_MODEL": "claude-code/claude-sonnet",
    "ANTHROPIC_DEFAULT_HAIKU_MODEL": "claude-code/claude-haiku",
    "CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS": "1",
    "ANTHROPIC_CUSTOM_HEADERS": "x-tfy-anthropic-beta: context-management-2025-06-27"
  }
}
```

<Note>
  `CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS` disables experimental features in Claude Code for stable behavior with TrueFoundry AI Gateway.
</Note>

<Note>
  Claude Code detects model capabilities (e.g. extended thinking `effort`, ToolSearch, beta tool blocks) by string-matching the model id. Make sure the value of `ANTHROPIC_DEFAULT_OPUS_MODEL`, `ANTHROPIC_DEFAULT_SONNET_MODEL`, and `ANTHROPIC_DEFAULT_HAIKU_MODEL` contains a recognizable Anthropic model id like `claude-opus-4-7`, `claude-sonnet-4-6`, or `claude-haiku-4-5` or `claude-haiku-4-5-20251001`. If you're using a TrueFoundry virtual model, ensure that the virtual model's display name is the same as the underlying Anthropic model id (e.g. `claude-haiku-4-5`), so the full value `your-account/claude-haiku-4-5` contains a recognizable id for Claude Code; otherwise Claude Code may attach parameters the underlying model doesn't support and Anthropic will return `400: This model does not support the effort parameter`.
</Note>

### Forwarding Anthropic Beta Features

Anthropic releases beta features (e.g. [context management](https://docs.anthropic.com/en/docs/build-with-claude/context-editing)) that require the `anthropic-beta` header on API requests. To forward a beta flag through the TrueFoundry AI Gateway, set the `x-tfy-anthropic-beta` header via `ANTHROPIC_CUSTOM_HEADERS` as shown in the config above.

To enable multiple beta features, pass them as a comma-separated list (no spaces):

```json theme={"dark"}
{
  "env": {
    "ANTHROPIC_CUSTOM_HEADERS": "x-tfy-anthropic-beta: context-management-2025-06-27,files-api-2025-04-14"
  }
}
```

<Note>
  Beta support depends on the routed provider. For direct Anthropic requests,
  Anthropic validates the beta identifier. For AWS Bedrock, Bedrock Mantle, and
  Google Vertex AI, the Gateway translates supported identifiers and omits
  identifiers that the provider does not accept.
</Note>

<Tip>
  `x-tfy-anthropic-beta` is a gateway-specific header that is mapped to the outbound `anthropic-beta` header. When it is present, it **replaces** Claude Code's own `anthropic-beta` header, body `anthropic_beta`, and any other client beta source — the values are not merged. A virtual model can override it only by setting `x-tfy-anthropic-beta` in `headers_override`; setting `anthropic-beta` there does not replace it.
</Tip>

## Using Claude Code VS Code Extension

The [Claude Code VS Code extension](https://marketplace.visualstudio.com/items?itemName=Anthropic.claude-code) works seamlessly with TrueFoundry once you've configured the CLI.

<Warning>
  The VS Code extension is **not standalone**. It requires the Claude Code CLI to be installed separately and configured first.
</Warning>

**Setup Steps:**

1. Install and configure the Claude Code CLI as described [above](#integrate-truefoundry-with-claude-code)
2. Install the VS Code extension
3. Launch VS Code from your terminal to inherit the configuration:

```bash lines theme={"dark"}
code .
```

<Note>
  The extension automatically uses your CLI configuration (base URL, API keys, model aliases). No separate setup needed.
</Note>

**Important for macOS/Linux:** Launch VS Code from the terminal where you've set up Claude Code. GUI applications don't inherit shell environment variables by default.

### Model Alias Configuration

The following environment variables map Claude Code's built-in aliases to your TrueFoundry models:

* `ANTHROPIC_DEFAULT_OPUS_MODEL`: Maps `opus` alias to your TrueFoundry Opus model
* `ANTHROPIC_DEFAULT_SONNET_MODEL`: Maps `sonnet` alias to your TrueFoundry Sonnet model
* `ANTHROPIC_DEFAULT_HAIKU_MODEL`: Maps `haiku` alias to your TrueFoundry Haiku model

**Benefits:** Model aliases enable seamless integration with Claude Code's built-in commands, flexible model switching with `/model opus` or `/model sonnet`, and optimized workflows by choosing the right model for each task.

### Example Usage

```bash lines theme={"dark"}
# Use different models for different tasks
claude --model opus "Design a scalable microservices architecture"
claude --model sonnet "Implement a user authentication system"
claude --model haiku "Write a function to validate email addresses"

# Switch models during a session
/model opusplan  # Uses opus for planning, sonnet for execution
```

## Claude Agent SDK

The [Claude Agent SDK](https://docs.claude.com/en/api/agent-sdk/overview) is the successor to the Claude Code SDK, providing programmatic access to build custom AI agents with the same capabilities as Claude Code.

<Note>
  The Claude Code SDK has been deprecated. If you're using the old SDK, migrate to the Claude Agent SDK for continued support and new features.
</Note>

### Installation

```bash theme={"dark"}
pip install claude-agent-sdk
```

### Key Changes from Claude Code SDK

**What changed:** The SDK no longer reads from filesystem settings automatically. You must explicitly specify which settings to load.

**Manual setup required:** You now need to explicitly load settings for:

* Settings files (`.claude/settings.json` for project, `~/.claude/settings.json` for user)
* `CLAUDE.md` files (project memory)
* Custom slash commands from `.claude/commands/`

### TrueFoundry Integration

Your existing `.claude/settings.json` configuration works seamlessly with the Agent SDK. Simply specify `setting_sources=["project"]` to load your TrueFoundry gateway configuration:

```python theme={"dark"}
from claude_agent_sdk import query, ClaudeAgentOptions

async for message in query(
    prompt="Analyze my codebase",
    options=ClaudeAgentOptions(
        setting_sources=["project"],  # Loads .claude/settings.json
        max_turns=5,
        allowed_tools=["Read", "Grep", "Glob"]
    )
):
    if message.type == "result":
        print(message.result)
```

All your existing TrueFoundry configurations (`Anthropic Direct`, `AWS Bedrock`, `Google Vertex AI`) work identically with the Agent SDK.

## Web search

Claude Code's built-in **web search** is an Anthropic *server-side* tool. When Claude Code runs against the AI Gateway (via `ANTHROPIC_BASE_URL`), there are two ways to satisfy it, and you can use both:

* **Provider-native passthrough** — Claude Code emits Anthropic's `web_search_20250305` server tool and the AI Gateway forwards it to the model's provider (the request tool, the `web_search_tool_result` blocks in the response, and the `num_search_queries` usage counter for billing). Nothing extra to configure; it works whenever the routed provider executes the Anthropic web-search tool (for example, the Anthropic API). A model whose provider doesn't run it simply returns no search results.
* **MCP web search** *(consistent across providers)* — for web search that behaves the same regardless of which model the gateway routes to, add a web-search MCP server. Because search runs at the MCP server rather than the model provider, it works on **every** model.

Point Claude Code at a web-search MCP server running behind the [TrueFoundry MCP Gateway](/docs/ai-gateway/mcp/mcp-overview) — for example [Tavily](/docs/ai-gateway/mcp/tavily-mcp-server) or [Exa](/docs/ai-gateway/mcp/exa-mcp-server) — so the search key and tool access stay server-side and centrally governed:

```bash theme={"dark"}
claude mcp add --transport http web-search https://<gateway>/<tenant>/mcp/<mcp-server-name>/server
```

or add it to `.mcp.json`:

```json theme={"dark"}
{
  "mcpServers": {
    "web-search": {
      "type": "http",
      "url": "https://<gateway>/<tenant>/mcp/<mcp-server-name>/server"
    }
  }
}
```

Replace `<mcp-server-name>` with the slug of the web-search server you registered on the gateway (for example `tavily` or `exa`); the alias after `--transport http` (here `web-search`) is just the local name Claude Code uses. See [Connect an MCP server from your IDE / client](/docs/ai-gateway/mcp/connect-mcp-from-ide) for the "Sign in with TrueFoundry" OAuth flow and the gateway MCP URL format.

### Disabling web search

To turn off Claude Code's built-in web search — for example to block model-side web access, or to force search through an MCP server only — deny the `WebSearch` tool in `settings.json`:

```json theme={"dark"}
{
  "permissions": {
    "deny": ["WebSearch"]
  }
}
```

Add `"WebFetch"` to the same list if you also want to block Claude Code from fetching URLs. To enforce this across a fleet, put the same `permissions.deny` block in `managed-settings.json` — managed settings can't be overridden by user or project settings.

## FAQs

<AccordionGroup>
  <Accordion title="How do I use the 1M (1 million) context window variant?">
    Some Claude models (e.g. Opus and Sonnet) offer a **1 million token context window** variant. To use it in Claude Code, just append `[1m]` to the end of the model name in your `settings.json`:

    ```json theme={"dark"}
    {
      "env": {
        "ANTHROPIC_MODEL": "claude-code/claude-sonnet[1m]"
      }
    }
    ```

    You **do not** need to create a separate model with `[1m]` in its name on TrueFoundry. Claude Code handles the suffix internally — it strips `[1m]` before sending the request and still treats it as the 1M context variant, so the underlying model on the AI Gateway stays the same.
  </Accordion>

  <Accordion title="How do I use Claude Opus 4.6 Fast Mode with the AI Gateway?">
    Claude Opus 4.6 supports a **fast mode** that provides lower-latency responses. To use it through the TrueFoundry AI Gateway, you need to create a virtual model with the correct additional parameters and headers.

    **Step 1: Create a Virtual Model**

    Create a virtual model in TrueFoundry that routes all traffic to `claude-opus-4-6`. In the virtual model configuration, set it to forward requests to your underlying `claude-opus-4-6` model.

    <Frame>
      <img src="https://mintcdn.com/truefoundry/9Bc3RHdMcCcbhtTP/images/Screenshot-2026-04-20-at-4.55.12-PM-1.png?fit=max&auto=format&n=9Bc3RHdMcCcbhtTP&q=85&s=2ff2adb77a0164e2b3dd588c481275ee" alt="Screenshot 2026 04 20 At 4 55 12 PM 1" width="3596" height="2006" data-path="images/Screenshot-2026-04-20-at-4.55.12-PM-1.png" />
    </Frame>

    **Step 2: Add the `speed` parameter**

    In the virtual model's additional parameters, add the following field:

    ```json theme={"dark"}
    {
      "speed": "fast"
    }
    ```

    This ensures every request sent through this virtual model includes the `speed: fast` parameter.

    <Frame>
      <img src="https://mintcdn.com/truefoundry/9Bc3RHdMcCcbhtTP/images/Screenshot-2026-04-20-at-4.54.54-PM-1.png?fit=max&auto=format&n=9Bc3RHdMcCcbhtTP&q=85&s=c5c81fe9eb18004f424bcb0eb1d94d19" alt="Screenshot 2026 04 20 At 4 54 54 PM 1" width="3590" height="2012" data-path="images/Screenshot-2026-04-20-at-4.54.54-PM-1.png" />
    </Frame>

    **Step 3: Add the required beta header**

    Fast mode requires the `anthropic-beta` header with the value `fast-mode-2026-02-01`. Add this as an additional header in the virtual model configuration:

    ```text theme={"dark"}
    anthropic-beta: fast-mode-2026-02-01
    ```

    If the client also sends `x-tfy-anthropic-beta` (for example via `ANTHROPIC_CUSTOM_HEADERS`), a virtual-model `anthropic-beta` override will **not** replace it. Set `x-tfy-anthropic-beta` on the virtual model instead, and include every token you want sent (including `fast-mode-2026-02-01`).

    <Frame>
      <img src="https://mintcdn.com/truefoundry/9Bc3RHdMcCcbhtTP/images/Screenshot-2026-04-20-at-4.54.45-PM-1.png?fit=max&auto=format&n=9Bc3RHdMcCcbhtTP&q=85&s=e37c3157b8e906a0ad66da253575efdc" alt="Screenshot 2026 04 20 At 4 54 45 PM 1" width="3600" height="2006" data-path="images/Screenshot-2026-04-20-at-4.54.45-PM-1.png" />
    </Frame>

    **Step 4: Use the virtual model in Claude Code**

    Once the virtual model is created, use its model name in your `settings.json`. Replace the `ANTHROPIC_MODEL` and the relevant alias (e.g. `ANTHROPIC_DEFAULT_OPUS_MODEL`) with the virtual model name:

    ```json theme={"dark"}
    {
      "env": {
        "ANTHROPIC_BASE_URL": "{GATEWAY_BASE_URL}",
        "ANTHROPIC_AUTH_TOKEN": "your-truefoundry-api-key",
        "ANTHROPIC_MODEL": "your-fast-opus-virtual-model-name",
        "ANTHROPIC_DEFAULT_OPUS_MODEL": "your-fast-opus-virtual-model-name",
        "ANTHROPIC_DEFAULT_SONNET_MODEL": "your-sonnet-model-name",
        "ANTHROPIC_DEFAULT_HAIKU_MODEL": "your-haiku-model-name",
        "CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS": "1"
      }
    }
    ```

    When selecting a model in Claude Code (via `/model` or the `--model` flag), choose the virtual model name you configured above. All requests will automatically include the fast mode parameter and the required beta header.
  </Accordion>

  <Accordion title="How do I control Fast Mode on the Pro plan?">
    Users can enable fast mode in Claude Code — either per-request with `/fast` or globally in their config so all requests use fast mode. Since fast mode uses significantly more credits, you may want to control when it's used. Create two `virtual models` — one that disables fast mode and one that allows it — then hand out the appropriate model ID to users.

    **Virtual Model 1: Fast mode disabled (strip `speed`)**

    Create a virtual model that routes to `claude-opus-4-6` and configure it to delete the `speed` field from the request body. This ensures requests always go through as standard, non-fast requests — even if the user has fast mode enabled.

    <Frame>
      <img src="https://mintcdn.com/truefoundry/9Bc3RHdMcCcbhtTP/images/Screenshot-2026-04-20-at-5.27.02-PM.png?fit=max&auto=format&n=9Bc3RHdMcCcbhtTP&q=85&s=e1066571415c17ff996aff9a945c0f86" alt="Screenshot 2026 04 20 At 5 27 02 PM" width="3592" height="2004" data-path="images/Screenshot-2026-04-20-at-5.27.02-PM.png" />
    </Frame>

    **Virtual Model 2: Fast mode allowed**

    Create a second virtual model that routes to `claude-opus-4-6` with no additional parameters or headers. This model passes requests through as-is, so when a user enables fast mode, it will reach Anthropic.

    <Frame>
      <img src="https://mintcdn.com/truefoundry/9Bc3RHdMcCcbhtTP/images/Screenshot-2026-04-20-at-5.27.28-PM.png?fit=max&auto=format&n=9Bc3RHdMcCcbhtTP&q=85&s=61d0e8fa41240e87362f219f383baed1" alt="Screenshot 2026 04 20 At 5 27 28 PM" width="3596" height="1998" data-path="images/Screenshot-2026-04-20-at-5.27.28-PM.png" />
    </Frame>

    Then use the appropriate virtual model name in `settings.json`:

    ```json theme={"dark"}
    {
      "env": {
        "ANTHROPIC_BASE_URL": "{GATEWAY_BASE_URL}",
        "ANTHROPIC_AUTH_TOKEN": "your-truefoundry-api-key",
        "ANTHROPIC_MODEL": "your-virtual-model-name",
        "ANTHROPIC_DEFAULT_OPUS_MODEL": "your-virtual-model-name",
        "ANTHROPIC_DEFAULT_SONNET_MODEL": "your-sonnet-model-name",
        "ANTHROPIC_DEFAULT_HAIKU_MODEL": "your-haiku-model-name",
        "CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS": "1"
      }
    }
    ```
  </Accordion>

  <Accordion title="Can I run guardrails on Claude Code's prompts and tool calls?">
    Yes. Beyond model requests, you can guardrail Claude Code's **prompt submissions and tool calls** using Claude Code hooks that post to the AI Gateway's `POST /hooks/claude-code` endpoint. A violation blocks the prompt or tool call — or rewrites it — directly in the client. See [Guardrails using Claude Code Hooks](/docs/ai-gateway/claude-code-hooks) for setup, the validation-vs-mutation capability matrix, and caveats.
  </Accordion>
</AccordionGroup>
