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.
Before you begin
One-time setupThe Setup guide tasks that this lab uses. Mark each one done once, and the labs stop listing it.
- Choose where to run commandsEvery track except the portal
- Sign in to AzureOn your own machine. Cloud Shell is already signed in.
- Install the
aigatewayextensionThe Azure CLI tracks and the Verify steps - Clone the labs repoThe Bicep + azd and Terraform tracks, the notebooks, and the code samples
You've done the one-time setup that this lab uses.
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. This lab protects the
learnMCP server from that lab. Any MCP server in your gateway works. - Complete Go keyless with Microsoft Entra ID and RBAC. 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.
Agent 365 tool threat protection is in preview, so its labels and behavior can change. See the October 8, 2026 release and Agent 365 tool threat protection.
Set these variables once. The steps and the Verify section reuse them.
# 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)"# 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.
Grant yourself the AI Gateway Tools User role
In the AI Gateway portal, select AccessEntra IDAdd 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 walks through this wizard.
The same assignment with the Azure CLI:
# 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"# 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.
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 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 |
// Lab 19 with azd: "azd up" creates the resource group rg-<environment name>, a gateway with lab 01's template, then
// the learn MCP server, the AI Gateway Tools User role on it for the signed-in user, and the runtime API key
// app-first-call. The tool threat protection stages are off until you turn them on and run "azd provision".
// The runtime API key is never an output.
targetScope = 'subscription'
@description('azd environment name. The resource group is rg-<environmentName>.')
@minLength(1)
@maxLength(60)
param environmentName string
@description('Region for every resource. Pick one where AI Gateway is available. List them with az provider show --namespace Microsoft.ApiManagement (Setup guide, Find the available regions).')
@metadata({ azd: { type: 'location' } })
param location string
@description('Evaluate each tool request before the tool runs. azd reads it from TOOL_THREAT_PRE_INVOCATION.')
param preInvocation bool = false
@description('Evaluate each tool result after the tool returns. azd reads it from TOOL_THREAT_POST_INVOCATION.')
param postInvocation bool = false
@description('Object ID of the user who calls the tools. azd sets AZURE_PRINCIPAL_ID to the signed-in user.')
param principalId string = ''
var suffix = take(uniqueString(subscription().id, environmentName, location), 6)
var tags = { 'azd-env-name': environmentName }
resource rg 'Microsoft.Resources/resourceGroups@2024-03-01' = {
name: 'rg-${environmentName}'
location: location
tags: tags
}
// Lab 01's template: the gateway, with no model.
module gateway '../../01-provision-gateway/infra/gateway.bicep' = {
name: 'aigw-gateway'
scope: rg
params: {
gatewayName: 'aigw-${suffix}'
location: location
tags: tags
}
}
module toolServer 'protected-tool-server.bicep' = {
name: 'aigw-protected-tool-server'
scope: rg
params: {
gatewayName: gateway.outputs.gatewayName
serverName: 'learn'
preInvocation: preInvocation
postInvocation: postInvocation
principalId: principalId
apiKeyName: 'app-first-call'
}
}
output AZURE_RESOURCE_GROUP string = rg.name
output AI_GATEWAY_NAME string = gateway.outputs.gatewayName
output AI_GATEWAY_ID string = gateway.outputs.gatewayId
output AI_GATEWAY_URL string = gateway.outputs.gatewayUrl
output MCP_SERVER string = 'learn'
output MCP_ENDPOINT string = toolServer.outputs.mcpEndpointinfra/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.
// Declares the learn MCP server of lab 04 with an optional Agent 365 tool threat protection policy, which has Microsoft
// Defender and Microsoft Purview evaluate each tool request (preInvocation), each tool result (postInvocation), or
// both. It assigns AI Gateway Tools User on the server to a user, so that user can call tools with a delegated token,
// and creates a runtime API key. The key is never an output.
// A deployment sends a PUT, which replaces the whole MCP server, so keep this template as its only source of truth.
@description('Name of the existing AI Gateway (Microsoft.ApiManagement/aigateways).')
param gatewayName string
@description('MCP server name. It becomes part of the endpoint URL and cannot be changed after creation.')
param serverName string = 'learn'
@description('Evaluate the tool name and arguments before the tool runs.')
param preInvocation bool = true
@description('Evaluate the tool result after the tool returns. The tool has already run.')
param postInvocation bool = true
@description('Object ID of the user who gets AI Gateway Tools User on the MCP server. Empty skips the role assignment.')
param principalId string = ''
@description('Runtime API key to create for the key-only test call.')
param apiKeyName string = 'app-first-call'
// AI Gateway Tools User: call the tools of an MCP server with a Microsoft Entra ID token.
var toolsUserRoleId = 'dce03f8d-857f-4e40-a90d-67770fa6ecd2'
#disable-next-line BCP081
resource gateway 'Microsoft.ApiManagement/aigateways@2026-11-01' existing = {
name: gatewayName
}
#disable-next-line BCP081
resource workspace 'Microsoft.ApiManagement/aigateways/workspaces@2026-11-01' existing = {
parent: gateway
name: 'default'
}
#disable-next-line BCP081
resource toolServer 'Microsoft.ApiManagement/aigateways/workspaces/toolServers@2026-11-01' = {
parent: workspace
name: serverName
properties: {
displayName: 'Microsoft Learn'
description: 'Search and fetch official Microsoft documentation and code samples.'
toolServerType: 'mcp'
endpoints: [
{
namespace: 'learn'
kind: 'mcp'
mode: 'failClosed'
mcp: {
endpoint: { url: 'https://learn.microsoft.com/api/mcp' }
transport: 'streamableHttp'
}
}
]
// A tool threat protection policy needs at least one stage.
policies: preInvocation || postInvocation
? [
{
type: 'toolThreatProtection'
preInvocation: preInvocation
postInvocation: postInvocation
}
]
: []
}
}
resource toolsUser 'Microsoft.Authorization/roleAssignments@2022-04-01' = if (!empty(principalId)) {
name: guid(toolServer.id, principalId, toolsUserRoleId)
scope: toolServer
properties: {
principalId: principalId
principalType: 'User'
roleDefinitionId: subscriptionResourceId('Microsoft.Authorization/roleDefinitions', toolsUserRoleId)
}
}
#disable-next-line BCP081
resource apiKey 'Microsoft.ApiManagement/aigateways/apiKeys@2026-11-01' = {
parent: gateway
name: apiKeyName
properties: {
displayName: apiKeyName
}
}
output toolServerId string = toolServer.id
output mcpEndpoint string = 'https://${gateway.properties.frontend.defaultHostname}/default/toolservers/${serverName}/mcp'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.
# 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)"# 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.
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.
# 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# 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 tsvazd 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.
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. 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 for a gateway with no model:
# Lab 19 with Terraform: creates the resource group rg-<environment_name>, a gateway with lab 01's module, then the
# learn MCP server, the AI Gateway Tools User role on it for the signed-in user, and the runtime API key
# app-first-call (tool-server.tf). The tool threat protection stages are off until you turn them on with -var.
# The runtime API key is never an output.
data "azapi_client_config" "current" {}
locals {
suffix = substr(sha1("${data.azapi_client_config.current.subscription_id}/${var.environment_name}/${var.location}"), 0, 6)
tags = { "environment-name" = var.environment_name }
}
resource "azurerm_resource_group" "rg" {
name = "rg-${var.environment_name}"
location = var.location
tags = local.tags
}
# Lab 01's module: the gateway, with no model.
module "gateway" {
source = "../../01-provision-gateway/terraform/gateway"
gateway_name = "aigw-${local.suffix}"
resource_group_id = azurerm_resource_group.rg.id
location = var.location
tags = local.tags
}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 |
# The learn MCP server of lab 04 with an optional Agent 365 tool threat protection policy, which has Microsoft
# Defender and Microsoft Purview evaluate each tool request (pre_invocation), each tool result (post_invocation), or
# both. The signed-in user gets AI Gateway Tools User on the server, to call tools with a delegated token.
# Terraform sends a PUT, which replaces the whole MCP server, so keep this file as its only source of truth.
locals {
# AI Gateway Tools User: call the tools of an MCP server with a Microsoft Entra ID token.
tools_user_role_id = "dce03f8d-857f-4e40-a90d-67770fa6ecd2"
principal_id = var.principal_id != "" ? var.principal_id : data.azapi_client_config.current.object_id
}
resource "azapi_resource" "tool_server" {
type = "Microsoft.ApiManagement/aigateways/workspaces/toolServers@2026-11-01"
name = "learn"
parent_id = "${module.gateway.gateway_id}/workspaces/default"
body = {
properties = {
displayName = "Microsoft Learn"
description = "Search and fetch official Microsoft documentation and code samples."
toolServerType = "mcp"
endpoints = [
{
namespace = "learn"
kind = "mcp"
mode = "failClosed"
mcp = {
endpoint = { url = "https://learn.microsoft.com/api/mcp" }
transport = "streamableHttp"
}
}
]
# A tool threat protection policy needs at least one stage.
policies = var.pre_invocation || var.post_invocation ? [
{
type = "toolThreatProtection"
preInvocation = var.pre_invocation
postInvocation = var.post_invocation
}
] : []
}
}
schema_validation_enabled = false
}
resource "azurerm_role_assignment" "tools_user" {
name = uuidv5("url", "${azapi_resource.tool_server.id}/${local.principal_id}/${local.tools_user_role_id}")
scope = azapi_resource.tool_server.id
role_definition_id = "/subscriptions/${data.azapi_client_config.current.subscription_id}/providers/Microsoft.Authorization/roleDefinitions/${local.tools_user_role_id}"
principal_id = local.principal_id
principal_type = "User"
}
# A runtime API key for the key-only test call. Read its value with az aigateway api-key list-secrets; it's never an
# output, so it stays out of the Terraform state.
resource "azapi_resource" "api_key" {
type = "Microsoft.ApiManagement/aigateways/apiKeys@2026-11-01"
name = "app-first-call"
parent_id = module.gateway.gateway_id
body = {
properties = {
displayName = "app-first-call"
}
}
schema_validation_enabled = false
}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.
# 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)"# 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: 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.
# 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)"# 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)" }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.
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.
#!/usr/bin/env bash
# Calls one tool on an AI Gateway MCP server that has Agent 365 tool threat protection, using the MCP
# Streamable HTTP handshake (initialize -> notifications/initialized -> tools/list -> tools/call).
# Prints whether the tool result came back, or the denial code and correlation ID the gateway returned.
#
# Usage:
# export AI_GATEWAY_URL="<gateway-url>"
# ./call-protected-tool.sh token [server-name] [query] # delegated Entra token for the signed-in az user
# ./call-protected-tool.sh key [server-name] [query] # runtime key in AI_GATEWAY_API_KEY (no bearer token)
#
# token mode uses AI_GATEWAY_TOKEN when set, otherwise it runs
# az account get-access-token --scope https://ai.gateway.azure.com/Data.All
# The script calls the Learn docs search tool (or the first tool whose name contains "search") unless you set
# TOOL_NAME, and sends the query as {"query": "..."}. Use a benign query. Requires curl and jq.
set -euo pipefail
AUTH="${1:?Pass token or key as the first argument}"
SERVER="${2:-learn}"
QUERY="${3:-What is Azure API Management?}"
: "${AI_GATEWAY_URL:?Set AI_GATEWAY_URL to the gateway runtime URL, for example https://aigw-labs-k3v7qz2m9xw4p.eastus2-01.ai.gateway.azure.com}"
command -v jq >/dev/null || { echo "This script needs jq." >&2; exit 1; }
ENDPOINT="${AI_GATEWAY_URL%/}/default/toolservers/${SERVER}/mcp"
case "$AUTH" in
token)
TOKEN="${AI_GATEWAY_TOKEN:-$(az account get-access-token --scope https://ai.gateway.azure.com/Data.All --query accessToken -o tsv)}"
# Delegated (user) tokens carry an scp claim. App-only tokens carry roles instead and can't be used for evaluation.
payload="$(printf '%s' "$TOKEN" | cut -d. -f2 | tr '_-' '/+')"
while [ $(( ${#payload} % 4 )) -ne 0 ]; do payload="${payload}="; done
scp="$(printf '%s' "$payload" | jq -Rr '@base64d | fromjson | .scp // empty' 2>/dev/null || true)"
if [ -n "$scp" ]; then
echo "Delegated token for the signed-in user (scp: $scp)"
else
echo "Warning: the token has no scp claim, so it isn't a delegated user token." >&2
fi
HEADERS=(-H "Authorization: Bearer $TOKEN") ;;
key)
: "${AI_GATEWAY_API_KEY:?Set AI_GATEWAY_API_KEY to a runtime key from Access > API keys}"
HEADERS=(-H "Authorization: Bearer $AI_GATEWAY_API_KEY") ;;
*)
echo "The first argument must be token or key." >&2; exit 1 ;;
esac
HEADERS+=(-H "Content-Type: application/json" -H "Accept: application/json, text/event-stream")
STATUS="" BODY="" SESSION_ID=""
# post <json>: sends one JSON-RPC message and sets STATUS and BODY (and SESSION_ID when the server returns one).
post() {
local raw head sid
raw="$(curl -sS --max-time 120 -D - "$ENDPOINT" "${HEADERS[@]}" --data "$1" | tr -d '\r')"
if [[ "$raw" == *$'\n\n'* ]]; then head="${raw%%$'\n\n'*}"; BODY="${raw#*$'\n\n'}"; else head="$raw"; BODY=""; fi
STATUS="$(printf '%s\n' "$head" | awk 'toupper($1) ~ /^HTTP/ {code=$2} END {print code}')"
sid="$(printf '%s\n' "$head" | awk -F': ' 'tolower($1)=="mcp-session-id" {print $2}')"
if [ -n "$sid" ]; then SESSION_ID="$sid"; fi
}
# response <id>: prints the JSON-RPC response with that id. The body can be JSON or server-sent events.
response() {
if printf '%s\n' "$BODY" | grep -q '^data:'; then
printf '%s\n' "$BODY" | sed -n 's/^data:[[:space:]]*//p'
else
printf '%s\n' "$BODY"
fi | jq -c --argjson id "$1" 'select(type == "object" and .id == $id)' 2>/dev/null || true
}
# require_success <step>: stops with the gateway's answer when the HTTP status isn't 2xx.
require_success() {
case "$STATUS" in
2??) ;;
*) echo "$1 failed with HTTP ${STATUS:-no response}:" >&2; printf '%s\n' "$BODY" >&2; exit 1 ;;
esac
}
echo "MCP endpoint: $ENDPOINT"
post '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-03-26","capabilities":{},"clientInfo":{"name":"aigateway-labs","version":"1.0"}}}'
require_success "initialize"
PROTOCOL="$(response 1 | jq -r '.result.protocolVersion // empty')"
if [ -z "$PROTOCOL" ]; then echo "initialize returned no result:" >&2; printf '%s\n' "$BODY" >&2; exit 1; fi
HEADERS+=(-H "MCP-Protocol-Version: $PROTOCOL")
if [ -n "$SESSION_ID" ]; then HEADERS+=(-H "Mcp-Session-Id: $SESSION_ID"); fi
post '{"jsonrpc":"2.0","method":"notifications/initialized"}'
require_success "notifications/initialized"
post '{"jsonrpc":"2.0","id":2,"method":"tools/list","params":{}}'
require_success "tools/list"
LIST="$(response 2)"
if [ -z "$LIST" ] || [ "$(printf '%s' "$LIST" | jq 'has("error")')" = "true" ]; then
echo "tools/list returned an error:" >&2; printf '%s\n' "${LIST:-$BODY}" >&2; exit 1
fi
echo "tools/list: HTTP $STATUS, $(printf '%s' "$LIST" | jq '.result.tools | length') tools (discovery isn't evaluated)"
TOOL="${TOOL_NAME:-$(printf '%s' "$LIST" | jq -r '[.result.tools[].name] |
([.[] | select(test("docs_search"; "i"))] + [.[] | select(test("search"; "i"))])[0] // empty')}"
if [ -z "$TOOL" ]; then echo "No tool name contains 'search'. Set TOOL_NAME to the tool to call." >&2; exit 1; fi
echo "tools/call: $TOOL with query: $QUERY"
post "$(jq -cn --arg name "$TOOL" --arg query "$QUERY" \
'{jsonrpc:"2.0",id:3,method:"tools/call",params:{name:$name,arguments:{query:$query}}}')"
require_success "tools/call"
CALL="$(response 3)"
if [ -z "$CALL" ]; then echo "tools/call returned no JSON-RPC response:" >&2; printf '%s\n' "$BODY" >&2; exit 1; fi
echo "HTTP status: $STATUS"
if [ "$(printf '%s' "$CALL" | jq 'has("error")')" = "true" ]; then
echo "JSON-RPC error:"; printf '%s' "$CALL" | jq '.error'
elif [ "$(printf '%s' "$CALL" | jq '.result.isError == true')" = "true" ]; then
echo "isError: true"
printf '%s' "$CALL" | jq -r '.result._meta["com.microsoft.azure.ai.gateway/denial"] // {} |
"Denial code: \(.code // "none")\nCorrelation ID: \(.correlationId // "none")"'
printf '%s' "$CALL" | jq -r '[.result.content[]? | select(.type == "text") | .text] | join("\n")'
else
echo "isError: false (the result was returned)"
printf '%s' "$CALL" | jq -r '[.result.content[]? | select(.type == "text") | .text] | join("\n") | .[0:400]'
echo "..."
fiOn GitHub, open infra/call-protected-tool.sh or infra/call-protected-tool.ps1.
# 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"# 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🔧 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.
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.
Start a new policy
Open the AI Gateway portal 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.
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.
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 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.
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.
# 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"# 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" }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.
# 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"# 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" }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.
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:
# 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# 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.policiesThe 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.
The learn MCP server has one toolThreatProtection policy with both stages turned on.
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:
{
"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-..."
}
}
}
}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
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.
# 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"# 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🔧 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.
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.
# 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"# 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🚦 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, 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.
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.Allbefore 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 recommends the same phased rollout, with alerts reviewed in the Microsoft Defender portal.
Automate the policy. The policy is the
toolThreatProtectionentry in the MCP server'sproperties.policies, as described in Agent 365 tool threat protection. The Bicep + azd track declares it ininfra/protected-tool-server.bicep, and the Terraform track interraform/tool-server.tf. With the Azure CLI,az aigateway mcp update --policiesreplaces the wholepoliciesarray, so read the current array first and keep any other policies, such as the request rate limits from Control which tools agents can call:# 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# 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.jsonGovern servers centrally. Govern MCP servers with Agent 365 adds inventory and blocking from the Microsoft 365 admin center on top of this policy.
Clean up
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.
# 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"# 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" }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 also purges soft-deleted
resources. It takes about two minutes.
# 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:
# 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"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.
# 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.
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.