---
title: Use your gateway's models and tools in Claude Code
summary: Point Claude Code at the Claude models that your gateway publishes from Microsoft Foundry, with a token limit and a daily budget for each caller, then give it Microsoft Learn tools from an MCP server on the same gateway, so every model and tool call uses your key, your limits, and your monitoring.
category: agents
level: Intermediate
duration: 40
tracks: [portal, cli, iac, terraform, code]
order: 17.6
status: new
illustration: diagrams/claude-code.svg
tags: [Claude Code, Anthropic, Claude, claude-opus-5-5, Anthropic Messages API, coding agents, MCP, MCP server, Microsoft Learn, token limit, cost limit]
objectives:
  - Publish Claude Opus 5.5, Sonnet 5.5, and Haiku 5.5 through the gateway, with a token limit for each caller and a daily budget on Opus
  - Point Claude Code at the gateway's Anthropic route with environment variables, without an Anthropic account
  - Run a one-shot prompt and an agent task in Claude Code on the gateway's models
  - Publish the Microsoft Learn MCP server through the gateway, and give Claude Code its tools with the same key
  - Hit the token limit and the budget from Claude Code, and switch it to another model
  - Track Claude Code's usage by key in Monitoring, and cut off access by suspending the key
prereqs:
  - 02-first-model-call
---

# Use your gateway's models and tools in Claude Code

Claude Code is Anthropic's coding agent for the terminal, and it can run on the Claude models in Microsoft Foundry.
Send its requests through your gateway, and Claude Code gets the same controls as your apps: a key that you can
suspend, a token limit and a budget for each caller, and usage in Monitoring. Developers don't need an Anthropic
account, and Claude Code never sees a Foundry credential, because the gateway calls Foundry with its managed
identity. In this lab you publish Claude Opus 5.5, Sonnet 5.5, and Haiku 5.5 for Claude Code, connect it with a few
environment variables, and give it Microsoft Learn tools from an MCP server on the same gateway. Then you run into
the token limit and the budget, and see how Claude Code reports them.

![Apps, agents, and coding agents such as Claude Code call Azure AI Gateway with a key or a Microsoft Entra ID token. The gateway applies access, aliases, MCP federation, token and cost limits, and observability, then calls the claude-opus-5-5, claude-sonnet-5-5, and claude-haiku-5-5 deployments in Microsoft Foundry with its managed identity, and the Microsoft Learn MCP server](../assets/diagrams/claude-code.svg "Claude Code sends every model call to the gateway's Anthropic route, with the key as a bearer token and an alias named after the Foundry account and deployment. The same key opens the learn MCP server. The gateway limits and records the traffic, then calls Foundry with its managed identity and Microsoft Learn without credentials.")

## Before you begin

<!-- setup: tools sign-in extension clone -->

- Complete [Publish a Foundry model and make your first call](../02-first-model-call/README.md). You need a gateway
  and permission to change it, for example **Contributor** on the resource group.
- A Foundry account with three Claude deployments, each named after its model: `claude-opus-5-5`,
  `claude-sonnet-5-5`, and `claude-haiku-5-5`. It can be the account behind lab 02's provider or another one. See
  [Deploy and use Claude models in Microsoft Foundry](https://learn.microsoft.com/azure/foundry/foundry-models/how-to/use-foundry-models-claude)
  for the regions and requirements. Model inference is billed per use.
- Permission to assign roles on that Foundry account, for example **Owner** or **User Access Administrator**. The
  gateway's managed identity needs the **Foundry User** role there to call the models.
- [Claude Code](https://code.claude.com/docs/en/setup). This lab was tested with version 2.1.326. You don't need an
  Anthropic account or a Claude subscription: Claude Code uses the gateway's key.
- `jq` for the Bash commands.

Set these variables once. Every track and the **Verify** section reuse them.

```bash title="Bash"
# Name your gateway, the Foundry account with the Claude deployments, and what this lab publishes on the gateway
export RG="<resource-group>"
export GATEWAY="<gateway>"
export FOUNDRY_RG="<foundry-resource-group>"      # resource group of the Foundry account with the Claude deployments
export FOUNDRY_ACCOUNT="<foundry-account-name>"   # the account name, not a project or deployment name
export PROVIDER="$FOUNDRY_ACCOUNT"                # the gateway's provider for the account, named after it
export KEY_NAME="claude-code"                     # the runtime key that Claude Code uses

# Read the gateway's resource ID and runtime URL
export GATEWAY_ID="$(az aigateway show -g "$RG" -n "$GATEWAY" --query id -o tsv)"
export AI_GATEWAY_URL="https://$(az aigateway show -g "$RG" -n "$GATEWAY" --query properties.frontend.defaultHostname -o tsv)"
echo "📝 Gateway $GATEWAY in $RG, with Foundry account $FOUNDRY_ACCOUNT in $FOUNDRY_RG"
echo "🌐 Runtime URL: $AI_GATEWAY_URL"
```

```powershell title="PowerShell"
# Name your gateway, the Foundry account with the Claude deployments, and what this lab publishes on the gateway
$RG              = "<resource-group>"
$GATEWAY         = "<gateway>"
$FOUNDRY_RG      = "<foundry-resource-group>"     # resource group of the Foundry account with the Claude deployments
$FOUNDRY_ACCOUNT = "<foundry-account-name>"       # the account name, not a project or deployment name
$PROVIDER        = $FOUNDRY_ACCOUNT               # the gateway's provider for the account, named after it
$KEY_NAME        = "claude-code"                  # the runtime key that Claude Code uses

# Read the gateway's resource ID and runtime URL
$GATEWAY_ID = az aigateway show -g $RG -n $GATEWAY --query id -o tsv
$env:AI_GATEWAY_URL = "https://$(az aigateway show -g $RG -n $GATEWAY --query properties.frontend.defaultHostname -o tsv)"
Write-Host "📝 Gateway $GATEWAY in $RG, with Foundry account $FOUNDRY_ACCOUNT in $FOUNDRY_RG"
Write-Host "🌐 Runtime URL: $env:AI_GATEWAY_URL"
```

Then create a small practice project with two deliberate problems: `add` subtracts, and `divide` doesn't guard against
zero. The **Connect Claude Code** section asks Claude Code to fix them. Create it outside any repository:

```bash title="Bash"
# Create the practice project's folder, and write calc.py with its two deliberate problems
mkdir -p ~/contoso-calc
cat > ~/contoso-calc/calc.py <<'EOF'
"""Tiny calculator used to try Claude Code with models from Azure AI Gateway."""


def add(a: float, b: float) -> float:
    return a - b


def divide(a: float, b: float) -> float:
    return a / b


if __name__ == "__main__":
    print(add(2, 3), divide(10, 2))
EOF
echo "📄 Practice project is ready: ~/contoso-calc/calc.py"
```

```powershell title="PowerShell"
# Create the practice project's folder, and write calc.py with its two deliberate problems
New-Item -ItemType Directory -Force -Path ~/contoso-calc | Out-Null
@'
"""Tiny calculator used to try Claude Code with models from Azure AI Gateway."""


def add(a: float, b: float) -> float:
    return a - b


def divide(a: float, b: float) -> float:
    return a / b


if __name__ == "__main__":
    print(add(2, 3), divide(10, 2))
'@ | Set-Content -Path ~/contoso-calc/calc.py
if ($?) { Write-Host "📄 Practice project is ready: ~/contoso-calc/calc.py" }
```

## How it works

Claude Code speaks Anthropic's Messages API, and the gateway serves that API for the Claude models in Foundry on its
Anthropic route, `/default/models/anthropic`. Point Claude Code at that route, and every model call goes through the
gateway. Claude Code still runs its agent loop on your machine: it reads files, edits them, and runs commands, and
only the model calls leave for the gateway. Five environment variables do it:

| Variable | Value | Why |
|---|---|---|
| `ANTHROPIC_BASE_URL` | `https://<gateway-host>/default/models/anthropic` | The gateway's Anthropic route. Claude Code adds `/v1/messages` itself, so leave out `/v1`. |
| `ANTHROPIC_AUTH_TOKEN` | The `claude-code` runtime key | Claude Code sends it as `Authorization: Bearer`, which the gateway accepts. Don't use `ANTHROPIC_API_KEY`: Claude Code sends that one in an `x-api-key` header, and the gateway rejects it with `401`. |
| `ANTHROPIC_DEFAULT_OPUS_MODEL` | `<foundry-account-name>/claude-opus-5-5` | The alias behind the `opus` tier, Claude Code's default model in this setup. |
| `ANTHROPIC_DEFAULT_SONNET_MODEL` | `<foundry-account-name>/claude-sonnet-5-5` | The alias behind the `sonnet` tier. |
| `ANTHROPIC_DEFAULT_HAIKU_MODEL` | `<foundry-account-name>/claude-haiku-5-5` | The alias behind the `haiku` tier, which Claude Code also uses for small background tasks. |

Claude Code picks a model by tier, so `--model sonnet` or `/model sonnet` switches it to the Sonnet alias. A model that
you saved with `/model`, or set in `ANTHROPIC_MODEL`, replaces the default, so the commands that need Opus pass
`--model opus`. The gateway gives each alias its own policies, and the **Identity** counter dimension gives each key its
own counters:

| Alias | Token limit for each caller | Cost limit for each caller |
|---|---|---|
| `<foundry-account-name>/claude-opus-5-5` | 100,000 tokens per minute | $5 per day |
| `<foundry-account-name>/claude-sonnet-5-5` | 100,000 tokens per minute | None |
| `<foundry-account-name>/claude-haiku-5-5` | 100,000 tokens per minute | None |

Opus is the default and the most expensive model, so it gets the budget. When a developer spends it, they can carry
on with Sonnet until the budget renews. Two things to know about the numbers:

- **Cached tokens barely count toward the token limit.** Claude Code sends its system prompt and tool definitions
  with every request, about 13,500 tokens, and caches them. In testing, cache reads barely counted toward the
  gateway's token limit, so even a 1,000 tokens-per-minute limit let short questions through. Output tokens are what
  fill it, which is why [Hit the limits](#hit-the-limits) asks for long stories.
- **Claude Code's cost is an estimate.** The `total_cost_usd` that Claude Code reports is its own estimate. The
  gateway's cost limit uses the gateway's meter, so the two don't match exactly.

## Publish your Claude models for Claude Code

Import the three Claude deployments into the gateway, publish an alias for each one with a token limit of 100,000
tokens per minute for each caller, add a daily budget of $5 for each caller to the Opus alias, and create the runtime
key `claude-code`. Pick a track.

<!-- track: portal | Portal -->

### Import the Claude deployments

1. Open the [AI Gateway portal](https://ai.gateway.azure.com) and select your gateway in the top bar.
2. Select **Models** › **Add** › **Models from Microsoft Foundry**.
3. In **Subscriptions** and **Resource groups**, select those of your Foundry account. Keep **Managed identity** as
   the **Authentication method**.
4. In **Models**, check that only your Foundry account is selected, with its `claude-opus-5-5`,
   `claude-sonnet-5-5`, and `claude-haiku-5-5` deployments: the page preselects every deployment it lists.
5. Under **Aliases**, keep **Create an alias for each model** selected, then select **Add models**. The page reports
   **Models and aliases imported.**

The import names each alias after the Foundry account and the deployment, for example
`<foundry-account-name>/claude-opus-5-5`. Claude Code sends these names in the request's `model` field.

### Add the token limit

1. Select **Policies** › **Add policy**. On the **Type** step, under **Cost and rate limits**, select
   **Token rate limit**, then **Next**.
2. On the **Scope** step, select **Individual assets**, select the three `<foundry-account-name>/claude-*-5-5` assets
   of type **Alias**, then **Next**.
3. On the **Details** step, set **Time period** to **Per minute** and **Allowed tokens** to `100000`. Keep
   **Counter dimensions** at **Identity**, so that each key gets its own counter. Select **Create**.

### Add the daily budget to Opus

1. Select **Policies** › **Add policy**. On the **Type** step, under **Cost and rate limits**, select **Cost limit**,
   then **Next**.
2. On the **Scope** step, select **Individual assets**, select the `<foundry-account-name>/claude-opus-5-5` asset of
   type **Alias**, then **Next**.
3. On the **Details** step, under **Parameters**, set **Budget amount** to `5` and **Renewal period** to **Daily**.
   Keep **Counter dimensions** at **Identity**. Select **Next**.
4. Skip the **Overrides** step, and select **Create**.

[Set a cost budget with cost limits](../07-cost-budgets/README.md) explains the budget's fields and overrides.

### Create the key for Claude Code

1. Select **Access** › **API keys** › **Create API key**.
2. In **Key name**, enter `claude-code` and select **Create**.
3. Copy the value from **API key created successfully**, for example with **Copy & done**, and paste it into your
   shell without echoing it:

```bash title="Bash"
# Paste the key without showing it, and export it for the test calls and Claude Code
printf "AI Gateway API key: " && read -rs AI_GATEWAY_API_KEY && export AI_GATEWAY_API_KEY && echo
echo "🔑 Key: in AI_GATEWAY_API_KEY (${#AI_GATEWAY_API_KEY} characters, not shown)"
```

```powershell title="PowerShell"
# Paste the key without showing it, and keep it in an environment variable for the test calls and Claude Code
$env:AI_GATEWAY_API_KEY = Read-Host "AI Gateway API key" -MaskInput
Write-Host "🔑 Key: in AI_GATEWAY_API_KEY ($($env:AI_GATEWAY_API_KEY.Length) characters, not shown)"
```

> **Checkpoint**
> **Models** › **Aliases** lists the three `<foundry-account-name>/claude-*-5-5` aliases, **Policies** lists a
> **Token rate limit** of 100,000 tokens per minute and a **Cost limit** of $5 per day, and **Access** › **API keys**
> lists `claude-code`.

<!-- track: cli | Azure CLI -->

### Import the Claude deployments

`az aigateway model-provider import --foundry-resource-id` imports the account's deployments as the models of a
provider. It also turns on the gateway's managed identity and grants it the **Foundry User** role on the account. It
doesn't create aliases. The command needs the `aigateway` extension 1.0.0b30 or later: if the `extensionVersion` that
`az aigateway version` prints is older, [run the installer again](../SETUP.md#install-the-aigateway-extension).

```bash title="Bash"
# Read the Foundry account's resource ID
export FOUNDRY_ID="$(az cognitiveservices account show -g "$FOUNDRY_RG" -n "$FOUNDRY_ACCOUNT" --query id -o tsv)"
echo "🆔 Foundry account: $FOUNDRY_ID"

# Import the account's deployments as a provider named after the account, and list its models
echo "🏭 Models in provider $PROVIDER:"
az aigateway model-provider import -g "$RG" --gateway-name "$GATEWAY" --name "$PROVIDER" \
  --foundry-resource-id "$FOUNDRY_ID" --query "join(', ', models[].name)" -o tsv
```

```powershell title="PowerShell"
# Read the Foundry account's resource ID
$FOUNDRY_ID = az cognitiveservices account show -g $FOUNDRY_RG -n $FOUNDRY_ACCOUNT --query id -o tsv
Write-Host "🆔 Foundry account: $FOUNDRY_ID"

# Import the account's deployments as a provider named after the account, and list its models
Write-Host "🏭 Models in provider ${PROVIDER}:"
az aigateway model-provider import -g $RG --gateway-name $GATEWAY --name $PROVIDER `
  --foundry-resource-id $FOUNDRY_ID --query "join(', ', models[].name)" -o tsv
```

Expected output (the order can differ, and other deployments in the account are listed too):

```text
🆔 Foundry account: /subscriptions/<subscription-id>/resourceGroups/<foundry-resource-group>/providers/Microsoft.CognitiveServices/accounts/<foundry-account-name>
🏭 Models in provider <foundry-account-name>:
claude-opus-5-5, claude-haiku-5-5, claude-sonnet-5-5
```

### Publish an alias for each model

Name each alias like the portal's import does, `<foundry-account-name>/<deployment>`, with `--routing-name`. Resource
names can't contain `/`, so `-n` uses `-` instead. Each alias gets a token limit of 100,000 tokens per minute for each
caller.

```bash title="Bash"
# Publish (or update) an alias for each Claude model, with 100,000 tokens per minute for each caller
for m in claude-opus-5-5 claude-sonnet-5-5 claude-haiku-5-5; do
  az aigateway model-alias set -g "$RG" --gateway-name "$GATEWAY" -n "$FOUNDRY_ACCOUNT-$m" \
    --routing-name "$FOUNDRY_ACCOUNT/$m" \
    --backend-model resource-id="$GATEWAY_ID/workspaces/default/modelProviders/$PROVIDER/models/$m" \
    --policies '[{"type": "tokenLimit", "count": 100000, "period": "minute", "counterKey": ["identity"]}]' \
    --only-show-errors -o none &&
    echo "🔖 Alias $FOUNDRY_ACCOUNT/$m: 100,000 tokens per minute for each caller"
done
```

```powershell title="PowerShell"
# Write the token limit to a file: 100,000 tokens per minute for each caller
ConvertTo-Json -Depth 5 -Compress -InputObject @(
  @{ type = 'tokenLimit'; count = 100000; period = 'minute'; counterKey = @('identity') }
) | Set-Content -Path policies.json

# Publish (or update) an alias for each Claude model with that token limit, then remove the file
foreach ($m in 'claude-opus-5-5', 'claude-sonnet-5-5', 'claude-haiku-5-5') {
  az aigateway model-alias set -g $RG --gateway-name $GATEWAY -n "$FOUNDRY_ACCOUNT-$m" `
    --routing-name "$FOUNDRY_ACCOUNT/$m" `
    --backend-model resource-id="$GATEWAY_ID/workspaces/default/modelProviders/$PROVIDER/models/$m" `
    --policies "@policies.json" --only-show-errors -o none
  if ($?) { Write-Host "🔖 Alias $FOUNDRY_ACCOUNT/${m}: 100,000 tokens per minute for each caller" }
}
Remove-Item policies.json
```

### Add the daily budget to Opus

`--policies` replaces the alias's whole list of policies, so give the Opus alias both: the token limit, and a cost
limit of $5 per day for each caller. The cost limit's `id` names its counter.

```bash title="Bash"
# Give the Opus alias the token limit and a daily budget of $5 for each caller, and show its policies
echo "🔐 Policies on $FOUNDRY_ACCOUNT/claude-opus-5-5:"
az aigateway model-alias update -g "$RG" --gateway-name "$GATEWAY" -n "$FOUNDRY_ACCOUNT-claude-opus-5-5" \
  --policies '[{"type": "tokenLimit", "count": 100000, "period": "minute", "counterKey": ["identity"]},
               {"type": "costLimit", "id": "claude-code-budget", "amount": 5, "period": "day",
                "counterKey": ["identity"]}]' \
  --query "properties.policies[].{policy:type, count:count, amount:amount, period:period}" -o table
```

```powershell title="PowerShell"
# Write both policies to a file: the token limit, and a daily budget of $5 for each caller
ConvertTo-Json -Depth 5 -Compress -InputObject @(
  @{ type = 'tokenLimit'; count = 100000; period = 'minute'; counterKey = @('identity') }
  @{ type = 'costLimit'; id = 'claude-code-budget'; amount = 5; period = 'day'; counterKey = @('identity') }
) | Set-Content -Path policies.json

# Give the Opus alias both policies, show them, then remove the file
Write-Host "🔐 Policies on $FOUNDRY_ACCOUNT/claude-opus-5-5:"
az aigateway model-alias update -g $RG --gateway-name $GATEWAY -n "$FOUNDRY_ACCOUNT-claude-opus-5-5" `
  --policies "@policies.json" `
  --query "properties.policies[].{policy:type, count:count, amount:amount, period:period}" -o table
Remove-Item policies.json
```

Expected output:

```text
🔐 Policies on <foundry-account-name>/claude-opus-5-5:
Policy      Count    Period    Amount
----------  -------  --------  --------
tokenLimit  100000   minute
costLimit            day       5.0
```

### Create the key for Claude Code

`api-key create` returns metadata only. Read the value with `list-secrets` straight into a variable, so it never
appears on screen.

```bash title="Bash"
# Create the runtime key that Claude Code uses, and show its state
echo "🔑 API key claude-code and its state:"
az aigateway api-key create -g "$RG" --gateway-name "$GATEWAY" -n "$KEY_NAME" \
  --query "{name:name, state:properties.state}"

# Read the key's value straight into a variable, so that it never shows on screen
AI_GATEWAY_API_KEY="$(az aigateway api-key list-secrets -g "$RG" --gateway-name "$GATEWAY" -n "$KEY_NAME" \
  --query primaryKey -o tsv)" && export AI_GATEWAY_API_KEY
echo "🔑 Key: in AI_GATEWAY_API_KEY (${#AI_GATEWAY_API_KEY} characters, not shown)"
```

```powershell title="PowerShell"
# Create the runtime key that Claude Code uses, and show its state
Write-Host "🔑 API key claude-code and its state:"
az aigateway api-key create -g $RG --gateway-name $GATEWAY -n $KEY_NAME `
  --query "{name:name, state:properties.state}"

# Read the key's value straight into an environment variable, so that it never shows on screen
$env:AI_GATEWAY_API_KEY = az aigateway api-key list-secrets -g $RG --gateway-name $GATEWAY -n $KEY_NAME `
  --query primaryKey -o tsv
Write-Host "🔑 Key: in AI_GATEWAY_API_KEY ($($env:AI_GATEWAY_API_KEY.Length) characters, not shown)"
```

> **Checkpoint**
> The provider lists the three Claude models, each alias printed `🔖`, the Opus alias shows a `tokenLimit` and a
> `costLimit`, and the key output shows `claude-code` as `active`.

<!-- track: iac | Bicep -->

**What you need:** your gateway from lab 02 and the variables from **Before you begin**. This track deploys onto
that gateway.

### Review the template

[`infra/claude-code.bicep`](infra/claude-code.bicep) references your gateway and the Foundry account. It grants the
gateway's managed identity the **Foundry User** role on the account, with lab 02's `foundry-user-role.bicep`, and
declares the provider, the three models, the three aliases with their policies, and the `claude-code` key. It names
the provider and the aliases like the portal's import, so the rest of the lab is the same on every track. If the
gateway already has the provider, `createProvider=false` keeps it as it is, with its authentication, and the template
only adds the models to it. If these aliases already exist, the deployment replaces their backends, routing and
policies with the template's.

<!-- include: infra/claude-code.bicep -->

### Deploy the template

Run the commands from the lab folder, `aigateway/labs/25-claude-code`. If the gateway's identity already has the
**Foundry User** role on the account, for example from an import in the portal, the commands tell the template to
skip the grant: a second assignment of the same role fails with `RoleAssignmentExists`. If the gateway already has the
provider, they tell the template to keep it, so that its settings, such as its authentication, don't change.

```bash title="Bash"
# Read the Foundry account's resource ID
export FOUNDRY_ID="$(az cognitiveservices account show -g "$FOUNDRY_RG" -n "$FOUNDRY_ACCOUNT" --query id -o tsv)"
echo "🆔 Foundry account: ${FOUNDRY_ID##*/}"

# Grant the gateway's identity Foundry User on the account only if it doesn't have the role there yet
PRINCIPAL_ID="$(az aigateway show -g "$RG" -n "$GATEWAY" --query identity.principalId -o tsv)"
ROLES="$(az role assignment list --assignee "$PRINCIPAL_ID" --scope "$FOUNDRY_ID" \
  --role 53ca6127-db72-4b80-b1b0-d745d6d5456d --query "length(@)" -o tsv)"
GRANT="$([ "$ROLES" = "0" ] && echo true || echo false)"
echo "🔐 Foundry User assignments: $ROLES, grantFoundryUser=$GRANT"

# Create the provider only if the gateway doesn't have it yet
PROVIDERS="$(az aigateway model-provider list -g "$RG" --gateway-name "$GATEWAY" \
  --query "length([?name=='$PROVIDER'])" -o tsv --only-show-errors)"
CREATE="$([ "$PROVIDERS" = "0" ] && echo true || echo false)"
echo "🏭 Providers named $PROVIDER: $PROVIDERS, createProvider=$CREATE"

# Deploy the template onto your gateway, and print the aliases that it published
echo "🚀 Aliases for Claude Code:"
az deployment group create -g "$RG" -n claude-code -f infra/claude-code.bicep \
  -p gatewayName="$GATEWAY" foundryAccountId="$FOUNDRY_ID" grantFoundryUser="$GRANT" createProvider="$CREATE" \
  --query "properties.outputs.aliasNames.value" -o tsv
```

```powershell title="PowerShell"
# Read the Foundry account's resource ID
$FOUNDRY_ID = az cognitiveservices account show -g $FOUNDRY_RG -n $FOUNDRY_ACCOUNT --query id -o tsv
Write-Host "🆔 Foundry account: $(Split-Path $FOUNDRY_ID -Leaf)"

# Grant the gateway's identity Foundry User on the account only if it doesn't have the role there yet
$PRINCIPAL_ID = az aigateway show -g $RG -n $GATEWAY --query identity.principalId -o tsv
$ROLES = az role assignment list --assignee $PRINCIPAL_ID --scope $FOUNDRY_ID `
  --role 53ca6127-db72-4b80-b1b0-d745d6d5456d --query "length(@)" -o tsv
$GRANT = if ($ROLES -eq "0") { "true" } else { "false" }
Write-Host "🔐 Foundry User assignments: $ROLES, grantFoundryUser=$GRANT"

# Create the provider only if the gateway doesn't have it yet
$PROVIDERS = az aigateway model-provider list -g $RG --gateway-name $GATEWAY `
  --query "length([?name=='$PROVIDER'])" -o tsv --only-show-errors
$CREATE = if ($PROVIDERS -eq "0") { "true" } else { "false" }
Write-Host "🏭 Providers named ${PROVIDER}: $PROVIDERS, createProvider=$CREATE"

# Deploy the template onto your gateway, and print the aliases that it published
Write-Host "🚀 Aliases for Claude Code:"
az deployment group create -g $RG -n claude-code -f infra/claude-code.bicep `
  -p gatewayName=$GATEWAY foundryAccountId=$FOUNDRY_ID grantFoundryUser=$GRANT createProvider=$CREATE `
  --query "properties.outputs.aliasNames.value" -o tsv
```

Expected output, after about a minute:

```text
🆔 Foundry account: <foundry-account-name>
🔐 Foundry User assignments: 0, grantFoundryUser=true
🏭 Providers named <foundry-account-name>: 0, createProvider=true
🚀 Aliases for Claude Code:
<foundry-account-name>/claude-opus-5-5
<foundry-account-name>/claude-sonnet-5-5
<foundry-account-name>/claude-haiku-5-5
```

> [!WARNING]
> Deploying the template again sets the aliases' policies back to the template's values, including changes that you
> made in the portal or with the Azure CLI.

### Read the key

The template creates the key but never outputs it. Read it straight into a variable:

```bash title="Bash"
# Read the claude-code key's value straight into a variable, so that it never shows on screen
AI_GATEWAY_API_KEY="$(az aigateway api-key list-secrets -g "$RG" --gateway-name "$GATEWAY" -n "$KEY_NAME" \
  --query primaryKey -o tsv)" && export AI_GATEWAY_API_KEY
echo "🔑 Key: in AI_GATEWAY_API_KEY (${#AI_GATEWAY_API_KEY} characters, not shown)"
```

```powershell title="PowerShell"
# Read the claude-code key's value straight into an environment variable, so that it never shows on screen
$env:AI_GATEWAY_API_KEY = az aigateway api-key list-secrets -g $RG --gateway-name $GATEWAY -n $KEY_NAME `
  --query primaryKey -o tsv
Write-Host "🔑 Key: in AI_GATEWAY_API_KEY ($($env:AI_GATEWAY_API_KEY.Length) characters, not shown)"
```

> **Checkpoint**
> The deployment printed the three aliases, and the last command printed the key's length. In the portal,
> **Models** › **Aliases** lists the three `<foundry-account-name>/claude-*-5-5` aliases.

<!-- track: terraform | Terraform -->

**What you need:** your gateway from lab 02 and the variables from **Before you begin**, plus Terraform 1.9 or later,
as in [Deploy a lab with Terraform](../SETUP.md#deploy-a-lab-with-terraform). Like the Bicep track, this track
deploys onto that gateway: it creates no resource group, and `terraform destroy` removes only what it added.

### Review the configuration

`terraform/main.tf` reads your gateway, the Foundry account, and its three Claude deployments with the `azapi`
provider. It reads the account by resource ID, so the account can be in another resource group or subscription. Then
it grants the gateway's managed identity the **Foundry User** role on the account, unless `grant_foundry_user` is
`false`:

<!-- include: terraform/main.tf -->

`terraform/claude-models.tf` declares the provider, the three models, the three aliases with their policies, and the
`claude-code` key, with the same names as the Bicep template, so the rest of the lab is the same on every track.
`create_provider = false` keeps a provider that the gateway already has, with its authentication, and adds only the
models to it. `terraform/variables.tf` declares the settings with the same defaults as the template: 100,000 tokens
per minute for each caller on every alias, and a budget of $5 a day on Opus.

<!-- include: terraform/claude-models.tf -->

### Deploy with terraform apply

Move into the lab's Terraform folder and point Terraform at your gateway and the Foundry account. Like the Bicep
track, the commands check the role and the provider first: a second assignment of the **Foundry User** role fails
with `RoleAssignmentExists`, and an existing provider keeps its settings. They also keep what Terraform already
manages in this folder, so that you can run them again without removing the role or the provider that Terraform
created. Then plan and apply the configuration. It takes less than a minute.

```bash title="Bash"
# Move into the lab's Terraform folder
cd ~/aigateway/labs/25-claude-code/terraform &&
  echo "📂 Terraform folder: $(pwd)"

# Deploy to the Azure CLI's current subscription, onto your gateway, with the Foundry account's deployments
export ARM_SUBSCRIPTION_ID="$(az account show --query id --output tsv)"
export TF_VAR_resource_group_name="$RG" TF_VAR_gateway_name="$GATEWAY"
export TF_VAR_foundry_account_id="$(az cognitiveservices account show -g "$FOUNDRY_RG" -n "$FOUNDRY_ACCOUNT" \
  --query id -o tsv)"
echo "🆔 Foundry account: ${TF_VAR_foundry_account_id##*/}"

# List what Terraform already manages in this folder: the checks below keep it
MANAGED="$(terraform state list 2>/dev/null)"

# Grant the gateway's identity Foundry User on the account only if it doesn't have the role there yet
PRINCIPAL_ID="$(az aigateway show -g "$RG" -n "$GATEWAY" --query identity.principalId -o tsv)"
ROLES="$(az role assignment list --assignee "$PRINCIPAL_ID" --scope "$TF_VAR_foundry_account_id" \
  --role 53ca6127-db72-4b80-b1b0-d745d6d5456d --query "length(@)" -o tsv)"
export TF_VAR_grant_foundry_user="$( { [ "$ROLES" = "0" ] || grep -q '^azurerm_role_assignment' <<<"$MANAGED"; } &&
  echo true || echo false)"
echo "🔐 Foundry User assignments: $ROLES, grant_foundry_user=$TF_VAR_grant_foundry_user"

# Create the provider only if the gateway doesn't have it yet
PROVIDERS="$(az aigateway model-provider list -g "$RG" --gateway-name "$GATEWAY" \
  --query "length([?name=='$PROVIDER'])" -o tsv --only-show-errors)"
export TF_VAR_create_provider="$( { [ "$PROVIDERS" = "0" ] || grep -q '^azapi_resource.provider' <<<"$MANAGED"; } &&
  echo true || echo false)"
echo "🏭 Providers named $PROVIDER: $PROVIDERS, create_provider=$TF_VAR_create_provider"

# Download the providers, plan and apply the configuration, and print the aliases that it published
terraform init &&
  terraform plan -out tfplan &&
  terraform apply tfplan &&
  echo "🚀 Aliases for Claude Code:" &&
  terraform output -json alias_names | jq -r '.[]'
```

```powershell title="PowerShell"
# Move into the lab's Terraform folder
Set-Location ~/aigateway/labs/25-claude-code/terraform
if ($?) { Write-Host "📂 Terraform folder: $(Get-Location)" }

# Deploy to the Azure CLI's current subscription, onto your gateway, with the Foundry account's deployments
$env:ARM_SUBSCRIPTION_ID     = az account show --query id --output tsv
$env:TF_VAR_resource_group_name = $RG
$env:TF_VAR_gateway_name        = $GATEWAY
$env:TF_VAR_foundry_account_id  = az cognitiveservices account show -g $FOUNDRY_RG -n $FOUNDRY_ACCOUNT --query id -o tsv
Write-Host "🆔 Foundry account: $(Split-Path $env:TF_VAR_foundry_account_id -Leaf)"

# List what Terraform already manages in this folder: the checks below keep it
$MANAGED = terraform state list 2>$null

# Grant the gateway's identity Foundry User on the account only if it doesn't have the role there yet
$PRINCIPAL_ID = az aigateway show -g $RG -n $GATEWAY --query identity.principalId -o tsv
$ROLES = az role assignment list --assignee $PRINCIPAL_ID --scope $env:TF_VAR_foundry_account_id `
  --role 53ca6127-db72-4b80-b1b0-d745d6d5456d --query "length(@)" -o tsv
$env:TF_VAR_grant_foundry_user =
  if ($ROLES -eq "0" -or ($MANAGED -match '^azurerm_role_assignment')) { "true" } else { "false" }
Write-Host "🔐 Foundry User assignments: $ROLES, grant_foundry_user=$env:TF_VAR_grant_foundry_user"

# Create the provider only if the gateway doesn't have it yet
$PROVIDERS = az aigateway model-provider list -g $RG --gateway-name $GATEWAY `
  --query "length([?name=='$PROVIDER'])" -o tsv --only-show-errors
$env:TF_VAR_create_provider =
  if ($PROVIDERS -eq "0" -or ($MANAGED -match '^azapi_resource.provider')) { "true" } else { "false" }
Write-Host "🏭 Providers named ${PROVIDER}: $PROVIDERS, create_provider=$env:TF_VAR_create_provider"

# Download the providers, plan and apply the configuration, and print the aliases that it published
terraform init
if ($?) { terraform plan -out tfplan }
if ($?) { terraform apply tfplan }
if ($?) { Write-Host "🚀 Aliases for Claude Code:"; terraform output -json alias_names | ConvertFrom-Json }
```

Expected output, between Terraform's own messages:

```text
📂 Terraform folder: /home/<user>/aigateway/labs/25-claude-code/terraform
🆔 Foundry account: <foundry-account-name>
🔐 Foundry User assignments: 0, grant_foundry_user=true
🏭 Providers named <foundry-account-name>: 0, create_provider=true
🚀 Aliases for Claude Code:
<foundry-account-name>/claude-opus-5-5
<foundry-account-name>/claude-sonnet-5-5
<foundry-account-name>/claude-haiku-5-5
```

The limits are Terraform variables, with the defaults in `terraform/variables.tf`. To change one, pass it to
`terraform plan`, for example `-var budget_amount=10`, and apply the plan: only the Opus alias changes.

> [!WARNING]
> Applying the configuration again sets the aliases' policies back to its values, including changes that you made in
> the portal or with the Azure CLI. If the models, the aliases, or the key already exist, for example from the portal's
> import or the Bicep track, `terraform apply` stops with `Error: Resource already exists`: Terraform doesn't take
> over resources that it didn't create. Delete them first with the Azure CLI track's commands in **Clean up**.

### Read the key

The configuration creates the key but never outputs it, so it stays out of the Terraform state. Read it from the
gateway straight into a variable:

```bash title="Bash"
# Read the claude-code key's value straight into a variable, so that it never shows on screen
AI_GATEWAY_API_KEY="$(az aigateway api-key list-secrets \
  --ids "$(terraform output -raw ai_gateway_id)/apiKeys/$(terraform output -raw api_key_name)" \
  --query primaryKey -o tsv)" && export AI_GATEWAY_API_KEY
echo "🔑 Key: in AI_GATEWAY_API_KEY (${#AI_GATEWAY_API_KEY} characters, not shown)"
```

```powershell title="PowerShell"
# Read the claude-code key's value straight into an environment variable, so that it never shows on screen
$env:AI_GATEWAY_API_KEY = az aigateway api-key list-secrets `
  --ids "$(terraform output -raw ai_gateway_id)/apiKeys/$(terraform output -raw api_key_name)" `
  --query primaryKey -o tsv
Write-Host "🔑 Key: in AI_GATEWAY_API_KEY ($($env:AI_GATEWAY_API_KEY.Length) characters, not shown)"
```

> **Checkpoint**
> `terraform apply` ended with `Apply complete! Resources: 9 added, 0 changed, 0 destroyed.` (7 when the checks set
> both `grant_foundry_user` and `create_provider` to `false`), the commands printed the three aliases, and the last
> command printed the key's length. In the portal, **Models** › **Aliases** lists the three
> `<foundry-account-name>/claude-*-5-5` aliases.

<!-- /tracks -->

<!-- steps -->

### Test the endpoint

Before you configure Claude Code, call the Opus alias the way Claude Code does: the Messages API, with the key as a
bearer token and the `anthropic-version` header.

```bash title="Bash"
# Call the Opus alias the way Claude Code does: the Messages API, with the key as a bearer token
curl -sS "${AI_GATEWAY_URL%/}/default/models/anthropic/v1/messages" \
  -H "Authorization: Bearer $AI_GATEWAY_API_KEY" \
  -H "anthropic-version: 2023-06-01" \
  -H "Content-Type: application/json" \
  -d "{\"model\": \"$FOUNDRY_ACCOUNT/claude-opus-5-5\", \"max_tokens\": 256,
       \"messages\": [{\"role\": \"user\", \"content\": \"In one sentence, what does a coding agent do?\"}]}" \
  | jq -r 'if .content then
             "✨ Backend model: \(.model)",
             "🤖 \([.content[] | select(.type == "text") | .text] | join(""))",
             "📊 Tokens: \(.usage.input_tokens) in, \(.usage.output_tokens) out"
           else "🚨 \(.error.message // .message // .)" end'
```

```powershell title="PowerShell"
# Build the request: the key as a bearer token, the Messages API version, and the Opus alias in model
$headers = @{ Authorization = "Bearer $env:AI_GATEWAY_API_KEY"; 'anthropic-version' = '2023-06-01' }
$body = @{
  model      = "$FOUNDRY_ACCOUNT/claude-opus-5-5"
  max_tokens = 256
  messages   = @(@{ role = 'user'; content = 'In one sentence, what does a coding agent do?' })
} | ConvertTo-Json -Depth 5

# Call the Opus alias the way Claude Code does, and print the backend model, the reply, and the tokens
$r = Invoke-RestMethod -Method Post -Uri "$($env:AI_GATEWAY_URL.TrimEnd('/'))/default/models/anthropic/v1/messages" `
  -Headers $headers -ContentType 'application/json' -Body $body
if ($?) {
  Write-Host "✨ Backend model: $($r.model)"
  Write-Host "🤖 $((@($r.content) | Where-Object type -eq 'text' | ForEach-Object text) -join '')"
  Write-Host "📊 Tokens: $($r.usage.input_tokens) in, $($r.usage.output_tokens) out"
}
```

Expected output (your text differs):

```text
✨ Backend model: claude-opus-5-5
🤖 A coding agent is an AI system that autonomously writes, runs, tests, and debugs code, using tools like a terminal, file editor, and documentation to complete programming tasks with minimal human guidance.
📊 Tokens: 23 in, 66 out
```

The gateway reads the key from the `Authorization: Bearer` header. In an `x-api-key` header, it gets `401`. Leave
out `anthropic-version`, and the call fails with `anthropic-version: header is required`. Claude Code sends that
header for you.

> [!NOTE]
> A new alias, policy, or key can take a minute to apply. If the call returns `401` or `404`, wait a minute and try
> again.

<!-- /steps -->

## Connect Claude Code

Claude Code reads its endpoint, key, and models from environment variables, so you can switch between the gateway
and other providers per terminal.

<!-- steps -->

### Point Claude Code at the gateway

```bash title="Bash"
# Clear any Anthropic API key: Claude Code would send it in x-api-key, which the gateway rejects
unset ANTHROPIC_API_KEY

# Point Claude Code at the gateway's Anthropic route, and give it the claude-code key as a bearer token
export ANTHROPIC_BASE_URL="${AI_GATEWAY_URL%/}/default/models/anthropic"
export ANTHROPIC_AUTH_TOKEN="$AI_GATEWAY_API_KEY"

# Map Claude Code's three model tiers to the gateway's aliases
export ANTHROPIC_DEFAULT_OPUS_MODEL="$FOUNDRY_ACCOUNT/claude-opus-5-5"
export ANTHROPIC_DEFAULT_SONNET_MODEL="$FOUNDRY_ACCOUNT/claude-sonnet-5-5"
export ANTHROPIC_DEFAULT_HAIKU_MODEL="$FOUNDRY_ACCOUNT/claude-haiku-5-5"
echo "🌐 Base URL: $ANTHROPIC_BASE_URL"
echo "🔖 Opus: $ANTHROPIC_DEFAULT_OPUS_MODEL"
echo "🔖 Sonnet: $ANTHROPIC_DEFAULT_SONNET_MODEL"
echo "🔖 Haiku: $ANTHROPIC_DEFAULT_HAIKU_MODEL"
echo "🔑 Key: in ANTHROPIC_AUTH_TOKEN (${#ANTHROPIC_AUTH_TOKEN} characters, not shown)"

# Check the Claude Code version
claude --version
```

```powershell title="PowerShell"
# Clear any Anthropic API key: Claude Code would send it in x-api-key, which the gateway rejects
Remove-Item Env:ANTHROPIC_API_KEY -ErrorAction SilentlyContinue

# Point Claude Code at the gateway's Anthropic route, and give it the claude-code key as a bearer token
$env:ANTHROPIC_BASE_URL   = "$($env:AI_GATEWAY_URL.TrimEnd('/'))/default/models/anthropic"
$env:ANTHROPIC_AUTH_TOKEN = $env:AI_GATEWAY_API_KEY

# Map Claude Code's three model tiers to the gateway's aliases
$env:ANTHROPIC_DEFAULT_OPUS_MODEL   = "$FOUNDRY_ACCOUNT/claude-opus-5-5"
$env:ANTHROPIC_DEFAULT_SONNET_MODEL = "$FOUNDRY_ACCOUNT/claude-sonnet-5-5"
$env:ANTHROPIC_DEFAULT_HAIKU_MODEL  = "$FOUNDRY_ACCOUNT/claude-haiku-5-5"
Write-Host "🌐 Base URL: $env:ANTHROPIC_BASE_URL"
Write-Host "🔖 Opus: $env:ANTHROPIC_DEFAULT_OPUS_MODEL"
Write-Host "🔖 Sonnet: $env:ANTHROPIC_DEFAULT_SONNET_MODEL"
Write-Host "🔖 Haiku: $env:ANTHROPIC_DEFAULT_HAIKU_MODEL"
Write-Host "🔑 Key: in ANTHROPIC_AUTH_TOKEN ($($env:ANTHROPIC_AUTH_TOKEN.Length) characters, not shown)"

# Check the Claude Code version
claude --version
```

Expected output:

```text
🌐 Base URL: https://<gateway-host>/default/models/anthropic
🔖 Opus: <foundry-account-name>/claude-opus-5-5
🔖 Sonnet: <foundry-account-name>/claude-sonnet-5-5
🔖 Haiku: <foundry-account-name>/claude-haiku-5-5
🔑 Key: in ANTHROPIC_AUTH_TOKEN (32 characters, not shown)
2.1.326 (Claude Code)
```

These variables last for the current terminal. [Go further](#go-further) shows how to keep them in Claude Code's
settings.

### Ask a quick question

`claude -p` runs one prompt and exits, and `--output-format json` returns the result with the models that Claude Code
used and its cost estimate:

```bash title="Bash"
# Move into the practice project
cd ~/contoso-calc &&
  echo "📂 Practice project: ~/contoso-calc"

# Run one prompt on Opus, and print the reply, the alias that answered, and the cost estimate
echo "🤖 Claude Code answer:"
claude -p "Reply with the single word pong" --model opus --output-format json \
  | jq -r 'if .is_error then "🚨 \(.result)"
           else "✅ \(.result) · \(.modelUsage | keys | join(", ")) · $\(.total_cost_usd * 10000 | round / 10000)" end'
```

```powershell title="PowerShell"
# Move into the practice project
Set-Location ~/contoso-calc
if ($?) { Write-Host "📂 Practice project: ~/contoso-calc" }

# Run one prompt on Opus, and print the reply, the alias that answered, and the cost estimate
Write-Host "🤖 Claude Code answer:"
$run = claude -p "Reply with the single word pong" --model opus --output-format json | ConvertFrom-Json
if ($run.is_error) { Write-Host "🚨 $($run.result)" }
else {
  $models = $run.modelUsage.PSObject.Properties.Name -join ', '
  Write-Host "✅ $($run.result) · $models · `$$([math]::Round($run.total_cost_usd, 4))"
}
```

Expected output (your cost differs):

```text
📂 Practice project: ~/contoso-calc
🤖 Claude Code answer:
✅ pong · <foundry-account-name>/claude-opus-5-5 · $0.0821
```

The alias in the output proves that the call went through the gateway. The cost estimate varies from run to run,
even for the same prompt: on Opus, it ranged from $0.003 to $0.08 in testing. Add `--model sonnet` or `--model haiku`
to ask another tier.

### Run an agent task

Start an interactive session in the practice project:

```bash
# Start an interactive Claude Code session in the practice project, on the gateway's models
cd ~/contoso-calc && echo "🚀 Starting Claude Code in ~/contoso-calc (type /exit to leave)"
claude
```

The first time, Claude Code asks you to pick a theme and shows its security notes. Then it asks whether you trust the
folder: select **Yes, I trust this folder**. The banner shows `Claude Code v2.1.326` and
`Opus 5.5 · API Usage Billing`. Claude Code runs on the gateway's Opus alias, and it doesn't ask you to sign in.

Type `/status` to see where the requests go. It shows `ANTHROPIC_AUTH_TOKEN` as the auth token, the gateway's
Anthropic route as the Anthropic base URL, and `Default (<foundry-account-name>/claude-opus-5-5)` as the model.

Then send this prompt:

```text
Fix the bug in calc.py and add a guard for division by zero
```

Claude Code reads `calc.py`, makes `add` return `a + b`, and makes `divide` raise an error, such as
`ZeroDivisionError`, when `b` is zero. Depending on its permission mode, it asks before each edit and command, or
runs them. In testing, the session started in auto mode, shown as `⏵⏵ auto mode on (shift+tab to cycle)` under the
prompt, and each step showed `Allowed by auto mode`. Press Shift+Tab to cycle the modes.

<!-- /steps -->

> **Checkpoint**
> Type `/exit` to leave the session, then run `python3 calc.py` (or `python calc.py`) in `~/contoso-calc`. It
> prints `5 5.0`: Claude Code fixed `add` with a model from your gateway.

## Publish Microsoft Learn tools for Claude Code

Claude Code calls tools as well as models. Publish an MCP server through the same gateway, and its tool calls get the
same controls as its model calls: one key that you can suspend, one endpoint per tool server, and one place to decide
which tools agents see. Here, the gateway publishes the public Microsoft Learn MCP server as `learn`, so Claude Code
can look up current Microsoft documentation while it codes.

Claude Code then has two connections to the gateway:

| | Models | MCP server |
|---|---|---|
| URL | `https://<gateway-host>/default/models/anthropic` | `https://<gateway-host>/default/toolservers/learn/mcp` |
| How the key is sent | `Authorization: Bearer <key>`, from `ANTHROPIC_AUTH_TOKEN` | The same `Authorization: Bearer <key>` header, which you set yourself |
| Key | `claude-code` | The same `claude-code` key. It needs no extra setup. |

> [!TIP]
> If your gateway already has `learn`, for example from
> [Federate MCP tools behind one endpoint](../04-federate-mcp-tools/README.md), skip to
> [Test the MCP endpoint](#test-the-mcp-endpoint).

Create the `learn` server with one backend, `https://learn.microsoft.com/api/mcp`, under the namespace `learn`. The
Learn server is public, so the backend needs no credentials. Pick a track.

<!-- track: portal | Portal -->

### Register the Learn server

1. Open the [AI Gateway portal](https://ai.gateway.azure.com), select your gateway, and select **MCP servers** ›
   **Add MCP server**.
2. On **Basic info**, set **Name** to `learn`, **Display name** to `Microsoft Learn`, and **Description** to
   `Search and fetch official Microsoft documentation and code samples.` In **Supported MCP versions**, select
   `2025-06-18`, the version that the Learn server reports. Select **Next**.
3. On **Backends**, select **Add backend** › **MCP server**. Set **Endpoint URL** to
   `https://learn.microsoft.com/api/mcp`, keep **Authentication** at **None**, and set **Namespace** to `learn`.
   Select **Add**, then **Next**, which saves the server and opens **Tools**.
4. On **Tools**, keep **Allow all tools**, and select **Create**.

[Register the Learn MCP server](../04-federate-mcp-tools/README.md#register-the-learn-mcp-server) in lab 04
explains each field.

### Copy the endpoint

When the server is ready, copy the **Endpoint URL** from its details page. It ends in
`/default/toolservers/learn/mcp`.

> **Checkpoint**
> **MCP servers** lists `learn` with one backend in the namespace `learn`.

<!-- track: cli | Azure CLI -->

### Register the Learn server

`az aigateway mcp create` registers the MCP server. `--endpoints` takes the backends as a JSON array.

```bash title="Bash"
# Register the public Microsoft Learn MCP server as learn, with one backend in the learn namespace and no credentials
MCP_ENDPOINT="$(az aigateway mcp create -g "$RG" --gateway-name "$GATEWAY" -n learn \
  --display-name "Microsoft Learn" \
  --description "Search and fetch official Microsoft documentation and code samples." \
  --endpoints '[{"kind": "mcp", "namespace": "learn", "required": true,
                 "mcp": {"url": "https://learn.microsoft.com/api/mcp", "transport": "streamableHttp"}}]' \
  --query "properties.gatewayEndpoints[0].url" -o tsv)" &&
  echo "🔌 MCP server learn is ready: $MCP_ENDPOINT"
```

```powershell title="PowerShell"
# Write the backend to a file: the public Microsoft Learn MCP server, in the learn namespace, with no credentials
ConvertTo-Json -Depth 10 -Compress -InputObject @(
  @{ kind = 'mcp'; namespace = 'learn'; required = $true
     mcp  = @{ transport = 'streamableHttp'; url = 'https://learn.microsoft.com/api/mcp' } }
) | Set-Content -Path endpoints.json

# Register the MCP server as learn with that backend, then remove the file
$MCP_ENDPOINT = az aigateway mcp create -g $RG --gateway-name $GATEWAY -n learn `
  --display-name "Microsoft Learn" `
  --description "Search and fetch official Microsoft documentation and code samples." `
  --endpoints "@endpoints.json" `
  --query "properties.gatewayEndpoints[0].url" -o tsv
if ($?) { Write-Host "🔌 MCP server learn is ready: $MCP_ENDPOINT" }
Remove-Item endpoints.json
```

If `learn` already exists, `mcp create` fails with the error `This MCP registration already exists; use mcp update.`
In that case, skip this step: the next section uses the existing server.

> **Checkpoint**
> The command prints `🔌 MCP server learn is ready:` and the endpoint, ending in `/default/toolservers/learn/mcp`.

<!-- track: iac | Bicep -->

### Deploy the Learn server

Lab 04's [`tool-server.bicep`](../04-federate-mcp-tools/infra/tool-server.bicep) references your gateway and declares
one `toolServers` resource, `learn`, with the public Learn backend. Deploy it from the lab folder,
`aigateway/labs/25-claude-code`:

```bash title="Bash"
# Deploy lab 04's template onto your gateway, and print the endpoint of the learn MCP server
echo "🔌 Endpoint of the learn MCP server:"
az deployment group create -g "$RG" -n learn-mcp -f ../04-federate-mcp-tools/infra/tool-server.bicep \
  -p gatewayName="$GATEWAY" --query properties.outputs.mcpEndpoint.value -o tsv
```

```powershell title="PowerShell"
# Deploy lab 04's template onto your gateway, and print the endpoint of the learn MCP server
Write-Host "🔌 Endpoint of the learn MCP server:"
az deployment group create -g $RG -n learn-mcp -f ../04-federate-mcp-tools/infra/tool-server.bicep `
  -p gatewayName=$GATEWAY --query properties.outputs.mcpEndpoint.value -o tsv
```

> [!WARNING]
> The deployment replaces the whole `learn` server, including backends and tool rules that you added in the portal.

> **Checkpoint**
> The commands print `🔌 Endpoint of the learn MCP server:` and the endpoint, ending in
> `/default/toolservers/learn/mcp`.

<!-- track: terraform | Terraform -->

### Deploy the Learn server

`terraform/learn-mcp.tf` declares the same `toolServers` resource as lab 04's template, `learn`, with the public
Learn backend, when `learn_mcp_server` is `true`:

<!-- include: terraform/learn-mcp.tf -->

In the terminal where you applied the configuration, so that the `TF_VAR_` variables are still set, move back into
the lab's `terraform` folder, then pass `learn_mcp_server` to `terraform plan` and apply the plan:

```bash title="Bash"
# Plan and apply the learn MCP server on your gateway, and print its endpoint
cd ~/aigateway/labs/25-claude-code/terraform &&
  terraform plan -var learn_mcp_server=true -out tfplan &&
  terraform apply tfplan &&
  echo "🔌 Endpoint of the learn MCP server: $(terraform output -raw mcp_endpoint)"
```

```powershell title="PowerShell"
# Plan and apply the learn MCP server on your gateway, and print its endpoint
Set-Location ~/aigateway/labs/25-claude-code/terraform
if ($?) { terraform plan -var learn_mcp_server=true -out tfplan }
if ($?) { terraform apply tfplan }
if ($?) { Write-Host "🔌 Endpoint of the learn MCP server: $(terraform output -raw mcp_endpoint)" }
```

Pass `-var learn_mcp_server=true` to every later `terraform plan` too: without it, Terraform plans to delete `learn`.
If `learn` already exists, for example from lab 04, `terraform apply` stops with `Error: Resource already exists`. In
that case, skip this step: the next section uses the existing server.

> **Checkpoint**
> The plan ended with `Plan: 1 to add, 0 to change, 0 to destroy.`, and the last command printed
> `🔌 Endpoint of the learn MCP server:` and the endpoint, ending in `/default/toolservers/learn/mcp`.

<!-- /tracks -->

<!-- steps -->

### Test the MCP endpoint

Save the endpoint, then list its tools the way Claude Code does: a JSON-RPC `tools/list` request with the key as a
bearer token.

```bash title="Bash"
# Save the endpoint of the learn MCP server on your gateway
export AI_GATEWAY_MCP_URL="${AI_GATEWAY_URL%/}/default/toolservers/learn/mcp"
echo "🔌 MCP endpoint: $AI_GATEWAY_MCP_URL"

# List the server's tools: a JSON-RPC tools/list request, with the key as a bearer token
echo "🔧 Tools on the learn MCP server:"
curl -sS "$AI_GATEWAY_MCP_URL" \
  -H "Authorization: Bearer $AI_GATEWAY_API_KEY" -H "Content-Type: application/json" \
  -H "Accept: application/json, text/event-stream" \
  -d '{"jsonrpc":"2.0","id":1,"method":"tools/list"}' | jq -r '.result.tools[].name'
```

```powershell title="PowerShell"
# Save the endpoint of the learn MCP server on your gateway
$env:AI_GATEWAY_MCP_URL = "$($env:AI_GATEWAY_URL.TrimEnd('/'))/default/toolservers/learn/mcp"
Write-Host "🔌 MCP endpoint: $env:AI_GATEWAY_MCP_URL"

# List the server's tools: a JSON-RPC tools/list request, with the key as a bearer token
Write-Host "🔧 Tools on the learn MCP server:"
$reply = Invoke-RestMethod -Method Post -Uri $env:AI_GATEWAY_MCP_URL `
  -Headers @{ Authorization = "Bearer $env:AI_GATEWAY_API_KEY"; Accept = "application/json, text/event-stream" } `
  -ContentType "application/json" -Body '{"jsonrpc":"2.0","id":1,"method":"tools/list"}'
$reply.result.tools.name
```

Expected output:

```text
🔌 MCP endpoint: https://<gateway-host>/default/toolservers/learn/mcp
🔧 Tools on the learn MCP server:
learn_microsoft_docs_search
learn_microsoft_code_sample_search
learn_microsoft_docs_fetch
```

Each name starts with the backend's namespace, `learn`. The Learn server can add tools over time, and **Allow all
tools** publishes them too.

<!-- /steps -->

## Add the Learn tools to Claude Code

`claude mcp add` registers an MCP server. With `--scope user`, Claude Code keeps it in `~/.claude.json` and offers it
in every project. Header values can refer to environment variables, so the file doesn't need to hold the key.

<!-- steps -->

### Add the server

Keep the single quotes around the header: they stop the shell from expanding `${AI_GATEWAY_API_KEY}`, so the file
stores the reference, and Claude Code reads the key from its environment each time it connects. Keep `--header` after
the name and the URL: it takes one or more values, so Claude Code would read anything after it as another header.

```bash title="Bash"
# Add the gateway's learn MCP server to Claude Code for your user, with a header that reads the key from the environment
claude mcp add --transport http --scope user ai-gateway-learn "$AI_GATEWAY_MCP_URL" \
  --header 'Authorization: Bearer ${AI_GATEWAY_API_KEY}' &&
  echo "🔌 MCP server ai-gateway-learn is ready in Claude Code"

# Check that Claude Code connects to it
echo "🔌 MCP servers in Claude Code:"
claude mcp list
```

```powershell title="PowerShell"
# Add the gateway's learn MCP server to Claude Code for your user, with a header that reads the key from the environment
claude mcp add --transport http --scope user ai-gateway-learn $env:AI_GATEWAY_MCP_URL `
  --header 'Authorization: Bearer ${AI_GATEWAY_API_KEY}'
if ($?) { Write-Host "🔌 MCP server ai-gateway-learn is ready in Claude Code" }

# Check that Claude Code connects to it
Write-Host "🔌 MCP servers in Claude Code:"
claude mcp list
```

Expected output:

```text
Added HTTP MCP server ai-gateway-learn with URL: https://<gateway-host>/default/toolservers/learn/mcp to user config
Headers: {
  "Authorization": "[REDACTED]"
}
File modified: <home>/.claude.json
🔌 MCP server ai-gateway-learn is ready in Claude Code
🔌 MCP servers in Claude Code:
Checking MCP server health…

ai-gateway-learn: https://<gateway-host>/default/toolservers/learn/mcp (HTTP) - ✔ Connected
```

`✔ Connected` means that Claude Code reached the gateway with the key. In the PowerShell version, `AI_GATEWAY_API_KEY`
must be an environment variable, as the earlier steps set it.

### Ask a question that needs the docs

Claude Code names the server's tools `mcp__ai-gateway-learn__<tool>`. `claude -p` can't ask for permission, so
`--allowedTools "mcp__ai-gateway-learn__*"` allows all the server's tools up front:

```bash
# Ask a question that needs current docs, and allow the Learn tools for this one-shot run
echo "🤖 Claude Code answer, with the Learn tools:"
claude -p "Use the Microsoft Learn tools to find the Azure Functions Core Tools command that creates a new Python function project. Answer in two sentences, with the command and the link to the page." \
  --allowedTools "mcp__ai-gateway-learn__*"
```

Expected output (your text differs):

```text
🤖 Claude Code answer, with the Learn tools:
To create a new Python function project with Azure Functions Core Tools, run `func init MyProjFolder --worker-runtime python --model V2` (use `--model V1` for the older programming model), which creates the project in a new folder called *MyProjFolder*. The command is documented at https://learn.microsoft.com/azure/azure-functions/functions-run-local#create-your-local-project, which also says to run Core Tools commands for Python inside a virtual environment.
```

The link comes from the Learn search that Claude Code ran through the gateway. In an interactive session, Claude Code
asks before it calls a tool, depending on its permission mode.

<!-- /steps -->

> **Checkpoint**
> `claude mcp list` shows `ai-gateway-learn` as `✔ Connected`, and the answer cites a `learn.microsoft.com` page.

## Hit the limits

Coding agents can spend tokens and money fast. Lower the limits for a few minutes to see how the gateway stops
Claude Code, and how Claude Code reports it. Short questions are mostly cached and barely count, so these tests ask
for long stories.

<!-- steps -->

### Lower the Haiku token limit

Lower the token limit on the Haiku alias to 1,000 tokens per minute for each caller:

- **Portal:** in **Policies**, open the **Token rate limit**, select **Edit**, set **Allowed tokens** to `1000`, and
  **Save**. The policy covers the three aliases, so all three get the lower limit. That's fine for the test.
- **Azure CLI, Bicep, and Terraform:** run the commands below. The three tracks give the aliases the same names.

```bash title="Bash"
# Lower the Haiku alias's token limit to 1,000 tokens per minute for each caller, and show its policies
echo "🔐 Policies on $FOUNDRY_ACCOUNT/claude-haiku-5-5:"
az aigateway model-alias update -g "$RG" --gateway-name "$GATEWAY" -n "$FOUNDRY_ACCOUNT-claude-haiku-5-5" \
  --policies '[{"type": "tokenLimit", "count": 1000, "period": "minute", "counterKey": ["identity"]}]' \
  --query "properties.policies[].{policy:type, count:count, period:period}" -o table
```

```powershell title="PowerShell"
# Write the lower token limit to a file: 1,000 tokens per minute for each caller
ConvertTo-Json -Depth 5 -Compress -InputObject @(
  @{ type = 'tokenLimit'; count = 1000; period = 'minute'; counterKey = @('identity') }
) | Set-Content -Path policies.json

# Give the Haiku alias the lower limit, show its policies, then remove the file
Write-Host "🔐 Policies on $FOUNDRY_ACCOUNT/claude-haiku-5-5:"
az aigateway model-alias update -g $RG --gateway-name $GATEWAY -n "$FOUNDRY_ACCOUNT-claude-haiku-5-5" `
  --policies "@policies.json" --query "properties.policies[].{policy:type, count:count, period:period}" -o table
Remove-Item policies.json
```

Expected output:

```text
🔐 Policies on <foundry-account-name>/claude-haiku-5-5:
Policy      Count    Period
----------  -------  --------
tokenLimit  1000     minute
```

Wait a minute for the change to reach the gateway.

### Run Haiku until the token limit

Ask Haiku for five long stories in a row, and stop at the first error:

```bash title="Bash"
# Ask Haiku for up to five long stories, print each run's output tokens, and stop at the first error
cd ~/contoso-calc
for i in 1 2 3 4 5; do
  RUN="$(claude -p "Write a 500-word short story about a gateway that guards a city" --model haiku --output-format json)"
  echo "$RUN" | jq -r --arg i "$i" \
    'if .is_error then "🚨 Run \($i): \(.result)" else "✅ Run \($i): \(.usage.output_tokens) output tokens" end'
  [ "$(echo "$RUN" | jq -r .is_error)" = "true" ] && break
done
```

```powershell title="PowerShell"
# Ask Haiku for up to five long stories, print each run's output tokens, and stop at the first error
Set-Location ~/contoso-calc
foreach ($i in 1..5) {
  $run = claude -p "Write a 500-word short story about a gateway that guards a city" --model haiku `
    --output-format json | ConvertFrom-Json
  if ($run.is_error) { Write-Host "🚨 Run ${i}: $($run.result)"; break }
  Write-Host "✅ Run ${i}: $($run.usage.output_tokens) output tokens"
}
```

Expected output (your numbers differ):

```text
✅ Run 1: 1055 output tokens
✅ Run 2: 6028 output tokens
🚨 Run 3: API Error: Request rejected (429) · Token limit is exceeded. Try again in 332 seconds.
```

The gateway counts a reply after it's sent, so the reply that crosses the limit still arrives in full, and the next
request gets `429`. Claude Code doesn't retry it: it shows the gateway's message, with the seconds until the window
resets.

### Restore the Haiku token limit

- **Portal:** set **Allowed tokens** on the **Token rate limit** back to `100000`.
- **Azure CLI, Bicep, and Terraform:**

```bash title="Bash"
# Restore the Haiku alias's token limit to 100,000 tokens per minute for each caller
az aigateway model-alias update -g "$RG" --gateway-name "$GATEWAY" -n "$FOUNDRY_ACCOUNT-claude-haiku-5-5" \
  --policies '[{"type": "tokenLimit", "count": 100000, "period": "minute", "counterKey": ["identity"]}]' -o none &&
  echo "🔐 Haiku is back to 100,000 tokens per minute for each caller"
```

```powershell title="PowerShell"
# Write the token limit to a file: 100,000 tokens per minute for each caller
ConvertTo-Json -Depth 5 -Compress -InputObject @(
  @{ type = 'tokenLimit'; count = 100000; period = 'minute'; counterKey = @('identity') }
) | Set-Content -Path policies.json

# Restore the Haiku alias's token limit, then remove the file
az aigateway model-alias update -g $RG --gateway-name $GATEWAY -n "$FOUNDRY_ACCOUNT-claude-haiku-5-5" `
  --policies "@policies.json" -o none
if ($?) { Write-Host "🔐 Haiku is back to 100,000 tokens per minute for each caller" }
Remove-Item policies.json
```

### Lower the Opus budget

Lower the daily budget on the Opus alias to $0.05 for each caller. Keep the cost limit's `id`: the gateway then keeps
the spend counted so far today. The agent task and the Learn question already ran on Opus, so the key may have spent
more than $0.05 today, and the first request may be blocked right away.

- **Portal:** in **Policies**, open the **Cost limit**, select **Edit**, set **Budget amount** to `0.05`, and **Save**.
- **Azure CLI, Bicep, and Terraform:**

```bash title="Bash"
# Lower the Opus budget to $0.05 a day for each caller, with the same id, so that today's spend still counts
az aigateway model-alias update -g "$RG" --gateway-name "$GATEWAY" -n "$FOUNDRY_ACCOUNT-claude-opus-5-5" \
  --policies '[{"type": "tokenLimit", "count": 100000, "period": "minute", "counterKey": ["identity"]},
               {"type": "costLimit", "id": "claude-code-budget", "amount": 0.05, "period": "day",
                "counterKey": ["identity"]}]' -o none &&
  echo "🔐 Opus budget: \$0.05 per day for each caller"
```

```powershell title="PowerShell"
# Write both policies to a file: the token limit, and the budget lowered to $0.05 a day with the same id
ConvertTo-Json -Depth 5 -Compress -InputObject @(
  @{ type = 'tokenLimit'; count = 100000; period = 'minute'; counterKey = @('identity') }
  @{ type = 'costLimit'; id = 'claude-code-budget'; amount = 0.05; period = 'day'; counterKey = @('identity') }
) | Set-Content -Path policies.json

# Give the Opus alias the lower budget, then remove the file
az aigateway model-alias update -g $RG --gateway-name $GATEWAY -n "$FOUNDRY_ACCOUNT-claude-opus-5-5" `
  --policies "@policies.json" -o none
if ($?) { Write-Host "🔐 Opus budget: `$0.05 per day for each caller" }
Remove-Item policies.json
```

Wait a minute for the change to reach the gateway.

### Run Opus until the budget

```bash title="Bash"
# Ask Opus for up to five stories, and stop at the first error
for i in 1 2 3 4 5; do
  RUN="$(claude -p "Write a 300-word short story about a gateway that guards a city" --model opus --output-format json)"
  echo "$RUN" | jq -r --arg i "$i" \
    'if .is_error then "🚨 Run \($i): \(.result)" else "✅ Run \($i): \(.usage.output_tokens) output tokens" end'
  [ "$(echo "$RUN" | jq -r .is_error)" = "true" ] && break
done
```

```powershell title="PowerShell"
# Ask Opus for up to five stories, and stop at the first error
foreach ($i in 1..5) {
  $run = claude -p "Write a 300-word short story about a gateway that guards a city" --model opus --output-format json |
    ConvertFrom-Json
  if ($run.is_error) { Write-Host "🚨 Run ${i}: $($run.result)"; break }
  Write-Host "✅ Run ${i}: $($run.usage.output_tokens) output tokens"
}
```

Expected output (run 1 may already be blocked):

```text
✅ Run 1: 573 output tokens
🚨 Run 2: Failed to authenticate. API Error: 403 LLM cost quota is exceeded. Try again in 4 hours, 6 minutes, and 5 seconds.
```

The gateway answers `403` with the time until the budget renews, at the end of the day. Claude Code reports it as
**Failed to authenticate**, and an interactive session shows `Please run /login · API Error: 403 …`. Don't sign in:
the key is fine, and the budget is spent.

### Carry on with Sonnet

The Sonnet alias has no budget, so switch to it. In an interactive session, type `/model sonnet`. Claude Code answers
`Set model to Sonnet 5.5 and saved as your default for new sessions`, so type `/model opus` when the budget renews.
In a one-shot run, add `--model sonnet`:

```bash
# Ask Sonnet instead: its alias has no budget, so the gateway lets the request through
claude -p "Reply with the single word pong" --model sonnet --output-format json \
  | jq -r 'if .is_error then "🚨 \(.result)"
           else "✅ \(.result) · \(.modelUsage | keys | join(", ")) · $\(.total_cost_usd * 10000 | round / 10000)" end'
```

Expected output (your cost differs):

```text
✅ pong · <foundry-account-name>/claude-sonnet-5-5 · $0.0411
```

`--fallback-model` doesn't help here: Claude Code uses it when the model is overloaded, not when the gateway answers
`403`.

### Restore the Opus budget

- **Portal:** set **Budget amount** on the **Cost limit** back to `5`.
- **Azure CLI, Bicep, and Terraform:**

```bash title="Bash"
# Restore the Opus budget to $5 a day for each caller, with the same id
az aigateway model-alias update -g "$RG" --gateway-name "$GATEWAY" -n "$FOUNDRY_ACCOUNT-claude-opus-5-5" \
  --policies '[{"type": "tokenLimit", "count": 100000, "period": "minute", "counterKey": ["identity"]},
               {"type": "costLimit", "id": "claude-code-budget", "amount": 5, "period": "day",
                "counterKey": ["identity"]}]' -o none &&
  echo "🔐 Opus budget: \$5 per day for each caller"
```

```powershell title="PowerShell"
# Write both policies to a file: the token limit, and the budget back at $5 a day with the same id
ConvertTo-Json -Depth 5 -Compress -InputObject @(
  @{ type = 'tokenLimit'; count = 100000; period = 'minute'; counterKey = @('identity') }
  @{ type = 'costLimit'; id = 'claude-code-budget'; amount = 5; period = 'day'; counterKey = @('identity') }
) | Set-Content -Path policies.json

# Restore the Opus budget, then remove the file
az aigateway model-alias update -g $RG --gateway-name $GATEWAY -n "$FOUNDRY_ACCOUNT-claude-opus-5-5" `
  --policies "@policies.json" -o none
if ($?) { Write-Host "🔐 Opus budget: `$5 per day for each caller" }
Remove-Item policies.json
```

On the Terraform track, the restore commands set the configuration's values back, so `terraform plan` shows no
changes.

<!-- /steps -->

> **Checkpoint**
> Haiku stopped with `429` and the seconds until the token window resets, Opus stopped with `403` and the time until
> the budget renews, and Sonnet answered while Opus was blocked.

## Verify

Every request from Claude Code carries the `claude-code` key. Use it to see the traffic and to switch Claude Code off.

<!-- steps -->

### See Claude Code's usage by key

If you set up Monitoring in [Monitor usage, cost, and traces](../13-monitoring/README.md), open **Monitoring** ›
**Models** in the AI Gateway portal. The three Claude aliases list the calls and the tokens from your sessions, and
**Model usage by caller identity** shows them under the `claude-code` key.

### Cut Claude Code off by suspending the key

Suspend the key, then call the gateway with it. Use `curl` for this test: Claude Code retries a `401` many times, so a
`claude -p` run seems to hang for minutes before it fails.

```bash title="Bash"
# Suspend the claude-code key: calls with it get 401 until you set it back to active
STATE="$(az aigateway api-key update -g "$RG" --gateway-name "$GATEWAY" -n "$KEY_NAME" --state suspended \
  --query properties.state -o tsv)" &&
  echo "🔑 API key claude-code is $STATE"

# Give the gateway time to apply the change
echo "⏳ Waiting 60 seconds for the key change to apply"
sleep 60

# Call the Haiku alias with the suspended key, and print the gateway's answer
echo "🚦 Expect HTTP 401 from the gateway:"
curl -sS "${AI_GATEWAY_URL%/}/default/models/anthropic/v1/messages" \
  -H "Authorization: Bearer $AI_GATEWAY_API_KEY" \
  -H "anthropic-version: 2023-06-01" -H "Content-Type: application/json" \
  -d "{\"model\": \"$FOUNDRY_ACCOUNT/claude-haiku-5-5\", \"max_tokens\": 16,
       \"messages\": [{\"role\": \"user\", \"content\": \"Say hi\"}]}" \
  -w "\n🚦 HTTP %{http_code}\n"
```

```powershell title="PowerShell"
# Suspend the claude-code key: calls with it get 401 until you set it back to active
$STATE = az aigateway api-key update -g $RG --gateway-name $GATEWAY -n $KEY_NAME --state suspended `
  --query properties.state -o tsv
if ($?) { Write-Host "🔑 API key claude-code is $STATE" }

# Give the gateway time to apply the change
Write-Host "⏳ Waiting 60 seconds for the key change to apply"
Start-Sleep 60

# Call the Haiku alias with the suspended key, and print the gateway's answer
Write-Host "🚦 Expect HTTP 401 from the gateway:"
$headers = @{ Authorization = "Bearer $env:AI_GATEWAY_API_KEY"; 'anthropic-version' = '2023-06-01' }
$body = @{
  model      = "$FOUNDRY_ACCOUNT/claude-haiku-5-5"
  max_tokens = 16
  messages   = @(@{ role = 'user'; content = 'Say hi' })
} | ConvertTo-Json -Depth 5
$r = Invoke-WebRequest -Method Post -Uri "$($env:AI_GATEWAY_URL.TrimEnd('/'))/default/models/anthropic/v1/messages" `
  -Headers $headers -ContentType 'application/json' -Body $body -SkipHttpErrorCheck
Write-Host $r.Content
Write-Host "🚦 HTTP $($r.StatusCode)"
```

Expected output:

```text
🔑 API key claude-code is suspended
⏳ Waiting 60 seconds for the key change to apply
🚦 Expect HTTP 401 from the gateway:
{ "statusCode": 401, "message": "Unauthorized. Missing or invalid Entra ID token, or missing Data.All scope." }
🚦 HTTP 401
```

One key change cuts off Claude Code on every machine that uses the key, without touching their settings. The key
guards the tools too: while it's suspended, `claude mcp list` can't connect to `ai-gateway-learn`.

### Turn Claude Code back on

```bash title="Bash"
# Turn the claude-code key back on
STATE="$(az aigateway api-key update -g "$RG" --gateway-name "$GATEWAY" -n "$KEY_NAME" --state active \
  --query properties.state -o tsv)" &&
  echo "🔑 API key claude-code is $STATE"

# Give the gateway time to apply the change
echo "⏳ Waiting 60 seconds for the key change to apply"
sleep 60

# Ask Claude Code again: it answers through the gateway
echo "🤖 Claude Code answer:"
cd ~/contoso-calc && claude -p "Say hi in three words"
```

```powershell title="PowerShell"
# Turn the claude-code key back on
$STATE = az aigateway api-key update -g $RG --gateway-name $GATEWAY -n $KEY_NAME --state active `
  --query properties.state -o tsv
if ($?) { Write-Host "🔑 API key claude-code is $STATE" }

# Give the gateway time to apply the change
Write-Host "⏳ Waiting 60 seconds for the key change to apply"
Start-Sleep 60

# Ask Claude Code again: it answers through the gateway
Write-Host "🤖 Claude Code answer:"
Set-Location ~/contoso-calc; claude -p "Say hi in three words"
```

<!-- /steps -->

> **Checkpoint**
> The gateway answered `401` while the key was suspended, and Claude Code answered again after
> `🔑 API key claude-code is active`.

## Go further

- **Sign in with Microsoft Entra ID instead of a key.** If the gateway accepts Entra tokens and you have the
  **AI Gateway Models User** role, as in [Authorize callers with Microsoft Entra ID](../11-entra-rbac/README.md), let
  Claude Code fetch a token itself. Add this setting to `~/.claude/settings.json`:

  ```json title="~/.claude/settings.json"
  {
    "apiKeyHelper": "az account get-access-token --scope https://ai.gateway.azure.com/Data.All --query accessToken -o tsv"
  }
  ```

  Then run `unset ANTHROPIC_AUTH_TOKEN` (Bash) or `Remove-Item Env:ANTHROPIC_AUTH_TOKEN` (PowerShell), and keep it
  out of the `env` block of your settings. If it's still set, Claude Code keeps sending the key as the bearer token
  instead of the helper's token, and the requests still succeed with the key. Claude Code runs the helper again every five minutes by default, so expired tokens
  don't stop long sessions. See [Settings](https://code.claude.com/docs/en/settings).
- **Keep the settings in a file.** Put the `ANTHROPIC_*` variables in the `env` block of `~/.claude/settings.json`,
  so every session uses the gateway without exports. Keep the key in your user settings, not in a project's
  `.claude/settings.json`, which gets committed with the repository.
- **Use Claude Code in VS Code.** The Claude Code extension reads the same variables. Set them in the
  `claudeCode.environmentVariables` setting. See [Use Claude Code in VS Code](https://code.claude.com/docs/en/vs-code).
- **Turn off nonessential traffic.** `CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC=1` turns off Claude Code's telemetry,
  error reports, and automatic updates. See [Environment variables](https://code.claude.com/docs/en/env-vars).
- **Give each developer their own key.** Keys are cheap, and the **Identity** counter dimension gives each key its own
  token limit and budget. Rotate or revoke them with [Manage runtime API keys](../10-api-keys/README.md).
- **Cap one run.** `claude -p --max-budget-usd 1` stops a one-shot run when Claude Code's own estimate reaches $1. The
  gateway's budget stays the limit that Claude Code can't change.
- **Choose which tools Claude Code can call.** On the gateway, publish only some Learn tools or cap tool calls per
  caller, as in [Control which tools agents can call](../05-mcp-tool-controls/README.md). In Claude Code, use
  `--allowedTools`, `--disallowedTools`, and `--permission-mode`.
- **Route across models.** Point an alias at several backend models, as in
  [Route by priority and weight](../22-model-routing/README.md), and Claude Code keeps sending the same name.

## Clean up

Remove the gateway from Claude Code, and delete the practice project:

- **Learn tools:** run `claude mcp remove ai-gateway-learn -s user`.
- **Environment:** close the terminal, or run
  `unset ANTHROPIC_BASE_URL ANTHROPIC_AUTH_TOKEN ANTHROPIC_DEFAULT_OPUS_MODEL ANTHROPIC_DEFAULT_SONNET_MODEL ANTHROPIC_DEFAULT_HAIKU_MODEL`
  (Bash) or `Remove-Item Env:ANTHROPIC_*` (PowerShell).
- **Practice project:** run `rm -rf ~/contoso-calc` (Bash) or `Remove-Item -Recurse -Force ~/contoso-calc`
  (PowerShell).

Then delete what you created on the gateway. Keep the gateway: the other labs reuse it. Keep the `learn` MCP server if
you continue with [Control which tools agents can call](../05-mcp-tool-controls/README.md), which builds on it. Pick a
track.

<!-- track: portal | Portal -->

### Delete the key, the policies, and the models

1. Delete `claude-code` in **Access** › **API keys**.
2. Delete the **Token rate limit** and the **Cost limit** that you added, in **Policies**.
3. If you don't need the Claude models on the gateway any more, delete the three `<foundry-account-name>/claude-*-5-5`
   aliases and the three models in **Models**.
4. If you don't need `learn`, delete it in **MCP servers**.

<!-- track: cli | Azure CLI -->

### Delete the key, the aliases, and the models

Delete the key:

```bash title="Bash"
# Delete the claude-code key: Claude Code stops working with it on every machine
az aigateway api-key delete -g "$RG" --gateway-name "$GATEWAY" -n "$KEY_NAME" --yes &&
  echo "🚮 API key claude-code is deleted"
```

```powershell title="PowerShell"
# Delete the claude-code key: Claude Code stops working with it on every machine
az aigateway api-key delete -g $RG --gateway-name $GATEWAY -n $KEY_NAME --yes
if ($?) { Write-Host "🚮 API key claude-code is deleted" }
```

If you don't need the Claude models on the gateway any more, delete the aliases, then the three models. The provider
can have other models of the same account, so the commands delete it only when it has no models left:

```bash title="Bash"
# Delete the three aliases first, so that nothing points at the models
for m in claude-opus-5-5 claude-sonnet-5-5 claude-haiku-5-5; do
  az aigateway model-alias delete -g "$RG" --gateway-name "$GATEWAY" -n "$FOUNDRY_ACCOUNT-$m" --yes &&
    echo "🚮 Alias $FOUNDRY_ACCOUNT/$m is deleted"
done

# Delete the three Claude models: the provider's other models, the Foundry account and its deployments stay
for m in claude-opus-5-5 claude-sonnet-5-5 claude-haiku-5-5; do
  az aigateway model delete -g "$RG" --gateway-name "$GATEWAY" --provider-name "$PROVIDER" -n "$m" --yes &&
    echo "🚮 Model $PROVIDER/$m is deleted"
done

# Delete the provider only if it has no models left
LEFT="$(az aigateway model list -g "$RG" --gateway-name "$GATEWAY" --provider-name "$PROVIDER" \
  --query "length(@)" -o tsv --only-show-errors)"
if [ "$LEFT" = "0" ]; then
  az aigateway model-provider delete -g "$RG" --gateway-name "$GATEWAY" -n "$PROVIDER" --yes &&
    echo "🚮 Provider $PROVIDER is deleted"
else
  echo "🏭 Provider $PROVIDER is kept, with its other models: $LEFT"
fi
```

```powershell title="PowerShell"
# Delete the three aliases first, so that nothing points at the models
foreach ($m in 'claude-opus-5-5', 'claude-sonnet-5-5', 'claude-haiku-5-5') {
  az aigateway model-alias delete -g $RG --gateway-name $GATEWAY -n "$FOUNDRY_ACCOUNT-$m" --yes
  if ($?) { Write-Host "🚮 Alias $FOUNDRY_ACCOUNT/$m is deleted" }
}

# Delete the three Claude models: the provider's other models, the Foundry account and its deployments stay
foreach ($m in 'claude-opus-5-5', 'claude-sonnet-5-5', 'claude-haiku-5-5') {
  az aigateway model delete -g $RG --gateway-name $GATEWAY --provider-name $PROVIDER -n $m --yes
  if ($?) { Write-Host "🚮 Model $PROVIDER/$m is deleted" }
}

# Delete the provider only if it has no models left
$LEFT = az aigateway model list -g $RG --gateway-name $GATEWAY --provider-name $PROVIDER `
  --query "length(@)" -o tsv --only-show-errors
if ($LEFT -eq "0") {
  az aigateway model-provider delete -g $RG --gateway-name $GATEWAY -n $PROVIDER --yes
  if ($?) { Write-Host "🚮 Provider $PROVIDER is deleted" }
} else {
  Write-Host "🏭 Provider $PROVIDER is kept, with its other models: $LEFT"
}
```

If you don't need `learn`, delete it:

```bash title="Bash"
# Delete the learn MCP server from the gateway
az aigateway mcp delete -g "$RG" --gateway-name "$GATEWAY" -n learn --yes &&
  echo "🚮 MCP server learn is deleted"
```

```powershell title="PowerShell"
# Delete the learn MCP server from the gateway
az aigateway mcp delete -g $RG --gateway-name $GATEWAY -n learn --yes
if ($?) { Write-Host "🚮 MCP server learn is deleted" }
```

<!-- track: iac | Bicep -->

### Delete what the templates deployed

The templates use the same names as the Azure CLI track, so run the Azure CLI track's commands: they delete the key,
the aliases, the models, the provider if it has no other models, and `learn`. Then delete the deployment records:

```bash title="Bash"
# Delete the records of the two deployments: the resources are already gone
az deployment group delete -g "$RG" -n claude-code &&
  az deployment group delete -g "$RG" -n learn-mcp &&
  echo "🚮 Deployment records claude-code and learn-mcp are deleted"
```

```powershell title="PowerShell"
# Delete the records of the two deployments: the resources are already gone
az deployment group delete -g $RG -n claude-code
az deployment group delete -g $RG -n learn-mcp
if ($?) { Write-Host "🚮 Deployment records claude-code and learn-mcp are deleted" }
```

<!-- track: terraform | Terraform -->

### Delete what Terraform created

Delete what `terraform apply` added to your gateway: the key, the aliases, the models, the provider and the
**Foundry User** role assignment if Terraform created them, and `learn` if you deployed it. The gateway, the Foundry
account, and its deployments stay. It takes a few seconds. The commands set the Terraform variables again, in case
you're in a new terminal.

To keep `learn` for [Control which tools agents can call](../05-mcp-tool-controls/README.md), first run
`terraform state rm 'azapi_resource.learn[0]'` in the Terraform folder: Terraform then stops managing it, and
`terraform destroy` leaves it on the gateway.

```bash title="Bash"
# Move into the lab's Terraform folder, and point Terraform at your gateway and the Foundry account
cd ~/aigateway/labs/25-claude-code/terraform &&
  echo "📂 Terraform folder: $(pwd)"
export ARM_SUBSCRIPTION_ID="$(az account show --query id --output tsv)"
export TF_VAR_resource_group_name="$RG" TF_VAR_gateway_name="$GATEWAY"
export TF_VAR_foundry_account_id="$(az cognitiveservices account show -g "$FOUNDRY_RG" -n "$FOUNDRY_ACCOUNT" \
  --query id -o tsv)"

# Delete everything that terraform apply added to your gateway: the gateway and the Foundry account stay
terraform destroy -auto-approve &&
  echo "🚮 Everything that terraform apply added is deleted"
```

```powershell title="PowerShell"
# Move into the lab's Terraform folder, and point Terraform at your gateway and the Foundry account
Set-Location ~/aigateway/labs/25-claude-code/terraform
if ($?) { Write-Host "📂 Terraform folder: $(Get-Location)" }
$env:ARM_SUBSCRIPTION_ID        = az account show --query id --output tsv
$env:TF_VAR_resource_group_name = $RG
$env:TF_VAR_gateway_name        = $GATEWAY
$env:TF_VAR_foundry_account_id  = az cognitiveservices account show -g $FOUNDRY_RG -n $FOUNDRY_ACCOUNT --query id -o tsv

# Delete everything that terraform apply added to your gateway: the gateway and the Foundry account stay
terraform destroy -auto-approve
if ($?) { Write-Host "🚮 Everything that terraform apply added is deleted" }
```

> **Checkpoint**
> `terraform destroy` ended with `Destroy complete! Resources: 9 destroyed.`, or 7 when Terraform didn't create the
> role assignment and the provider. Add one when Terraform manages `learn`.

<!-- /tracks -->

On the portal, Azure CLI, and Bicep tracks, the gateway's managed identity keeps the **Foundry User** role on the
Foundry account, and so it does on the Terraform track when the checks set `grant_foundry_user` to `false`. Leave it
if another provider on the gateway uses the account. Otherwise, remove it in the Foundry account's **Access control
(IAM)** in the Azure portal.

## Next steps

- [Throttle tokens per caller with token limits](../06-token-limits/README.md) and
  [Set a cost budget with cost limits](../07-cost-budgets/README.md): tune the limits for agent traffic, with
  overrides for some keys.
- [Manage runtime API keys](../10-api-keys/README.md): rotate, suspend, and revoke the keys that developers use.
- [Monitor usage, cost, and traces](../13-monitoring/README.md): see Claude Code's usage by key next to your apps.
- [Use your gateway's models and tools in GitHub Copilot](../24-github-copilot-byok/README.md): give GitHub Copilot
  the same gateway.
- [Federate MCP tools behind one endpoint](../04-federate-mcp-tools/README.md) and
  [Control which tools agents can call](../05-mcp-tool-controls/README.md): grow and govern the tools that Claude Code
  calls.
- [Authorize callers with Microsoft Entra ID](../11-entra-rbac/README.md): replace the key with Entra tokens.
- Claude Code docs: [LLM gateway configuration](https://code.claude.com/docs/en/llm-gateway),
  [Model configuration](https://code.claude.com/docs/en/model-config),
  [MCP](https://code.claude.com/docs/en/mcp), and [Manage costs](https://code.claude.com/docs/en/costs).
