---
title: Govern MCP tool calls with agent hooks
summary: Run your own allow-or-deny rules on every MCP tool call. An agent hooks policy asks an Azure function before the tool runs and again before the result reaches the agent, authenticated with the gateway's managed identity.
category: tools
level: Advanced
duration: 40
tracks: [portal, cli, iac, terraform]
order: 30
status: emerging
illustration: diagrams/agent-hooks.svg
tags: [agent hooks, MCP, tools, Azure Functions, Flex Consumption, managed identity, App Service Authentication, Entra ID, failClosed, preToolCall, postToolCall]
objectives:
  - Explain when the gateway calls an agent hook, what it sends, and how an allow or deny verdict changes a tool call
  - Deploy a Python decision service on Azure Functions that only the gateway's managed identity can call
  - Attach an agent hooks policy to an MCP server in the AI Gateway portal, with the Azure CLI, with Bicep and azd, or with Terraform
  - Prove allowed, blocked, and withheld tool calls over MCP, and read the decision log
  - Choose between agent hooks, tool allow and block lists, and tool threat protection, and between fail closed and fail open
prereqs:
  - 04-federate-mcp-tools
---

# Govern MCP tool calls with agent hooks

Allow and block lists decide which tools an agent can call, but not what it can do with them. Your rules are often
about the call itself: no customer email addresses in a search, no refund above a limit, no secret in a result that
goes back to the model. In this lab you write those rules in a small Azure function, and an **agent hooks** policy
on your MCP server asks it for a verdict before each tool runs and again before each result reaches the agent.

## 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, the decision service, the agent hooks policy, and a key, so you can skip this section. You need only
> the one-time setup above and permission to register applications in Microsoft Entra ID.

- Complete [Federate MCP tools behind one endpoint](../04-federate-mcp-tools/README.md). This lab governs the
  `learn` MCP server from that lab. Any MCP server in your gateway works.
- Permission to manage policies on the gateway and to create resources, for example **Contributor** on a
  subscription or resource group.
- Permission to register applications in Microsoft Entra ID. The decision service trusts only tokens issued for
  its own app registration.
- A region with the Azure Functions Flex Consumption plan. The lab deploys the function app in the gateway's region;
  `az functionapp list-flexconsumption-locations --query "[].name" -o tsv` lists the regions that have it.
- Your gateway's system-assigned managed identity, which every gateway has. The hook uses it to authenticate.
- Run the scripts from the lab's folder, `~/aigateway/labs/30-agent-hooks`.

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

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

```bash title="Bash"
# Set your resource group and gateway, and the MCP server that you govern
export RG="<resource-group>"
export GATEWAY="<gateway>"
export MCP_SERVER="learn"                    # the MCP server you govern 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 a runtime key from Access › API keys without showing it: the test script calls tools with it
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 govern
$RG         = "<resource-group>"
$GATEWAY    = "<gateway>"
$MCP_SERVER = "learn"                        # the MCP server you govern 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 a runtime key from Access › API keys without showing it: the test script calls tools with it
$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

An **agent hooks** policy on an MCP server sends each `tools/call` to a decision service that you run, and enforces
its verdict. The gateway is the host of the [Agent Hooks control contract](https://responsibleai.github.io/agent-hooks/):
it posts an `AgentContext` JSON document to your HTTPS endpoint, and the service answers HTTP `200` with
`{"decision": "allow"}` or `{"decision": "deny", "reason": "…"}`. Discovery and session traffic, such as
`initialize` and `tools/list`, isn't sent.

The gateway authenticates to the service with its managed identity (a Microsoft Entra token for the audience that
you set), with an API key header, or anonymously, and adds the literal headers that you configure. The `mode`
decides what happens when the service fails or doesn't answer in time: `failClosed`, the default, blocks the call;
`failOpen` lets it through. Settings at the policy level apply to both hooks, and each hook can override them.

| Intervention point | Policy key | `interception_point` | The service gets | Effect of a deny |
|---|---|---|---|---|
| **Before tool call** | `preToolCall` | `pre_tool_call` | The tool name and arguments | The tool never runs |
| **After tool call** | `postToolCall` | `post_tool_call` | The tool name, arguments, and result | The result is withheld, but the tool already ran |

![An agent sends tools/call to the MCP server on AI Gateway; the agent hooks policy asks an Azure function before the call and after it, and enforces its allow or deny](../assets/diagrams/agent-hooks.svg "A deny before the call means the tool never runs. A deny after the call withholds the result. With failClosed, a hook that fails also blocks the call.")

Verdicts can only allow or deny: transforms, warnings, and approvals aren't supported.

## Review the decision service

The decision service is one Python function, `tool-hook`, in [`infra/hook/function_app.py`](infra/hook/function_app.py).
It answers both intervention points:

| Point | Rule | Reason in the verdict |
|---|---|---|
| Before tool call | The tool name matches a pattern in the `BLOCKED_TOOLS` app setting, `*code_sample*` by default | `blocked_tool:<pattern>` |
| Before tool call | The arguments contain an email address | `personal_data:email_address` |
| Before tool call | The arguments contain a secret, such as a storage account key, a SAS signature, a private key, or a JWT | `secret_in_arguments:<kind>` |
| After tool call | The result contains a secret | `secret_in_result:<kind>` |
| Either | Nothing matches | `policy_satisfied`, with `allow` |

<!-- include: infra/hook/function_app.py -->

On GitHub, open [infra/hook/function_app.py](infra/hook/function_app.py).

Before a call, the gateway posts the tool call. This is a real request for the docs search tool, with the IDs
shortened:

```json
{
  "spec": "agent-hooks/0.1",
  "interception_point": "pre_tool_call",
  "timestamp": "2026-11-16T02:47:51.711Z",
  "sequence": 0,
  "agent": { "framework": "microsoft.azure.aigateway" },
  "tool_call": {
    "id": "2",
    "name": "learn_microsoft_docs_search",
    "args": { "query": "What is Azure Functions?" }
  },
  "target": { "query": "What is Azure Functions?" },
  "request_id": "7c73b7ce-…",
  "trace": { "trace_id": "524b7585…", "span_id": "ea417be7…" }
}
```

After the call, the request has `"interception_point": "post_tool_call"`, the same `tool_call` and `request_id`,
and the MCP tool result in `target`:

```json
"target": {
  "isError": false,
  "content": [ { "type": "text", "text": "{\"results\":[{\"title\":\"Azure Functions overview\", …}]}" } ]
}
```

The [policy reference](https://ai.gateway.azure.com/docs/policies/agent-hooks) also shows a `tool_result` object,
which the gateway doesn't send yet, so the function reads both. It treats any request it can't parse as a deny.

The function allows anonymous calls because **App Service Authentication** stands in front of it: the platform
rejects every request with HTTP `401` unless it carries a Microsoft Entra token issued for the hook's app
registration to the gateway's managed identity. Each request also carries the policy's custom headers, here
`x-hook-policy: lab30`, which the decision log records with the caller's object ID.

> [!IMPORTANT]
> Keep the decision service fast and available. The gateway waits about 30 seconds for a verdict, and every tool
> call waits for it. Don't log tool arguments, results, or tokens: this function logs only the tool name, the
> decision, the reason, and the request ID.

## Deploy the decision service

The AI Gateway portal doesn't create function apps or app registrations, so on the **Portal** track, follow the
**Azure CLI** steps here, then attach the hook in the portal.

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

### Register an app for the hook

The gateway asks Microsoft Entra ID for a token whose audience is the hook's **application ID URI**. Register an app
with that URI and create its service principal, so that the gateway's managed identity can get tokens for it. The
function app name is `func-` plus the first part of your gateway's host name, which is unique.

```bash title="Bash"
# Name the decision service's resource group and function app, in the gateway's region
export HOOK_RG="rg-aigw-lab30-hook"
export HOOK_APP="func-$(echo "$AI_GATEWAY_URL" | cut -d/ -f3 | cut -d. -f1)"
export LOCATION="$(az aigateway show -g "$RG" -n "$GATEWAY" --query location -o tsv)"
echo "📝 Function app $HOOK_APP in $HOOK_RG, in $LOCATION"

# Register an app for the decision service: the gateway asks Microsoft Entra ID for tokens issued to it
export HOOK_CLIENT_ID="$(az ad app create --display-name "$HOOK_APP" --sign-in-audience AzureADMyOrg --query appId -o tsv)"
echo "🆔 App registration $HOOK_APP: $HOOK_CLIENT_ID"

# Give it an application ID URI: the token audience that the policy asks for
export HOOK_AUDIENCE="api://$HOOK_CLIENT_ID"
az ad app update --id "$HOOK_CLIENT_ID" --identifier-uris "$HOOK_AUDIENCE" &&
  echo "👤 Token audience: $HOOK_AUDIENCE"

# Create its service principal, so that managed identities in your tenant can get tokens for it
az ad sp create --id "$HOOK_CLIENT_ID" -o none &&
  echo "👤 Service principal for $HOOK_APP is ready"
```

```powershell title="PowerShell"
# Name the decision service's resource group and function app, in the gateway's region
$HOOK_RG  = "rg-aigw-lab30-hook"
$HOOK_APP = "func-" + ([uri]$env:AI_GATEWAY_URL).Host.Split('.')[0]
$LOCATION = az aigateway show -g $RG -n $GATEWAY --query location -o tsv
Write-Host "📝 Function app $HOOK_APP in $HOOK_RG, in $LOCATION"

# Register an app for the decision service: the gateway asks Microsoft Entra ID for tokens issued to it
$HOOK_CLIENT_ID = az ad app create --display-name $HOOK_APP --sign-in-audience AzureADMyOrg --query appId -o tsv
Write-Host "🆔 App registration ${HOOK_APP}: $HOOK_CLIENT_ID"

# Give it an application ID URI: the token audience that the policy asks for
$HOOK_AUDIENCE = "api://$HOOK_CLIENT_ID"
az ad app update --id $HOOK_CLIENT_ID --identifier-uris $HOOK_AUDIENCE
if ($?) { Write-Host "👤 Token audience: $HOOK_AUDIENCE" }

# Create its service principal, so that managed identities in your tenant can get tokens for it
az ad sp create --id $HOOK_CLIENT_ID -o none
if ($?) { Write-Host "👤 Service principal for $HOOK_APP is ready" }
```

### Deploy the function app

[`infra/hook.bicep`](infra/hook.bicep) creates a Python function app on the Flex Consumption plan, with App Service
Authentication that lets in only the gateway's identity, a private storage account that the app reaches with its
managed identity, and Application Insights for the decision log. It takes three to five minutes.

```bash title="Bash"
# Read the object ID of the gateway's managed identity: the only caller that the decision service lets in
export GATEWAY_PRINCIPAL_ID="$(az aigateway show -g "$RG" -n "$GATEWAY" --query identity.principalId -o tsv)"
echo "👤 Gateway identity: $GATEWAY_PRINCIPAL_ID"

# Create a resource group for the decision service
az group create -n "$HOOK_RG" -l "$LOCATION" -o none &&
  echo "📦 Resource group $HOOK_RG is ready in $LOCATION"

# Deploy the function app, its network, storage, and logs, without code yet
az deployment group create -g "$HOOK_RG" -n lab30-hook -f infra/hook.bicep -o none \
  -p appName="$HOOK_APP" hookClientId="$HOOK_CLIENT_ID" hookAudience="$HOOK_AUDIENCE" \
  gatewayPrincipalId="$GATEWAY_PRINCIPAL_ID" &&
  echo "🚀 Function app $HOOK_APP is deployed"

# Read the hook's URL and the Log Analytics workspace ID from the deployment's outputs
export HOOK_URL="$(az deployment group show -g "$HOOK_RG" -n lab30-hook --query properties.outputs.hookUrl.value -o tsv)"
export HOOK_LOG_WORKSPACE_ID="$(az deployment group show -g "$HOOK_RG" -n lab30-hook --query properties.outputs.logWorkspaceId.value -o tsv)"
echo "🌐 Hook URL: $HOOK_URL"
echo "🆔 Log Analytics workspace ID: $HOOK_LOG_WORKSPACE_ID"
```

```powershell title="PowerShell"
# Read the object ID of the gateway's managed identity: the only caller that the decision service lets in
$GATEWAY_PRINCIPAL_ID = az aigateway show -g $RG -n $GATEWAY --query identity.principalId -o tsv
Write-Host "👤 Gateway identity: $GATEWAY_PRINCIPAL_ID"

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

# Deploy the function app, its network, storage, and logs, without code yet
az deployment group create -g $HOOK_RG -n lab30-hook -f infra/hook.bicep -o none `
  -p appName=$HOOK_APP hookClientId=$HOOK_CLIENT_ID hookAudience=$HOOK_AUDIENCE `
  gatewayPrincipalId=$GATEWAY_PRINCIPAL_ID
if ($?) { Write-Host "🚀 Function app $HOOK_APP is deployed" }

# Read the hook's URL and the Log Analytics workspace ID from the deployment's outputs
$HOOK_URL              = az deployment group show -g $HOOK_RG -n lab30-hook --query properties.outputs.hookUrl.value -o tsv
$HOOK_LOG_WORKSPACE_ID = az deployment group show -g $HOOK_RG -n lab30-hook --query properties.outputs.logWorkspaceId.value -o tsv
Write-Host "🌐 Hook URL: $HOOK_URL"
Write-Host "🆔 Log Analytics workspace ID: $HOOK_LOG_WORKSPACE_ID"
```

### Deploy the code

Restart the new app once, so that it reaches its private storage, then zip the function's three files in
`infra/hook` and upload them. Zip only those files, so that local files such as `local.settings.json` stay on your
machine. Flex Consumption builds the app from `requirements.txt`.

```bash title="Bash"
# Restart the new app once: its first upload can fail until it reaches its private storage
az functionapp restart -g "$HOOK_RG" -n "$HOOK_APP" &&
  echo "⏳ $HOOK_APP restarted"

# Zip the function's three files from inside its folder
(cd infra/hook && zip -q ../../hook.zip function_app.py host.json requirements.txt) &&
  echo "📄 hook.zip is ready"

# Upload the code and build it remotely, then delete the zip file
az functionapp deployment source config-zip -g "$HOOK_RG" -n "$HOOK_APP" --src hook.zip --build-remote true -o none &&
  echo "🚀 The decision service is deployed to $HOOK_APP"
rm hook.zip

# Call the hook without a token: App Service Authentication answers 401 before the function runs
echo "🔐 Anonymous call to the hook: HTTP $(curl -s -o /dev/null -w '%{http_code}' -X POST "$HOOK_URL" -H 'Content-Type: application/json' -d '{}')"
```

```powershell title="PowerShell"
# Restart the new app once: its first upload can fail until it reaches its private storage
az functionapp restart -g $HOOK_RG -n $HOOK_APP
if ($?) { Write-Host "⏳ $HOOK_APP restarted" }

# Zip the function's three files
Compress-Archive -Path infra/hook/function_app.py, infra/hook/host.json, infra/hook/requirements.txt -DestinationPath hook.zip -Force
if ($?) { Write-Host "📄 hook.zip is ready" }

# Upload the code and build it remotely, then delete the zip file
az functionapp deployment source config-zip -g $HOOK_RG -n $HOOK_APP --src hook.zip --build-remote true -o none
if ($?) { Write-Host "🚀 The decision service is deployed to $HOOK_APP" }
Remove-Item hook.zip

# Call the hook without a token: App Service Authentication answers 401 before the function runs
$anonymous = Invoke-WebRequest -Method Post -Uri $HOOK_URL -ContentType 'application/json' -Body '{}' -SkipHttpErrorCheck
Write-Host "🔐 Anonymous call to the hook: HTTP $($anonymous.StatusCode)"
```

> **Checkpoint**
> The upload ends with `🚀 The decision service is deployed`, and the anonymous call prints
> `🔐 Anonymous call to the hook: HTTP 401`. Keep the values of `HOOK_URL` and `HOOK_AUDIENCE`: the portal asks for
> them.

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

**What you need:** only the one-time setup from **Before you begin**, and permission to register applications in
Microsoft Entra ID. This track doesn't use your gateway or `learn` server from lab 04: `azd up` creates a new gateway
with its own `learn` server, the decision service, and the policy, so it works on its own.

### Review the templates

`infra/main.bicep` creates the resource group `rg-<environment name>`, registers the hook's app in Microsoft Entra
ID with the Microsoft Graph Bicep extension, and calls lab 01's
[gateway.bicep](../01-provision-gateway/infra/gateway.bicep) for a gateway with no model. Then it deploys the
decision service and the governed MCP server. azd fills two parameters from environment values:

| Parameter | azd environment value | Default |
|---|---|---|
| `hookMode` | `HOOK_MODE` | `failClosed` |
| `blockedTools` | `HOOK_BLOCKED_TOOLS` | `*code_sample*` |

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

`infra/hook-registration.bicep` registers the app and its service principal, with an application ID URI that
the policy uses as the token audience.

<!-- include: infra/hook-registration.bicep -->

`infra/hook.bicep` is the function app that the **Azure CLI** track deploys too: Flex Consumption, App Service
Authentication that lets in only the gateway's identity, a private storage account, and Application Insights.

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

`infra/guarded-tool-server.bicep` declares the `learn` server of lab 04 with an `agentHooks` policy that calls the
decision service before and after each tool call, and creates the `app-first-call` key.

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

`azure.yaml` deploys the `infra/hook` folder to the function app. Its hooks restart the new app before the first
upload, and delete the app registration before `azd down` deletes the resource group, because the registration
lives in Microsoft Entra ID.

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

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

### Deploy with azd up

Move into the lab's folder, create an azd environment named `aigw-lab30` in your current subscription, then provision
everything and deploy the function's code. It takes four to eight minutes.

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

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

# Provision the app registration, the gateway, the decision service, and the governed MCP server, then deploy the code
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/30-agent-hooks
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-lab30 --location eastus2 --subscription (az account show --query id --output tsv)
if ($?) { Write-Host "📝 azd environment aigw-lab30 deploys to eastus2" }

# Provision the app registration, the gateway, the decision service, and the governed MCP server, then deploy the code
azd up
if ($?) { Write-Host "🚀 Gateway deployed: $(azd env get-value AI_GATEWAY_URL)" }
```

For another region, use one that has both AI Gateway and Flex Consumption, 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.

```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 decision service's outputs: the function app, its URL, its token audience, and its log workspace
export HOOK_RG="$RG"
export HOOK_APP="$(azd env get-value HOOK_APP_NAME)"
export HOOK_URL="$(azd env get-value HOOK_URL)"
export HOOK_AUDIENCE="$(azd env get-value HOOK_AUDIENCE)"
export HOOK_LOG_WORKSPACE_ID="$(azd env get-value HOOK_LOG_WORKSPACE_ID)"
echo "🌐 Hook URL: $HOOK_URL"
echo "👤 Token audience: $HOOK_AUDIENCE"

# 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)"
```

```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 decision service's outputs: the function app, its URL, its token audience, and its log workspace
$HOOK_RG               = $RG
$HOOK_APP              = azd env get-value HOOK_APP_NAME
$HOOK_URL              = azd env get-value HOOK_URL
$HOOK_AUDIENCE         = azd env get-value HOOK_AUDIENCE
$HOOK_LOG_WORKSPACE_ID = azd env get-value HOOK_LOG_WORKSPACE_ID
Write-Host "🌐 Hook URL: $HOOK_URL"
Write-Host "👤 Token audience: $HOOK_AUDIENCE"

# 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)"
```

> **Checkpoint**
> `azd up` ended with `SUCCESS`, the hook URL ends with `/api/tool-hook`, and the token audience starts with
> `api://`.

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

**What you need:** only the one-time setup from **Before you begin**, plus Terraform 1.9 or later, as in
[Deploy a lab with Terraform](../SETUP.md#deploy-a-lab-with-terraform), and permission to register applications in
Microsoft Entra ID. This track doesn't use your gateway or `learn` server from lab 04: `terraform apply` creates a
new gateway with its own `learn` server, the decision service, and the policy, so it works on its own.

### Review the configuration

The configuration deploys the same resources as the Bicep templates. `terraform/main.tf` creates the resource group
`rg-<environment_name>` and calls lab 01's [gateway module](../01-provision-gateway/terraform/gateway) for a gateway
with no model. `terraform/variables.tf` declares the two settings of the Bicep track, with the same defaults:

| Variable | Bicep parameter | Default |
|---|---|---|
| `hook_mode` | `hookMode` | `failClosed` |
| `blocked_tools` | `blockedTools` | `*code_sample*` |

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

`terraform/hook-registration.tf` registers the app and its service principal with the `azuread` provider, which
signs in to Microsoft Entra ID with your Azure CLI session. The application ID URI is the token audience.

<!-- include: terraform/hook-registration.tf -->

`terraform/hook.tf` is the function app of `infra/hook.bicep`: Flex Consumption, App Service Authentication that
lets in only the gateway's identity, a private storage account, and Application Insights. The network, storage, logs,
plan, and role assignments use `azurerm`. The function app and its App Service Authentication settings use `azapi`,
because `azurerm_function_app_flex_consumption` always writes an `AzureWebJobsStorage` connection string with an
account key, which a storage account without shared keys rejects.

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

`terraform/hook-code.tf` deploys the function in `infra/hook`, like `azd deploy`. The `archive` provider zips only its
three files, so local files such as `local.settings.json` stay on your machine. Then the Azure CLI on your machine
restarts the new app once and uploads the zip with a remote build. Terraform runs the upload again when the code
changes.

<!-- include: terraform/hook-code.tf -->

`terraform/guarded-tool-server.tf` declares the `learn` server of lab 04 with the agent hooks policy, and creates the
`app-first-call` key, like `infra/guarded-tool-server.bicep`. [`terraform/providers.tf`](terraform/providers.tf)
adds the `azuread` and `archive` providers to the quick start's.

<!-- include: terraform/guarded-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 five minutes. While the code uploads, the Azure CLI prints progress lines such as
`WARNING: Checking the health of the function app`.

```bash title="Bash"
# Move into the lab's Terraform folder
cd ~/aigateway/labs/30-agent-hooks/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 app registration, the gateway, the decision service and its code,
# and the governed MCP server
terraform init &&
  terraform plan -out tfplan &&
  terraform apply tfplan &&
  echo "🚀 Gateway deployed: $(terraform output -raw ai_gateway_url)"
```

```powershell title="PowerShell"
# Move into the lab's Terraform folder
Set-Location ~/aigateway/labs/30-agent-hooks/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 app registration, the gateway, the decision service and its code,
# and the governed MCP server
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 that has both AI Gateway and Flex Consumption, 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.

```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 decision service's outputs: the function app, its URL, its token audience, and its log workspace
export HOOK_RG="$RG"
export HOOK_APP="$(terraform output -raw hook_app_name)"
export HOOK_URL="$(terraform output -raw hook_url)"
export HOOK_AUDIENCE="$(terraform output -raw hook_audience)"
export HOOK_LOG_WORKSPACE_ID="$(terraform output -raw hook_log_workspace_id)"
echo "🌐 Hook URL: $HOOK_URL"
echo "👤 Token audience: $HOOK_AUDIENCE"

# 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)"
```

```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 decision service's outputs: the function app, its URL, its token audience, and its log workspace
$HOOK_RG               = $RG
$HOOK_APP              = terraform output -raw hook_app_name
$HOOK_URL              = terraform output -raw hook_url
$HOOK_AUDIENCE         = terraform output -raw hook_audience
$HOOK_LOG_WORKSPACE_ID = terraform output -raw hook_log_workspace_id
Write-Host "🌐 Hook URL: $HOOK_URL"
Write-Host "👤 Token audience: $HOOK_AUDIENCE"

# 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)"
```

> **Checkpoint**
> `terraform apply` ended with `Apply complete! Resources: 22 added, 0 changed, 0 destroyed.`, the hook URL ends
> with `/api/tool-hook`, and the token audience starts with `api://`.

<!-- /tracks -->

## Attach the hook to the MCP server

Add an agent hooks policy to the `learn` MCP server that calls your decision service as the gateway's managed
identity, and blocks the call when the service fails. The portal configures one intervention point per policy; the
Azure CLI, Bicep + azd, and Terraform tracks configure both.

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

### Choose the policy type

Open the [AI Gateway portal](https://ai.gateway.azure.com) and select your gateway from the gateway switcher. Select
**Policies** › **Add policy**. On the **Type** step, under **Security**, select **Agent hooks**. Its card carries the
**Preview** and **MCP server** badges and reads "Invoke governance controls at MCP tool-call intervention points,
with hooks hosted in any service." Select **Next**.

![The Add policy wizard on the Type step, with Agent hooks selected under Security](../assets/screens/agent-hooks-01-type.webp "Agent hooks sits in the Security group, after Agent 365 tool threat protection. 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 the `learn` server,
**Microsoft Learn** in lab 04, then select **Next**.

![The Scope step with the Microsoft Learn MCP server checked](../assets/screens/agent-hooks-02-scope.webp "Each agent hooks policy belongs to one MCP server. Repeat the wizard for other servers.")

### Configure the hook

On the **Details** step, set:

| Field | Value |
|---|---|
| **Intervention point** | **Before tool call** |
| **Endpoint** | The value of `HOOK_URL`, such as `https://func-<name>.azurewebsites.net/api/tool-hook` |
| **Failure mode** | **Fail closed** |
| **Authentication** | **Managed identity** |
| **Managed identity** | **System-assigned managed identity** |
| **Token audience** | The value of `HOOK_AUDIENCE`, such as `api://<client-id>` |
| **Headers** | Select **Add header**, then enter `x-hook-policy` as **Header name** and `lab30` as **Value** |

Then select **Create**. The hint under **Intervention point** reads "Only one intervention point is supported in
this preview."

![The Details step with Before tool call, the function URL, Fail closed, managed identity authentication, the token audience, and one header](../assets/screens/agent-hooks-03-details.webp "Header values are literal and returned by reads, so never put a secret in them. API key authentication keeps its key separately.")

### Check the policy list

The **Policies** list shows **Before tool calls** under **Configuration**, **Agent hooks** under **Type**, and
**MCP server: Microsoft Learn** under **Scope**.

![The Policies list with one Agent hooks policy on the Microsoft Learn MCP server](../assets/screens/agent-hooks-04-policy-list.webp "Select the policy to see its settings, edit it, or delete it.")

To add **After tool call** to the same policy, run the **Azure CLI** track's steps instead: they replace the
portal's policy with one that has both intervention points.

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

### Write the policy

`az aigateway mcp update --policies` replaces the server's whole policy array. Read the server's policies with
`az aigateway mcp show`, keep the others, and add the hook.

```bash title="Bash"
# Describe the hook: ask the decision service before and after each tool call, as the gateway's managed identity
HOOK_POLICY="$(jq -cn --arg url "$HOOK_URL" --arg aud "$HOOK_AUDIENCE" '{id:"tool-guard",type:"agentHooks",scope:"resource",mode:"failClosed",endpoint:{url:$url},authentication:{managedIdentity:{resource:$aud}},headers:[{name:"x-hook-policy",value:"lab30"}],hooks:{preToolCall:{},postToolCall:{}}}')"
echo "📝 Agent hooks policy tool-guard calls $HOOK_URL"

# Read the server's policies, keep every policy except agent hooks, and add the new one
POLICIES="$(az aigateway mcp show -g "$RG" --gateway-name "$GATEWAY" -n "$MCP_SERVER" -o json |
  jq -c --argjson hook "$HOOK_POLICY" '[(.properties.policies // [])[] | select(.type != "agentHooks")] + [$hook]')"
echo "📝 Policies to write: $(jq length <<< "$POLICIES"), including tool-guard"

# Replace the server's whole policies array with the merged one
az aigateway mcp update -g "$RG" --gateway-name "$GATEWAY" -n "$MCP_SERVER" --policies "$POLICIES" -o none &&
  echo "🔐 Agent hooks policy tool-guard is on the $MCP_SERVER MCP server"
```

```powershell title="PowerShell"
# Describe the hook: ask the decision service before and after each tool call, as the gateway's managed identity
$hookPolicy = [pscustomobject]@{
  id             = 'tool-guard'; type = 'agentHooks'; scope = 'resource'; mode = 'failClosed'
  endpoint       = @{ url = $HOOK_URL }
  authentication = @{ managedIdentity = @{ resource = $HOOK_AUDIENCE } }
  headers        = @(@{ name = 'x-hook-policy'; value = 'lab30' })
  hooks          = @{ preToolCall = @{}; postToolCall = @{} }
}
Write-Host "📝 Agent hooks policy tool-guard calls $HOOK_URL"

# Read the server's policies, keep every policy except agent hooks, and add the new one
$current  = az aigateway mcp show -g $RG --gateway-name $GATEWAY -n $MCP_SERVER -o json | ConvertFrom-Json
$policies = @($current.properties.policies | Where-Object { $_ -and $_.type -ne 'agentHooks' }) + $hookPolicy
Write-Host "📝 Policies to write: $($policies.Count), including tool-guard"

# Write the policies to a file, which --policies reads with the @ prefix, then replace the whole policies array
ConvertTo-Json -InputObject $policies -Depth 10 -Compress | Set-Content -Path policies.json
az aigateway mcp update -g $RG --gateway-name $GATEWAY -n $MCP_SERVER --policies '@policies.json' -o none
if ($?) { Write-Host "🔐 Agent hooks policy tool-guard is on the $MCP_SERVER MCP server" }
Remove-Item policies.json
```

### Read the policy back

```bash title="Bash"
# Read the agent hooks policy on the MCP server
echo "🔐 Agent hooks policy on the $MCP_SERVER MCP server:"
az aigateway mcp show -g "$RG" --gateway-name "$GATEWAY" -n "$MCP_SERVER" --query "properties.policies[?type=='agentHooks']"
```

```powershell title="PowerShell"
# Read the agent hooks policy on the MCP server
Write-Host "🔐 Agent hooks policy on the $MCP_SERVER MCP server:"
az aigateway mcp show -g $RG --gateway-name $GATEWAY -n $MCP_SERVER --query "properties.policies[?type=='agentHooks']"
```

> **Checkpoint**
> The policy has `"type": "agentHooks"`, `"mode": "failClosed"`, your `endpoint.url`, `managedIdentity.resource`,
> and both `preToolCall` and `postToolCall` under `hooks`. The CLI masks header values as `"***"`; the gateway still
> sends `lab30`, which the decision log shows in **Verify**.

In the AI Gateway portal, **Policies** lists it as **Before and after tool calls**, of type **Agent hooks**. Select
it to see both intervention points with their settings.

![The Agent hooks policy page with Before tool call and After tool call, each with the endpoint, Fail closed, managed identity, token audience, and header](../assets/screens/agent-hooks-05-both-points.webp "The policy page shows the shared settings under each intervention point.")

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

### Read the policy that azd attached

`azd up` already attached the policy. Read it back.

```bash title="Bash"
# Read the agent hooks policy on the MCP server
echo "🔐 Agent hooks policy on the $MCP_SERVER MCP server:"
az aigateway mcp show -g "$RG" --gateway-name "$GATEWAY" -n "$MCP_SERVER" --query "properties.policies[?type=='agentHooks']"
```

```powershell title="PowerShell"
# Read the agent hooks policy on the MCP server
Write-Host "🔐 Agent hooks policy on the $MCP_SERVER MCP server:"
az aigateway mcp show -g $RG --gateway-name $GATEWAY -n $MCP_SERVER --query "properties.policies[?type=='agentHooks']"
```

> **Checkpoint**
> The policy has `"id": "tool-guard"`, `"type": "agentHooks"`, `"mode": "failClosed"`, the hook URL, the token
> audience, and both `preToolCall` and `postToolCall` under `hooks`. The CLI masks header values as `"***"`.

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

### Read the policy that Terraform attached

`terraform apply` already attached the policy. Read it back, then move back to the lab's folder, where the next
steps run the test script.

```bash title="Bash"
# Read the agent hooks policy on the MCP server
echo "🔐 Agent hooks policy on the $MCP_SERVER MCP server:"
az aigateway mcp show -g "$RG" --gateway-name "$GATEWAY" -n "$MCP_SERVER" --query "properties.policies[?type=='agentHooks']"

# Move back to the lab's folder, where the next steps run the test script
cd .. &&
  echo "📂 Lab folder: $(pwd)"
```

```powershell title="PowerShell"
# Read the agent hooks policy on the MCP server
Write-Host "🔐 Agent hooks policy on the $MCP_SERVER MCP server:"
az aigateway mcp show -g $RG --gateway-name $GATEWAY -n $MCP_SERVER --query "properties.policies[?type=='agentHooks']"

# Move back to the lab's folder, where the next steps run the test script
Set-Location ..
if ($?) { Write-Host "📂 Lab folder: $(Get-Location)" }
```

> **Checkpoint**
> The policy has `"id": "tool-guard"`, `"type": "agentHooks"`, `"mode": "failClosed"`, the hook URL, the token
> audience, and both `preToolCall` and `postToolCall` under `hooks`. The CLI masks header values as `"***"`.

<!-- /tracks -->

> [!WARNING]
> Don't edit a policy with both intervention points in the portal. Its **Edit policy** panel reads "This policy has
> both intervention points. Choose one to continue.", and saving keeps only the point that you choose. Change such a
> policy with the Azure CLI, Bicep, or Terraform.

![The Edit policy panel of a policy with both intervention points, asking to choose one](../assets/screens/agent-hooks-06-edit-both-points.webp "The portal shows both hooks on the policy's page, but its editor keeps only one.")

## Call tools through the hook

[`infra/call-tool.sh`](infra/call-tool.sh) runs the MCP handshake and calls one tool with your runtime key. It
prints `isError: false` with the start of the result, or `isError: true` with the gateway's message.

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

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

<!-- steps -->

### Call an allowed tool

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

# Ask the docs search tool a harmless question: the hook allows the call and the result
echo "🔧 Allowed tool call:"
./infra/call-tool.sh learn_microsoft_docs_search '{"query":"What is Azure Functions Flex Consumption?"}' "$MCP_SERVER"
```

```powershell title="PowerShell"
# Ask the docs search tool a harmless question: the hook allows the call and the result
Write-Host "🔧 Allowed tool call:"
./infra/call-tool.ps1 learn_microsoft_docs_search '{"query":"What is Azure Functions Flex Consumption?"}' $MCP_SERVER
```

```text title="Expected output"
🔧 Allowed tool call:
tools/call learn_microsoft_docs_search {"query":"What is Azure Functions Flex Consumption?"}
HTTP status: 200
isError: false (the result was returned)
{"results":[{"title":"Azure Functions Flex Consumption plan hosting", …
...
```

### Call a blocked tool

```bash title="Bash"
# Call the code sample tool, which matches the BLOCKED_TOOLS pattern *code_sample*: the hook denies it before it runs
echo "🔧 Blocked tool call:"
./infra/call-tool.sh learn_microsoft_code_sample_search '{"query":"azure functions python http trigger"}' "$MCP_SERVER"
```

```powershell title="PowerShell"
# Call the code sample tool, which matches the BLOCKED_TOOLS pattern *code_sample*: the hook denies it before it runs
Write-Host "🔧 Blocked tool call:"
./infra/call-tool.ps1 learn_microsoft_code_sample_search '{"query":"azure functions python http trigger"}' $MCP_SERVER
```

```text title="Expected output"
🔧 Blocked tool call:
tools/call learn_microsoft_code_sample_search {"query":"azure functions python http trigger"}
HTTP status: 200
isError: true
Tool call blocked by a policy before execution
```

### Send an email address to a tool

```bash title="Bash"
# Put an email address in the arguments of an allowed tool: the hook denies the call before it runs
echo "🔧 Tool call with an email address:"
./infra/call-tool.sh learn_microsoft_docs_search '{"query":"Send the report to megan.bowen@contoso.com"}' "$MCP_SERVER"
```

```powershell title="PowerShell"
# Put an email address in the arguments of an allowed tool: the hook denies the call before it runs
Write-Host "🔧 Tool call with an email address:"
./infra/call-tool.ps1 learn_microsoft_docs_search '{"query":"Send the report to megan.bowen@contoso.com"}' $MCP_SERVER
```

```text title="Expected output"
🔧 Tool call with an email address:
tools/call learn_microsoft_docs_search {"query":"Send the report to megan.bowen@contoso.com"}
HTTP status: 200
isError: true
Tool call blocked by a policy before execution
```

### Get a result that contains a secret

The Azurite storage emulator documents a well-known development account key, so a search for its connection string
returns text that looks like a storage account key. The tool runs, and the hook withholds its result. On the
**Portal** track, the policy has only **Before tool call**, so the result comes back.

```bash title="Bash"
# Search for a connection string with an account key: the hook allows the call, then withholds the result
echo "🔧 Tool call whose result contains a key:"
./infra/call-tool.sh learn_microsoft_docs_search '{"query":"Azurite default connection string AccountKey"}' "$MCP_SERVER"
```

```powershell title="PowerShell"
# Search for a connection string with an account key: the hook allows the call, then withholds the result
Write-Host "🔧 Tool call whose result contains a key:"
./infra/call-tool.ps1 learn_microsoft_docs_search '{"query":"Azurite default connection string AccountKey"}' $MCP_SERVER
```

```text title="Expected output"
🔧 Tool call whose result contains a key:
tools/call learn_microsoft_docs_search {"query":"Azurite default connection string AccountKey"}
HTTP status: 200
isError: true
Tool result blocked by a policy after execution
```

<!-- /steps -->

> **Checkpoint**
> The harmless search returns results, the code sample tool and the email address are blocked **before
> execution**, and the connection string search is blocked **after execution**. Search results can change; if the
> last call returns results, they don't contain a key.

## Understand verdicts and failures

The gateway answers a denied call the way MCP reports a failed tool: HTTP `200`, with `isError: true` in the
JSON-RPC result. Agents read it as a tool error, not a transport error.

| What happens | Before tool call | After tool call |
|---|---|---|
| The service answers `allow` | The tool runs | The caller gets the result |
| The service answers `deny` | "Tool call blocked by a policy before execution". The tool doesn't run | "Tool result blocked by a policy after execution". The tool already ran |
| The service fails: it's stopped, answers `401` or another error, or takes more than about 30 seconds | `failClosed`: the same as a deny. `failOpen`: the tool runs | `failClosed`: the same as a deny. `failOpen`: the caller gets the result |

The gateway doesn't pass the `reason` to the caller, and with `failClosed` a failure looks exactly like a deny. Read
the reason in the decision log, by the gateway's `request_id`, which is the same for both hooks of one call.

> [!CAUTION]
> A deny after the call withholds the result, but it can't undo what the tool did. For tools that write, send, or
> delete, decide **before** the call, and build agents that don't retry a call whose result was withheld.

Agent hooks complement the gateway's built-in tool controls:

| You need | Use | Lab |
|---|---|---|
| Hide or block tools by name, the same way for every caller | Tool allow and block lists | [Lab 05](../05-mcp-tool-controls/README.md) |
| Microsoft Defender and Microsoft Purview verdicts on prompt injection and sensitive data, for delegated user calls | Agent 365 tool threat protection | [Lab 19](../19-tool-threat-protection/README.md) |
| Your own rules on tool arguments and results, such as business limits, data that must not leave, or a custom detector | Agent hooks | This lab |

## Verify

<!-- steps -->

### Read the decision log

The function writes one line for each verdict to Application Insights, which stores it in Log Analytics. Lines
arrive two to five minutes after the calls.

```bash title="Bash"
# Read the decision service's verdicts of the last hour: tool, decision, reason, request ID, caller, and header
echo "📊 Decisions of the last hour:"
az monitor log-analytics query -w "$HOOK_LOG_WORKSPACE_ID" -o tsv --analytics-query \
  "AppTraces | where TimeGenerated > ago(1h) and Message startswith 'agent-hook' | order by TimeGenerated asc | project Message"
```

```powershell title="PowerShell"
# Read the decision service's verdicts of the last hour: tool, decision, reason, request ID, caller, and header
Write-Host "📊 Decisions of the last hour:"
az monitor log-analytics query -w $HOOK_LOG_WORKSPACE_ID -o tsv --analytics-query `
  "AppTraces | where TimeGenerated > ago(1h) and Message startswith 'agent-hook' | order by TimeGenerated asc | project Message"
```

```text title="Expected output"
📊 Decisions of the last hour:
agent-hook point=pre_tool_call tool=learn_microsoft_docs_search decision=allow reason=policy_satisfied request_id=d12fc93f-… caller=2db50daf-… policy=lab30	PrimaryResult
agent-hook point=post_tool_call tool=learn_microsoft_docs_search decision=allow reason=policy_satisfied request_id=d12fc93f-… caller=2db50daf-… policy=lab30	PrimaryResult
agent-hook point=pre_tool_call tool=learn_microsoft_code_sample_search decision=deny reason=blocked_tool:*code_sample* request_id=d8ec2ebf-… caller=2db50daf-… policy=lab30	PrimaryResult
agent-hook point=pre_tool_call tool=learn_microsoft_docs_search decision=deny reason=personal_data:email_address request_id=5760e4b2-… caller=2db50daf-… policy=lab30	PrimaryResult
agent-hook point=pre_tool_call tool=learn_microsoft_docs_search decision=allow reason=policy_satisfied request_id=99895621-… caller=2db50daf-… policy=lab30	PrimaryResult
agent-hook point=post_tool_call tool=learn_microsoft_docs_search decision=deny reason=secret_in_result:storage_account_key request_id=99895621-… caller=2db50daf-… policy=lab30	PrimaryResult
```

`caller` is the object ID of the gateway's managed identity, which App Service Authentication validated, and
`policy` is the header that the policy adds. The portal track has no `post_tool_call` lines.

### See the policy fail closed

Stop the decision service and call the harmless search again. The gateway can't get a verdict, so `failClosed`
blocks the call. Then start the service again.

```bash title="Bash"
# Stop the decision service, so that the gateway can't get a verdict, and give the stop half a minute to apply
az functionapp stop -g "$HOOK_RG" -n "$HOOK_APP" &&
  echo "⏳ $HOOK_APP is stopping" && sleep 30

# Call the harmless search again: with failClosed, the gateway blocks it
echo "🔧 Allowed tool call while the hook is down:"
./infra/call-tool.sh learn_microsoft_docs_search '{"query":"What is Azure Functions Flex Consumption?"}' "$MCP_SERVER"

# Start the decision service again
az functionapp start -g "$HOOK_RG" -n "$HOOK_APP" &&
  echo "🚀 $HOOK_APP is running again"
```

```powershell title="PowerShell"
# Stop the decision service, so that the gateway can't get a verdict, and give the stop half a minute to apply
az functionapp stop -g $HOOK_RG -n $HOOK_APP
if ($?) { Write-Host "⏳ $HOOK_APP is stopping"; Start-Sleep -Seconds 30 }

# Call the harmless search again: with failClosed, the gateway blocks it
Write-Host "🔧 Allowed tool call while the hook is down:"
./infra/call-tool.ps1 learn_microsoft_docs_search '{"query":"What is Azure Functions Flex Consumption?"}' $MCP_SERVER

# Start the decision service again
az functionapp start -g $HOOK_RG -n $HOOK_APP
if ($?) { Write-Host "🚀 $HOOK_APP is running again" }
```

```text title="Expected output"
⏳ <hook-app> is stopping
🔧 Allowed tool call while the hook is down:
tools/call learn_microsoft_docs_search {"query":"What is Azure Functions Flex Consumption?"}
HTTP status: 200
isError: true
Tool call blocked by a policy before execution
🚀 <hook-app> is running again
```

<!-- /steps -->

> **Checkpoint**
> The decision log has an `allow` or a `deny` with a reason for each call, and the harmless search is blocked while
> the decision service is stopped. The log has no line for that call, because the function never ran.

## Go further

- **Fail open for low-risk servers.** Set `mode` to `failOpen` so that tool calls continue when the service is
  down, or override it for one point, such as `"postToolCall": {"mode": "failOpen"}`. On the **Bicep + azd**
  track, run `azd env set HOOK_MODE failOpen` and `azd provision`. On the **Terraform** track, run
  `terraform plan -var hook_mode=failOpen -out tfplan` and `terraform apply tfplan` in the `terraform` folder. Then
  repeat the stop test: the search returns results, and so does the code sample search that the service blocks.
  Fail open lets every call through while the service is down.
- **Change the rules without a deployment.** The blocked tool patterns are an app setting:
  `az functionapp config appsettings set -g "$HOOK_RG" -n "$HOOK_APP" --settings "BLOCKED_TOOLS=*code_sample*,*fetch*"`.
- **Use a key instead of an identity.** The product's
  [pre-tool call hook guide](https://ai.gateway.azure.com/docs/policies/create-pre-tool-call-hook) uses a
  function key in an `x-functions-key` header, with **API key** authentication. The policy stores the key, and the
  portal asks for it again whenever the server's policies change. A managed identity keeps secrets out of the policy.
- **Use another identity.** Set `managedIdentity.clientId` to the client ID of a user-assigned identity on the
  gateway, and allow that identity's object ID in App Service Authentication.
- **Call your own rules engine.** The service can call anything that decides quickly: a ticket system that checks
  for an approved change, a data loss prevention API, or a model that classifies the arguments.

## Clean up

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

### Delete the policy

In the AI Gateway portal, select **Policies**. On the **Before tool calls** row of type **Agent hooks**, select
**More actions** (**⋯**) › **Delete**. In **Delete this policy?**, select **Delete**. Tool calls on the server no
longer wait for the hook.

### Delete the decision service

The **Azure CLI** steps of **Deploy the decision service** created a resource group and an app registration. Delete
them with the **Azure CLI** track's last three commands below.

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

### Remove the policy and the decision service

```bash title="Bash"
# Remove the agent hooks policy from the MCP server, and keep its other policies
POLICIES="$(az aigateway mcp show -g "$RG" --gateway-name "$GATEWAY" -n "$MCP_SERVER" -o json |
  jq -c '[(.properties.policies // [])[] | select(.type != "agentHooks")]')"
az aigateway mcp update -g "$RG" --gateway-name "$GATEWAY" -n "$MCP_SERVER" --policies "$POLICIES" -o none &&
  echo "🚮 The agent hooks policy is removed from the $MCP_SERVER MCP server"

# Delete the decision service's resource group: the function app, its network, storage, and logs
az group delete -n "$HOOK_RG" --yes --no-wait &&
  echo "⏳ Resource group $HOOK_RG is being deleted"

# Read the app registration's object ID, which the purge needs, then delete the app registration
HOOK_OBJECT_ID="$(az ad app show --id "$HOOK_CLIENT_ID" --query id -o tsv)" &&
  az ad app delete --id "$HOOK_CLIENT_ID" &&
  echo "🚮 App registration $HOOK_CLIENT_ID is deleted"

# Purge the app registration from the deleted items
az rest --method delete --url "https://graph.microsoft.com/v1.0/directory/deletedItems/$HOOK_OBJECT_ID" &&
  echo "🚮 App registration $HOOK_OBJECT_ID is purged"
```

```powershell title="PowerShell"
# Remove the agent hooks policy from the MCP server, and keep its other policies
$current  = az aigateway mcp show -g $RG --gateway-name $GATEWAY -n $MCP_SERVER -o json | ConvertFrom-Json
$policies = @($current.properties.policies | Where-Object { $_ -and $_.type -ne 'agentHooks' })
ConvertTo-Json -InputObject $policies -Depth 10 -Compress | Set-Content -Path policies.json
az aigateway mcp update -g $RG --gateway-name $GATEWAY -n $MCP_SERVER --policies '@policies.json' -o none
if ($?) { Write-Host "🚮 The agent hooks policy is removed from the $MCP_SERVER MCP server" }
Remove-Item policies.json

# Delete the decision service's resource group: the function app, its network, storage, and logs
az group delete -n $HOOK_RG --yes --no-wait
if ($?) { Write-Host "⏳ Resource group $HOOK_RG is being deleted" }

# Read the app registration's object ID, which the purge needs, then delete the app registration
$HOOK_OBJECT_ID = az ad app show --id $HOOK_CLIENT_ID --query id -o tsv
az ad app delete --id $HOOK_CLIENT_ID
if ($?) { Write-Host "🚮 App registration $HOOK_CLIENT_ID is deleted" }

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

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

### Delete everything azd created

In the `aigateway/labs/30-agent-hooks` folder, delete the resource group with the gateway, the `learn` MCP server,
the decision service, and the key. Before that, the `predown` hook deletes the app registration and purges it.
[`--purge`](../SETUP.md#delete-what-azd-created) also purges soft-deleted resources. It takes about ten minutes.

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

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

### Delete everything Terraform created

In the lab's Terraform folder, delete the app registration and the resource group with the gateway, the `learn` MCP
server, the decision service, and the key. Microsoft Entra ID keeps a deleted app registration in its deleted items
for 30 days, so purge it too, like `azd down` does. Read its object ID first, because `terraform destroy` removes the
outputs. It takes about four minutes.

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

# Read the app registration's object ID, which the purge needs after terraform destroy
HOOK_OBJECT_ID="$(terraform output -raw hook_object_id)" &&
  echo "🆔 App registration: $HOOK_OBJECT_ID"

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

# Purge the app registration from the deleted items
az rest --method delete --url "https://graph.microsoft.com/v1.0/directory/deletedItems/$HOOK_OBJECT_ID" &&
  echo "🚮 App registration $HOOK_OBJECT_ID is purged"
```

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

# Read the app registration's object ID, which the purge needs after terraform destroy
$HOOK_OBJECT_ID = terraform output -raw hook_object_id
if ($?) { Write-Host "🆔 App registration: $HOOK_OBJECT_ID" }

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

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

<!-- /tracks -->

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

## Next steps

- [Control which tools agents can call](../05-mcp-tool-controls/README.md)
- [Protect tool calls with Agent 365 threat protection](../19-tool-threat-protection/README.md)
- [Monitor usage, cost, and traces](../13-monitoring/README.md)
- [Agent hooks policy](https://ai.gateway.azure.com/docs/policies/agent-hooks) in the AI Gateway docs
