Azure AI Gateway Labs
Documentation Open portal
Enterprise readiness · Lab 19Emerging

Protect tool calls with Agent 365 threat protection

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.

Advanced 30 min PortalBicepTerraform Updated
Source Edit

What you'll do

  • 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

Before you start

Tracks: Portal, Bicep + azd, Terraform

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.

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. 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. 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 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)"

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.

StageWhat's evaluatedWhat it preventsCost
Before tool invocationThe tool name and argumentsThe tool never runs, so there are no side effectsOne evaluation round trip
After tool invocationThe tool result, including error resultsThe result never reaches the agent. The tool already ran.One evaluation round trip
BothBoth of the aboveRequires two allow decisionsUp 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.

Choose your track
1

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:

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.

1

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.

infra/call-protected-tool.shGitHub
#!/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 "..."
fi

On GitHub, open infra/call-protected-tool.sh or 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
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.

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.

Choose your track
1

Start a new policy

Open the AI Gateway portal and select your gateway from the gateway switcher. Select Policies, then Add policy.

2

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.

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

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 policy applies to individual MCP servers. Check the learn server, then select Next.
4

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.

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 new policy, its scope, and the two stages it runs in.
1

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.

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 modeBehavior
DisabledDefender skips its inspection. The gateway's policy stays on.
AuditDefender records findings without blocking threats. Token-exchange, transport, and verdict failures still fail closed at the gateway.
BlockDefender 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:

CodeMeaning
ToolEvaluationIdentityRequiredThe request has no usable bearer token, or the gateway can't read the token tenant it needs for the OBO exchange
ToolEvaluationDeniedThe evaluation service denied the request or the result
ToolEvaluationInvalidRequestThe evaluation input isn't valid
ToolEvaluationRequestTooLargeThe evaluation input exceeds the supported size
ToolEvaluationUnavailableToken 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

1

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

2

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

3

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.

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

    # 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
  • Govern 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

Choose your track
1

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.

2

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" }

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

Finished the lab?

Mark it complete to track your progress across paths. It's saved only in this browser.