---
title: Roll out coding agents with mobile device management (MDM)
description: Deploy and centrally manage coding-agent configuration across teams with the Unity Gateway CLI and mobile device management (MDM).
canonical_url: https://docs.databricks.com/gcp/en/ai-gateway/coding-agent-rollout
---

# Roll out coding agents with mobile device management (MDM)

> [!NOTE]
> **Beta**
>
> This feature is in [Beta](https://docs.databricks.com/gcp/en/release-notes/release-types.md). To use it, a workspace admin must turn on **Unity Gateway Managed Configuration** from the **Previews** page. See [Manage Databricks previews](https://docs.databricks.com/gcp/en/admin/workspace-settings/manage-previews.md).

Use mobile device management (MDM) and the Unity Gateway CLI to distribute Claude Code and Codex settings. Publish a coding agent configuration in your workspace, then provision each managed device with your MDM software. Developers sign in with their own Databricks accounts when they use the agents.

This guide includes provisioning instructions for [Jamf Pro on macOS](https://docs.databricks.com/gcp/en/ai-gateway/coding-agent-rollout.md#deploy-with-your-mdm-software) and [Microsoft Intune on Windows](https://docs.databricks.com/gcp/en/ai-gateway/coding-agent-rollout.md#deploy-with-your-mdm-software). On Linux, use the same `ug configure --global` workflow in your device management tool.

Your MDM software runs a provisioning script with administrator privileges on each device. The script installs `ug`, the Databricks CLI, and the coding agents in shared locations. It then runs `ug configure --global` to configure the agents' machine-wide settings. On macOS and Linux, this run rebuilds the native managed files from the published workspace configuration. On Windows, it merges the gateway configuration into Claude Code's and Codex's managed files and also provisions Claude desktop if the app is installed. Developers launch agents without administrator privileges.

> [!NOTE]
>
> The `agent_native_config` file rebuild and `--from-file` preview described in this guide apply to macOS and Linux. On Windows, `--global` updates `%ProgramFiles%\ClaudeCode\managed-settings.json` and `%ProgramData%\OpenAI\Codex\requirements.toml`. Codex has no machine-wide `config.toml` layer on Windows.
>
> MDM provisioning doesn't configure GitHub Copilot CLI or GitHub Copilot in Visual Studio Code. Developers set up GitHub Copilot themselves with `ug configure --agents copilot`.
>
> The machine-wide run leaves per-user MCP connections and skills alone. Each developer runs `ug configure` or launches an agent through `ug` to sync those resources.

## Roll out with MDM

### <a id="configure-coding-agents" />Configure coding agents

Enable the agents your team uses and publish the configuration in your workspace. See [Configure coding agents](https://docs.databricks.com/gcp/en/ai-gateway/coding-agent-configure-govern.md).

Each enabled agent needs at least one model in the configuration that the service principal from the next step can use. For example, Claude Code needs Claude models. `ug configure --global` skips any agent without models.

To set managed agent settings and requirements, add `agent_native_config` to each agent's `config`. See [Agent native managed configuration](https://docs.databricks.com/gcp/en/ai-gateway/coding-agent-configure-govern.md#agent-native-managed-configuration).

To preview a configuration saved as `coding-agent-config.json` before publishing it, run:

```bash
ug configure --global --dry-run \
  --workspace https://<workspace-hostname> \
  --from-file coding-agent-config.json
```

The preview shows the files that `ug` would create, replace, or remove, their contents, and any settings that `ug` skips because it controls those keys. It writes no files.

Run the preview with the same `ug` version and operating system that you plan to deploy. Review the generated files before you publish the configuration.

### <a id="create-a-provisioning-service-principal" />Create a provisioning service principal

The MDM policy uses a service principal only to read the published configuration while it runs. Developers authenticate as themselves. The script uses the service principal's credentials temporarily, so that `ug` can connect to the workspace and download the coding agent configuration.

1. [Add a service principal](https://docs.databricks.com/gcp/en/admin/users-groups/manage-service-principals.md#add-sp) to your workspace, for example `ug-mdm-provisioning`.

2. Leave only the **Workspace access** entitlement enabled. The service principal doesn't need other entitlements. See [Manage entitlements](https://docs.databricks.com/gcp/en/security/auth/entitlements.md).

3. Grant the service principal access to the models, MCP servers, and skills in the published configuration, including the required Unity Catalog privileges. See [Grant access to models, MCP servers, and skills](https://docs.databricks.com/gcp/en/ai-gateway/coding-agent-bring-your-own-providers.md#grant-access).

4. On the service principal's **Secrets** tab, click **Generate secret**. Choose a lifetime that matches your rotation policy. Under **Scope**, click **Other APIs**, add the `ai-gateway` and `unity-catalog` scopes, and set each to **Read**. See [ Step 1: Create an OAuth secret](https://docs.databricks.com/gcp/en/dev-tools/auth/oauth-m2m.md#create-secret).

   ![Generate OAuth secret dialog with the ai-gateway and unity-catalog scopes added under Other APIs, each set to Read](https://docs.databricks.com/gcp/en/images/ai-gateway/coding-agent-rollout-sp-secret.png)

5. Copy the client ID and secret. You can't view the secret again after you close the dialog.

### <a id="deploy-with-your-mdm-software" />Deploy with your MDM software

> [!IMPORTANT]
>
> Install `ug` in a shared location that developers on the device can read and run, outside root's or SYSTEM's private profile. `ug configure --global` refuses an installation in a user's home directory. The machine-wide agent settings run `ug` from the shared installation to authenticate each developer.
>
> Install Codex in a version that meets the [Codex version requirement](https://docs.databricks.com/gcp/en/ai-gateway/coding-agent-codex-settings.md#requirements).

#### Jamf Pro (macOS)

These steps deploy Claude Code and Codex to macOS devices with Jamf Pro. Each device needs:

* Network access to your workspace URL, PyPI (`pypi.org` and `files.pythonhosted.org`), GitHub (`github.com` and `raw.githubusercontent.com`), `astral.sh`, `nodejs.org`, and `registry.npmjs.org`.
* Command Line Tools for Xcode, or permission for the script to install them with `softwareupdate`. `ug` is installed from GitHub, which requires `git`.

#### Add the script

1. In Jamf Pro, go to **Settings > Computer Management > Scripts > New**, and name the script `Unity Gateway provision`.

   ![Jamf Pro New Script page on the General tab with the display name Unity Gateway provision](https://docs.databricks.com/gcp/en/images/ai-gateway/coding-agent-rollout-jamf-new-script.png)

2. On the **Script** tab, paste the following script:

   **View the provisioning script**

   ```bash
   #!/bin/bash
   #
   # macOS MDM provisioning script, written for Jamf Pro policies: install
   # ug, the Databricks CLI, Claude Code and Codex machine-wide and run
   # `ug configure --global` as root, which builds machine-wide settings
   # from the published agent configuration. It also adds aliases to
   # /etc/zshrc and /etc/bashrc, so users launch with `claude` or `codex`
   # in a new terminal, with no sudo.
   #
   # Jamf parameters ($1-$3 are reserved by Jamf):
   #   $4  Databricks workspace URL, starting with https://
   #   $5  Service principal OAuth client id
   #   $6  Service principal OAuth client secret
   #
   # The token is used for this run only; developers sign in with their own
   # OAuth. Needs access to PyPI, GitHub, astral.sh, nodejs.org and npmjs.org.

   set -euo pipefail
   umask 022
   export HOME=/var/root
   export PATH=/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin
   WORKSPACE="${4%/}"
   PREFIX=/usr/local/unity-gateway
   NODE_VERSION=22.23.5
   NODE_SHA256=89fadefd7798158d8990ca9ed7dbb58f8ca7593adb92fe3da8a445db99415533
   UG_REPO=https://github.com/databricks/unity-gateway
   UV_URL=https://astral.sh/uv/install.sh
   CLI_URL=https://raw.githubusercontent.com
   CLI_URL="$CLI_URL/databricks/setup-cli/main/install.sh"
   CLT_MARKER=/tmp/.com.apple.dt.CommandLineTools
   CLT_MARKER="$CLT_MARKER.installondemand.in-progress"

   # ug must be in a shared path: the machine-wide agent settings
   # run it by absolute path for every user.
   export UV_TOOL_DIR="$PREFIX/tools"
   export UV_TOOL_BIN_DIR=/usr/local/bin
   export UV_PYTHON_INSTALL_DIR="$PREFIX/python"
   export UV_PYTHON_PREFERENCE=only-managed
   # ug's npm installer must put agents on every user's PATH, not in root's home.
   export npm_config_prefix=/usr/local
   mkdir -p /usr/local/bin

   # Get ug from git
   if ! xcode-select -p >/dev/null 2>&1; then
     touch "$CLT_MARKER"
     clt="$(softwareupdate -l 2>/dev/null \
       | sed -n 's/^\* Label: \(Command Line Tools.*\)$/\1/p' \
       | tail -n1)"
     softwareupdate -i "$clt"
     rm -f "$CLT_MARKER"
   fi

   if ! command -v uv >/dev/null; then
     curl -LsSf "$UV_URL" \
       | env UV_INSTALL_DIR=/usr/local/bin UV_NO_MODIFY_PATH=1 sh
   fi
   uv tool install --force "git+$UG_REPO"

   if [ ! -x /usr/local/bin/databricks ]; then
     curl -fsSL "$CLI_URL" | sh
   fi

   # ug configure installs missing agents with npm; provide a shared Node.js runtime.
   if ! command -v node >/dev/null || ! command -v npm >/dev/null; then
     tmp="$(mktemp -d)"
     trap 'rm -rf "$tmp"' EXIT
     package="node-v$NODE_VERSION.pkg"
     /usr/bin/curl -fsSL -o "$tmp/$package" \
       "https://nodejs.org/dist/v$NODE_VERSION/$package"
     printf '%s  %s\n' "$NODE_SHA256" "$tmp/$package" | /usr/bin/shasum -a 256 -c -
     /usr/sbin/installer -pkg "$tmp/$package" -target /
   fi

   # Get short lived credential; curl reads the client id and secret from
   # stdin (-K -) so they don't appear in its arguments.
   resp="$(printf 'user = "%s:%s"\n' "$5" "$6" \
     | curl -sS -K - \
         -d grant_type=client_credentials \
         --data-urlencode 'scope=ai-gateway:read unity-catalog:read' \
         "$WORKSPACE/oidc/v1/token")"
   if ! DATABRICKS_BEARER="$(printf '%s' "$resp" \
       | plutil -extract access_token raw -o - -)"; then
     echo "Token request to $WORKSPACE failed: $resp" >&2
     exit 1
   fi
   export DATABRICKS_BEARER

   /usr/local/bin/ug configure --global --mdm --workspace "$WORKSPACE" \
     --agents claude,codex </dev/null
   unset DATABRICKS_BEARER resp

   # Aliases for every user's interactive zsh and bash shells. The block is
   # rewritten on each run, which restores it if a macOS update resets
   # the file.
   for rc in /etc/zshrc /etc/bashrc; do
     [ -f "$rc" ] || continue
     sed -i '' '/^# BEGIN unity-gateway/,/^# END unity-gateway/d' "$rc"
     cat >>"$rc" <<'ALIASES'
   # BEGIN unity-gateway (managed by MDM)
   alias claude='UG_SKIP_OS_SETTINGS=1 ug claude'
   alias codex='UG_SKIP_OS_SETTINGS=1 ug codex'
   # END unity-gateway
   ALIASES
   done
   ```

3. On the **Options** tab, label **Parameter 4** `Workspace URL`, **Parameter 5** `Client ID`, and **Parameter 6** `Client secret`.

   ![Jamf Pro script Options tab with Parameter 4 labeled Workspace URL, Parameter 5 labeled Client ID, and Parameter 6 labeled Client secret](https://docs.databricks.com/gcp/en/images/ai-gateway/coding-agent-rollout-jamf-script-parameters.png)

4. Click **Save**.

The script reinstalls `ug` on each run and installs the Databricks CLI only when it's missing. If Node.js or npm is missing, the script installs the official Node.js 22.23.5 package after checking its pinned SHA-256 checksum. `ug configure` then reuses existing agents on the shared PATH, or installs Claude Code and Codex through npm with Unity Gateway's built-in installer. Agents the workspace doesn't enable aren't installed. The script doesn't otherwise update Node.js, the agents, or the CLI; to keep them current, modify the script to match how you update software on your devices.

Macs provisioned with the previous version of this script keep their native agent installations. Running the new script is not a migration to npm. To move those Macs to npm, remove the old native installations with your software-management process, and then run the policy again.

Update existing Codex installations to meet the [Codex version requirement](https://docs.databricks.com/gcp/en/ai-gateway/coding-agent-codex-settings.md#requirements).

#### Create the policy

1. Go to **Computers > Policies > New**.

2. In **General**, set **Trigger** to **Recurring Check-in** and **Execution Frequency** to **Once every day**. Each device runs `ug configure --global --mdm` daily, which applies configuration updates you publish in the workspace.

   ![Jamf Pro New Policy General options with the Recurring Check-in trigger selected and Execution Frequency set to Once every day](https://docs.databricks.com/gcp/en/images/ai-gateway/coding-agent-rollout-jamf-policy-trigger.png)

3. In **Scripts**, add `Unity Gateway provision` with **Priority** set to **After**. Enter the parameters:

   | Parameter         | Value                                         |
   | ----------------- | --------------------------------------------- |
   | 4 (Workspace URL) | Your workspace URL, starting with `https://`. |
   | 5 (Client ID)     | The service principal's client ID.            |
   | 6 (Client secret) | The service principal's secret.               |

   ![Jamf Pro policy Scripts options showing the Unity Gateway provision script with Priority set to After and placeholder values for the workspace URL, client ID, and client secret](https://docs.databricks.com/gcp/en/images/ai-gateway/coding-agent-rollout-jamf-policy-script-values.png)

4. In **Scope**, select the devices to target. Start with a small group of pilot devices.

5. Click **Save**. Jamf Pro runs the policy on each targeted device at its next check-in.

#### Microsoft Intune (Windows)

These steps show how to save the Windows provisioning script locally, package it as a Win32 app, and deploy it through Intune to a pilot group containing one device. Intune runs the installer as SYSTEM.

#### Before you begin

* [Enroll a Windows device in Intune](https://learn.microsoft.com/en-us/intune/device-enrollment/windows/guide). Use Windows 11 Pro, Enterprise, or Education.
* [Publish your coding-agent configuration](https://docs.databricks.com/gcp/en/ai-gateway/coding-agent-configure-govern.md) with both Claude Code and Codex enabled and models that the provisioning service principal can access. The installer checks that both agents are installed.
* Complete [Create a provisioning service principal](https://docs.databricks.com/gcp/en/ai-gateway/coding-agent-rollout.md#create-a-provisioning-service-principal) and have its client ID and secret available.

The packaging computer can be different from the deployment device. The target device needs network access as SYSTEM to your workspace, GitHub and its release-download hosts, PyPI, `nodejs.org`, and `registry.npmjs.org`.

> [!WARNING]
>
> Intune install arguments are not a secure secret channel. The example below passes the provisioning secret as an argument, which can appear in app settings and endpoint management or process logs. Use this form only if your organization's credential policy permits it. Restrict access to the app configuration, use a dedicated short-lived secret, and redact logs before sharing them. Do not embed credentials in the script or package.
>
> If your organization prohibits secret arguments, supply `DATABRICKS_CLIENT_SECRET` through an approved runtime credential source instead. Intune does not supply that credential source or populate the environment variable automatically.

#### Prepare the package

1. On the packaging computer, open Windows PowerShell as an administrator. Create folders for the package source, tools, and output:

   ```powershell
   New-Item -ItemType Directory -Force -Path C:\UGPackage, C:\UGTools, C:\UGOutput | Out-Null
   ```

2. Open a local file in Notepad:

   ```powershell
   notepad C:\UGPackage\windows-provision.ps1
   ```

3. Copy the following script into Notepad, save it as `C:\UGPackage\windows-provision.ps1`, and close Notepad. If using **Save As**, choose **All files** so the name does not end in `.txt`.

   **View the Windows provisioning script**

   ```powershell
   # Run as SYSTEM or administrator in 64-bit PowerShell.
   # Developers sign in with their own Databricks accounts.
   [CmdletBinding()]
   param(
     [string]$Workspace = $env:DATABRICKS_HOST,
     [string]$ClientId = $env:DATABRICKS_CLIENT_ID,
     [string]$ClientSecret = $env:DATABRICKS_CLIENT_SECRET,
     [string]$UgRef = '4504ca99115801f033149dc92d936ed80a2246f9',
     [switch]$Uninstall
   )

   # Check inputs and set shared install locations
   $ErrorActionPreference = 'Stop'
   $ProgressPreference = 'SilentlyContinue'
   [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
   if (-not [Environment]::Is64BitProcess) { throw 'Run this script in 64-bit PowerShell.' }
   $principal = New-Object Security.Principal.WindowsPrincipal(
     [Security.Principal.WindowsIdentity]::GetCurrent())
   if (-not $principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) {
     throw 'Run this script as administrator or SYSTEM.'
   }
   if (-not $Uninstall) {
     if (-not $Workspace -or -not $ClientId -or -not $ClientSecret) {
       throw 'Supply Workspace, ClientId and ClientSecret as parameters or DATABRICKS_HOST, DATABRICKS_CLIENT_ID and DATABRICKS_CLIENT_SECRET environment variables.'
     }
     $uri = $null
     if (-not [Uri]::TryCreate($Workspace, [UriKind]::Absolute, [ref]$uri) -or
         $uri.Scheme -ne 'https' -or $uri.UserInfo -or $uri.Query -or $uri.Fragment -or
         $uri.AbsolutePath -ne '/') { throw 'Workspace must be an https:// workspace origin.' }
     if (-not $UgRef) { throw 'Supply a ug release tag or commit with -UgRef.' }
     $Workspace = $Workspace.TrimEnd('/')
   }
   $nativeArch = (Get-ItemProperty 'HKLM:\SYSTEM\CurrentControlSet\Control\Session Manager\Environment').PROCESSOR_ARCHITECTURE
   if ($nativeArch -notin 'ARM64', 'AMD64') { throw "Unsupported architecture: $nativeArch" }
   $Arm = $nativeArch -eq 'ARM64'
   $Prefix = Join-Path $env:ProgramW6432 'UnityGateway'
   $BinDir = Join-Path $Prefix 'bin'
   $NodeDir = Join-Path $Prefix 'node'
   $NpmDir = Join-Path $Prefix 'npm'
   $NodeReleases = 'https://nodejs.org/dist'
   $CliReleases = 'https://github.com/databricks/cli/releases/download'
   $CliVersionUrl = 'https://raw.githubusercontent.com/databricks/setup-cli/main/VERSION'
   $UgRepo = 'https://github.com/databricks/unity-gateway'
   $GitVersion = '2.56.0.windows.4'
   $UvVersion = '0.13.7'
   $GitHashes = @{
     AMD64 = '4961a4a8cc778d8b6e00a5819e5fe4d078b754555aff7aedc2d77a5d74c2de80'
     ARM64 = 'e7dcc4adbb0eb373064598cd18bc75e60128707d816ead51cd9bd98e356f0075'
   }
   $UvHashes = @{
     AMD64 = '0cdc5b38fe5a8168ed6a25814f5ba43c21d313dd3187314fccb37b7cec46e021'
     ARM64 = '505d9e65e7692bac3ddf98c66754aa26c5050c409c184af30a881a0a72cc85e3'
   }
   $env:PYTHONUTF8 = '1'
   $env:UV_TOOL_DIR = Join-Path $Prefix 'tools'
   $env:UV_TOOL_BIN_DIR = $BinDir
   $env:UV_PYTHON_INSTALL_DIR = Join-Path $Prefix 'python'
   $env:UV_PYTHON_PREFERENCE = 'only-managed'
   # Copies, not cache hard links, so installed files inherit Program Files' read access for users.
   $env:UV_LINK_MODE = 'copy'
   $env:npm_config_prefix = $NpmDir

   # Download, checksum, PATH and profile helpers
   function Get-File($Url, $OutFile) {
     Invoke-WebRequest -UseBasicParsing -Uri $Url -OutFile $OutFile
   }
   function Get-Text($Url) {
     $file = Join-Path $Tmp ([guid]::NewGuid())
     Get-File $Url $file
     (Get-Content -Raw -LiteralPath $file).Trim()
   }
   function Assert-Sha256($Path, $Expected) {
     if ($Expected -notmatch '^[a-fA-F0-9]{64}$' -or
         (Get-FileHash -Algorithm SHA256 -LiteralPath $Path).Hash -ne $Expected) {
       throw "Checksum mismatch or missing SHA256 for $Path"
     }
   }
   function Get-Sha256Sum($SumsFile, $Name) {
     foreach ($line in Get-Content -LiteralPath $SumsFile) {
       $parts = $line -split '\s+', 2
       if ($parts.Count -eq 2 -and $parts[1].TrimStart('*') -eq $Name) { return $parts[0] }
     }
     throw "No checksum for $Name"
   }
   function Update-PathEntry($Path, $Dir, [switch]$Remove) {
     if ($Remove) { return (($Path -split ';' | Where-Object { $_ -ne $Dir }) -join ';') }
     if (($Path -split ';') -contains $Dir) { return $Path }
     return ($Path.TrimEnd(';') + ';' + $Dir).TrimStart(';')
   }
   function Set-MachinePath($Dir, [switch]$Remove) {
     $key = [Microsoft.Win32.Registry]::LocalMachine.OpenSubKey(
       'SYSTEM\CurrentControlSet\Control\Session Manager\Environment', $true)
     try {
       $path = $key.GetValue('Path', '', [Microsoft.Win32.RegistryValueOptions]::DoNotExpandEnvironmentNames)
       $kind = $key.GetValueKind('Path')
       $updated = Update-PathEntry $path $Dir -Remove:$Remove
       if ($updated -ne $path) { $key.SetValue('Path', $updated, $kind) }
     } finally { if ($key) { $key.Dispose() } }
     $env:Path = Update-PathEntry $env:Path $Dir -Remove:$Remove
   }
   function Set-SharedReadAccess($Dir) {
     if (-not (Test-Path -LiteralPath $Dir -PathType Container)) { throw "Shared runtime folder not found: $Dir" }
     foreach ($permission in '*S-1-5-32-545:(OI)(CI)RX', '*S-1-5-32-545:RX') {
       & "$env:SystemRoot\System32\icacls.exe" $Dir /grant $permission /T /Q
       if ($LASTEXITCODE -ne 0) { throw "Setting shared runtime permissions failed: $LASTEXITCODE" }
     }
   }
   function Get-AgentAliases($Ug) {
     $escaped = $Ug.Replace("'", "''")
     @"
   # BEGIN unity-gateway
   function claude {
     `$previous = `$env:UG_SKIP_OS_SETTINGS
     try { `$env:UG_SKIP_OS_SETTINGS = '1'; & '$escaped' claude @args }
     finally { `$env:UG_SKIP_OS_SETTINGS = `$previous }
   }
   function codex {
     `$previous = `$env:UG_SKIP_OS_SETTINGS
     try { `$env:UG_SKIP_OS_SETTINGS = '1'; & '$escaped' codex @args }
     finally { `$env:UG_SKIP_OS_SETTINGS = `$previous }
   }
   # END unity-gateway
   "@
   }
   function Update-AgentProfile($Text, $Block) {
     $text = "$Text" -replace '(?s)# BEGIN unity-gateway.*?# END unity-gateway\r?\n?', ''
     if (-not $Block) { return $text.TrimEnd() }
     ($text.TrimEnd() + "`r`n" + $Block).TrimStart()
   }

   $profiles = @("$env:SystemRoot\System32\WindowsPowerShell\v1.0\profile.ps1")
   $pwsh7 = Join-Path $env:ProgramW6432 'PowerShell\7'
   if (Test-Path -LiteralPath $pwsh7) { $profiles += Join-Path $pwsh7 'profile.ps1' }

   # Remove this deployment; leave shared Git and execution policy alone
   if ($Uninstall) {
     $ug = Join-Path $BinDir 'ug.exe'
     if (-not (Test-Path -LiteralPath $ug)) { throw 'ug is missing; repair the installation before uninstalling.' }
     $previousSkip = $env:UG_SKIP_OS_SETTINGS
     try {
       $env:UG_SKIP_OS_SETTINGS = $null
       $null | & $ug revert
       if ($LASTEXITCODE -ne 0) { throw "ug revert failed: $LASTEXITCODE" }
     } finally { $env:UG_SKIP_OS_SETTINGS = $previousSkip }
     foreach ($path in $profiles) {
       if (Test-Path -LiteralPath $path) {
         $text = Get-Content -Raw -LiteralPath $path
         Set-Content -LiteralPath $path -Encoding UTF8 -Value (Update-AgentProfile $text '')
       }
     }
     foreach ($dir in $BinDir, $NpmDir, $NodeDir) { Set-MachinePath $dir -Remove }
     Remove-Item -Recurse -Force -LiteralPath $Prefix
     Write-Output 'Unity Gateway deployment removed. Shared Git and execution policy were left unchanged.'
     return
   }

   New-Item -ItemType Directory -Force -Path $BinDir, $NpmDir | Out-Null
   Set-MachinePath $BinDir
   Set-MachinePath $NpmDir
   $Tmp = Join-Path $Prefix ".tmp-$([guid]::NewGuid())"
   New-Item -ItemType Directory -Path $Tmp | Out-Null
   try {
     # Install Git
     if (-not (Get-Command git.exe -ErrorAction SilentlyContinue)) {
       $suffix = if ($Arm) { 'arm64' } else { '64-bit' }
       $name = "Git-2.56.0.4-$suffix.exe"
       $setup = Join-Path $Tmp $name
       Get-File "https://github.com/git-for-windows/git/releases/download/v$GitVersion/$name" $setup
       Assert-Sha256 $setup $GitHashes[$nativeArch]
       $proc = Start-Process -FilePath $setup -Wait -PassThru `
         -ArgumentList '/VERYSILENT', '/ALLUSERS', '/NORESTART', '/SUPPRESSMSGBOXES', '/SP-'
       if ($proc.ExitCode -ne 0) { throw "Git setup failed: $($proc.ExitCode)" }
       Set-MachinePath (Join-Path $env:ProgramW6432 'Git\cmd')
     }

     # Install uv and ug
     $uv = Join-Path $BinDir 'uv.exe'
     if (-not (Test-Path -LiteralPath $uv)) {
       $target = if ($Arm) { 'aarch64-pc-windows-msvc' } else { 'x86_64-pc-windows-msvc' }
       $zip = Join-Path $Tmp 'uv.zip'
       Get-File "https://github.com/astral-sh/uv/releases/download/$UvVersion/uv-$target.zip" $zip
       Assert-Sha256 $zip $UvHashes[$nativeArch]
       Expand-Archive -LiteralPath $zip -DestinationPath (Join-Path $Tmp 'uv')
       Copy-Item (Join-Path $Tmp 'uv\uv.exe') $BinDir
     }
     & $uv tool install --force --python cpython-3.13-windows-x86_64-none "git+$UgRepo@$UgRef"
     if ($LASTEXITCODE -ne 0) { throw "uv tool install failed: $LASTEXITCODE" }

     # Install the Databricks CLI
     if (-not (Test-Path -LiteralPath (Join-Path $BinDir 'databricks.exe'))) {
       $version = Get-Text $CliVersionUrl
       $arch = if ($Arm) { 'arm64' } else { 'amd64' }
       $zip = "databricks_cli_${version}_windows_$arch.zip"
       $base = "$CliReleases/v$version"
       Get-File "$base/$zip" (Join-Path $Tmp $zip)
       Get-File "$base/databricks_cli_${version}_SHA256SUMS" (Join-Path $Tmp 'cli-sums')
       Assert-Sha256 (Join-Path $Tmp $zip) (Get-Sha256Sum (Join-Path $Tmp 'cli-sums') $zip)
       Expand-Archive -LiteralPath (Join-Path $Tmp $zip) -DestinationPath (Join-Path $Tmp 'cli')
       Copy-Item (Join-Path $Tmp 'cli\databricks.exe') $BinDir
     }

     # Install Node.js for ug's npm agent installer
     if (-not (Test-Path -LiteralPath (Join-Path $NodeDir 'npm.cmd'))) {
       $releases = Invoke-RestMethod -UseBasicParsing -Uri "$NodeReleases/index.json"
       $version = ($releases | Where-Object { $_.lts } | Select-Object -First 1).version
       if ($version -notmatch '^v\d+\.\d+\.\d+$') { throw 'No valid Node.js LTS release found.' }
       $name = "node-$version-win-$(if ($Arm) { 'arm64' } else { 'x64' })"
       Get-File "$NodeReleases/$version/$name.zip" (Join-Path $Tmp "$name.zip")
       Get-File "$NodeReleases/$version/SHASUMS256.txt" (Join-Path $Tmp 'node-sums')
       Assert-Sha256 (Join-Path $Tmp "$name.zip") (Get-Sha256Sum (Join-Path $Tmp 'node-sums') "$name.zip")
       Expand-Archive -LiteralPath (Join-Path $Tmp "$name.zip") -DestinationPath $Tmp
       New-Item -ItemType Directory -Force -Path $NodeDir | Out-Null
       Copy-Item (Join-Path $Tmp "$name\*") $NodeDir -Recurse -Force
     }
     Set-MachinePath $NodeDir
   } finally {
     Remove-Item -Recurse -Force -LiteralPath $Tmp -ErrorAction SilentlyContinue
   }

   # Get a provisioning token and configure agents with ug's npm fallback
   $previousBearer = $env:DATABRICKS_BEARER
   $previousSkip = $env:UG_SKIP_OS_SETTINGS
   try {
     $basic = [Convert]::ToBase64String([Text.Encoding]::UTF8.GetBytes("${ClientId}:${ClientSecret}"))
     $resp = Invoke-RestMethod -UseBasicParsing -Method Post `
       -Uri "$Workspace/oidc/v1/token" -Headers @{ Authorization = "Basic $basic" } `
       -ContentType 'application/x-www-form-urlencoded' `
       -Body @{ grant_type = 'client_credentials'; scope = 'ai-gateway:read unity-catalog:read' }
     if (-not $resp.access_token) { throw 'Token request returned no access_token.' }
     $env:DATABRICKS_BEARER = $resp.access_token
     $env:UG_SKIP_OS_SETTINGS = $null
     $null | & (Join-Path $BinDir 'ug.exe') configure --global --mdm --workspace $Workspace --agents claude,codex
     if ($LASTEXITCODE -ne 0) { throw "ug configure failed: $LASTEXITCODE" }
   } finally {
     $env:DATABRICKS_BEARER = $previousBearer
     $env:UG_SKIP_OS_SETTINGS = $previousSkip
     $ClientSecret = $null
     $basic = $null
     $resp = $null
   }
   foreach ($name in 'claude', 'codex') {
     if (-not (Test-Path -LiteralPath (Join-Path $NpmDir "$name.cmd"))) {
       throw "$name was not installed in $NpmDir. Check ug configure's output."
     }
   }

   # Allow standard users to read and run the shared installation
   Set-SharedReadAccess $Prefix

   # Add PowerShell aliases for all users
   if ((Get-ExecutionPolicy -Scope LocalMachine) -in 'Undefined', 'Restricted') {
     try { Set-ExecutionPolicy -Scope LocalMachine RemoteSigned -Force }
     catch { if ($_.FullyQualifiedErrorId -notlike 'ExecutionPolicyOverride*') { throw } }
   }
   foreach ($scope in 'MachinePolicy', 'UserPolicy', 'LocalMachine') {
     if ((Get-ExecutionPolicy -Scope $scope) -in 'AllSigned', 'Restricted') {
       Write-Warning "$scope execution policy may prevent the PowerShell aliases from loading."
     }
   }
   $block = Get-AgentAliases (Join-Path $BinDir 'ug.exe')
   foreach ($path in $profiles) {
     $text = if (Test-Path -LiteralPath $path) { Get-Content -Raw -LiteralPath $path } else { '' }
     Set-Content -LiteralPath $path -Encoding UTF8 -Value (Update-AgentProfile $text $block)
   }

   # Record a completed deployment and keep the script for Intune uninstall
   $scriptHash = (Get-FileHash -Algorithm SHA256 -LiteralPath $PSCommandPath).Hash
   $installedScript = Join-Path $Prefix 'windows-provision.ps1'
   if ([IO.Path]::GetFullPath($PSCommandPath) -ne [IO.Path]::GetFullPath($installedScript)) {
     Copy-Item -LiteralPath $PSCommandPath -Destination $installedScript -Force
   }
   @{
     workspace = $Workspace
     ugRef = $UgRef
     scriptSha256 = $scriptHash
   } | ConvertTo-Json | Set-Content -LiteralPath (Join-Path $Prefix 'provisioned.json') -Encoding UTF8
   Write-Output 'Unity Gateway provisioning completed.'
   ```

   Keep the credential inputs unchanged. You supply the workspace URL, client ID, and secret in the Intune app settings later. The script includes the shared-runtime permission repair for standard users. Do not run it manually before testing Intune delivery.

4. If SYSTEM cannot reach public package registries, add your approved mirror settings below `$ErrorActionPreference = 'Stop'`, after the script's `param(...)` block, before packaging:

   ```powershell
   $env:UV_DEFAULT_INDEX = 'https://<approved-pypi-host>/simple'
   $env:npm_config_registry = 'https://<approved-npm-host>/'
   ```

   Omit these lines when public registries are reachable. Do not put proxy passwords in the package.

5. Download Microsoft's [Win32 Content Prep Tool](https://github.com/microsoft/Microsoft-Win32-Content-Prep-Tool) and save `IntuneWinAppUtil.exe` under `C:\UGTools`. Keep the source folder limited to `windows-provision.ps1`. Build the package:

   ```powershell
   & C:\UGTools\IntuneWinAppUtil.exe -c C:\UGPackage -s windows-provision.ps1 -o C:\UGOutput -q
   if ($LASTEXITCODE -ne 0) { throw "Packaging failed: $LASTEXITCODE" }
   Get-Item C:\UGOutput\windows-provision.intunewin
   ```

   The output is `C:\UGOutput\windows-provision.intunewin`. Transfer this file to the computer you use to open Intune if needed.

#### Create a pilot device group and app

1. In the [Intune admin center](https://intune.microsoft.com), open **Devices > All devices** and note your test device's name.
2. In the main navigation, open **Groups > All groups > New group**. Use **Security** as the group type, **Assigned** membership, and name it `Unity Gateway Windows pilot`. Add only the target devices.
3. Open **Apps > All apps > Create**, select **Windows app (Win32)**, and upload `windows-provision.intunewin`.
4. On **App information**, enter `Unity Gateway Windows pilot` as the name and `Databricks` as the publisher. Click **Next**.

#### Configure the install command

In the Intune admin center, continue configuring the Win32 app on the **Program** page. Enter the commands Intune uses to install and remove the app.

The script installs shared tools under `C:\Program Files\UnityGateway`, gives standard users read/run access, and runs `ug configure --global --mdm`. It adds PowerShell launch functions and changes an unset or `Restricted` LocalMachine execution policy to `RemoteSigned`. It does not override Group Policy. Confirm these changes meet your device policy before assignment.

1. Choose **Command line** if an installer-type selector appears.

2. In **Install command**, paste the following command. Replace `<workspace-url>`, `<client-id>`, and `<client-secret>`. Use the complete `https://` workspace origin, without a trailing path:

   ```text
   C:\Windows\Sysnative\WindowsPowerShell\v1.0\powershell.exe -NoProfile -ExecutionPolicy Bypass -File ".\windows-provision.ps1" -Workspace "<workspace-url>" -ClientId "<client-id>" -ClientSecret "<client-secret>" -UgRef "main"
   ```

   This command installs Unity Gateway from `main`. To pin a version instead, pass a commit SHA or tag to `-UgRef` and use the [`windows-provision.ps1` script](https://github.com/databricks/unity-gateway/blob/main/scripts/mdm/windows-provision.ps1) from that ref when you prepare the package.

   Do not paste the populated command into a terminal or include it in screenshots.

3. In **Uninstall command**, enter:

   ```text
   C:\Windows\Sysnative\WindowsPowerShell\v1.0\powershell.exe -NoProfile -ExecutionPolicy Bypass -File "C:\Program Files\UnityGateway\windows-provision.ps1" -Uninstall
   ```

   The commands assume Windows is installed on `C:`. Adjust the paths for other installation drives. The uninstall field does not expand environment variables. `Sysnative` selects 64-bit PowerShell when the 32-bit Intune management process starts the installer.

4. Set the remaining Program options:

   | Setting                    | Value                              |
   | -------------------------- | ---------------------------------- |
   | Install behavior           | **System**                         |
   | Installation time required | **60 minutes**                     |
   | Device restart behavior    | **No specific action**             |
   | Allow available uninstall  | **No**, if shown, during the pilot |
   | Return codes               | Defaults                           |

5. Click **Next**.

#### Set requirements, detection, and assignment

In the Intune admin center, continue through the remaining pages of the Win32 app wizard. These settings define which devices can install the app, how Intune detects a completed installation, and which pilot group receives it.

1. On **Requirements**, select the target architecture (x64 or ARM64, where listed) and a Windows 11 minimum version that the test device meets. Leave optional resource requirements unset for the pilot.

2. On **Detection rules**, select **Manually configure detection rules > Add > File**:

   | Field                                          | Value                           |
   | ---------------------------------------------- | ------------------------------- |
   | Path                                           | `C:\Program Files\UnityGateway` |
   | File or folder                                 | `provisioned.json`              |
   | Detection method                               | **File or folder exists**       |
   | Associated with a 32-bit app on 64-bit clients | **No**                          |

   The script writes the marker after configure, runtime-permission repair, and profile setup finish. If the file exists from a previous install, Intune can report Installed without running the new package. Use a clean enrolled test device for the initial delivery test.

3. Add nothing on **Dependencies** or **Supersedence** for this pilot. The script installs its own dependencies.

4. On **Assignments**, add **Unity Gateway Windows pilot** under **Required**. Leave **Available** and **Uninstall** empty; do not assign to **All users** or **All devices**.

5. Review the summary and click **Create**.

#### Sync and verify installation

1. Open **Devices > All devices > your device > Sync**. Keep the device online.

2. Monitor **Apps > All apps > Unity Gateway Windows pilot > Device install status**, not just the Sync pane. A sync requests check-in, but installation and reporting can take additional time.

3. After the app reports **Installed**, check the target device:

   ```powershell
   Test-Path 'C:\Program Files\UnityGateway\provisioned.json'
   Get-Content 'C:\Program Files\UnityGateway\provisioned.json'
   ```

   Expect `True` and a marker containing your workspace URL and the requested `ugRef`. For this example, `ugRef` is the literal branch name `main`, not the resolved commit.

4. Restart Windows or sign out and back in before the developer opens PowerShell. Existing terminals can retain a stale PATH, preventing Codex's npm launcher from finding Node.js.

5. In a normal, non-administrator Windows PowerShell session, check command resolution:

   ```powershell
   Get-Command ug, node, claude, codex | Select-Object Name, Source, CommandType
   ```

   Expect `ug` and `node` under Program Files and `claude`/`codex` with the `Function` command type. Run each agent separately and complete a prompt after signing in as the developer. Keep a separate recovery administrator; demoting your only administrator is not a prerequisite.

If installation fails, inspect `AppWorkload.log` and `AppActionProcessor.log` under `C:\ProgramData\Microsoft\IntuneManagementExtension\Logs`. Logs can contain the secret-bearing install command. Redact credentials and tokens before sharing an excerpt. An installer exit code of `1`, reported as `0x80070001`, is generic and does not identify the underlying script error.

If uv is installed but `ug` is missing, check Git/PyPI access in SYSTEM context and your approved registry settings. Rebuild and upload the package if those settings change. Do not map exit code `1` to success. For a profile blocked by organization policy, use `$env:UG_SKIP_OS_SETTINGS = '1'; ug claude` or `ug codex` directly instead of overriding the policy.

For software updates, use a revised package with version-aware detection and supersedence. The marker-existence rule above is for the initial pilot; it does not schedule configuration refreshes. For removal, remove the Required assignment before assigning Uninstall. The script runs `ug revert` before deleting its runtime and profile blocks; it leaves shared Git, execution policy, and the developer's Databricks credentials unchanged.

### Tell your developers

After provisioning finishes, developers run `claude` or `codex` in a new terminal. On Windows, restart or sign out and back in first to refresh the machine PATH. The aliases in the macOS provisioning script launch `ug claude` or `ug codex`. On first launch, the developer signs in to Databricks and `ug` sets up their user-level MCP servers and skills. Coding agent activity is attributed to that developer.

Developers can also run the agent's own command after their first `ug` launch. The machine-wide settings still route model requests through the gateway. Model discovery, tracing, and Smart Routing require an `ug` launch.

## <a id="roll-out-claude-desktop-with-mdm" />Roll out Claude desktop

On macOS and Windows, `ug configure --global` also configures the Claude desktop app for every user on the device. Install Claude desktop before the provisioning script runs `ug configure --global`. The Jamf Pro and Intune scripts above don't install Claude desktop.

When a user first opens Claude desktop, they sign in with their own Databricks account. Users can also [import their claude.ai projects and chats](https://docs.databricks.com/gcp/en/ai-gateway/coding-agent-claude-desktop.md#import-claudeai).

## Verify the rollout

On a pilot device, sign in with the developer's operating-system account and check that:

* `ug status` reports `Machine-wide settings: From the published agent configuration`.
* The agent opens and responds using a configured model.
* The configured MCP servers and skills are available, and the developer can use them.
* Requests appear in Unity Gateway usage tracking, and traces appear if tracing is enabled. See [Monitor coding agent activity](https://docs.databricks.com/gcp/en/ai-gateway/coding-agent-observability.md).

Repeat these checks after you change the provisioning script or the published configuration.

## Maintain credentials and configuration

To rotate the service principal's secret:

1. Generate a new secret for the service principal.
2. Update the secret in your deployment settings:
   * For macOS, update the MDM policy parameter.
   * For Intune, open **Apps > All apps > Unity Gateway Windows pilot > Properties > Program > Edit** and replace the `-ClientSecret` argument in **Install command**. Save the change. If you use a runtime credential source instead, update the secret there.
3. Complete a provisioning run on a pilot device with the new secret before deleting the old secret.

If the secret is compromised, rotate it immediately and delete the old secret. The token the script requests is short-lived, and the script doesn't write it to the device, so there is no per-device credential to revoke.

Changing the Intune install command does not rerun provisioning on devices already detected as installed. The new secret is used for subsequent installations, repairs, or explicitly scheduled provisioning runs. Existing developer sessions use their own OAuth and do not need the provisioning secret. To test rotation on an already installed device, use a deployment revision with version-aware detection rather than the marker-existence rule in the pilot example.

To update the configuration, publish changes in the workspace and schedule provisioning again. Devices apply changes when the policy or installer runs. Each `ug configure --global` run rebuilds the machine-wide files from the published configuration, so settings you remove disappear and manual edits to those files are replaced. On devices provisioned with `--global`, developers' `ug configure` and agent launches do not change the machine-wide files. Intune's marker-existence detection does not trigger a refresh while it reports the app as installed.

If a device already received a published configuration, removing the configuration from the workspace does not remove its machine-wide settings. A later `ug configure --global` exits with code 5 and keeps the files. To remove them deliberately, run `ug revert` as root. For command options, see the [ug CLI reference](https://docs.databricks.com/gcp/en/ai-gateway/coding-agent-ug-cli.md#manage-your-setup).

## Troubleshooting

| Error                                                                             | Cause                                                                                                                                                                                                                                                                                                                                                            |
| --------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `Token request to ... failed: {"error":"invalid_client"...}`                      | The client ID or secret in the MDM policy is wrong, or the secret expired.                                                                                                                                                                                                                                                                                       |
| `Token request ... failed: ... Scopes ... are not assigned to the client`         | The secret doesn't have the `ai-gateway:read` and `unity-catalog:read` scopes.                                                                                                                                                                                                                                                                                   |
| `None of the coding agents enabled by your workspace configuration are available` | No enabled agent has models the service principal can use, for example Claude Code configured without Claude models.                                                                                                                                                                                                                                             |
| Claude desktop shows **Additional setup needed** in Cowork on Windows.            | The Windows Virtual Machine Platform feature isn't enabled. Add `Enable-WindowsOptionalFeature -Online -FeatureName VirtualMachinePlatform -All -NoRestart` to the Intune script, then restart the device. See [Deploy Claude Desktop for Windows](https://support.claude.com/en/articles/12622703-deploy-claude-desktop-for-windows) in the Claude Help Center. |
