---
title: Connect Microsoft 365 Copilot to MCP tools as the signed-in user
summary: Let Microsoft 365 Copilot and Copilot Cowork call your MCP tools through Azure AI Gateway as the signed-in user. The gateway checks the user's role, then exchanges the user's token with Microsoft Entra ID on-behalf-of, so the backend sees the user and no secret leaves the gateway.
category: tools
level: Advanced
duration: 60
tracks: [portal, cli, iac, terraform]
order: 30.5
status: emerging
illustration: diagrams/copilot-obo.svg
tags: [on-behalf-of, OBO, MCP, Microsoft 365 Copilot, Copilot Cowork, Entra ID, Azure Container Apps, token exchange, federated credential, managed identity]
objectives:
  - Explain each token and app registration of the on-behalf-of chain from Microsoft 365 Copilot to an MCP backend
  - Deploy an Entra-protected MCP server on Azure Container Apps that accepts only tokens exchanged by the gateway
  - Register an MCP server with an on-behalf-of backend in the Azure CLI, with Bicep and azd, or with Terraform, and validate it in the AI Gateway portal
  - Prove that the backend sees the signed-in user, and that a token for the gateway doesn't work on the backend
  - Connect the MCP server to Microsoft 365 Copilot and call its tools as yourself in Copilot Cowork
prereqs:
  - 04-federate-mcp-tools
  - 11-entra-rbac
---

# Connect Microsoft 365 Copilot to MCP tools as the signed-in user

An agent that acts for a person should reach your systems as that person, not as a shared service account. Your
API then applies its own permissions to each user, and its logs show who asked. In this lab, Microsoft 365 Copilot
and Copilot Cowork call MCP tools through Azure AI Gateway as the signed-in user. The gateway checks the user's
role on the MCP server, then exchanges the user's token with Microsoft Entra ID **on behalf of** the user for a
token that only your backend accepts. The gateway signs in with a managed identity, so no secret leaves it.

> [!NOTE]
> This lab adapts [ai-gateway-end-to-end](https://github.com/kostapetan/ai-gateway-end-to-end) by Kosta Petan. His
> repository has the Bicep templates, a Terraform branch, an architecture walkthrough with diagrams of each token, and
> the `dummy-mcp` server that this lab's MCP server is based on. Thanks, Kosta!

## Before you begin

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

> [!TIP]
> On the **Bicep + azd** and **Terraform** tracks, `azd up` or `terraform apply` creates its own gateway, the
> backend, the app registrations, and the MCP server, so you can skip the variables below. You still need the
> permissions in this list.

- Complete [Federate MCP tools behind one endpoint](../04-federate-mcp-tools/README.md) and
  [Go keyless with Microsoft Entra ID and RBAC](../11-entra-rbac/README.md). This lab adds an MCP server to your
  gateway and calls it with a Microsoft Entra token.
- Permission to register applications in Microsoft Entra ID, and to grant tenant-wide consent to them, for example
  the **Cloud Application Administrator** role. The lab registers three apps and consents to their delegated scopes
  for everyone in the tenant.
- **Owner** or **User Access Administrator** on the subscription. The lab assigns roles on the container registry
  and on the MCP server.
- Permission to read, update, and retrieve the secrets of MCP servers on the gateway, for example **Contributor**
  on it. The first on-behalf-of setup retrieves secrets even when the backend stores none.
- For the portal's **Validate** button, admin consent for the AI Gateway portal to read app registrations with the
  Microsoft Graph `Application.Read.All` permission. The portal asks for it with **Authorize directory access**.
- A recent Bicep CLI, which `az bicep upgrade` installs. The templates register the apps with the Microsoft Graph
  Bicep extension.
- `jq`, for the Bash commands.
- For the Microsoft 365 steps, an admin who can add connectors in the Microsoft 365 admin center, and a user with a
  Microsoft 365 Copilot license and access to Copilot Cowork. Both must be in the Microsoft Entra tenant of your
  gateway's subscription.
- Run the scripts from the lab's folder, `~/aigateway/labs/33-copilot-obo-mcp`.

> [!NOTE]
> On-behalf-of backends are an emerging capability of Azure AI Gateway. Labels and behavior can change; see the
> [release note](https://ai.gateway.azure.com/docs/releases#release-2026-11-06).

Set these variables once. The steps and the **Verify** section reuse them.

```bash title="Bash"
# Set your resource group and gateway, and the MCP server that you create in this lab
export RG="<resource-group>"
export GATEWAY="<gateway>"
export MCP_SERVER="obo-demo"                 # the MCP server you create in this lab
echo "📝 Gateway $GATEWAY in $RG, MCP server $MCP_SERVER"

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

```powershell title="PowerShell"
# Set your resource group and gateway, and the MCP server that you create in this lab
$RG         = "<resource-group>"
$GATEWAY    = "<gateway>"
$MCP_SERVER = "obo-demo"                     # the MCP server you create in this lab
Write-Host "📝 Gateway $GATEWAY in $RG, MCP server $MCP_SERVER"

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

This lab uses no API key: every call carries a Microsoft Entra token for the signed-in user.

## How it works

An MCP backend with **on-behalf-of** authentication receives a token for the user who called the gateway, not for
the gateway. The chain has three app registrations and one managed identity, which the lab names after a base name
such as `aigw-lab33-k3v7qz`:

| Piece | What it is | Its job |
|---|---|---|
| Connector app, `<base>-copilot-connector` | An app registration with a client secret | Microsoft 365 Copilot signs the user in with it and gets a token for AI Gateway with the `Data.All` scope |
| Token exchange app, `<base>-token-exchange` | An app registration with no secret, whose federated credential trusts the gateway identity | The gateway signs in as this app to exchange the user's token |
| Backend app, `<base>-mcp-backend` | An app registration that exposes the `user_impersonation` scope | The audience of the token that the MCP server accepts |
| Gateway identity, `id-<base>-gateway` | A user-assigned managed identity on the gateway | Proves to Microsoft Entra ID that the gateway is the token exchange app |
| MCP server, `ca-<base>-mcp` | A Python MCP server on Azure Container Apps, behind Container Apps authentication | Runs the tools for the user in the token |

A tool call goes through four tokens. You never handle any of them after the first:

| # | Token | Audience | Scope | Checked by |
|---|---|---|---|---|
| 1 | The user's token, which Microsoft 365 Copilot gets with the connector app | AI Gateway | `Data.All` | AI Gateway, then the **AI Gateway Tools User** role on the MCP server |
| 2 | A federation token, which AI Gateway gets on behalf of the user | The token exchange app | `FederationApp.Access` | Microsoft Entra ID: the token exchange app pre-authorizes AI Gateway for this scope |
| 3 | An assertion from the gateway identity | `api://AzureADTokenExchange` | | Microsoft Entra ID: the federated credential on the token exchange app |
| 4 | The backend token, which the token exchange app gets on behalf of the user, with the assertion as its credential | The backend app's client ID | `user_impersonation` | Container Apps authentication, then the MCP server |

![Microsoft 365 Copilot calls the gateway with the user's token; the gateway checks the role, exchanges the token with Microsoft Entra ID as the token exchange app with its managed identity, and calls the MCP server on Azure Container Apps with a token for the backend](../assets/diagrams/copilot-obo.svg "The user's identity reaches the backend in every token. The gateway's managed identity replaces a client secret in the exchange.")

Each token keeps the user's object ID (`oid`), so the backend sees the same person that signed in to Copilot. The
gateway grants nothing by itself: the user needs the **AI Gateway Tools User** role on the MCP server, and the
tenant-wide consent of the token exchange app to the backend's scope. **Owner** and **Contributor** don't include
the Tools User role.

## Review the MCP server

The MCP server is one Python file, [`infra/mcp-server/server.py`](infra/mcp-server/server.py), built with FastMCP. Its
three read-only tools show who called them:

| Tool | Returns |
|---|---|
| `whoami` | The claims of the token that the backend received: the user's name and object ID, the audience, the calling app, the scopes, and the token version |
| `echo` | `<your name> said: <message>` |
| `get_server_time` | The server's time in UTC |

The token passes two checks before a tool runs:

| Check | Rule | Result when it fails |
|---|---|---|
| Container Apps authentication | A valid Microsoft Entra v2.0 token for the backend app, requested by the token exchange app. Only `/healthz` is open | HTTP `401` before the container sees the call |
| `server.py` | The same issuer, audience, and signature; the `user_impersonation` scope; and the calling app (`azp`) in `ALLOWED_CLIENT_IDS` | HTTP `401`, and a warning in the log |

<!-- include: infra/mcp-server/server.py -->

On GitHub, open [infra/mcp-server/server.py](infra/mcp-server/server.py).

A v2.0 access token's audience is the backend app's client ID, not its `api://` URI, so the server compares `aud`
with `BACKEND_CLIENT_ID`. Each call logs `Call from user <object ID> through app <client ID> with scope
user_impersonation`, which **Verify** reads.

## Deploy the backend and register the MCP server

The AI Gateway portal doesn't create app registrations or container apps, so on the **Portal** track, follow the
**Azure CLI** steps here, then check the on-behalf-of settings in the portal.

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

### Deploy the backend

[`infra/backend.bicep`](infra/backend.bicep) creates the two managed identities, the three app registrations, and
the MCP server on Azure Container Apps. An ACR Tasks run builds the server's image from this repository on GitHub, so
you don't need Docker. It takes about four minutes.

```bash title="Bash"
# Move into the lab's folder, which holds the templates and the scripts
cd ~/aigateway/labs/33-copilot-obo-mcp &&
  echo "📂 Lab folder: $(pwd)"

# Name the backend's resource group, in the gateway's region
export BACKEND_RG="rg-aigw-lab33-backend"
export LOCATION="$(az aigateway show -g "$RG" -n "$GATEWAY" --query location -o tsv)"
echo "📝 Backend in $BACKEND_RG, in $LOCATION"

# Create the resource group
az group create -n "$BACKEND_RG" -l "$LOCATION" -o none &&
  echo "📦 Resource group $BACKEND_RG is ready in $LOCATION"

# Deploy the identities, the app registrations, and the MCP server
az deployment group create -g "$BACKEND_RG" -n lab33-backend -f infra/backend.bicep -o none &&
  echo "🚀 The backend is deployed to $BACKEND_RG"
```

```powershell title="PowerShell"
# Move into the lab's folder, which holds the templates and the scripts
Set-Location ~/aigateway/labs/33-copilot-obo-mcp
if ($?) { Write-Host "📂 Lab folder: $(Get-Location)" }

# Name the backend's resource group, in the gateway's region
$BACKEND_RG = "rg-aigw-lab33-backend"
$LOCATION   = az aigateway show -g $RG -n $GATEWAY --query location -o tsv
Write-Host "📝 Backend in $BACKEND_RG, in $LOCATION"

# Create the resource group
az group create -n $BACKEND_RG -l $LOCATION -o none
if ($?) { Write-Host "📦 Resource group $BACKEND_RG is ready in $LOCATION" }

# Deploy the identities, the app registrations, and the MCP server
az deployment group create -g $BACKEND_RG -n lab33-backend -f infra/backend.bicep -o none
if ($?) { Write-Host "🚀 The backend is deployed to $BACKEND_RG" }
```

### Read the outputs

Read the IDs that the next steps need from the deployment's outputs, then call the backend without a token.

```bash title="Bash"
# Read the deployment's outputs
OUTPUTS="$(az deployment group show -g "$BACKEND_RG" -n lab33-backend --query properties.outputs -o json)"
export IDENTITY_ID="$(echo "$OUTPUTS" | jq -r .gatewayIdentityId.value)"
export IDENTITY_CLIENT_ID="$(echo "$OUTPUTS" | jq -r .gatewayIdentityClientId.value)"
export BACKEND_APP_ID="$(echo "$OUTPUTS" | jq -r .backendAppId.value)"
export BACKEND_SCOPE="$(echo "$OUTPUTS" | jq -r .backendScope.value)"
export TOKEN_EXCHANGE_APP_ID="$(echo "$OUTPUTS" | jq -r .tokenExchangeAppId.value)"
export CONNECTOR_APP_ID="$(echo "$OUTPUTS" | jq -r .connectorAppId.value)"
export BACKEND_URL="$(echo "$OUTPUTS" | jq -r .backendUrl.value)"
echo "🔐 Backend scope: $BACKEND_SCOPE"
echo "🌐 Backend URL: $BACKEND_URL"

# Call the backend without a token: Container Apps authentication answers 401 before the server runs
echo "🔐 Anonymous call to the backend: HTTP $(curl -s -o /dev/null -w '%{http_code}' -X POST "$BACKEND_URL" -H 'Content-Type: application/json' -d '{}')"

# Call the health probe, the only path open without a token
echo "✅ Health probe: HTTP $(curl -s -o /dev/null -w '%{http_code}' "${BACKEND_URL%/mcp}/healthz")"
```

```powershell title="PowerShell"
# Read the deployment's outputs
$OUTPUTS = az deployment group show -g $BACKEND_RG -n lab33-backend --query properties.outputs -o json | ConvertFrom-Json
$IDENTITY_ID           = $OUTPUTS.gatewayIdentityId.value
$IDENTITY_CLIENT_ID    = $OUTPUTS.gatewayIdentityClientId.value
$BACKEND_APP_ID        = $OUTPUTS.backendAppId.value
$BACKEND_SCOPE         = $OUTPUTS.backendScope.value
$TOKEN_EXCHANGE_APP_ID = $OUTPUTS.tokenExchangeAppId.value
$CONNECTOR_APP_ID      = $OUTPUTS.connectorAppId.value
$env:BACKEND_URL       = $OUTPUTS.backendUrl.value
Write-Host "🔐 Backend scope: $BACKEND_SCOPE"
Write-Host "🌐 Backend URL: $env:BACKEND_URL"

# Call the backend without a token: Container Apps authentication answers 401 before the server runs
$anonymous = Invoke-WebRequest -Method Post -Uri $env:BACKEND_URL -ContentType 'application/json' -Body '{}' -SkipHttpErrorCheck
Write-Host "🔐 Anonymous call to the backend: HTTP $($anonymous.StatusCode)"

# Call the health probe, the only path open without a token
$health = Invoke-WebRequest -Uri ($env:BACKEND_URL -replace '/mcp$', '/healthz') -SkipHttpErrorCheck
Write-Host "✅ Health probe: HTTP $($health.StatusCode)"
```

> **Checkpoint**
> The backend scope looks like `api://<backend app ID>/user_impersonation`, the backend URL ends with
> `.azurecontainerapps.io/mcp`, the anonymous call prints `HTTP 401`, and the health probe prints `HTTP 200`.

### Attach the gateway identity

The gateway signs in as the token exchange app with the user-assigned identity, so attach it to the gateway. The
gateway keeps its system-assigned identity.

```bash title="Bash"
# Attach the user-assigned identity to the gateway
az aigateway identity assign -g "$RG" -n "$GATEWAY" --user-assigned "$IDENTITY_ID" -o none &&
  echo "👤 The gateway identity is attached to $GATEWAY"
```

```powershell title="PowerShell"
# Attach the user-assigned identity to the gateway
az aigateway identity assign -g $RG -n $GATEWAY --user-assigned $IDENTITY_ID -o none
if ($?) { Write-Host "👤 The gateway identity is attached to $GATEWAY" }
```

### Register the MCP server

Create the `obo-demo` MCP server with one backend. Its `oauth2` authentication uses the `tokenExchange` grant with
the `entraOnBehalfOf` profile: the gateway signs in as the token exchange app with the identity's **client** ID, and
asks for the backend's scope. The `az aigateway mcp create` command has no dedicated flags for these settings, so pass
the whole backend as JSON with `--endpoints`.

```bash title="Bash"
# Describe the backend: the MCP server's URL, and the on-behalf-of token exchange that calls it as the user
ENDPOINTS="$(jq -nc --arg url "$BACKEND_URL" --arg app "$TOKEN_EXCHANGE_APP_ID" \
  --arg identity "$IDENTITY_CLIENT_ID" --arg scope "$BACKEND_SCOPE" '[{
    kind: "mcp", namespace: "demo", required: true,
    mcp: {url: $url, transport: "streamableHttp"},
    authentication: {oauth2: {grantType: "tokenExchange", tokenExchange: {
      profile: "entraOnBehalfOf",
      federatedClientApplication: {applicationId: $app,
        appCredential: {type: "userAssignedManagedIdentity", clientId: $identity}},
      scopes: [$scope]}}}}]')"

# Register the MCP server with the MCP versions that the backend supports
az aigateway mcp create -g "$RG" --gateway-name "$GATEWAY" -n "$MCP_SERVER" --display-name "OBO demo" \
  --description "Demo MCP server on Azure Container Apps, called as the signed-in user with Microsoft Entra ID on-behalf-of." \
  --versions 2025-11-25 2025-06-18 2025-03-26 --endpoints "$ENDPOINTS" \
  --query "{name:name,mcpEndpoint:properties.gatewayEndpoints[0].url}" &&
  echo "🔌 MCP server $MCP_SERVER is ready"
```

```powershell title="PowerShell"
# Describe the backend: the MCP server's URL, and the on-behalf-of token exchange that calls it as the user
$endpoints = @(@{
  kind           = "mcp"; namespace = "demo"; required = $true
  mcp            = @{ url = $env:BACKEND_URL; transport = "streamableHttp" }
  authentication = @{ oauth2 = @{ grantType = "tokenExchange"; tokenExchange = @{
    profile                    = "entraOnBehalfOf"
    federatedClientApplication = @{
      applicationId = $TOKEN_EXCHANGE_APP_ID
      appCredential = @{ type = "userAssignedManagedIdentity"; clientId = $IDENTITY_CLIENT_ID }
    }
    scopes                     = @($BACKEND_SCOPE)
  } } }
})
ConvertTo-Json -InputObject $endpoints -Depth 10 -Compress | Set-Content endpoints.json

# Register the MCP server with the MCP versions that the backend supports
az aigateway mcp create -g $RG --gateway-name $GATEWAY -n $MCP_SERVER --display-name "OBO demo" `
  --description "Demo MCP server on Azure Container Apps, called as the signed-in user with Microsoft Entra ID on-behalf-of." `
  --versions 2025-11-25 2025-06-18 2025-03-26 --endpoints "@endpoints.json" `
  --query "{name:name,mcpEndpoint:properties.gatewayEndpoints[0].url}"
if ($?) { Write-Host "🔌 MCP server $MCP_SERVER is ready" }
Remove-Item endpoints.json
```

The display name must be unique on the gateway: a second server named `OBO demo` fails with a `502`.

### Grant yourself the Tools User role

The gateway lets a user call the server's tools only with the **AI Gateway Tools User** role on it. Assign it to
yourself. It can take several minutes to apply.

```bash title="Bash"
# Assign AI Gateway Tools User (dce03f8d-…) on the MCP server to yourself
az role assignment create --assignee-object-id "$(az ad signed-in-user show --query id -o tsv)" \
  --assignee-principal-type User --role "dce03f8d-857f-4e40-a90d-67770fa6ecd2" \
  --scope "$GATEWAY_ID/workspaces/default/toolServers/$MCP_SERVER" --output none &&
  echo "🔐 You have the AI Gateway Tools User role on the $MCP_SERVER MCP server"
```

```powershell title="PowerShell"
# Assign AI Gateway Tools User (dce03f8d-…) on the MCP server to yourself
az role assignment create --assignee-object-id (az ad signed-in-user show --query id -o tsv) `
  --assignee-principal-type User --role "dce03f8d-857f-4e40-a90d-67770fa6ecd2" `
  --scope "$GATEWAY_ID/workspaces/default/toolServers/$MCP_SERVER" --output none
if ($?) { Write-Host "🔐 You have the AI Gateway Tools User role on the $MCP_SERVER MCP server" }
```

> **Checkpoint**
> `az aigateway mcp create` printed the server's name and an `mcpEndpoint` that ends with
> `/default/toolservers/obo-demo/mcp`, and the role assignment printed its `🔐` line.

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

**What you need:** only the one-time setup from **Before you begin**, and the permissions in its list. This track
doesn't use your gateway from lab 04: `azd up` creates a new gateway with the backend, the app registrations, and
the `obo-demo` MCP server, so it works on its own.

### Review the templates

`infra/main.bicep` creates the resource group `rg-<environment name>` and calls lab 01's
[gateway.bicep](../01-provision-gateway/infra/gateway.bicep) for a gateway with no model. Then it deploys the backend,
attaches the gateway identity with lab 12's
[gateway-identity.bicep](../12-backend-identity/infra/gateway-identity.bicep), and registers the MCP server. azd fills
two parameters from environment values:

| Parameter | azd environment value | Default |
|---|---|---|
| `principalId` | `AZURE_PRINCIPAL_ID` | You, the signed-in user, who gets the Tools User role |
| `mcpServerSource` | `MCP_SERVER_SOURCE` | The `infra/mcp-server` folder of this repository's `main` branch |

<!-- include: infra/main.bicep -->

`infra/backend.bicep` is the template that the **Azure CLI** track deploys: the two managed identities, the app
registrations, and the MCP server on Azure Container Apps.

<!-- include: infra/backend.bicep -->

`infra/entra.bicep` registers the three apps with the Microsoft Graph Bicep extension. It creates or updates each app
by its unique name, and grants the tenant-wide consents. The extension can't create client secrets, so the connector's
secret comes later, from the Azure CLI.

<!-- include: infra/entra.bicep -->

An app's application ID URI contains its client ID, which exists only after the app does, so
`infra/app-identifier-uri.bicep` sets `api://<client ID>` in a second step. The token exchange fails with a `502`
without it.

<!-- include: infra/app-identifier-uri.bicep -->

`infra/mcp-server.bicep` builds the image with an ACR Tasks run, so the deployment waits for the build, then runs it on
Azure Container Apps with one replica always on. Container Apps authentication validates every token before the
container sees the call.

<!-- include: infra/mcp-server.bicep -->

`infra/obo-tool-server.bicep` registers the MCP server with the on-behalf-of backend, and assigns the Tools User role
on it.

<!-- include: infra/obo-tool-server.bicep -->

`azure.yaml` has no service to deploy: the image builds during provisioning. Its `predown` hook deletes and purges the
app registrations before `azd down` deletes the resource group, because they live in Microsoft Entra ID.

<!-- include: azure.yaml -->

> [!WARNING]
> A Bicep deployment sends a `PUT`, which replaces the whole MCP server, including backends and policies that you
> added in the portal. Keep the template as the only source of truth for this server, and change it with
> `azd provision`.

### Deploy with azd up

Move into the lab's folder, create an azd environment named `aigw-lab33` in your current subscription, then provision
everything. It takes about seven minutes.

```bash title="Bash"
# Move into the lab's folder, which holds the azd project
cd ~/aigateway/labs/33-copilot-obo-mcp &&
  echo "📂 Lab folder: $(pwd)"

# Create an azd environment in your current subscription, so that azd doesn't prompt you
azd env new aigw-lab33 --location eastus2 --subscription "$(az account show --query id --output tsv)" &&
  echo "📝 azd environment aigw-lab33 deploys to eastus2"

# Provision the gateway, the backend, the app registrations, and the MCP server
azd up &&
  echo "🚀 Gateway deployed: $(azd env get-value AI_GATEWAY_URL)"
```

```powershell title="PowerShell"
# Move into the lab's folder, which holds the azd project
Set-Location ~/aigateway/labs/33-copilot-obo-mcp
if ($?) { Write-Host "📂 Lab folder: $(Get-Location)" }

# Create an azd environment in your current subscription, so that azd doesn't prompt you
azd env new aigw-lab33 --location eastus2 --subscription (az account show --query id --output tsv)
if ($?) { Write-Host "📝 azd environment aigw-lab33 deploys to eastus2" }

# Provision the gateway, the backend, the app registrations, and the MCP server
azd up
if ($?) { Write-Host "🚀 Gateway deployed: $(azd env get-value AI_GATEWAY_URL)" }
```

For another region, use one that has both AI Gateway and Azure Container Apps, from [Find the available
regions](../SETUP.md#find-the-available-regions).

### Read the outputs

Set the variables that the next steps, **Verify**, and **Clean up** use from azd's environment values, then call the
backend without a token.

```bash title="Bash"
# Read azd's outputs: the resource group, the gateway, the MCP server, and the gateway's ID and runtime URL
export RG="$(azd env get-value AZURE_RESOURCE_GROUP)"
export GATEWAY="$(azd env get-value AI_GATEWAY_NAME)"
export MCP_SERVER="$(azd env get-value MCP_SERVER)"
export GATEWAY_ID="$(azd env get-value AI_GATEWAY_ID)"
export AI_GATEWAY_URL="$(azd env get-value AI_GATEWAY_URL)"
echo "📝 Gateway $GATEWAY in $RG, MCP server $MCP_SERVER"
echo "🌐 Runtime URL: $AI_GATEWAY_URL"

# Read the backend's outputs: its URL, its scope, and the connector app
export BACKEND_RG="$RG"
export BACKEND_URL="$(azd env get-value BACKEND_URL)"
export BACKEND_SCOPE="$(azd env get-value BACKEND_SCOPE)"
export CONNECTOR_APP_ID="$(azd env get-value CONNECTOR_APP_ID)"
echo "🔐 Backend scope: $BACKEND_SCOPE"
echo "🌐 Backend URL: $BACKEND_URL"

# Call the backend without a token: Container Apps authentication answers 401 before the server runs
echo "🔐 Anonymous call to the backend: HTTP $(curl -s -o /dev/null -w '%{http_code}' -X POST "$BACKEND_URL" -H 'Content-Type: application/json' -d '{}')"
```

```powershell title="PowerShell"
# Read azd's outputs: the resource group, the gateway, the MCP server, and the gateway's ID and runtime URL
$RG                 = azd env get-value AZURE_RESOURCE_GROUP
$GATEWAY            = azd env get-value AI_GATEWAY_NAME
$MCP_SERVER         = azd env get-value MCP_SERVER
$GATEWAY_ID         = azd env get-value AI_GATEWAY_ID
$env:AI_GATEWAY_URL = azd env get-value AI_GATEWAY_URL
Write-Host "📝 Gateway $GATEWAY in $RG, MCP server $MCP_SERVER"
Write-Host "🌐 Runtime URL: $env:AI_GATEWAY_URL"

# Read the backend's outputs: its URL, its scope, and the connector app
$BACKEND_RG       = $RG
$env:BACKEND_URL  = azd env get-value BACKEND_URL
$BACKEND_SCOPE    = azd env get-value BACKEND_SCOPE
$CONNECTOR_APP_ID = azd env get-value CONNECTOR_APP_ID
Write-Host "🔐 Backend scope: $BACKEND_SCOPE"
Write-Host "🌐 Backend URL: $env:BACKEND_URL"

# Call the backend without a token: Container Apps authentication answers 401 before the server runs
$anonymous = Invoke-WebRequest -Method Post -Uri $env:BACKEND_URL -ContentType 'application/json' -Body '{}' -SkipHttpErrorCheck
Write-Host "🔐 Anonymous call to the backend: HTTP $($anonymous.StatusCode)"
```

> **Checkpoint**
> `azd up` ended with `SUCCESS`, the backend scope looks like `api://<backend app ID>/user_impersonation`, and the
> anonymous call prints `HTTP 401`.

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

**What you need:** only the one-time setup from **Before you begin**, plus Terraform 1.9 or later, as in
[Deploy a lab with Terraform](../SETUP.md#deploy-a-lab-with-terraform), and the permissions in the list. This track
doesn't use your gateway from lab 04: `terraform apply` creates a new gateway with the backend, the app
registrations, and the `obo-demo` MCP server, so it works on its own.

### Review the configuration

The configuration deploys the same resources as the Bicep templates. `terraform/main.tf` creates the resource group
`rg-<environment_name>` and the gateway with both of its identities. `terraform/variables.tf` declares the two
settings of the Bicep track, with the same defaults:

| Variable | Bicep parameter | Default |
|---|---|---|
| `principal_id` | `principalId` | You, the signed-in user of the Azure CLI, who gets the Tools User role |
| `mcp_server_source` | `mcpServerSource` | The `infra/mcp-server` folder of this repository's `main` branch |

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

`terraform/entra.tf` registers the three apps with the `azuread` provider, which signs in to Microsoft Entra ID with
your Azure CLI session, and grants the tenant-wide consents. `terraform destroy` deletes the apps. The connector's
secret comes later, from the Azure CLI, so it never lands in the Terraform state.

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

`terraform/mcp-server.tf` builds the image with an ACR Tasks run and runs it on Azure Container Apps behind Container
Apps authentication, like `infra/mcp-server.bicep`. The image tag is a hash of the server's files, so Terraform
builds again only when they change.

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

`terraform/tool-server.tf` registers the MCP server with the on-behalf-of backend, and assigns the Tools User role on
it. [`terraform/providers.tf`](terraform/providers.tf) adds the `azuread` and `time` providers to the quick start's.

<!-- include: terraform/tool-server.tf -->

> [!WARNING]
> Terraform sends a `PUT`, which replaces the whole MCP server, including backends and policies that you added in
> the portal. Keep the configuration as the only source of truth for this server, and change it with
> `terraform apply`.

### Deploy with terraform apply

Move into the lab's Terraform folder, select your current subscription, then plan and apply the configuration. The
configuration reads Azure AI Gateway's service principal in your tenant, so create it first if your tenant doesn't
have it yet. It takes about eight minutes.

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

# Deploy to the Azure CLI's current subscription
export ARM_SUBSCRIPTION_ID="$(az account show --query id --output tsv)" &&
  echo "📍 Subscription: $ARM_SUBSCRIPTION_ID"

# Create Azure AI Gateway's service principal in your tenant, unless it's there already
{ az ad sp show --id 18550318-e177-4205-a743-6816d6fcdc3f -o none 2>/dev/null ||
  az ad sp create --id 18550318-e177-4205-a743-6816d6fcdc3f -o none; } &&
  echo "🤖 Azure AI Gateway's service principal is in your tenant"

# Download the providers, then plan and apply the gateway, the backend, the app registrations, and the MCP server
terraform init &&
  terraform plan -out tfplan &&
  terraform apply tfplan &&
  echo "🚀 Gateway deployed: $(terraform output -raw ai_gateway_url)"
```

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

# Deploy to the Azure CLI's current subscription
$env:ARM_SUBSCRIPTION_ID = az account show --query id --output tsv
if ($?) { Write-Host "📍 Subscription: $env:ARM_SUBSCRIPTION_ID" }

# Create Azure AI Gateway's service principal in your tenant, unless it's there already
az ad sp show --id 18550318-e177-4205-a743-6816d6fcdc3f -o none 2>$null
if (-not $?) { az ad sp create --id 18550318-e177-4205-a743-6816d6fcdc3f -o none }
if ($?) { Write-Host "🤖 Azure AI Gateway's service principal is in your tenant" }

# Download the providers, then plan and apply the gateway, the backend, the app registrations, and the MCP server
terraform init
if ($?) { terraform plan -out tfplan }
if ($?) { terraform apply tfplan }
if ($?) { Write-Host "🚀 Gateway deployed: $(terraform output -raw ai_gateway_url)" }
```

Terraform only reads the service principal, so `terraform destroy` never deletes it. The configuration deploys to
`eastus2`. For another region that has both AI Gateway and Azure Container Apps, from [Find the available
regions](../SETUP.md#find-the-available-regions), run `export TF_VAR_location=<region>` (PowerShell:
`$env:TF_VAR_location = "<region>"`) before `terraform plan`.

### Read the outputs

Set the variables that the next steps, **Verify**, and **Clean up** use from the Terraform outputs, call the backend
without a token, then move back to the lab's folder, which holds the scripts.

```bash title="Bash"
# Read the configuration's outputs: the resource group, the gateway, the MCP server, and the gateway's ID and
# runtime URL
export RG="$(terraform output -raw azure_resource_group)"
export GATEWAY="$(terraform output -raw ai_gateway_name)"
export MCP_SERVER="$(terraform output -raw mcp_server)"
export GATEWAY_ID="$(terraform output -raw ai_gateway_id)"
export AI_GATEWAY_URL="$(terraform output -raw ai_gateway_url)"
echo "📝 Gateway $GATEWAY in $RG, MCP server $MCP_SERVER"
echo "🌐 Runtime URL: $AI_GATEWAY_URL"

# Read the backend's outputs: its URL, its scope, and the connector app
export BACKEND_RG="$RG"
export BACKEND_URL="$(terraform output -raw backend_url)"
export BACKEND_SCOPE="$(terraform output -raw backend_scope)"
export CONNECTOR_APP_ID="$(terraform output -raw connector_app_id)"
echo "🔐 Backend scope: $BACKEND_SCOPE"
echo "🌐 Backend URL: $BACKEND_URL"

# Call the backend without a token: Container Apps authentication answers 401 before the server runs
echo "🔐 Anonymous call to the backend: HTTP $(curl -s -o /dev/null -w '%{http_code}' -X POST "$BACKEND_URL" -H 'Content-Type: application/json' -d '{}')"

# Move back to the lab's folder, which holds the scripts
cd .. &&
  echo "📂 Lab folder: $(pwd)"
```

```powershell title="PowerShell"
# Read the configuration's outputs: the resource group, the gateway, the MCP server, and the gateway's ID and
# runtime URL
$RG                 = terraform output -raw azure_resource_group
$GATEWAY            = terraform output -raw ai_gateway_name
$MCP_SERVER         = terraform output -raw mcp_server
$GATEWAY_ID         = terraform output -raw ai_gateway_id
$env:AI_GATEWAY_URL = terraform output -raw ai_gateway_url
Write-Host "📝 Gateway $GATEWAY in $RG, MCP server $MCP_SERVER"
Write-Host "🌐 Runtime URL: $env:AI_GATEWAY_URL"

# Read the backend's outputs: its URL, its scope, and the connector app
$BACKEND_RG       = $RG
$env:BACKEND_URL  = terraform output -raw backend_url
$BACKEND_SCOPE    = terraform output -raw backend_scope
$CONNECTOR_APP_ID = terraform output -raw connector_app_id
Write-Host "🔐 Backend scope: $BACKEND_SCOPE"
Write-Host "🌐 Backend URL: $env:BACKEND_URL"

# Call the backend without a token: Container Apps authentication answers 401 before the server runs
$anonymous = Invoke-WebRequest -Method Post -Uri $env:BACKEND_URL -ContentType 'application/json' -Body '{}' -SkipHttpErrorCheck
Write-Host "🔐 Anonymous call to the backend: HTTP $($anonymous.StatusCode)"

# Move back to the lab's folder, which holds the scripts
Set-Location ..
if ($?) { Write-Host "📂 Lab folder: $(Get-Location)" }
```

> **Checkpoint**
> `terraform apply` ended with `Apply complete! Resources: 28 added, 0 changed, 0 destroyed.`, the backend scope looks
> like `api://<backend app ID>/user_impersonation`, and the anonymous call prints `HTTP 401`.

<!-- /tracks -->

## Check the on-behalf-of settings

Check that the gateway has both identities, and that the backend of the MCP server exchanges the user's token.

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

### Open the MCP server

Open the [AI Gateway portal](https://ai.gateway.azure.com) and select your gateway from the gateway switcher. Select
**MCP servers** › **OBO demo**. The **Overview** tab lists the supported MCP versions `2025-11-25, 2025-06-18,
2025-03-26`, and one backend of type **MCP** with the authentication **OAuth 2.0 (on behalf of)** and the namespace
`demo`.

![The OBO demo MCP server's Overview tab, with its MCP versions, Active status, and one backend with OAuth 2.0 (on behalf of) authentication in the demo namespace](../assets/screens/copilot-obo-02-overview.webp "The Backends table shows how the gateway authenticates to each backend. Test in catalog opens the server in the catalog.")

### Validate the backend

1. In the **Backends** table, on the backend's row, select **More actions** (**⋯**) › **Edit**. The **Edit MCP
   backend** panel shows **Authentication** **OAuth 2.0** with the OAuth profile **On behalf of**, and the values
   that you deployed:

   | Field | Value |
   |---|---|
   | **Token exchange application (client) ID** | The token exchange app's client ID |
   | **Managed identity for token exchange** | `id-<base>-gateway` |
   | **Backend API scope to request** | `api://<backend app ID>/user_impersonation` |
   | **Namespace** | `demo` |

2. Select **Validate**. If the portal asks, approve **Authorize directory access**, which lets it read your app
   registrations. The portal checks the token exchange app, its federated credential, and its consent to the
   backend's scope, then shows **Directory checks successful. Runtime verification pending.**

   ![The Edit MCP backend panel with OAuth 2.0 and On behalf of, the token exchange app, the managed identity, and the backend scope, and the result of Validate](../assets/screens/copilot-obo-01-edit-backend.webp "Validate checks the directory. The first successful call with a user's token verifies the runtime flow.")

3. Select **Cancel**, so that you don't change the server.

The portal asks for full scopes, such as `api://<backend app ID>/user_impersonation`: one to ten scopes for the same
resource, one per line. It rejects `.default`.

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

### Read the settings back

```bash title="Bash"
# Read the gateway's identities: the system-assigned one, and the user-assigned one that signs in as the token
# exchange app
echo "👤 Gateway identities: $(az aigateway show -g "$RG" -n "$GATEWAY" --query identity.type -o tsv)"

# Read the MCP server's backend: its URL, and how the gateway gets a token for it
echo "🔐 Backend of the $MCP_SERVER MCP server:"
az aigateway mcp show -g "$RG" --gateway-name "$GATEWAY" -n "$MCP_SERVER" \
  --query "properties.endpoints[].{namespace:namespace,mode:mode,url:mcp.endpoint.url,oauth2:authentication.oauth2}"
```

```powershell title="PowerShell"
# Read the gateway's identities: the system-assigned one, and the user-assigned one that signs in as the token
# exchange app
Write-Host "👤 Gateway identities: $(az aigateway show -g $RG -n $GATEWAY --query identity.type -o tsv)"

# Read the MCP server's backend: its URL, and how the gateway gets a token for it
Write-Host "🔐 Backend of the $MCP_SERVER MCP server:"
az aigateway mcp show -g $RG --gateway-name $GATEWAY -n $MCP_SERVER `
  --query "properties.endpoints[].{namespace:namespace,mode:mode,url:mcp.endpoint.url,oauth2:authentication.oauth2}"
```

```text title="Expected output"
👤 Gateway identities: SystemAssigned, UserAssigned
🔐 Backend of the obo-demo MCP server:
[
  {
    "mode": "failClosed",
    "namespace": "demo",
    "oauth2": {
      "grantType": "tokenExchange",
      "tokenExchange": {
        "federatedClientApplication": {
          "appCredential": {
            "clientId": "<gateway identity client ID>",
            "type": "userAssignedManagedIdentity"
          },
          "applicationId": "<token exchange app ID>"
        },
        "profile": "entraOnBehalfOf",
        "scopes": [
          "api://<backend app ID>/user_impersonation"
        ]
      }
    },
    "url": "https://ca-<base>-mcp.<environment>.<region>.azurecontainerapps.io/mcp"
  }
]
```

> **Checkpoint**
> The gateway has both identities, and the backend uses the `entraOnBehalfOf` profile with the
> `userAssignedManagedIdentity` credential and your backend scope.

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

### Read the settings that azd deployed

`azd up` already attached the identity and registered the MCP server. Read them back.

```bash title="Bash"
# Read the gateway's identities: the system-assigned one, and the user-assigned one that signs in as the token
# exchange app
echo "👤 Gateway identities: $(az aigateway show -g "$RG" -n "$GATEWAY" --query identity.type -o tsv)"

# Read the MCP server's backend: its URL, and how the gateway gets a token for it
echo "🔐 Backend of the $MCP_SERVER MCP server:"
az aigateway mcp show -g "$RG" --gateway-name "$GATEWAY" -n "$MCP_SERVER" \
  --query "properties.endpoints[].{namespace:namespace,mode:mode,url:mcp.endpoint.url,oauth2:authentication.oauth2}"
```

```powershell title="PowerShell"
# Read the gateway's identities: the system-assigned one, and the user-assigned one that signs in as the token
# exchange app
Write-Host "👤 Gateway identities: $(az aigateway show -g $RG -n $GATEWAY --query identity.type -o tsv)"

# Read the MCP server's backend: its URL, and how the gateway gets a token for it
Write-Host "🔐 Backend of the $MCP_SERVER MCP server:"
az aigateway mcp show -g $RG --gateway-name $GATEWAY -n $MCP_SERVER `
  --query "properties.endpoints[].{namespace:namespace,mode:mode,url:mcp.endpoint.url,oauth2:authentication.oauth2}"
```

> **Checkpoint**
> The gateway identities are `SystemAssigned, UserAssigned`, and the backend uses the `entraOnBehalfOf` profile with
> the `userAssignedManagedIdentity` credential and your backend scope.

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

### Read the settings that Terraform deployed

`terraform apply` already attached the identity and registered the MCP server. Read them back.

```bash title="Bash"
# Read the gateway's identities: the system-assigned one, and the user-assigned one that signs in as the token
# exchange app
echo "👤 Gateway identities: $(az aigateway show -g "$RG" -n "$GATEWAY" --query identity.type -o tsv)"

# Read the MCP server's backend: its URL, and how the gateway gets a token for it
echo "🔐 Backend of the $MCP_SERVER MCP server:"
az aigateway mcp show -g "$RG" --gateway-name "$GATEWAY" -n "$MCP_SERVER" \
  --query "properties.endpoints[].{namespace:namespace,mode:mode,url:mcp.endpoint.url,oauth2:authentication.oauth2}"
```

```powershell title="PowerShell"
# Read the gateway's identities: the system-assigned one, and the user-assigned one that signs in as the token
# exchange app
Write-Host "👤 Gateway identities: $(az aigateway show -g $RG -n $GATEWAY --query identity.type -o tsv)"

# Read the MCP server's backend: its URL, and how the gateway gets a token for it
Write-Host "🔐 Backend of the $MCP_SERVER MCP server:"
az aigateway mcp show -g $RG --gateway-name $GATEWAY -n $MCP_SERVER `
  --query "properties.endpoints[].{namespace:namespace,mode:mode,url:mcp.endpoint.url,oauth2:authentication.oauth2}"
```

> **Checkpoint**
> The gateway identities are `SystemAssigned, UserAssigned`, and the backend uses the `entraOnBehalfOf` profile with
> the `userAssignedManagedIdentity` credential and your backend scope.

<!-- /tracks -->

## Call the tools as yourself

Before you connect Copilot, call the tools as yourself, first in the portal's catalog, then with a script that checks
each link of the chain. If a call fails with `403`, wait a few minutes for your role assignment to apply.

<!-- steps -->

### Test in the catalog

1. In the AI Gateway portal, on the **OBO demo** server's **Overview** tab, select **Test in catalog**.
2. Keep the method **Microsoft Entra ID** and the MCP version `2025-11-25`, then select **Connect**. The panel lists
   the tools **Echo**, **Get server time**, and **Whoami**.
3. Select **Whoami** › **Run**. The **Output** shows **Success** with your name and username, the scope
   `user_impersonation`, and the token version `2.0`.

![The catalog page of OBO demo, connected with Microsoft Entra ID, with the Whoami tool's output: Success, the user's name and username, the user_impersonation scope, and token version 2.0](../assets/screens/copilot-obo-03-test-whoami.webp "The backend saw you. A successful call verifies the runtime flow for your user, which listing the tools alone doesn't.")

### Run the test script

[`infra/call-obo-tool.sh`](infra/call-obo-tool.sh) (PowerShell 7:
[`infra/call-obo-tool.ps1`](infra/call-obo-tool.ps1)) calls the MCP server as the signed-in Azure CLI user. It
gets a token for AI Gateway with `az account get-access-token --scope https://ai.gateway.azure.com/Data.All`, calls
`demo_whoami`, and compares the user and audience that the backend saw with your token. Then it sends your token for
the gateway straight to the backend. It never prints a token.

```bash title="Bash"
# Make the test script executable
chmod +x infra/call-obo-tool.sh &&
  echo "📄 infra/call-obo-tool.sh is executable"

# Call the MCP server as yourself, and check each link of the on-behalf-of chain
./infra/call-obo-tool.sh "$MCP_SERVER"
```

```powershell title="PowerShell"
# Call the MCP server as yourself, and check each link of the on-behalf-of chain
./infra/call-obo-tool.ps1 -Server $MCP_SERVER
```

```text title="Expected output"
MCP endpoint: https://<gateway-host>/default/toolservers/obo-demo/mcp
1. Without a token: HTTP 401, as expected
   Your token for the gateway: aud <guid> scp Data.All oid <your object ID>
2. Handshake: MCP version 2025-06-18, tools: demo_echo, demo_get_server_time, demo_whoami
3. demo_whoami: the backend received this token:
{ "name": "Adele Vance", "username": "AdeleV@contoso.onmicrosoft.com", "object_id": "<your object ID>", "audience": "<backend app ID>", "client_app_id": "<token exchange app ID>", "scopes": "user_impersonation" }
   Same user as your token for the gateway, different audience: the gateway exchanged it on your behalf
4. Your gateway token sent straight to the backend: HTTP 401, as expected
```

<!-- /steps -->

> **Checkpoint**
> `demo_whoami` returns your object ID, the backend app as the audience, and the token exchange app as the calling
> app. Your token for the gateway gets `401` on the backend.

## Connect Microsoft 365 Copilot

Microsoft 365 Copilot reaches MCP servers through **connectors**. The connector signs each user in with OAuth 2.0
and the connector app, gets a token for AI Gateway, and sends it to the MCP endpoint. Register the OAuth client in
the Teams Developer Portal, then add the connector in the Microsoft 365 admin center.

<!-- steps -->

### Create the connector's client secret

The connector app needs a client secret, which neither Bicep nor this lab's Terraform configuration creates, so that
it never lands in a template or a state file. Create one that expires in seven days, and print the other values
that the registration asks for.

```bash title="Bash"
# Read your tenant ID: the connector's sign-in endpoints use it
export TENANT_ID="$(az account show --query tenantId -o tsv)"
echo "🆔 Tenant ID: $TENANT_ID"

# Give the connector app a client secret that expires in 7 days, and keep it only in this shell
CONNECTOR_SECRET="$(az ad app credential reset --id "$CONNECTOR_APP_ID" --append --display-name "Microsoft 365 Copilot connector" --only-show-errors \
  --end-date "$(date -u -d '+7 days' +%F 2>/dev/null || date -u -v+7d +%F)" --query password -o tsv)"
echo "🔑 Client secret: in CONNECTOR_SECRET (${#CONNECTOR_SECRET} characters, not shown), expires in 7 days"

# Print the values of the OAuth client registration
echo "🔌 Base URL: $AI_GATEWAY_URL/default/toolservers/$MCP_SERVER/mcp"
echo "🆔 Client ID: $CONNECTOR_APP_ID"
echo "🌐 Authorization endpoint: https://login.microsoftonline.com/$TENANT_ID/oauth2/v2.0/authorize"
echo "🌐 Token and refresh endpoint: https://login.microsoftonline.com/$TENANT_ID/oauth2/v2.0/token"
```

```powershell title="PowerShell"
# Read your tenant ID: the connector's sign-in endpoints use it
$TENANT_ID = az account show --query tenantId -o tsv
Write-Host "🆔 Tenant ID: $TENANT_ID"

# Give the connector app a client secret that expires in 7 days, and keep it only in this session
$CONNECTOR_SECRET = az ad app credential reset --id $CONNECTOR_APP_ID --append --display-name "Microsoft 365 Copilot connector" --only-show-errors `
  --end-date (Get-Date).ToUniversalTime().AddDays(7).ToString("yyyy-MM-dd") --query password -o tsv
Write-Host "🔑 Client secret: in CONNECTOR_SECRET ($($CONNECTOR_SECRET.Length) characters, not shown), expires in 7 days"

# Print the values of the OAuth client registration
Write-Host "🔌 Base URL: $env:AI_GATEWAY_URL/default/toolservers/$MCP_SERVER/mcp"
Write-Host "🆔 Client ID: $CONNECTOR_APP_ID"
Write-Host "🌐 Authorization endpoint: https://login.microsoftonline.com/$TENANT_ID/oauth2/v2.0/authorize"
Write-Host "🌐 Token and refresh endpoint: https://login.microsoftonline.com/$TENANT_ID/oauth2/v2.0/token"
```

### Register the OAuth client

1. Open the [Teams Developer Portal](https://dev.teams.microsoft.com) and sign in as an admin of your tenant.
2. Select **Tools** › **OAuth client registration** › **Register client**, and fill in the form:

   | Field | Value |
   |---|---|
   | **Registration name** | `AI Gateway OBO demo` |
   | **Base URL** | The `🔌 Base URL` that the previous step printed: your MCP endpoint |
   | **Restrict usage by organization** | **My organization only** |
   | **Restrict usage by Teams app** | **Any Teams app (for testing and store validation only)** |
   | **Client ID** | The `🆔 Client ID` |
   | **Client secret** | Your client secret. To copy it without printing it, run `printf %s "$CONNECTOR_SECRET" \| pbcopy` on macOS, or `Set-Clipboard $CONNECTOR_SECRET` in PowerShell |
   | **Authorization endpoint** | The `🌐 Authorization endpoint` |
   | **Token endpoint** and **Refresh endpoint** | The `🌐 Token and refresh endpoint` |
   | **Scope** | `https://ai.gateway.azure.com/Data.All offline_access` |

   Turn on **Enable PKCE**.

   ![The OAuth client registration form with the MCP endpoint as Base URL, My organization only, Any Teams app, and the connector app's client ID](../assets/screens/copilot-obo-04-registration.webp "Any Teams app lets the connector use the registration. An existing Teams app binding doesn't work for MCP connectors.")

3. Select **Save**. The portal shows **OAuth configuration "AI Gateway OBO demo" created successfully**. Copy the
   **OAuth client registration ID**: the connector asks for it.

The scope asks Microsoft Entra ID for a token for AI Gateway, and `offline_access` for a refresh token, so users sign
in once. The connector app already has tenant-wide consent to both, so users get no consent prompt.

### Add the connector

1. Open the [Microsoft 365 admin center](https://admin.cloud.microsoft) and allow pop-ups for it: the sign-in in
   step 3 opens one.
2. Select **Copilot** › **Connectors** › **Gallery** › **Created by your org**. On **Create a new connector**,
   select **Add**, then **Connect to MCP server** › **Add**.
3. Fill in the five steps of the form:
   1. **Display name**: `AI Gateway OBO demo`.
   2. **Description**: `Demo MCP tools behind Azure AI Gateway. The gateway calls the backend as the signed-in
      user with Microsoft Entra ID on-behalf-of. Use it to ask who you are, echo a message, or get the server
      time.` Copilot reads the description to decide when to use the tools.
   3. **MCP endpoint URL**: your MCP endpoint, the `🔌 Base URL`.
   4. The developer details: **Developer name** `Contoso`, **Website URL** `https://github.com/Azure/aigateway`,
      **Privacy policy URL** `https://privacy.microsoft.com/privacystatement`, and **Terms of use URL**
      `https://www.microsoft.com/legal/terms-of-use`.
   5. **Authentication type**: **OAuth 2.0**. Paste the **Reference ID**, the OAuth client registration ID, then
      select **Authorize** and sign in. The button changes to **Edit**.

   ![Step 5 of Connect to MCP server, with OAuth 2.0 and a checked Reference ID](../assets/screens/copilot-obo-05-connector.webp "Authorize signs you in through the gateway once, with the registration that you created.")

4. Check the **Notice**, then select **Create**. The **Success** page shows **Created connection** and **Linking data
   source**. Select **Done**.

   ![The Success page: Created connection AI Gateway OBO demo, and Linking data source](../assets/screens/copilot-obo-06-created.webp "The connector can take up to 30 minutes to be ready.")

### Check the connection and its tools

1. Select **Your Connections**. Within 30 minutes, the **AI Gateway OBO demo** row shows the state **Ready**.

   ![Your Connections with AI Gateway OBO demo in the Ready state](../assets/screens/copilot-obo-07-connections.webp "Ready means that Copilot users can install the connector's plugin.")

2. Select the connection, then **Tools** › **Sign in**. The sign-in completes without a prompt and shows **Sign in
   successful**. Select **View tools**: the connector lists the three tools.

   ![The connector's Available tools list with three tools](../assets/screens/copilot-obo-08-tools.webp "The tools show as Write: the gateway doesn't pass the server's read-only annotations yet, so Copilot asks before each call.")

<!-- /steps -->

> **Checkpoint**
> The connection **AI Gateway OBO demo** is **Ready**, and **View tools** lists three tools.

The gateway doesn't pass the tools' `readOnlyHint` annotations on to the connector yet, so Copilot treats them as
**Write** tools and asks the user to approve each call.

## Use the tools in Copilot Cowork

Copilot Cowork runs the connector's tools as the signed-in user. Sign in to Microsoft 365 Copilot as the user that
has the Tools User role, you on this lab.

<!-- steps -->

### Install and connect the plugin

1. Open [Microsoft 365 Copilot](https://copilot.cloud.microsoft) and select **Plugins**. On the **Cowork** tab,
   search for `OBO`, then on **AI Gateway OBO demo**, select **Install**. Copilot shows **Plugin installed. Connect
   your account below to get started.**

   ![The AI Gateway OBO demo plugin, created by Contoso, with the Install button](../assets/screens/copilot-obo-09-plugin.webp "The connector appears as a plugin for everyone that its staged rollout includes.")

2. Turn on the plugin and select **Connect**. The connection shows **Connected.**

   ![The plugin page with the toggle on, and the AI Gateway OBO demo connection Connected](../assets/screens/copilot-obo-10-connected.webp "Connect signs you in through the gateway once. Copilot refreshes the token after that.")

### Ask who the backend sees

1. Select **New**, choose **Cowork**, and send this prompt:

   ```text
   Using the AI Gateway OBO demo connector, call the whoami tool and tell me who the backend sees as the caller: name, object ID, token audience, and calling app.
   ```

2. Cowork shows a **Demo_whoami** card with **No parameters**. Select **Approve**.

   ![The Demo_whoami approval card with No parameters, and the Cancel and Approve buttons](../assets/screens/copilot-obo-11-approve.webp "Cowork asks before each call to a Write tool.")

3. Cowork answers with your name and object ID, the backend app as the token audience, and the token exchange app as
   the calling app.

   ![Cowork's answer: the backend sees Adele Vance as the caller, with the object ID, the token audience, and the calling app](../assets/screens/copilot-obo-12-cowork-answer.webp "The same person who signed in to Copilot reached the backend, with a token that only the backend accepts.")

<!-- /steps -->

> **Checkpoint**
> Cowork's answer shows your name and object ID, the same as `demo_whoami` returned to the test script.

Use **Cowork** for this lab. In Copilot **Chat** mode, the call waits for an approval that the chat doesn't show.

## Verify

<!-- steps -->

### Read the backend's log

The MCP server logs one line for each call, with the user's object ID, the calling app, and the scope. The lines
reach Log Analytics a few minutes after the calls.

```bash title="Bash"
# Find the Log Analytics workspace of the container app
WS="$(az monitor log-analytics workspace list -g "$BACKEND_RG" --query "[0].customerId" -o tsv)"

# Read the calls of the last hour: the user, the calling app, and the scope
echo "📊 Calls of the last hour:"
az monitor log-analytics query -w "$WS" -o tsv --analytics-query \
  "ContainerAppConsoleLogs_CL | where TimeGenerated > ago(1h) and Log_s has 'Call from user' | order by TimeGenerated asc | project Log_s"
```

```powershell title="PowerShell"
# Find the Log Analytics workspace of the container app
$WS = az monitor log-analytics workspace list -g $BACKEND_RG --query "[0].customerId" -o tsv

# Read the calls of the last hour: the user, the calling app, and the scope
Write-Host "📊 Calls of the last hour:"
az monitor log-analytics query -w $WS -o tsv --analytics-query `
  "ContainerAppConsoleLogs_CL | where TimeGenerated > ago(1h) and Log_s has 'Call from user' | order by TimeGenerated asc | project Log_s"
```

```text title="Expected output"
📊 Calls of the last hour:
INFO:obo-demo:Call from user <your object ID> through app <token exchange app ID> with scope user_impersonation	PrimaryResult
```

The catalog, the test script, and Cowork each add lines with your object ID. The calling app is always the token
exchange app: nothing else gets a token that the backend accepts.

### Call the gateway with a token for another API

The gateway accepts only tokens for AI Gateway with the `Data.All` scope. Send it a token for Azure Resource Manager
instead.

```bash title="Bash"
# Read the MCP endpoint of the server
MCP_ENDPOINT="$(az aigateway mcp show -g "$RG" --gateway-name "$GATEWAY" -n "$MCP_SERVER" --query "properties.gatewayEndpoints[0].url" -o tsv)"

# Call it with a token for Azure Resource Manager, then forget the token
ARM_TOKEN="$(az account get-access-token --query accessToken -o tsv)"
curl -s -w "\nHTTP %{http_code}\n" -X POST "$MCP_ENDPOINT" -H "Authorization: Bearer $ARM_TOKEN" \
  -H 'Content-Type: application/json' -H 'Accept: application/json, text/event-stream' \
  -d '{"jsonrpc":"2.0","id":1,"method":"tools/list"}'
unset ARM_TOKEN
```

```powershell title="PowerShell"
# Read the MCP endpoint of the server
$MCP_ENDPOINT = az aigateway mcp show -g $RG --gateway-name $GATEWAY -n $MCP_SERVER --query "properties.gatewayEndpoints[0].url" -o tsv

# Call it with a token for Azure Resource Manager, then forget the token
$armToken = az account get-access-token --query accessToken -o tsv
$response = Invoke-WebRequest -Method Post -Uri $MCP_ENDPOINT -ContentType 'application/json' `
  -Headers @{ Authorization = "Bearer $armToken"; Accept = 'application/json, text/event-stream' } `
  -Body '{"jsonrpc":"2.0","id":1,"method":"tools/list"}' -SkipHttpErrorCheck
Write-Host "$($response.Content)`nHTTP $($response.StatusCode)"
Remove-Variable armToken
```

```text title="Expected output"
{ "statusCode": 401, "message": "Unauthorized. Missing or invalid Entra ID token, or missing Data.All scope." }
HTTP 401
```

<!-- /steps -->

> **Checkpoint**
> The log shows your object ID with the token exchange app and the `user_impersonation` scope, and the token for
> Azure Resource Manager gets `401`.

## Go further

- **Call your own API.** Replace the demo server with an API that already accepts Microsoft Entra tokens for its own
  scope. Grant the token exchange app consent to that scope, and put the scope in the backend's `scopes`. The API
  then applies its own permissions to each user.
- **Grant the role to a group.** Assign **AI Gateway Tools User** on the MCP server to a Microsoft Entra group
  instead of single users, so that the group decides who can call the tools from Copilot.
- **Add controls to the calls.** The user's identity also works with the gateway's tool controls: hide tools with
  [allow and block lists](../05-mcp-tool-controls/README.md), or check each call with
  [agent hooks](../30-agent-hooks/README.md).
- **Deploy your own server.** Fork the repository and point the image build at your branch: run
  `azd env set MCP_SERVER_SOURCE "https://github.com/<you>/aigateway.git#<branch>:labs/33-copilot-obo-mcp/infra/mcp-server"`
  and `azd provision`, or `terraform plan -var mcp_server_source=<the same value> -out tfplan` and
  `terraform apply tfplan` in the `terraform` folder.
- **Use the server from other MCP clients.** Any client that sends a Microsoft Entra token for AI Gateway works, such
  as one that you configure with the token from
  `az account get-access-token --scope https://ai.gateway.azure.com/Data.All`. The gateway doesn't publish OAuth
  protected resource metadata yet, so clients that discover the sign-in from the server can't sign in on their own.
- **Rotate the connector's secret.** It expires in seven days. Create a new one with the same command, update the
  **Client secret** of the OAuth client registration, and delete the old one with `az ad app credential delete`.

## Clean up

Remove the connector from Microsoft 365 first, then the Azure resources.

<!-- steps -->

### Remove the connector from Microsoft 365

1. In Microsoft 365 Copilot, select **Plugins**. On the **Cowork** tab, open **AI Gateway OBO demo**, select
   **Disconnect**, and turn off the plugin. Then select **More actions** › **Uninstall**, and confirm.
2. In the Microsoft 365 admin center, select **Copilot** › **Connectors** › **Your Connections**. On the **AI Gateway
   OBO demo** row, select **More Actions** › **View Details** › **Delete**, and confirm.
3. In the Teams Developer Portal, select **Tools** › **OAuth client registration**. On the **AI Gateway OBO demo**
   row, select the actions menu › **Delete**, and confirm.

<!-- /steps -->

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

### Delete the MCP server and the backend

In the AI Gateway portal, select **MCP servers**. On the **OBO demo** row, select **More actions** (**⋯**) ›
**Delete**, and confirm. Then delete the rest with the **Azure CLI** track's commands below, from the gateway
identity on: the **Azure CLI** steps of **Deploy the backend and register the MCP server** created them.

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

### Remove the MCP server and the backend

```bash title="Bash"
# Delete your AI Gateway Tools User role assignment on the MCP server
az role assignment delete --assignee "$(az ad signed-in-user show --query id -o tsv)" \
  --role "dce03f8d-857f-4e40-a90d-67770fa6ecd2" --scope "$GATEWAY_ID/workspaces/default/toolServers/$MCP_SERVER" &&
  echo "🚮 Your AI Gateway Tools User role assignment on $MCP_SERVER is deleted"

# Delete the MCP server from the gateway
az aigateway mcp delete -g "$RG" --gateway-name "$GATEWAY" -n "$MCP_SERVER" --yes &&
  echo "🚮 MCP server $MCP_SERVER is deleted"

# Detach the user-assigned identity from the gateway, and keep the system-assigned one
az aigateway identity remove -g "$RG" -n "$GATEWAY" --user-assigned "$IDENTITY_ID" -o none &&
  echo "👤 The gateway identity is detached from $GATEWAY"

# Delete the backend's resource group: the identities, the container app, its registry, and its logs
az group delete -n "$BACKEND_RG" --yes --no-wait &&
  echo "⏳ Resource group $BACKEND_RG is being deleted"

# Delete the three app registrations, then purge them from the deleted items
for app in "$CONNECTOR_APP_ID" "$TOKEN_EXCHANGE_APP_ID" "$BACKEND_APP_ID"; do
  id="$(az ad app show --id "$app" --query id -o tsv)" &&
    az ad app delete --id "$app" &&
    az rest --method delete --url "https://graph.microsoft.com/v1.0/directory/deletedItems/$id" &&
    echo "🚮 App registration $app is deleted and purged"
done
```

```powershell title="PowerShell"
# Delete your AI Gateway Tools User role assignment on the MCP server
az role assignment delete --assignee (az ad signed-in-user show --query id -o tsv) `
  --role "dce03f8d-857f-4e40-a90d-67770fa6ecd2" --scope "$GATEWAY_ID/workspaces/default/toolServers/$MCP_SERVER"
if ($?) { Write-Host "🚮 Your AI Gateway Tools User role assignment on $MCP_SERVER is deleted" }

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

# Detach the user-assigned identity from the gateway, and keep the system-assigned one
az aigateway identity remove -g $RG -n $GATEWAY --user-assigned $IDENTITY_ID -o none
if ($?) { Write-Host "👤 The gateway identity is detached from $GATEWAY" }

# Delete the backend's resource group: the identities, the container app, its registry, and its logs
az group delete -n $BACKEND_RG --yes --no-wait
if ($?) { Write-Host "⏳ Resource group $BACKEND_RG is being deleted" }

# Delete the three app registrations, then purge them from the deleted items
foreach ($app in @($CONNECTOR_APP_ID, $TOKEN_EXCHANGE_APP_ID, $BACKEND_APP_ID)) {
  $id = az ad app show --id $app --query id -o tsv
  az ad app delete --id $app
  if ($?) { az rest --method delete --url "https://graph.microsoft.com/v1.0/directory/deletedItems/$id" }
  if ($?) { Write-Host "🚮 App registration $app is deleted and purged" }
}
```

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

### Delete everything azd created

In the `aigateway/labs/33-copilot-obo-mcp` folder, delete the resource group with the gateway, the backend, and the
MCP server. Before that, the `predown` hook deletes the app registrations and purges them.
[`--purge`](../SETUP.md#delete-what-azd-created) also purges soft-deleted resources. It takes about ten minutes.

```bash
# Delete everything that azd up created, and purge the soft-deleted resources
azd down --purge --force &&
  echo "🚮 Everything that azd up created is deleted"
```

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

### Delete everything Terraform created

In the lab's Terraform folder, delete the app registrations and the resource group with the gateway, the backend, and
the MCP server. Microsoft Entra ID keeps deleted app registrations in its deleted items for 30 days, so purge them
too, like `azd down` does. Read their object IDs first, because `terraform destroy` removes the outputs. It takes
about 25 minutes, most of it to delete the Container Apps environment.

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

# Read the app registrations' object IDs, which the purge needs after terraform destroy
CONNECTOR_OBJECT_ID="$(az ad app show --id "$(terraform output -raw connector_app_id)" --query id -o tsv)"
TOKEN_EXCHANGE_OBJECT_ID="$(az ad app show --id "$(terraform output -raw token_exchange_app_id)" --query id -o tsv)"
BACKEND_OBJECT_ID="$(az ad app show --id "$(terraform output -raw backend_app_id)" --query id -o tsv)"
echo "🆔 App registrations: $CONNECTOR_OBJECT_ID $TOKEN_EXCHANGE_OBJECT_ID $BACKEND_OBJECT_ID"

# Delete everything that terraform apply created, including the app registrations
terraform destroy -auto-approve &&
  echo "🚮 Everything that terraform apply created is deleted"

# Purge the app registrations from the deleted items
for id in "$CONNECTOR_OBJECT_ID" "$TOKEN_EXCHANGE_OBJECT_ID" "$BACKEND_OBJECT_ID"; do
  az rest --method delete --url "https://graph.microsoft.com/v1.0/directory/deletedItems/$id" &&
    echo "🚮 App registration $id is purged"
done
```

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

# Read the app registrations' object IDs, which the purge needs after terraform destroy
$CONNECTOR_OBJECT_ID      = az ad app show --id (terraform output -raw connector_app_id) --query id -o tsv
$TOKEN_EXCHANGE_OBJECT_ID = az ad app show --id (terraform output -raw token_exchange_app_id) --query id -o tsv
$BACKEND_OBJECT_ID        = az ad app show --id (terraform output -raw backend_app_id) --query id -o tsv
Write-Host "🆔 App registrations: $CONNECTOR_OBJECT_ID $TOKEN_EXCHANGE_OBJECT_ID $BACKEND_OBJECT_ID"

# Delete everything that terraform apply created, including the app registrations
terraform destroy -auto-approve
if ($?) { Write-Host "🚮 Everything that terraform apply created is deleted" }

# Purge the app registrations from the deleted items
foreach ($id in @($CONNECTOR_OBJECT_ID, $TOKEN_EXCHANGE_OBJECT_ID, $BACKEND_OBJECT_ID)) {
  az rest --method delete --url "https://graph.microsoft.com/v1.0/directory/deletedItems/$id"
  if ($?) { Write-Host "🚮 App registration $id is purged" }
}
```

<!-- /tracks -->

Keep the gateway and the `learn` MCP server from lab 04: the next labs reuse them. `azd down` and
`terraform destroy` don't touch them, because the Bicep + azd and Terraform tracks created their own gateways.

## Next steps

- [Call backends with managed identities](../12-backend-identity/README.md)
- [Control which tools agents can call](../05-mcp-tool-controls/README.md)
- [Govern MCP tool calls with agent hooks](../30-agent-hooks/README.md)
- [Protect tool calls with Agent 365 threat protection](../19-tool-threat-protection/README.md)
- [Access MCP server backends with user credentials](https://ai.gateway.azure.com/docs/toolservers/access-backends-with-user-credentials) in the AI Gateway docs
