> ## 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.

# Deploy coding agents with MDM

> Roll out Claude Code, Codex, Claude Desktop, and other coding agents to every employee through MDM, routed through the TrueFoundry AI Gateway.

Use your Mobile Device Management (MDM) system to connect every employee's coding agents to the **TrueFoundry AI Gateway**. You write one configuration file, `mdm.toml`, that lists the agents, models, sign-in method, MCP servers, and Skills to deploy. A script that your MDM runs on a schedule runs the `tfy-local-ai-setup` binary, which applies that file on each device and keeps it applied.

This guide is for IT administrators. To connect agents on your own computer without MDM, see [Set Up Your IDEs](https://www.truefoundry.com/docs/ai-gateway/personal-setup.md).

## How it works

```mermaid theme={"dark"}
flowchart LR
  A["MDM runs the script<br/>on a schedule, as root"] --> B["Script installs the pinned<br/>binary and writes mdm.toml"]
  B --> C["Binary signs in as the<br/>logged-in employee"]
  C --> D["Binary writes locked managed<br/>settings for each agent"]
  D --> E["Agents send requests to the<br/>AI Gateway as that employee"]
```

On each run, the binary:

1. **Writes managed settings** that employees cannot edit: the gateway URL, models, sign-in, MCP servers, and policy for each agent. It locks the Claude Code, Codex, and Claude Desktop files, its own policy file (`agents-policy.json`), Cursor hooks, and other agents' managed settings (`chflags schg` on macOS, `chattr +i` on Linux, an admin-only ACL on Windows).
2. **Writes user settings** for agents that have no managed settings, installs Skills in each agent's Skills folder, and adds a shell block for agents that read the gateway from environment variables. Employees can edit these files; the next run reapplies them. The first time the binary edits an existing user file, it keeps the original as a `.bak` copy. For every path, see [Files written](https://www.truefoundry.com/docs/ai-gateway/mdm/configuration-reference.md#files-written).
3. **Signs the employee in** and refreshes their credential, so no shared API key is ever distributed.

Each request is attributed to the individual employee in the gateway. The binary does not install the agents themselves and does not create a schedule; your MDM handles both.

## Supported agents

**Managed** settings are machine-wide and locked; employees cannot edit them. **User** settings are in the employee's home directory; employees can edit them, and the next run reapplies them. Skills are always per-user.

| Agent | Table in `mdm.toml` | What is configured |
| - | - | - |
| [Claude Code](https://www.truefoundry.com/docs/ai-gateway/mdm/claude.md) | `[agents.claude-code]` | Managed gateway, models, sign-in, policy, and MCP servers; user Skills |
| [Codex](https://www.truefoundry.com/docs/ai-gateway/mdm/codex.md) (CLI and desktop app) | `[agents.codex]` | Managed configuration for the CLI and desktop app; user Skills |
| [Claude Desktop](https://www.truefoundry.com/docs/ai-gateway/mdm/claude.md#add-claude-desktop) | `[agents.claude-desktop]` | Managed gateway, models, sign-in, MCP servers, and preferences; Skill ZIPs for upload. macOS and Windows only |
| OpenCode | `[agents.opencode]` | Managed provider, models, and MCP servers; user Skills |
| Qwen Code | `[agents.qwen-code]` | Managed settings and MCP servers; user Skills |
| Gemini CLI | `[agents.gemini-cli]` | Managed settings and MCP servers, plus a user shell environment for the gateway and credentials |
| Grok Build | `[agents.grok-build]` | Managed requirements and defaults on macOS and Linux; user configuration on Windows. User settings can override the default model and MCP servers |
| Pi, GitHub Copilot CLI, Goose | `[agents.pi]`, `[agents.copilot-cli]`, `[agents.goose]` | User models, MCP servers, and Skills |
| VS Code | `[agents.vscode]` | User configuration. Model sign-in can need a step in the app |
| Cursor | `[agents.cursor]` | MCP servers and Skills. Monitoring is configured separately |

All agents are supported on macOS, Linux, and Windows except Claude Desktop. Native Windows deployment does not configure WSL unless you pass `--wsl`. For each agent's extra options, see the [configuration reference](https://www.truefoundry.com/docs/ai-gateway/mdm/configuration-reference.md#fields).

## Before you start

* **An MDM that runs scripts** as root on macOS/Linux or as Administrator/SYSTEM on Windows, on a schedule. Jamf, Kandji, Mosyle, Intune, SCCM, Group Policy, and configuration tools such as Ansible, Chef, or Puppet all work.
* **Your connection details:** the TrueFoundry control-plane URL (the address of your TrueFoundry console), your tenant name, and the gateway base URL. Copy the gateway URL, including any `/api/llm` path, from a [Playground code snippet](https://www.truefoundry.com/docs/ai-gateway/quick-start.md#gateway-base-url).
* **Gateway models that employees can access.** Claude Code needs Opus, Sonnet, and Haiku tier models. Codex needs a [Virtual Model with a bare OpenAI model slug](https://www.truefoundry.com/docs/ai-gateway/openai-codex-cli.md#why-you-need-a-virtual-model), such as `gpt-5.4`.
* **Identity controls in your vendors' consoles.** Enforce SSO in [Claude](https://support.claude.com/en/articles/13132885-set-up-single-sign-on-sso) and in [OpenAI](https://learn.chatgpt.com/docs/enterprise/managed-configuration) so employees cannot fall back to personal accounts.
* **The agents, installed separately.** You can deploy the configuration before or after installing them.

### Choose how employees sign in

Every employee signs in with their own TrueFoundry identity. Choose one method for your rollout:

| | Device login (default) | OIDC |
| - | - | - |
| **Set in `mdm.toml`** | `mode = "api-key"` | `mode = "oidc"` plus `[auth.oidc]` |
| **When the browser opens** | During the first MDM run, in the employee's session | The first time Claude Code or Codex needs a token. Claude Desktop asks on first launch. With additional agents or Cursor monitoring, also once during the first MDM run |
| **Where the credential lives** | Written into the agents' managed settings and refreshed on every run | Nowhere in config files. Agents ask the binary for a token when they need one |
| **How long sign-in lasts** | 30 days, renewed on every successful run | Until your OIDC client's `refresh_token_ttl` passes without using an agent |
| **Extra setup** | None | [Set up OIDC sign-in](#set-up-oidc-sign-in) |

Start with **device login** unless your security team requires OIDC.

## Set up OIDC sign-in

Skip this section if you use device login.

With OIDC, no credential is written into the agents' configuration. Claude Code and Codex ask the installed `tfy-local-ai-setup` binary for a token when they need one, and Claude Desktop signs in itself. One public OIDC client, with no client secret, serves all three agents. Other agents, such as OpenCode or Gemini CLI, and Cursor monitoring do not ask for tokens on demand; the first MDM run signs the employee in for them, as described in [What employees see](#what-employees-see).

> [!NOTE]
>
> **Claude Desktop 2.7032.0 or later is required** on every device before you roll out OIDC. These settings replace the older `interactive` and `inferenceGatewayOidc` pair, which the binary removes on its next run. The issuer, client ID, scopes, and token type stay the same.

### Create the OIDC client

**1. Create a Personal Access Token**

Create a [Personal Access Token](https://www.truefoundry.com/docs/generating-truefoundry-api-keys.md#create-a-pat) as a user with the **Manage settings** permission on the tenant. You need it only to create the client.

**2. Create the client**

Replace the control-plane URL and token, then run:

```bash theme={"dark"}
curl --request PUT '<your-control-plane-url>/api/svc/v1/oidc/clients' \
  --header 'Content-Type: application/json' \
  --header 'Authorization: Bearer <your-PAT>' \
  --data '{
    "manifest": {
      "name": "tfy-mdm",
      "display_name": "TrueFoundry MDM",
      "client_type": "public",
      "application_type": "native",
      "token_endpoint_auth_method": "none",
      "pkce": "required",
      "redirect_uris": [
        "http://127.0.0.1/callback",
        "http://127.0.0.1:8585/callback",
        "http://127.0.0.1:8586/callback",
        "http://127.0.0.1:8587/callback"
      ],
      "allowed_scopes": ["openid", "profile", "email", "offline_access"],
      "allowed_grant_types": ["authorization_code", "refresh_token"],
      "access_token_ttl": "1d",
      "refresh_token_ttl": "7d",
      "refresh_token_max_uses": 1
    }
  }'
```

On a self-hosted control plane, use its URL; the path stays `/api/svc/v1/oidc/clients`.

* **Redirect URIs:** Claude Desktop uses `http://127.0.0.1/callback`. The binary, which signs in for Claude Code and Codex, listens on port 8585, or on 8586 or 8587 if that port is busy.
* **`refresh_token_ttl`** sets how long an employee stays signed in without using an agent. With `refresh_token_max_uses: 1`, each refresh issues a new refresh token.

**3. Copy the client ID**

The response looks like `{ "data": { "id": "cli_...", "manifest": { ... } } }`. `data.id` is the client ID.

Sending the request again with the same `manifest.name` updates the client and keeps its ID. `client_type` cannot be changed after creation.

**4. Find the issuer**

The issuer is your control-plane URL followed by `/<tenant>`, for example `https://<tenant_name>.truefoundry.cloud/<tenant_name>`. Open `<issuer>/.well-known/openid-configuration` and copy its `issuer` value exactly.

**5. Add OIDC to mdm.toml**

When you [write `mdm.toml`](#deploy-to-a-pilot-device), replace its `[auth]` table:

```toml theme={"dark"}
[auth]
mode = "oidc"

[auth.oidc]
issuer = "https://<tenant_name>.truefoundry.cloud/<tenant_name>"
client_id = "cli_abc123"
```

The client ID is public, so it is safe in the script. To use OIDC for only some agents, keep `mode = "api-key"` and set `auth = "oidc"` in the `[agents.claude-code]`, `[agents.codex]`, or `[agents.claude-desktop]` table. All additional agents must use the same mode.

### What employees see

* **MDM runs** write the configuration for Claude Code, Codex, and Claude Desktop without opening a browser. If you also deploy additional agents, such as OpenCode or Gemini CLI, or Cursor monitoring, the first MDM run signs the employee in once through the browser.
* **Claude Code and Codex** open a browser sign-in the first time they need a token. Later requests reuse the cached access token, or refresh it silently, without a browser.
* **Claude Desktop** asks the employee to sign in on first launch and keeps its own session.
* **When the refresh token expires**, after `refresh_token_ttl` without use, the next request opens the browser again.

### What OIDC writes

* **Claude Code:** `apiKeyHelper` in `managed-settings.json` runs `tfy-local-ai-setup --_print-oidc-token`.
* **Codex:** `[model_providers.truefoundry.auth]` has a `command` that runs the binary with `--_print-oidc-token`.
* **Claude Desktop:** `inferenceCredentialKind` = `external-idp` and `inferenceIdpOidc` = `{"bearerTokenType":"access_token","clientId":"<client-id>","issuer":"<issuer>","scopes":"openid profile email offline_access"}`.

No token is stored in any of these files. The binary caches tokens in the employee's `~/.tf/oidc-*` files, separate from device login's `~/.tf/refresh-token`. For each agent's file paths, see What gets written for [Claude Code and Claude Desktop](https://www.truefoundry.com/docs/ai-gateway/mdm/claude.md#what-gets-written) and for [Codex](https://www.truefoundry.com/docs/ai-gateway/mdm/codex.md#what-gets-written).

Keep the Claude Desktop defaults:

* **`bearerTokenType` must be `access_token`.** The gateway validates access tokens and rejects ID tokens, which are Desktop's default.
* **Keep `openid` in the scopes**, or Desktop's sign-in fails. Desktop still sends the access token to the gateway.

The binary flags `--oidc-bearer-token-type` and `--oidc-scopes` change these values; leave them at their defaults for TrueFoundry.

### Limitations

* Codex's [ChatGPT subscription mode](https://www.truefoundry.com/docs/ai-gateway/mdm/codex.md#use-a-chatgpt-business-or-enterprise-subscription) needs device login. Claude Code with a [Claude Enterprise or Team subscription](https://www.truefoundry.com/docs/ai-gateway/mdm/claude.md#use-a-claude-enterprise-or-team-subscription) is also set up with device login.
* [`mcp_servers = ["@all"]`](#add-mcp-servers-and-skills) uses the employee's cached OIDC sign-in. Until the employee has signed in once, runs with it fail without writing any configuration, so Claude Code never receives its sign-in command. Roll out with a fixed `mcp_servers` list first.

## Deploy to a pilot device

Test on one device per operating system, with an employee who is logged in and available to complete a browser sign-in.

> [!WARNING]
>
> **On a device that already has a TrueFoundry rollout, `mdm.toml` replaces what the binary manages there.** For example, a file without `mcp_servers` removes the gateway MCP servers an earlier rollout deployed, and one without `[monitoring.cursor]` removes its Cursor hooks. Before you run on such a device, copy the existing settings into `mdm.toml`: MCP servers, Cursor monitoring, prompt blocks, and the Claude Code policy. Then preview the changes with a dry run, `sudo DRY_RUN=true ./deploy-mdm.sh`, as described in **Preview before applying** below.

**1. Write mdm.toml**

Copy this file and edit it. It contains every setting you are likely to need: the active lines are a working rollout of Claude Code and Codex, and every other setting is commented out with what it does and its default. To turn a setting on, remove the `#`. To use a setting under a commented `[table]` line, uncomment that table line too. An agent is deployed only when its `[agents.<id>]` table is present.

```toml mdm.toml theme={"dark"}
# mdm.toml: coding-agent rollout through the TrueFoundry AI Gateway.
#
# How to read this file:
#   - The active lines are a working rollout of Claude Code and Codex.
#   - Every other setting is commented out, with what it does and its default.
#     Remove the # to use it. For a setting under a commented [table] line,
#     uncomment that table line too.
#   - An agent is deployed only when its [agents.<id>] table is present.
#   - Never put a token, refresh token, or client secret in this file.

# =====================================================================
# Connection (required)
# =====================================================================
control_plane_url = "<your-control-plane-url>"   # The address of your TrueFoundry console
tenant_name = "<your-tenant-name>"
gateway_url = "<your-gateway-url>"               # From a Playground code snippet, including any /api/llm path

# =====================================================================
# MCP servers and Skills that every agent gets (default: none)
# =====================================================================
# Each list takes one of:
#   ["@all"]     Everything each employee can access, checked again on every run.
#                Skills follow their latest published version.
#   ["a", "b"]   A fixed list. MCP servers: registry names. Skills: [repo/]name[:version];
#                omit :version to follow the latest.
#   []           None. Removing the line also deploys none, and removes what
#                an earlier run deployed.
# An agent's own mcp_servers or skills (see Agents below) replaces the list for that agent.
#
# MCP ["@all"] reuses the employee's existing sign-in and never opens a browser.
# Until an employee has signed in once, the whole run exits 1 and writes nothing,
# so roll out with a fixed list first and switch to ["@all"] later.
# mcp_servers = ["github", "linear"]
# skills = ["@all"]

# =====================================================================
# Sign-in
# =====================================================================
[auth]
# "api-key": device login, the default. Each employee signs in once in the browser
#            during the first run. Their own credential is written into the agents'
#            settings and renewed on every run; after 30 days without a successful
#            run, they sign in again. No shared key is used.
# "oidc":    agents ask the binary for a token when they need one, so no credential
#            is stored in config files. Needs [auth.oidc]. With agents other than
#            Claude Code, Codex, and Claude Desktop, or with Cursor monitoring, the
#            first run also opens the browser once.
mode = "api-key"

# Required when mode, or any agent's auth, is "oidc". See Set up OIDC sign-in.
# [auth.oidc]
# issuer = "<your-control-plane-url>/<your-tenant-name>"
# client_id = "<your-oidc-client-id>"   # Public client ID. Never a client secret

# =====================================================================
# Agents
# =====================================================================
# Every agent table also accepts these keys:
#   mcp_servers = ["github"]   Replaces the shared MCP list for this agent. [] for none. ["@all"] is not accepted here
#   skills = []                Replaces the shared Skills list for this agent. [] for none. ["@all"] is not accepted here
#   auth = "oidc"              Overrides [auth] mode for this agent. Claude Code, Codex, and Claude Desktop
#                              can each differ; all other agents must use the same mode

# ---- Claude Code: managed settings, locked on the device ----
[agents.claude-code]
# auth = "oidc"
# gateway = "<other-gateway-url>"   # Send only Claude Code to another gateway. Default: gateway_url
# mcp_servers = ["github"]
# skills = []

# Gateway model for each Claude tier. Add [1m] to request 1M context from a model
# that supports it, for example "claude-code/claude-opus[1m]".
[agents.claude-code.models]
opus = "claude-code/claude-opus"
sonnet = "claude-code/claude-sonnet"
haiku = "claude-code/claude-haiku"

# Claude Code policy (advanced): any key from Claude Code's managed settings.
# Without this table, the binary keeps the policy in the device's existing
# managed-settings.json, or applies a built-in baseline. Uncommenting it REPLACES
# that policy, so include every rule you want. See Set the Claude Code policy.
# [agents.claude-code.managed_settings]
# allowManagedPermissionRulesOnly = true   # Ignore permission rules employees add themselves
# allowManagedHooksOnly = true             # Ignore hooks employees add themselves
# transcriptRetentionDays = 14             # Delete local session transcripts after this many days
# strictKnownMarketplaces = []             # Allow no plugin marketplaces

# [agents.claude-code.managed_settings.permissions]
# disableBypassPermissionsMode = "disable" # Block --dangerously-skip-permissions
# deny = []                                # Tool calls that are always refused
# ask = [                                  # Tool calls that always need the employee's approval
#   "Bash(git push:*)",
#   "Edit(**)",
#   "Read(**/.env)",
#   "Read(**/secrets/**)",
#   "Read(**/.ssh/**)",
#   "Read(**/credentials/**)",
# ]

# Allow only MCP servers behind your gateway:
# [[agents.claude-code.managed_settings.allowedMcpServers]]
# serverUrl = "https://<your-gateway-host>/*"

# ---- Codex (CLI and desktop app): managed settings, locked on the device ----
[agents.codex]
model = "gpt-5.4"                      # Required. A Virtual Model whose name is a bare OpenAI model ID
# auth = "oidc"
# auth_mode = "chatgpt-subscription"   # Bill ChatGPT Business or Enterprise seats instead of the gateway's
#                                      # provider keys; requests still go through the gateway. Employees also
#                                      # sign in to ChatGPT in Codex. Needs auth = "api-key"
# gateway = "<other-gateway-url>"      # Send only Codex to another gateway. Default: gateway_url
# mcp_servers = []
# skills = []

# ---- Claude Desktop (macOS and Windows): managed settings, locked on the device ----
# [agents.claude-desktop]
# auth = "oidc"
# gateway = "<other-gateway-url>"   # Send only Claude Desktop to another gateway. Default: gateway_url
# tool_search_enabled = true        # Load MCP tool definitions only when needed. Default: the app's own setting
# prefer_1m_context = true          # Prefer 1M context for tiers that support it (see context below)
# mcp_servers = []
# skills = []                       # Desktop Skills are saved as ZIPs that employees upload in the app

# Gateway model for each tier. Default: the same models as Claude Code.
# [agents.claude-desktop.models]
# opus = "claude-code/claude-opus"
# sonnet = "claude-code/claude-sonnet"
# haiku = "claude-code/claude-haiku"

# 1M context for one tier. Repeat the table for sonnet and haiku.
# [agents.claude-desktop.context.opus]
# supports_1m = true                # The model behind this tier supports 1M context
# prefer_1m = true                  # Use 1M by default. Needs supports_1m = true

# Let employees import their claude.ai history.
# [agents.claude-desktop.history_import]
# enabled = true                    # Default: false. The other keys apply only when true
# encoding = "json-string"          # macOS only: json-string (default) or native-dict. Windows always uses JSON
# export_enabled = true             # Show the Export button. Default: true
# banner_behavior = "detect"        # off, detect (default), or show
# automatic_3p = false              # Beta. Import earlier sessions without asking. Default: false

# ---- Other agents ----
# models:        Gateway models the agent offers. Required.
# default_model: The model selected at start. Must be in models. Default: the first one.
# headers:       Extra request headers as "Name: Value", for example to tag requests in Request Logs.

# [agents.opencode]                 # Managed settings
# models = ["gpt-5.4", "<your-claude-model>"]
# default_model = "gpt-5.4"
# gateway_only = true               # Hide every other provider, so employees can pick only gateway models. Default: false
# headers = ['X-TFY-METADATA: {"team":"engineering"}']

# [agents.qwen-code]                # Managed settings
# models = ["gpt-5.4"]
# default_model = "gpt-5.4"
# headers = ["X-Team: engineering"]

# [agents.gemini-cli]               # Managed settings, plus a block in the employee's shell profile
# models = ["<your-gemini-model>"]
# default_model = "<your-gemini-model>"
# headers = ["X-Team: engineering"]

# [agents.grok-build]               # Managed on macOS and Linux, user settings on Windows.
# models = ["gpt-5.4"]              # Employees can change the default model and MCP servers
# default_model = "gpt-5.4"
# headers = ["X-Team: engineering"]

# [agents.pi]                       # User settings, applied again on every run
# models = ["gpt-5.4"]
# default_model = "gpt-5.4"
# headers = ["X-Team: engineering"]

# [agents.copilot-cli]              # GitHub Copilot CLI. User settings
# models = ["gpt-5.4"]
# default_model = "gpt-5.4"
# headers = ["X-Team: engineering"]

# [agents.goose]                    # User settings
# models = ["gpt-5.4"]
# default_model = "gpt-5.4"
# headers = ["X-Team: engineering"]

# [agents.vscode]                   # User settings. Model sign-in can need a step in the app
# models = ["gpt-5.4"]
# default_model = "gpt-5.4"
# utility_model = "mainAgent"       # Model for background tasks such as titles and summaries: mainAgent
#                                   # (the gateway model in use, default), copilot (GitHub Copilot's), or none
# headers = ["X-Team: engineering"]

# [agents.cursor]                   # MCP servers and Skills only. Set Cursor's models in Cursor
# mcp_servers = ["github"]

# =====================================================================
# Block new prompts in Claude Code, Codex, or Cursor
# =====================================================================
# [restrictions]
# blocked_agents = ["cursor"]       # claude-code, codex, cursor. [] lifts every block; deleting
#                                   # the table instead keeps the blocks from the last run
# message = "Contact IT for access" # Shown when a prompt is blocked. Default: "Your organization has
#                                   # disabled this application. Please use an approved alternative..."

# =====================================================================
# Send Cursor activity to the gateway (gateway v0.185.0 or later)
# =====================================================================
# Sends prompts, responses, tool and MCP calls, and session events to
# <gateway>/hooks/cursor with the employee's credential. Model routing is unchanged.
# [monitoring.cursor]
# enabled = true                    # false, or deleting the table, removes the hooks on the next run
# require_login = false             # true blocks Cursor prompts and tool calls when no credential is available
```

Before you deploy:

* Replace `control_plane_url`, `tenant_name`, and `gateway_url` with your connection details.
* Replace the model IDs with gateway models your employees can access.
* Keep a table only for each agent you deploy. Claude Code, Codex, Claude Desktop, and agents with managed settings are configured even before they are installed.
* Optional: uncomment the Claude Code policy to set your own. Without it, the binary keeps the policy in an existing `managed-settings.json`, or applies a built-in baseline. See [Set the Claude Code policy](https://www.truefoundry.com/docs/ai-gateway/mdm/claude.md#set-the-claude-code-policy).

Unknown keys and duplicate tables fail validation. A few rarely needed options, such as per-agent token limits and wire protocols, are listed only in the [configuration reference](https://www.truefoundry.com/docs/ai-gateway/mdm/configuration-reference.md#fields), with each field's type, default, and accepted values. Files in the older layout, with `url`, `tenant`, and `tools`, still work; see [Older file layout](https://www.truefoundry.com/docs/ai-gateway/mdm/configuration-reference.md#older-file-layout).

**2. Create the deployment script**

The script installs a pinned `tfy-local-ai-setup` release, checks it against the release's checksums, and stops if they are missing or do not match. It then writes your `mdm.toml` and runs the binary. Copy the script for your platform and paste your `mdm.toml` into the **Configuration** section at the top.

> [tab] macOS
>
> ```bash deploy-mdm.sh theme={"dark"}
> #!/bin/bash
> # Installs tfy-local-ai-setup, writes mdm.toml, and applies it.
> # Run on a schedule as root. Preview without applying: sudo DRY_RUN=true ./deploy-mdm.sh
> set -euo pipefail
>
> # ---- Configuration: edit this section ----
> RELEASE_TAG="v2.3.2"
> MDM_TOML=$(cat <<'TOML'
> # Paste your mdm.toml here, between the two TOML lines.
> TOML
> )
> # ---- End of configuration ----
>
> BINARY="/usr/local/bin/tfy-local-ai-setup"
> CONFIG="/Library/Application Support/TrueFoundry/mdm.toml"
> LOG_FILE="/var/log/tfy-mdm-setup.log"
> DRY_RUN="${DRY_RUN:-false}"
>
> [[ "$(id -u)" -eq 0 ]] || { echo "Run as root" >&2; exit 1; }
> case "$(uname -m)" in
>   arm64) ASSET="tfy-local-ai-setup-darwin-arm64" ;;
>   x86_64) ASSET="tfy-local-ai-setup-darwin-amd64" ;;
>   *) echo "Unsupported CPU: $(uname -m)" >&2; exit 1 ;;
> esac
> WORK_DIR="$(mktemp -d)"
> trap 'rm -rf "${WORK_DIR}"' EXIT
>
> # 1. Install the pinned release if it is missing or a different version.
> if [[ ! -x "${BINARY}" || "$(cat "${BINARY}.version" 2>/dev/null)" != "${RELEASE_TAG}" ]]; then
>   BASE="https://github.com/truefoundry/tfy-local-ai-setup/releases/download/${RELEASE_TAG}"
>   curl -fLsS --retry 3 -o "${WORK_DIR}/${ASSET}" "${BASE}/${ASSET}"
>   curl -fLsS --retry 3 -o "${WORK_DIR}/SHA256SUMS" "${BASE}/SHA256SUMS"
>   (cd "${WORK_DIR}" && grep "  ${ASSET}\$" SHA256SUMS | shasum -a 256 -c -)
>   mkdir -p "$(dirname "${BINARY}")"
>   install -o root -g wheel -m 755 "${WORK_DIR}/${ASSET}" "${BINARY}.new"
>   mv -f "${BINARY}.new" "${BINARY}"
>   echo "${RELEASE_TAG}" > "${BINARY}.version"
> fi
>
> # 2. Write the configuration: root-owned, readable by everyone.
> RUN_ARGS=("--log-file=${LOG_FILE}")
> if [[ "${DRY_RUN}" == "true" ]]; then
>   CONFIG="${WORK_DIR}/mdm.toml"
>   RUN_ARGS+=(--dry-run)
> fi
> mkdir -p "$(dirname "${CONFIG}")"
> printf '%s\n' "${MDM_TOML}" > "${WORK_DIR}/mdm.toml.new"
> install -o root -g wheel -m 644 "${WORK_DIR}/mdm.toml.new" "${CONFIG}"
>
> # 3. Apply it. The script exits with the binary's exit code.
> "${BINARY}" --config="${CONFIG}" "${RUN_ARGS[@]}"
> ```

> [tab] Linux
>
> A root job on Linux has no login session from which to find the employee. Set `TFY_MDM_USER` to the employee's account in the job that runs the script.
>
> ```bash deploy-mdm.sh theme={"dark"}
> #!/bin/bash
> # Installs tfy-local-ai-setup, writes mdm.toml, and applies it.
> # Run on a schedule as root with TFY_MDM_USER set to the employee account.
> # Preview without applying: sudo TFY_MDM_USER=alice DRY_RUN=true ./deploy-mdm.sh
> set -euo pipefail
>
> # ---- Configuration: edit this section ----
> RELEASE_TAG="v2.3.2"
> MDM_TOML=$(cat <<'TOML'
> # Paste your mdm.toml here, between the two TOML lines.
> TOML
> )
> # ---- End of configuration ----
>
> BINARY="/usr/local/bin/tfy-local-ai-setup"
> CONFIG="/etc/truefoundry/mdm.toml"
> LOG_FILE="/var/log/tfy-mdm-setup.log"
> DRY_RUN="${DRY_RUN:-false}"
>
> [[ "$(id -u)" -eq 0 ]] || { echo "Run as root" >&2; exit 1; }
> TARGET_USER="${TFY_MDM_USER:?Set TFY_MDM_USER to the employee account}"
> [[ "$(id -u "${TARGET_USER}")" -ne 0 ]] || { echo "Select a non-root employee" >&2; exit 1; }
> export SUDO_USER="${TARGET_USER}"
> case "$(uname -m)" in
>   x86_64) ASSET="tfy-local-ai-setup-linux-amd64" ;;
>   aarch64|arm64) ASSET="tfy-local-ai-setup-linux-arm64" ;;
>   *) echo "Unsupported CPU: $(uname -m)" >&2; exit 1 ;;
> esac
> WORK_DIR="$(mktemp -d)"
> trap 'rm -rf "${WORK_DIR}"' EXIT
>
> # 1. Install the pinned release if it is missing or a different version.
> if [[ ! -x "${BINARY}" || "$(cat "${BINARY}.version" 2>/dev/null)" != "${RELEASE_TAG}" ]]; then
>   BASE="https://github.com/truefoundry/tfy-local-ai-setup/releases/download/${RELEASE_TAG}"
>   curl -fLsS --retry 3 -o "${WORK_DIR}/${ASSET}" "${BASE}/${ASSET}"
>   curl -fLsS --retry 3 -o "${WORK_DIR}/SHA256SUMS" "${BASE}/SHA256SUMS"
>   (cd "${WORK_DIR}" && grep "  ${ASSET}\$" SHA256SUMS | sha256sum -c -)
>   mkdir -p "$(dirname "${BINARY}")"
>   install -o root -g root -m 755 "${WORK_DIR}/${ASSET}" "${BINARY}.new"
>   mv -f "${BINARY}.new" "${BINARY}"
>   echo "${RELEASE_TAG}" > "${BINARY}.version"
> fi
>
> # 2. Write the configuration: root-owned, readable by everyone.
> RUN_ARGS=("--log-file=${LOG_FILE}")
> if [[ "${DRY_RUN}" == "true" ]]; then
>   CONFIG="${WORK_DIR}/mdm.toml"
>   RUN_ARGS+=(--dry-run)
> fi
> mkdir -p "$(dirname "${CONFIG}")"
> printf '%s\n' "${MDM_TOML}" > "${WORK_DIR}/mdm.toml.new"
> install -o root -g root -m 644 "${WORK_DIR}/mdm.toml.new" "${CONFIG}"
>
> # 3. Apply it. The script exits with the binary's exit code.
> "${BINARY}" --config="${CONFIG}" "${RUN_ARGS[@]}"
> ```

> [tab] Windows
>
> Run the script in a 64-bit PowerShell process, as SYSTEM or elevated. The x86-64 binary also runs on Windows on Arm.
>
> ```powershell deploy-mdm.ps1 theme={"dark"}
> # Installs tfy-local-ai-setup, writes mdm.toml, and applies it.
> # Run on a schedule as SYSTEM or Administrator. To preview without applying, set $DryRun = $true.
> $ErrorActionPreference = 'Stop'
>
> # ---- Configuration: edit this section ----
> $ReleaseTag = 'v2.3.2'
> # Paste your mdm.toml between @' and '@. Keep '@ at the start of its line.
> $MdmToml = @'
> # Paste your mdm.toml here.
> '@
> # ---- End of configuration ----
>
> $DryRun = $false
> if (-not [Environment]::Is64BitProcess) { throw 'Use 64-bit PowerShell' }
> $Asset = 'tfy-local-ai-setup-windows-amd64.exe'
> $SetupDir = Join-Path $env:ProgramFiles 'TrueFoundry'
> $Binary = Join-Path $SetupDir 'tfy-local-ai-setup.exe'
> $WorkDir = Join-Path ([IO.Path]::GetTempPath()) ("tfy-mdm-" + [guid]::NewGuid())
> New-Item -ItemType Directory -Force -Path $SetupDir, $WorkDir | Out-Null
>
> try {
>   # 1. Install the pinned release if it is missing or a different version.
>   $installed = if (Test-Path "$Binary.version") { (Get-Content "$Binary.version" -Raw).Trim() } else { '' }
>   if (-not (Test-Path $Binary) -or $installed -ne $ReleaseTag) {
>     [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
>     $base = "https://github.com/truefoundry/tfy-local-ai-setup/releases/download/$ReleaseTag"
>     Invoke-WebRequest -UseBasicParsing "$base/$Asset" -OutFile "$WorkDir\$Asset"
>     Invoke-WebRequest -UseBasicParsing "$base/SHA256SUMS" -OutFile "$WorkDir\SHA256SUMS"
>     $line = Select-String -Path "$WorkDir\SHA256SUMS" -Pattern "  $([regex]::Escape($Asset))$"
>     $actual = (Get-FileHash "$WorkDir\$Asset" -Algorithm SHA256).Hash
>     if (-not $line -or $actual -ne $line.Line.Split(' ')[0]) { throw "Checksum mismatch for $Asset" }
>     # A running binary can be renamed but not overwritten.
>     Remove-Item "$Binary.old" -Force -ErrorAction SilentlyContinue
>     if (Test-Path $Binary) { Move-Item $Binary "$Binary.old" -Force }
>     Move-Item "$WorkDir\$Asset" $Binary
>     Set-Content -Path "$Binary.version" -Value $ReleaseTag
>   }
>
>   # 2. Write the configuration. Program Files is writable only by administrators.
>   $config = if ($DryRun) { "$WorkDir\mdm.toml" } else { "$SetupDir\mdm.toml" }
>   [IO.File]::WriteAllText($config, $MdmToml)
>   $runArgs = @("--config=$config", "--log-file=$SetupDir\mdm-setup.log")
>   if ($DryRun) { $runArgs += '--dry-run' }
>
>   # 3. Apply it. The script exits with the binary's exit code.
>   & $Binary @runArgs
>   $code = $LASTEXITCODE
> } finally {
>   Remove-Item -Recurse -Force $WorkDir -ErrorAction SilentlyContinue
> }
> exit $code
> ```

Keep `RELEASE_TAG` the same across your rollout. To upgrade, change it and redeploy the script.

**3. Run it through your MDM**

Add the script to your MDM and run it once on the pilot device while the employee is logged in.

With device login, the run opens a browser sign-in in the employee's session if they have not signed in before. Ask them to complete it while the run is in progress. The binary then writes each agent's configuration in the same run.

With OIDC, a run that configures only Claude Code, Codex, and Claude Desktop writes the configuration without opening a browser, and the employee signs in later from the agent. With additional agents or Cursor monitoring, the run also signs the employee in once. See [What employees see](#what-employees-see).

**Checkpoint:** the MDM reports exit code `0`, and neither the script's output nor the log file (`/var/log/tfy-mdm-setup.log`, or `C:\Program Files\TrueFoundry\mdm-setup.log`) shows errors. Some errors appear only in the script's output, so always check the exit code. If sign-in failed or timed out, run the script again when the employee is available. See [Exit codes](#exit-codes).

> [accordion] Preview before applying
>
> Run the script with a dry run from an administrator terminal: `sudo DRY_RUN=true ./deploy-mdm.sh`. On Windows, set `$DryRun = $true` in the script. The preview prints each agent's changes without writing them.
>
> A dry run still signs the employee in when needed, and its output can include their live credential. Do not share it.

**4. Check that the settings are locked**

Confirm the managed files exist and employees cannot change them:

> [tab] macOS
>
> ```bash theme={"dark"}
> ls -lO "/Library/Application Support/ClaudeCode/managed-settings.json"   # expect "schg"
> ls -lO /etc/codex/managed_config.toml                                      # expect "schg"
> ```

> [tab] Linux
>
> ```bash theme={"dark"}
> lsattr /etc/claude-code/managed-settings.json   # expect the "i" attribute
> lsattr /etc/codex/managed_config.toml           # expect the "i" attribute
> ```

> [tab] Windows
>
> ```powershell theme={"dark"}
> icacls "C:\Program Files\ClaudeCode\managed-settings.json"   # expect Users read-only
> icacls C:\ProgramData\OpenAI\Codex                           # expect owner Administrators, Users:(RX)
> ```

**Checkpoint:** each file shows its lock. To check what each file contains, see Verify the deployment for [Claude Code and Claude Desktop](https://www.truefoundry.com/docs/ai-gateway/mdm/claude.md#verify-the-deployment) and for [Codex](https://www.truefoundry.com/docs/ai-gateway/mdm/codex.md#verify-the-deployment).

**5. Send a test request**

Restart each agent, open a new terminal for terminal-based agents, and send:

```text theme={"dark"}
Reply exactly TFY-CHAT-OK. Do not use tools.
```

**Checkpoint:** the reply arrives without an authentication or model error, and the request appears in **TrueFoundry → AI Gateway → Request Logs** under the employee and the expected model. A reply alone does not prove the request went through the gateway.

If you deployed MCP servers or Skills, test them separately: employees authorize each MCP server inside their agent. See the [FAQ](#faq).

## Roll out to your fleet

1. **Widen gradually.** After the pilot passes on each operating system, deploy to a small group, then to everyone.
2. **Schedule the script to run regularly**, plus on demand. Each run refreshes device-login credentials and reapplies settings that employees changed, so run it often enough to refresh credentials before they expire; hourly is a common choice. On Intune, platform scripts run only once, so use Remediations or a scheduled task.
3. **Tell employees what to expect:** a one-time browser sign-in, restarting their agents after the first run, and authorizing MCP servers inside each agent.
4. **Install agents in any order.** Claude Code, Codex, Claude Desktop, and agents with managed settings are configured before installation. Agents configured through user settings are configured on the first run after they are installed.

### Windows Subsystem for Linux

Claude Code and Codex running inside WSL read the distribution's own `/etc/claude-code` and `/etc/codex`, not the Windows configuration. Add `--wsl` to the binary's command in your script to also configure Claude Code and Codex in the employee's WSL distributions.

* It is off by default because reaching a stopped distribution starts it.
* Running distributions are updated on every run; stopped ones at most once a day, so they can be up to 24 hours behind.
* Container distributions, such as `docker-desktop`, `rancher-desktop`, and `podman-machine-*`, are skipped.
* Inside WSL this routes traffic but does not enforce it: anyone who can run `wsl.exe` is root in the distribution.
* WSL does not inherit Windows VPN or proxy routes, so check that the gateway is reachable from inside.
* [Prompt blocks](#block-an-agent) from native Windows hooks do not cover WSL.

Verify with `wsl.exe -d Ubuntu cat /etc/claude-code/managed-settings.json` for Claude Code, or `wsl.exe -d Ubuntu cat /etc/codex/managed_config.toml` for Codex.

### Exit codes

The script exits with the binary's exit code, so your MDM can report failures:

* **`0`:** configuration applied.
* **`1`:** the run failed. Check the script's output and the log file; the next run retries. Configuration already written stays in place if the run failed after some agents were configured.
* **`2`:** invalid command-line flags or arguments. Check the binary's command in your script.
* **`3`:** configuration applied, but a Skill in `mdm.toml` does not exist. Fix the Skill reference.

## Customize your rollout

The settings you are likely to need are already in your [`mdm.toml`](#deploy-to-a-pilot-device), commented out, and the rest are in the [configuration reference](https://www.truefoundry.com/docs/ai-gateway/mdm/configuration-reference.md#fields). Uncomment what you need in the script's TOML block and redeploy it. The settings below need more than one line of explanation. For agent-specific options, see:

> [card] [Claude Code and Claude Desktop](https://www.truefoundry.com/docs/ai-gateway/mdm/claude.md)
>
> Policy, MCP allowlist, models, Claude Enterprise or Team subscriptions, Desktop connectors, tool search, 1M context, claude.ai history import.

> [card] [Codex](https://www.truefoundry.com/docs/ai-gateway/mdm/codex.md)
>
> Models, ChatGPT Business or Enterprise subscriptions, MCP allowlists, Windows enforcement.

### Add MCP servers and Skills

Register the resources in TrueFoundry and grant employees access first. Then set the top-level `mcp_servers` and `skills` lists in `mdm.toml`. Each takes one of three values:

| Value | Deploys |
| - | - |
| `["@all"]` | Every MCP server or published Skill each employee can access, checked again on every run. Skills follow their latest published versions |
| A list, such as `["github", "linear"]` | Exactly those [MCP registry names](https://www.truefoundry.com/docs/ai-gateway/mcp/mcp-overview.md) or [Skill references](https://www.truefoundry.com/docs/ai-gateway/skills/skills-registry.md), `[repo/]name[:version]` |
| `[]`, or the line left out | Nothing. Resources an earlier run deployed are removed |

* **Every agent gets the shared lists.** Set an agent's own `mcp_servers` or `skills` to a list to replace them for that agent, or `[]` to deploy nothing to it. `["@all"]` is accepted only in the shared lists.
* **Pin a Skill version**, as in `:1`, for a fixed rollout, or omit it to follow the latest version. Some agents also read other agents' Skill folders, so an empty list does not guarantee a Skill is hidden in that agent.
* **Deployed MCP servers are added alongside servers the employee added.** To block other servers, see [restrict Claude Code to gateway MCP servers](https://www.truefoundry.com/docs/ai-gateway/mdm/claude.md#restrict-mcp-servers-to-the-gateway) and [Codex MCP allowlists](https://www.truefoundry.com/docs/ai-gateway/mdm/codex.md#restrict-mcp-servers).

> [!WARNING]
>
> **`mcp_servers = ["@all"]` never opens a browser.** It uses the employee's existing sign-in, and if there is none, the whole run exits with code `1` and writes nothing, so a new employee is never signed in. Roll out with a fixed list first, and switch to `["@all"]` after employees have signed in. `skills = ["@all"]` does not block the rest of the configuration; it is retried on later runs.

With `["@all"]`, a failed lookup keeps the existing configuration and retries on the next run. A successful lookup that finds nothing removes the resources it deployed earlier.

### Monitor Cursor activity

> [!NOTE]
>
> Cursor monitoring requires TrueFoundry AI Gateway **v0.185.0** or later. Older gateways don't accept these events.

With `[monitoring.cursor]` enabled, the binary installs managed Cursor hooks that send prompts, agent responses, tool and MCP events, and session events to `<gateway>/hooks/cursor` with the employee's credential. These events can contain prompt and tool content. Monitoring does not change Cursor's model routing.

* `require_login = true` blocks agent prompts and tool and MCP calls when no credential is available. Delivery failures and gateway verdicts never block.
* To remove the hooks, set `enabled = false` or delete the table, and run the script again.
* **For monitoring only**, `mdm.toml` still needs at least one agent table. Add `[agents.cursor]` with `mcp_servers = []` and `skills = []`, so nothing else is deployed to Cursor. Without those two lines, Cursor also gets the shared MCP servers and Skills.

### Block an agent

Supported for Claude Code, Codex, and Cursor. List the agents in `[restrictions]` `blocked_agents` to stop employees from submitting prompts in them.

* `message` is what employees see when a prompt is blocked. If unset, they see "Your organization has disabled this application. Please use an approved alternative or contact your administrator."
* To remove every block, set `blocked_agents = []`. If you delete the `[restrictions]` table instead, the blocks from the last run stay in place.
* It blocks new prompts, not launching the app, manual editing, or Cursor Tab completions. Claude Code needs version 2.1.295 or later, and Codex may ask employees to trust the hook in `/hooks`.

## Monitor usage

Once agents route through the gateway, every model request and MCP tool call is logged with the employee, model, server, and tool, with no extra instrumentation.

* **Requests and metrics:** see [Request logging](https://www.truefoundry.com/docs/ai-gateway/request-logging.md) and [Analytics](https://www.truefoundry.com/docs/ai-gateway/analytics-overview.md) for models, MCP servers, and guardrails.
* **Your SIEM:** [export traces over OpenTelemetry](https://www.truefoundry.com/docs/ai-gateway/export-opentelemetry-data.md) to platforms such as Grafana, Datadog, or Splunk.
* **Spending:** set [budget limits](https://www.truefoundry.com/docs/ai-gateway/budget-limiting-v2.md) and [rate limits](https://www.truefoundry.com/docs/ai-gateway/ratelimiting-v2.md) per employee and team.

### Data retention

The gateway controls what is logged and where it goes, including request logging and audit, independent of any setting on the device. Local transcripts and retention on the providers' side are set separately:

* **Claude:** `transcriptRetentionDays` in the [Claude Code policy](https://www.truefoundry.com/docs/ai-gateway/mdm/claude.md#set-the-claude-code-policy) deletes local transcripts; 7 to 14 days is a common choice. Anthropic-side retention, Zero Data Retention, and compliance are configured with Anthropic; see [Claude's data retention documentation](https://platform.claude.com/docs/en/build-with-claude/zero-data-retention).
* **OpenAI:** retention of prompts and outputs is governed by your agreement with OpenAI, and differs between API usage and ChatGPT subscription plans. See OpenAI's [managed configuration](https://learn.chatgpt.com/docs/enterprise/managed-configuration) documentation for the admin controls on your plan.

## Update a rollout

Edit the TOML block or `RELEASE_TAG` in your script and redeploy it. The next run applies the change; restart agents that read settings at launch. Each run makes the device match `mdm.toml`, so preview larger changes with a dry run on a pilot device first. MCP servers and Skills that are no longer selected are removed, while entries employees added themselves are kept.

## Troubleshooting

| Symptom | Likely cause | Fix |
| - | - | - |
| Script output or log file shows `could not determine logged-in user` | Nobody was logged in, or `TFY_MDM_USER` is unset on Linux | Run while the employee is logged in. On Linux, set `TFY_MDM_USER` |
| Log shows `MCP refresh failed` | `mcp_servers = ["@all"]` is set and the employee has never signed in | Deploy a fixed `mcp_servers` list until the employee signs in |
| A browser opens on every run | The refresh token is not being saved in the employee's `~/.tf` directory | Check that the employee owns `~/.tf`, then run with `--debug` |
| Agent is unauthenticated after sign-in | The run did not finish after sign-in, or the agent was not restarted | Run the script again, then restart the agent |
| Script stops with a checksum error | `RELEASE_TAG` is wrong, the download was altered, or the release has no `SHA256SUMS` | Check the tag against the [releases page](https://github.com/truefoundry/tfy-local-ai-setup/releases) |
| Exit code `3` | A Skill in `skills` or an agent's `skills` does not exist | Correct the Skill reference |

For agent-specific issues, see Troubleshooting for [Claude Code and Claude Desktop](https://www.truefoundry.com/docs/ai-gateway/mdm/claude.md#troubleshooting) and for [Codex](https://www.truefoundry.com/docs/ai-gateway/mdm/codex.md#troubleshooting). When you contact support, share your TOML and the relevant log lines. Do not share files from `~/.tf`, dry-run output, or generated agent settings, which can contain credentials.

## FAQ

> [accordion] Will employees need to sign in on every scheduled run?
>
> No. With device login, the browser opens on the first run and again only after 30 days without a successful run. With OIDC, MDM runs open a browser at most once, on the first run, and only if you deploy agents other than Claude Code, Codex, and Claude Desktop, or Cursor monitoring. See [What employees see](#what-employees-see).

> [accordion] An employee closed the browser sign-in window. What now?
>
> With device login, run the MDM script again while the employee is available. With OIDC, the employee uses Claude Code or Codex again to get a new sign-in; they do not need to wait for the next MDM run.

> [accordion] Does deploying an MCP server sign the employee in to it?
>
> No. Employees authorize each server inside their agent, for example with `/mcp` in Claude Code or `codex mcp login <server-name>`.

> [accordion] Can employees change the configuration or use other providers?
>
> They cannot edit locked managed settings; user settings they edit are reapplied on the next run. The gateway setting alone does not block direct access to other providers, so use network controls if you need that.

> [accordion] What happens if nobody is logged in?
>
> The run exits with code `1`, and the next scheduled run retries once an employee is logged in.

> [accordion] Can employees also use personal setup?
>
> Yes, for agents that IT does not manage. Personal setup leaves IT-managed agents alone.

## Reference

> [card] [Configuration reference](https://www.truefoundry.com/docs/ai-gateway/mdm/configuration-reference.md)
>
> Every `mdm.toml` field, CLI flag, version requirement, and file path.

> [card] [Claude Code and Claude Desktop](https://www.truefoundry.com/docs/ai-gateway/mdm/claude.md)
>
> What MDM writes for Claude Code and Claude Desktop, and how to verify it.

> [card] [Codex](https://www.truefoundry.com/docs/ai-gateway/mdm/codex.md)
>
> What MDM writes for Codex, and how to verify it.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.