---
title: Protect tool calls with Agent 365 threat protection
summary: Have Microsoft Defender and Microsoft Purview evaluate every tool call on an MCP server, before the tool runs, after it returns, or both, and see how a fail-closed denial reaches the caller.
category: production
level: Advanced
duration: 30
tracks: [portal, iac, terraform]
order: 19
status: emerging
illustration: diagrams/threat-protection.svg
tags: [Agent 365, tool threat protection, Microsoft Defender, Microsoft Purview, prompt injection, MCP, on-behalf-of, Entra ID]
objectives:
  - Explain what the before-invocation and after-invocation stages evaluate and what each one can and can't prevent
  - Add an Agent 365 tool threat protection policy to an MCP server in the AI Gateway portal, with Bicep and azd, or with Terraform
  - Call a protected tool with a delegated Microsoft Entra ID token and read the result
  - Recognize the documented denial codes and why a key-only call fails closed
prereqs:
  - 04-federate-mcp-tools
  - 11-entra-rbac
---

# Protect tool calls with Agent 365 threat protection

Your agents call tools that read web pages, tickets, and documents, and any of that content can carry a prompt
injection or leak sensitive data back to the model. Content filters on the model don't see what goes into a tool
or what comes out of it. In this lab you add **Agent 365 tool threat protection** to an MCP server, so Microsoft
Defender and Microsoft Purview evaluate each tool request, each tool result, or both, and the gateway only lets
allowed calls through.

![The gateway sends the tool request and the tool result to Microsoft Defender and Microsoft Purview for an allow decision](../assets/diagrams/threat-protection.svg "The gateway asks for an allow decision before the tool runs, after it returns, or both. Anything other than an allow fails closed.")

<!-- widget: request-lifecycle -->

## Before you begin

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

> [!TIP]
> On the **Bicep + azd** and **Terraform** tracks, `azd up` or `terraform apply` creates its own gateway, the `learn`
> MCP server, your **AI Gateway Tools User** role assignment on it, and a key, so you can skip this section except for
> the Microsoft Agent 365 license. You need only the one-time setup above, signed in as a user.

- Complete [Federate MCP tools behind one endpoint](../04-federate-mcp-tools/README.md). This lab protects the
  `learn` MCP server from that lab. Any MCP server in your gateway works.
- Complete [Go keyless with Microsoft Entra ID and RBAC](../11-entra-rbac/README.md). Tool threat protection
  only works for callers that send a **delegated** Microsoft Entra ID bearer token issued for AI Gateway.
- A **Microsoft Agent 365 license** in your tenant. Agent 365 runs the Microsoft Defender and Microsoft Purview
  checks.
- Permission to manage policies on the gateway, for example **Contributor** on its resource group, and permission
  to create role assignments if your user doesn't have a data-plane role yet.
- Your Azure CLI sign-in as a **user**, not a service principal.
- Run the scripts and samples from the lab's folder, `~/aigateway/labs/19-tool-threat-protection`.

> [!NOTE]
> Agent 365 tool threat protection is in preview, so its labels and behavior can change. See the
> [October 8, 2026 release](https://ai.gateway.azure.com/docs/releases#release-2026-10-08) and
> [Agent 365 tool threat protection](https://ai.gateway.azure.com/docs/policies/tool-threat-protection).

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 protect
export RG="<resource-group>"
export GATEWAY="<gateway>"
export MCP_SERVER="learn"                    # the MCP server you protect 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"

# Paste the runtime key from Access › API keys without showing it: you use it once, to see a key-only call fail closed
printf "AI Gateway API key: " && read -rs AI_GATEWAY_API_KEY && export AI_GATEWAY_API_KEY && echo
echo "🔑 Key: in AI_GATEWAY_API_KEY (${#AI_GATEWAY_API_KEY} characters, not shown)"
```

```powershell title="PowerShell"
# Set your resource group and gateway, and the MCP server that you protect
$RG         = "<resource-group>"
$GATEWAY    = "<gateway>"
$MCP_SERVER = "learn"                        # the MCP server you protect 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"

# Paste the runtime key from Access › API keys without showing it: you use it once, to see a key-only call fail closed
$env:AI_GATEWAY_API_KEY = Read-Host "AI Gateway API key" -MaskInput
Write-Host "🔑 Key: in AI_GATEWAY_API_KEY ($($env:AI_GATEWAY_API_KEY.Length) characters, not shown)"
```

## How it works

Tool threat protection is a policy on one MCP server. It covers every tool on that server, whether the server is
backed by remote MCP endpoints, OpenAPI services, or both, and every caller. The gateway first runs its usual
authentication, authorization, and policies. Only requests that pass are sent for evaluation.

For each `tools/call`, the gateway exchanges the caller's delegated token on behalf of the user (OBO) and asks
Microsoft Defender and Microsoft Purview for a verdict on malicious content, prompt injection, and sensitive-data
risks. Discovery and session traffic, such as `initialize`, `tools/list`, and notifications, isn't evaluated.

The evaluation must return a valid **allow**. A denial, timeout, token-exchange failure, malformed verdict, or
unavailable evaluator fails closed: the caller gets a normal tool result over HTTP `200` with `isError: true`, a
denial code, and a correlation ID.

| Stage | What's evaluated | What it prevents | Cost |
|---|---|---|---|
| **Before tool invocation** | The tool name and arguments | The tool never runs, so there are no side effects | One evaluation round trip |
| **After tool invocation** | The tool result, including error results | The result never reaches the agent. The tool **already ran**. | One evaluation round trip |
| **Both** | Both of the above | Requires two allow decisions | Up to two round trips per call |

## Prepare a delegated caller

The policy evaluates each call on behalf of the signed-in user, so you test it with your own user token. Give
your user permission to call tools on the server, then make one call **before** you add the policy. That proves
the token and the role work, so any later failure comes from the policy.

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

### Grant yourself the AI Gateway Tools User role

In the AI Gateway portal, select **Access** › **Entra ID** › **Add role assignment**. Enter your name or object ID in
**Search directory identities**, check your account, and select **Next**. Select
**Invoke gateway assets only**, then **Next**. Select **Specific assets**, check **Microsoft Learn**, the MCP server
with the scope `/workspaces/default/toolServers/learn`, under **Resources**, and confirm that **Azure roles to
assign** shows **AI Gateway Tools User**. Select **Next**, check the assignment on the **Review** step, then select
**Assign**. The [Entra ID lab](../11-entra-rbac/README.md) walks through this wizard.

The same assignment with the Azure CLI:

```bash
# Give your user the AI Gateway Tools User role on the MCP server, so that your token can call its tools
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
# Give your user the AI Gateway Tools User role on the MCP server, so that your token can call its tools
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" }
```

If you already have **AI Gateway User** or **AI Gateway Tools User** at the gateway scope, skip this step. Role
assignments can take several minutes to apply.

> **Note**
> To assign a role, you need **Owner**, **User Access Administrator**, or **Role Based Access Control
> Administrator** on the gateway or above. **Contributor** isn't enough, and neither is a role whose permission to
> assign roles carries a condition that excludes this role. The portal then reports "1 role assignment failed."
> without a reason. Ask an owner of the subscription to assign the role.

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

**What you need:** only the one-time setup from **Before you begin**, signed in as a **user**. This track doesn't use
your gateway or `learn` server from lab 04: `azd up` creates a new gateway with its own `learn` server, so it works on
its own. You still need the Microsoft Agent 365 license.

### 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 calls
`infra/protected-tool-server.bicep`, which azd fills from environment values:

| Parameter | azd environment value | Default |
|---|---|---|
| `preInvocation` | `TOOL_THREAT_PRE_INVOCATION` | `false` |
| `postInvocation` | `TOOL_THREAT_POST_INVOCATION` | `false` |
| `principalId` | `AZURE_PRINCIPAL_ID`, which azd sets to the signed-in user | Your user's object ID |

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

`infra/protected-tool-server.bicep` declares the `learn` server of lab 04 with its `learn` backend. Its `policies`
array holds one `toolThreatProtection` policy with `preInvocation` and `postInvocation` when at least one stage is
on, and nothing when both are off. It assigns **AI Gateway Tools User** on the server to `principalId`, as the
portal step does, and creates the `app-first-call` key.

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

> [!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-lab19` in your current subscription, then provision
everything. It takes about two minutes. Both stages are off at first, so you can test your token before you add
the policy.

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

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

# Provision the gateway, the learn MCP server, your role on it, and the key, with both stages off
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/19-tool-threat-protection
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-lab19 --location eastus2 --subscription (az account show --query id --output tsv)
if ($?) { Write-Host "📝 azd environment aigw-lab19 deploys to eastus2" }

# Provision the gateway, the learn MCP server, your role on it, and the key, with both stages off
azd up
if ($?) { Write-Host "🚀 Gateway deployed: $(azd env get-value AI_GATEWAY_URL)" }
```

For another region, use its name from [Find the available
regions](../SETUP.md#find-the-available-regions).

### Read the outputs and the key

Set the variables that the next steps, **Verify**, and **Clean up** use from azd's environment values, and read
the key from the gateway, so that it never shows on screen. The last command lists your roles on the MCP server.

```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 app-first-call key from the gateway, so that it never shows on screen
export AI_GATEWAY_API_KEY="$(az aigateway api-key list-secrets --ids "$GATEWAY_ID/apiKeys/app-first-call" \
  --query primaryKey --output tsv)"
echo "🔑 Key: in AI_GATEWAY_API_KEY (${#AI_GATEWAY_API_KEY} characters, not shown)"

# List your roles on the MCP server: expect AI Gateway Tools User
echo "🔐 Your roles on the $MCP_SERVER MCP server:"
az role assignment list --assignee "$(az ad signed-in-user show --query id -o tsv)" \
  --scope "$GATEWAY_ID/workspaces/default/toolServers/$MCP_SERVER" --query "[].roleDefinitionName" -o tsv
```

```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 app-first-call key from the gateway, so that it never shows on screen
$env:AI_GATEWAY_API_KEY = az aigateway api-key list-secrets --ids "$GATEWAY_ID/apiKeys/app-first-call" `
  --query primaryKey --output tsv
Write-Host "🔑 Key: in AI_GATEWAY_API_KEY ($($env:AI_GATEWAY_API_KEY.Length) characters, not shown)"

# List your roles on the MCP server: expect AI Gateway Tools User
Write-Host "🔐 Your roles on the $MCP_SERVER MCP server:"
az role assignment list --assignee (az ad signed-in-user show --query id -o tsv) `
  --scope "$GATEWAY_ID/workspaces/default/toolServers/$MCP_SERVER" --query "[].roleDefinitionName" -o tsv
```

> **Checkpoint**
> `azd up` ended with `SUCCESS`, and the role listing under `🔐 Your roles on the learn MCP server:` printed
> `AI Gateway Tools User`. Role assignments can take several minutes to apply.

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

**What you need:** only the one-time setup from **Before you begin**, signed in as a **user**, plus Terraform 1.9 or
later, as in [Deploy a lab with Terraform](../SETUP.md#deploy-a-lab-with-terraform). This track doesn't use your
gateway or `learn` server from lab 04: `terraform apply` creates a new gateway with its own `learn` server, so it works
on its own. You still need the Microsoft Agent 365 license.

### Review the configuration

`terraform/main.tf` creates the resource group `rg-<environment_name>` and calls lab 01's
[gateway module](../01-provision-gateway/terraform/gateway) for a gateway with no model:

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

`terraform/tool-server.tf` declares the `learn` MCP server with the `azapi` provider, which sends the AI Gateway API
version, `2026-11-01`, as is. It also gives the signed-in user **AI Gateway Tools User** on the server, and creates
the `app-first-call` key. Its settings are Terraform variables, with the defaults in `terraform/variables.tf`:

| Variable | What it does | Default |
|---|---|---|
| `pre_invocation` | Evaluates each tool request before the tool runs | `false` |
| `post_invocation` | Evaluates each tool result after the tool returns | `false` |
| `principal_id` | Gets AI Gateway Tools User on the MCP server | Empty, for the signed-in user |

<!-- 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. It
takes about three minutes, most of it while the new gateway activates. Both stages are off at first, so you can test
your token before you add the policy.

```bash title="Bash"
# Move into the lab's Terraform folder
cd ~/aigateway/labs/19-tool-threat-protection/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"

# Download the providers, then plan and apply the gateway, the learn MCP server, your role on it, and the key, with
# both stages off
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/19-tool-threat-protection/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" }

# Download the providers, then plan and apply the gateway, the learn MCP server, your role on it, and the key, with
# both stages off
terraform init
if ($?) { terraform plan -out tfplan }
if ($?) { terraform apply tfplan }
if ($?) { Write-Host "🚀 Gateway deployed: $(terraform output -raw ai_gateway_url)" }
```

The configuration deploys to `eastus2`. For another region, use its name 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 and the key

Set the variables that the next steps, **Verify**, and **Clean up** use from the Terraform outputs, and read the key
from the gateway, so that it never shows on screen or lands in the Terraform state. The last command lists your roles
on the MCP server. Then move back to the lab's folder, where the next steps run their 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 app-first-call key from the gateway, so that it never lands in a file or the Terraform state
export AI_GATEWAY_API_KEY="$(az aigateway api-key list-secrets --ids "$GATEWAY_ID/apiKeys/app-first-call" \
  --query primaryKey --output tsv)"
echo "🔑 Key: in AI_GATEWAY_API_KEY (${#AI_GATEWAY_API_KEY} characters, not shown)"

# List your roles on the MCP server: expect AI Gateway Tools User
echo "🔐 Your roles on the $MCP_SERVER MCP server:"
az role assignment list --assignee "$(az ad signed-in-user show --query id -o tsv)" \
  --scope "$GATEWAY_ID/workspaces/default/toolServers/$MCP_SERVER" --query "[].roleDefinitionName" -o tsv

# 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 app-first-call key from the gateway, so that it never lands in a file or the Terraform state
$env:AI_GATEWAY_API_KEY = az aigateway api-key list-secrets --ids "$GATEWAY_ID/apiKeys/app-first-call" `
  --query primaryKey --output tsv
Write-Host "🔑 Key: in AI_GATEWAY_API_KEY ($($env:AI_GATEWAY_API_KEY.Length) characters, not shown)"

# List your roles on the MCP server: expect AI Gateway Tools User
Write-Host "🔐 Your roles on the $MCP_SERVER MCP server:"
az role assignment list --assignee (az ad signed-in-user show --query id -o tsv) `
  --scope "$GATEWAY_ID/workspaces/default/toolServers/$MCP_SERVER" --query "[].roleDefinitionName" -o tsv

# 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: 5 added, 0 changed, 0 destroyed.`, and the role listing
> under `🔐 Your roles on the learn MCP server:` printed `AI Gateway Tools User`. Role assignments can take several
> minutes to apply.

<!-- /tracks -->

<!-- steps -->

### Call a tool with your user token

The script below gets a token for `https://ai.gateway.azure.com/Data.All` from the Azure CLI, checks that it's a
delegated user token, runs the MCP handshake, and calls the server's search tool with a harmless question.

<!-- include: infra/call-protected-tool.sh -->

On GitHub, open [infra/call-protected-tool.sh](infra/call-protected-tool.sh) or
[infra/call-protected-tool.ps1](infra/call-protected-tool.ps1).

```bash
# Make the test script executable, once
chmod +x infra/call-protected-tool.sh

# Call the server's search tool with your delegated user token: the script prints each MCP step and the result
echo "🔧 Tool call on $MCP_SERVER with your user token:"
./infra/call-protected-tool.sh token "$MCP_SERVER"
```

```powershell
# Call the server's search tool with your delegated user token: the script prints each MCP step and the result
Write-Host "🔧 Tool call on $MCP_SERVER with your user token:"
./infra/call-protected-tool.ps1 -Auth token -Server $MCP_SERVER
```

```text title="Expected output"
🔧 Tool call on learn with your user token:
Delegated token for the signed-in user (scp: ...)
MCP endpoint: <gateway-url>/default/toolservers/learn/mcp
tools/list: HTTP 200, <n> tools (discovery isn't evaluated)
tools/call: learn_microsoft_docs_search with query: What is Azure API Management?
HTTP status: 200
isError: false (the result was returned)
...
```

The tool names and count depend on your server and can change as the Learn server evolves. If `tools/call` fails with HTTP `401` or `403`, fix the token or
the role before you continue.

<!-- /steps -->

> **Checkpoint**
> A tool call with your delegated token returns a result with `isError: false`.

## Add tool threat protection

Pick one track. Both add the same policy to the `learn` server, with both stages turned on. Each MCP server can
have only one tool threat protection policy, and you can't set it at gateway scope or on a single tool.

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

### Start a new policy

Open the [AI Gateway portal](https://ai.gateway.azure.com) and select your gateway from the gateway switcher.
Select **Policies**, then **Add policy**.

### Choose the policy type

On the **Type** step, under **Security**, select **Agent 365 tool threat protection**. Its card carries the
**MCP server** badge and reads "Evaluate tool calls and results with Microsoft Defender and Microsoft Purview
for threats, prompt injection, and sensitive-data risks." Select **Next**.

![The Add policy wizard on the Type step, with Agent 365 tool threat protection selected under Security](../assets/screens/tool-threat-protection-01-policy-type.webp "Agent 365 tool threat protection sits in the Security group, between IP filter and Agent hooks. Its MCP server badge means it applies to MCP servers only.")

### Select the MCP server

On the **Scope** step, the wizard notes that this policy applies to individual MCP servers. Check
**Microsoft Learn**, the `learn` MCP server, which the list shows with the type **Tool**. **Next** stays unavailable
until you check a server. Then select **Next**.

![The Scope step of the Add policy wizard, with the Microsoft Learn MCP server checked and the Next button](../assets/screens/tool-threat-protection-02-scope.webp "The policy applies to individual MCP servers. Check the learn server, then select Next.")

### Choose the evaluation stages

On the **Details** step, the wizard reminds you that Microsoft Entra ID is required for this policy, because the
evaluation runs on behalf of the caller. Both stages are selected by default:

- **Before tool invocation: Evaluate the request payload**
- **After tool invocation: Evaluate the tool output**

Keep both. To evaluate a single stage, clear the other one; at least one stage must stay selected. Then select
**Create**.

![The Details step of the Add policy wizard, with both evaluation stages selected and the Create button](../assets/screens/tool-threat-protection-03-stages.webp "Both stages are selected by default. Clear one to evaluate only the requests or only the results.")

The **Policies** list shows the new **Agent 365 tool threat protection** policy on **MCP server: Microsoft Learn**,
running **Before tool execution and Before returning the tool result**.

![The Policies page of the AI Gateway portal, with the Agent 365 tool threat protection policy on the Microsoft Learn MCP server](../assets/screens/tool-threat-protection-04-policy-list.webp "The new policy, its scope, and the two stages it runs in.")

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

### Turn on both stages

Set both stages to `true` and provision again. Only the MCP server changes: the template adds one
`toolThreatProtection` entry to its `policies` array. To evaluate only the requests, leave
`TOOL_THREAT_POST_INVOCATION` at `false`.

```bash title="Bash"
# Turn on both evaluation stages in the azd environment
azd env set TOOL_THREAT_PRE_INVOCATION true &&
  echo "📝 TOOL_THREAT_PRE_INVOCATION: true"
azd env set TOOL_THREAT_POST_INVOCATION true &&
  echo "📝 TOOL_THREAT_POST_INVOCATION: true"

# Deploy again: the template adds a toolThreatProtection policy to the learn MCP server
azd provision &&
  echo "🔐 Tool threat protection is on for the learn MCP server, before and after each tool call"
```

```powershell title="PowerShell"
# Turn on both evaluation stages in the azd environment
azd env set TOOL_THREAT_PRE_INVOCATION true
if ($?) { Write-Host "📝 TOOL_THREAT_PRE_INVOCATION: true" }
azd env set TOOL_THREAT_POST_INVOCATION true
if ($?) { Write-Host "📝 TOOL_THREAT_POST_INVOCATION: true" }

# Deploy again: the template adds a toolThreatProtection policy to the learn MCP server
azd provision
if ($?) { Write-Host "🔐 Tool threat protection is on for the learn MCP server, before and after each tool call" }
```

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

### Turn on both stages

Pass both stages as `true` to `terraform plan` and apply the plan. Only the MCP server changes: the configuration adds
one `toolThreatProtection` entry to its `policies` array. To evaluate only the requests, leave out
`-var post_invocation=true`. Run it from the lab's folder: `-chdir` points Terraform at the `terraform` folder.

```bash title="Bash"
# Plan the change: turn on both evaluation stages
terraform -chdir=terraform plan -var pre_invocation=true -var post_invocation=true -out tfplan &&
  echo "📝 The plan updates only the learn MCP server"

# Apply the plan: the configuration adds a toolThreatProtection policy to the learn MCP server
terraform -chdir=terraform apply tfplan &&
  echo "🔐 Tool threat protection is on for the learn MCP server, before and after each tool call"
```

```powershell title="PowerShell"
# Plan the change: turn on both evaluation stages
terraform -chdir=terraform plan -var pre_invocation=true -var post_invocation=true -out tfplan
if ($?) { Write-Host "📝 The plan updates only the learn MCP server" }

# Apply the plan: the configuration adds a toolThreatProtection policy to the learn MCP server
terraform -chdir=terraform apply tfplan
if ($?) { Write-Host "🔐 Tool threat protection is on for the learn MCP server, before and after each tool call" }
```

> **Checkpoint**
> The plan ended with `Plan: 0 to add, 1 to change, 0 to destroy.`, for `azapi_resource.tool_server`, and the apply
> with `Apply complete! Resources: 0 added, 1 changed, 0 destroyed.`

Keep passing both `-var` options to every later `terraform plan` or `terraform destroy` on this configuration:
without them, Terraform goes back to the defaults and removes the policy.

<!-- /tracks -->

<!-- steps -->

### Confirm the policy

The new policy appears in the portal's **Policies** list. The policy is stored on the MCP server, so you can also
read it with `az aigateway mcp show`:

```bash
# Read the MCP server's policies: expect one toolThreatProtection entry with both stages on
echo "🔐 Policies on the $MCP_SERVER MCP server:"
az aigateway mcp show -g "$RG" --gateway-name "$GATEWAY" -n "$MCP_SERVER" --query properties.policies
```

```powershell
# Read the MCP server's policies: expect one toolThreatProtection entry with both stages on
Write-Host "🔐 Policies on the $MCP_SERVER MCP server:"
az aigateway mcp show -g $RG --gateway-name $GATEWAY -n $MCP_SERVER --query properties.policies
```

The list includes an entry with `"type": "toolThreatProtection"`, `"preInvocation": true`, and
`"postInvocation": true`. The service adds `"scope": "resource"` when it returns a policy set on the server.

<!-- /steps -->

> **Checkpoint**
> The `learn` MCP server has one `toolThreatProtection` policy with both stages turned on.

> [!CAUTION]
> A post-invocation denial withholds the result, but it can't undo what the tool already did. The gateway doesn't
> retry or reverse the call. Build agents so they **don't automatically retry** a tool call whose result was
> withheld, especially for tools that write, send, or delete. For those tools, keep **Before tool invocation**
> turned on so a risky request never runs.

## Understand verdicts and failures

The gateway doesn't decide what's risky. Agent 365 decides which Microsoft Defender and Microsoft Purview checks run,
and Defender's runtime protection runs in the policy mode that your security team sets in Microsoft Defender. You
can't change that mode at the gateway.

| Defender policy mode | Behavior |
|---|---|
| **Disabled** | Defender skips its inspection. The gateway's policy stays on. |
| **Audit** | Defender records findings without blocking threats. Token-exchange, transport, and verdict failures still fail closed at the gateway. |
| **Block** | Defender enforces its checks and can return a block verdict, which the gateway returns as `ToolEvaluationDenied`. |

Whatever the mode, the gateway continues only on a completed Defender evaluation with an **allow** verdict. If the
response reports a skipped or failed-open Defender evaluation, the gateway returns `ToolEvaluationUnavailable`
instead of allowing the call.

When a call fails closed, the caller sees one of these codes in the result's
`_meta["com.microsoft.azure.ai.gateway/denial"].code`:

| Code | Meaning |
|---|---|
| `ToolEvaluationIdentityRequired` | The request has no usable bearer token, or the gateway can't read the token tenant it needs for the OBO exchange |
| `ToolEvaluationDenied` | The evaluation service denied the request or the result |
| `ToolEvaluationInvalidRequest` | The evaluation input isn't valid |
| `ToolEvaluationRequestTooLarge` | The evaluation input exceeds the supported size |
| `ToolEvaluationUnavailable` | Token exchange or evaluation failed, timed out, returned an invalid verdict, or was unavailable |

A denied call looks like this. The HTTP status is still `200`, so clients must check `result.isError`:

```json
{
  "jsonrpc": "2.0",
  "id": 42,
  "result": {
    "isError": true,
    "content": [
      { "type": "text", "text": "Tool 'mcp_tail_logs' requires a validated delegated caller token." }
    ],
    "_meta": {
      "com.microsoft.azure.ai.gateway/denial": {
        "code": "ToolEvaluationIdentityRequired",
        "correlationId": "9f2c1b6e-..."
      }
    }
  }
}
```

> [!TIP]
> Log the `correlationId` with every denial in your agent. It's the value to share when you investigate a
> denial with your security team.

## Verify

<!-- steps -->

### Call the protected tool with your user token

Run the same benign call as before. Allow a few seconds per call, because each enabled stage adds an evaluation
round trip.

```bash
# Call the protected tool again with your delegated user token: both stages evaluate the call
echo "🔧 Tool call on $MCP_SERVER with your user token:"
./infra/call-protected-tool.sh token "$MCP_SERVER"
```

```powershell
# Call the protected tool again with your delegated user token: both stages evaluate the call
Write-Host "🔧 Tool call on $MCP_SERVER with your user token:"
./infra/call-protected-tool.ps1 -Auth token -Server $MCP_SERVER
```

```text title="Expected output"
🔧 Tool call on learn with your user token:
...
tools/list: HTTP 200, <n> tools (discovery isn't evaluated)
tools/call: learn_microsoft_docs_search with query: What is Azure API Management?
HTTP status: 200
isError: false (the result was returned)
...
```

A harmless question about Azure is allowed at both stages, so the result comes back as before. The first call
right after you add the policy can return `ToolEvaluationUnavailable` with "could not be evaluated by the security
service". Wait a minute and call again. If you still see `ToolEvaluationUnavailable` or `ToolEvaluationDenied`, see
[Troubleshooting](../TROUBLESHOOTING.md#lab-19-tool-threat-protection).

### Call it with a runtime key only

Now call the same tool with the API key and no bearer token. The key still authenticates you to the gateway, so
`initialize` and `tools/list` succeed. The `tools/call` needs an evaluation, and without a delegated token the
gateway can't run one, so it fails closed.

```bash
# Call the same tool with the runtime key and no bearer token: the gateway can't evaluate it, so it fails closed
echo "🚦 Key-only tool call on $MCP_SERVER, expect a ToolEvaluationIdentityRequired denial:"
./infra/call-protected-tool.sh key "$MCP_SERVER"
```

```powershell
# Call the same tool with the runtime key and no bearer token: the gateway can't evaluate it, so it fails closed
Write-Host "🚦 Key-only tool call on $MCP_SERVER, expect a ToolEvaluationIdentityRequired denial:"
./infra/call-protected-tool.ps1 -Auth key -Server $MCP_SERVER
```

```text title="Expected output"
🚦 Key-only tool call on learn, expect a ToolEvaluationIdentityRequired denial:
...
tools/list: HTTP 200, <n> tools (discovery isn't evaluated)
tools/call: learn_microsoft_docs_search with query: What is Azure API Management?
HTTP status: 200
isError: true
Denial code: ToolEvaluationIdentityRequired
Correlation ID: <guid>
Tool 'learn_microsoft_docs_search' requires a validated delegated caller token. Do not retry this tool.
```

The denial text can differ. The code is what matters.

### Look for the call in Monitoring

If you set up Application Insights in [Monitor usage, cost, and traces](../13-monitoring/README.md), open
**Monitoring**. The **Tools** tab shows MCP tool executions, and **Traces** shows each request with its policy
steps. Find your calls by time and compare the allowed call with the key-only call.

<!-- /steps -->

> **Checkpoint**
> A delegated call returns its result. A key-only call to the same tool returns `isError: true` with
> `ToolEvaluationIdentityRequired`, while `tools/list` still works.

## Go further

- **Choose stages per server.** Keep **Before tool invocation** on for tools with side effects, such as sending
  mail or changing records. Add **After tool invocation** for tools that return untrusted content, such as web
  pages, tickets, or documents. For read-only tools that only return trusted content, weigh the extra round trip.
- **Move your agents to delegated tokens.** Agents that call tools with runtime keys or app-only tokens, such as a
  managed identity, can't use protected servers. Plan an on-behalf-of flow with the scope
  `https://ai.gateway.azure.com/Data.All` before you protect a server they depend on.
- **Roll out in Audit mode first.** Ask your security team to start Defender in **Audit**, review what it flags,
  and then switch to **Block**. Defender's
  [runtime protection guidance](https://learn.microsoft.com/defender-endpoint/configure-ai-agent-runtime-protection#enable-runtime-protection)
  recommends the same phased rollout, with alerts reviewed in the Microsoft Defender portal.
- **Automate the policy.** The policy is the `toolThreatProtection` entry in the MCP server's
  `properties.policies`, as described in
  [Agent 365 tool threat protection](https://ai.gateway.azure.com/docs/policies/tool-threat-protection).
  The Bicep + azd track declares it in `infra/protected-tool-server.bicep`, and the Terraform track in
  `terraform/tool-server.tf`. With the Azure CLI,
  `az aigateway mcp update --policies` replaces the whole `policies` array, so read the current array first and
  keep any other policies, such as the request rate limits from
  [Control which tools agents can call](../05-mcp-tool-controls/README.md):

  ```bash title="Bash"
  # Write the server's other policies, plus a toolThreatProtection policy with both stages on, to a file
  az aigateway mcp show -g "$RG" --gateway-name "$GATEWAY" -n "$MCP_SERVER" --query properties -o json \
    | jq -c '[(.policies // [])[] | select(.type != "toolThreatProtection") | del(.scope)]
        + [{type:"toolThreatProtection",preInvocation:true,postInvocation:true}]' > policies.json

  # Replace the server's whole policy array with the file's, print the new array, then delete the file
  az aigateway mcp update -g "$RG" --gateway-name "$GATEWAY" -n "$MCP_SERVER" --policies @policies.json \
    --query properties.policies &&
    echo "🔐 Tool threat protection is on for the $MCP_SERVER MCP server, before and after each tool call"
  rm policies.json
  ```

  ```powershell title="PowerShell"
  # Write the server's other policies, plus a toolThreatProtection policy with both stages on, to a file
  $p = az aigateway mcp show -g $RG --gateway-name $GATEWAY -n $MCP_SERVER --query properties.policies -o json |
       ConvertFrom-Json
  $p = @($p | Where-Object { $_ -and $_.type -ne 'toolThreatProtection' } | Select-Object * -ExcludeProperty scope) +
       @(@{ type = 'toolThreatProtection'; preInvocation = $true; postInvocation = $true })
  ConvertTo-Json -Depth 10 -Compress -InputObject $p | Set-Content policies.json

  # Replace the server's whole policy array with the file's, print the new array, then delete the file
  az aigateway mcp update -g $RG --gateway-name $GATEWAY -n $MCP_SERVER --policies "@policies.json" `
    --query properties.policies
  if ($?) { Write-Host "🔐 Tool threat protection is on for the $MCP_SERVER MCP server, before and after each tool call" }
  Remove-Item policies.json
  ```

- **Govern servers centrally.** [Govern MCP servers with Agent 365](../20-agent-365-governance/README.md) adds
  inventory and blocking from the Microsoft 365 admin center on top of this policy.

## Clean up

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

### Delete the policy

In the AI Gateway portal, select **Policies**. On the row of the **Agent 365 tool threat protection** policy,
select **More actions** (**…**), then **Delete**. **Delete this policy?** warns that the policy's behavior is no
longer applied to its assets, and that the MCP server stays in the gateway. Select **Delete**. The list shows
**No policies configured**, and tool calls with a runtime key work again.

### Remove the role assignment

If you added **AI Gateway Tools User** only for this lab, remove it in **Access**, or run the commands below. Like
assigning a role, removing one needs **Owner**, **User Access Administrator**, or **Role Based Access Control
Administrator**. If you can't remove it, it goes away when you delete the gateway.

```bash
# Remove your AI Gateway Tools User role 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 on the $MCP_SERVER MCP server is removed"
```

```powershell
# Remove your AI Gateway Tools User role 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 on the $MCP_SERVER MCP server is removed" }
```

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

### Delete everything azd created

In the `aigateway/labs/19-tool-threat-protection` folder, delete the resource group with the gateway, the `learn` MCP
server, its role assignment, and the key. [`--purge`](../SETUP.md#delete-what-azd-created) also purges soft-deleted
resources. It takes about two 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"
```

To keep this gateway for other labs instead, skip `azd down` and remove the policy:

```bash
# Turn off both evaluation stages in the azd environment
azd env set TOOL_THREAT_PRE_INVOCATION false
azd env set TOOL_THREAT_POST_INVOCATION false &&
  echo "📝 Both evaluation stages are off in the azd environment"

# Deploy again, which removes the toolThreatProtection policy from the learn MCP server
azd provision &&
  echo "🚮 The tool threat protection policy is removed from the learn MCP server"
```

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

### Delete everything Terraform created

In the `aigateway/labs/19-tool-threat-protection/terraform` folder, delete the resource group with the gateway, the
`learn` MCP server, its role assignment, and the key. It takes about a minute.

```bash
# Move into the lab's Terraform folder
cd ~/aigateway/labs/19-tool-threat-protection/terraform &&
  echo "📂 Terraform folder: $(pwd)"

# Delete everything that terraform apply created
terraform destroy -auto-approve &&
  echo "🚮 Everything that terraform apply created is deleted"
```

To keep this gateway for other labs instead, skip `terraform destroy` and remove the policy: plan and apply again
without `-var`, which goes back to both stages off.

<!-- /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

- [Govern MCP servers with Agent 365](../20-agent-365-governance/README.md)
- [Control which tools agents can call](../05-mcp-tool-controls/README.md)
- [Lock down backend traffic with private networking](../18-private-networking/README.md)
- [Agent 365 tool threat protection](https://ai.gateway.azure.com/docs/policies/tool-threat-protection) in the AI Gateway docs
