# Protect an MCP server with Agent Gateway and external token exchange: Google Drive behind the MCP proxy

> Put the IndyKite Agent Gateway (IAG) in MCP proxy mode in front of any MCP server - demonstrated end to end with a Google Drive MCP server in the iag-mcp-demo reference app.

**Category:** Agent Gateway

## Summary

This tutorial uses external token exchange: the delegation tokens are minted by your own identity provider's OAuth 2.0 token exchange (RFC 8693), not by the IndyKite Token Service. Follow the chapters in order to understand IAG's MCP proxy mode with that setup, run the Google Drive MCP server as a container, model the wf-drive workflow and its delegation chain in the IKG, configure the drive-mcp-iag gateway, run a Google Drive search through it, verify denials in the audit trail, remediate one live with the AuthZEN-guarded grant button, and see the same recipe extended to a graph-filtered ERP and a Salesforce CRM.

This tutorial is grounded in the [iag-mcp-demo](https://github.com/indykite/developer-hub/tree/master/a2a/iag-mcp-demo) reference application, running its **canbank usecase** provisioned with the instant-stack app. It puts the IndyKite Agent Gateway (IAG) in **MCP proxy mode** (`protected_agent.protocol: mcp`) in front of an MCP server - and proves the mode is downstream-agnostic by protecting a **Google Drive MCP server** that has nothing to do with IndyKite. Users log in at an **external identity provider** (IdP), which also introspects tokens and performs the OAuth 2.0 token exchange (RFC 8693) that gives every gateway its delegation token; the demo uses Curity, and any IdP with those endpoints fits. Every request is authorized against the Identity Knowledge Graph (IKG) before it is forwarded: who the caller is, which workflow they may trigger, and through which chain of agents. And because that authorization is graph data, it changes live: a denied request is remediated with one AuthZEN-guarded click, explained with a **why?** graph, and revoked again. The closing chapter shows the same recipe carried further - a Postgres-backed ERP whose rows are pre-filtered by AuthZEN search/resource, and a CRM agent that files Salesforce cases on behalf of the delegated user.

The whole demo, every agent, gateway and external service and the numbered request flow between them, is drawn and explained in the [Agent Gateway architecture guide](/guides/guide-iag-architecture). Read it first if you want the map before the route.

**External token exchange or Token Service?** In this tutorial the delegation tokens come from your identity provider's token exchange. If your provider has no token exchange, or you want the delegation tokens issued by a service you run, follow [Follow a delegation chain across agents: Agent Gateway with the IndyKite Token Service](/tutorials/tutorial-agent-gateway-delegation-chain) instead; its first chapter compares the two.

### What you will have at the end

1. A clear mental model of what IAG's MCP proxy mode does and does not do (session pass-through, SSE streaming, header handling, per-request authorization).
2. A Google Drive MCP server running as a container: the reference stdio server wrapped into MCP Streamable HTTP.
3. A `Workflow` node (`external_id=wf-drive`), an `Agent` node (`indykiteagent-drive`), and the `CAN_TRIGGER` / `INVOKES` relationships in the IKG.
4. The admission KBAC policy that lets a user reach the Drive server only when a workflow they can trigger has exactly the request's delegation chain as its path of agents, and the Token Introspect configurations that tell IndyKite which tokens of your IdP to accept.
5. A dedicated gateway instance, `drive-mcp-iag`, proxying MCP traffic on port `8887`.
6. A full-text Google Drive search executed through the gateway as an authorized user - and the same call denied with `403` for everyone else, with matching audit records.
7. The **deny → remediate → allow** loop: a denied user's red audit card grants Drive access with one AuthZEN-guarded click (writing `CAN_TRIGGER` relationships via the Capture API), a **why?** card renders the authorization path live from the graph, and a revoke resets the world.
8. A view of where the recipe leads: the **ERP** profile (a Postgres-backed MCP server whose rows are pre-filtered per caller by AuthZEN search/resource) and the **CRM** profile (a gateway-protected agent filing Salesforce cases on behalf of the delegated user).

### Prerequisites

- An **IndyKite project** with AuthZEN/KBAC and ContX IQ enabled, provisioned with the **canbank dataset** via the [instant-stack](https://github.com/indykite/developer-hub/tree/master/instant-stack) app (`DATASET=canbank`) or, request by request, with the demo's Bruno collection (`bruno/iag-demo`) - chapter 5 explains the parts of that dataset this tutorial relies on.
- An **external OAuth 2.0 IdP** with a token introspection endpoint, the client credentials grant, and token exchange (RFC 8693). It holds the demo's clients - `console` for the chatbot login and one machine-to-machine client per gateway (`indykiteagent`, `indykiteagent-2` to `-4`, `indykiteagent-mcp`, and `indykiteagent-drive` for this tutorial) - and `millicent` as a login user (chapter 7 logs in as her).
- **Docker and Docker Compose v2**, plus a Google account for chapter 3. The gateways run the `indykite/agent-gateway` image with a platform release tag from [IndyKite on Docker Hub](https://hub.docker.com/u/indykite).
- The base iag-mcp-demo configured per the [repo README](https://github.com/indykite/developer-hub/tree/master/a2a/iag-mcp-demo) with the **canbank usecase** active - this tutorial adds the Drive pieces on top and bootstraps the usecase env file (`.env.canbank`) in chapter 7.

### Who this tutorial is for

- Developers exposing **MCP servers** to AI agents who need token introspection, authorization, and audit in front of them - without changing the MCP server itself.
- Platform and security engineers who want the same enforcement point for MCP tool calls as for A2A agent calls.
- AI agents consuming this doc as a runbook - every chapter uses explicit service names, ports, file paths, and commands.

### Demo topology at a glance

The iag-mcp-demo is **usecase-driven**: the agents, gateways, and compose topology are domain-agnostic, and a usecase bundle (`usecases/canbank/` - domain vocabulary, per-agent skills, demo script) plus a matching provisioned IndyKite project make it "the CanBank demo". Activate it with `./switch-usecase.sh canbank`. This tutorial focuses on the services below; the Google Drive pair only starts when the `drive` compose profile is enabled.

| Service | Role | Port |
| --- | --- | --- |
| `chatbot` | Web UI; users log in here, and the demo scripts reuse its session token. | `3000` |
| `mcp-iag` | IAG in MCP proxy mode in front of the IndyKite MCP server. | `8886` |
| `drive-mcp-iag` | IAG in MCP proxy mode in front of the Google Drive MCP server (profile `drive`). | `8887` |
| `drive-mcp` | Google Drive MCP server: stdio reference server wrapped into Streamable HTTP (profile `drive`). | `8000` |
| `erp-mcp-iag` | IAG in MCP proxy mode in front of the ERP MCP server (profile `erp`; chapter 8's "Beyond Drive" section). | `8889` |
| `erp-mcp` + `erp-db` | Postgres-backed ERP MCP server and its database (profile `erp`). Deliberately **not** published to the host - only the gateway reaches them. | internal only |
| `analyst-iag` | IAG in front of the analyst agent (used by the optional analyst path in chapter 7). | `8885` |
| `analyst` | A2A data analyst agent; can use both the IndyKite and the Drive MCP backends. | `6005` |

## Chapter 1: What MCP proxy mode is

How one configuration switch turns the Agent Gateway into an authorization-enforcing proxy for any MCP Streamable HTTP server, with an external identity provider issuing the tokens.

## Chapter 1: What MCP proxy mode is

The **IndyKite Agent Gateway (IAG)** protects exactly one downstream per instance. By default (`protected_agent.protocol: a2a`) that downstream is an A2A agent. Set `protected_agent.protocol: mcp` and the same gateway instead proxies **MCP Streamable HTTP** traffic to a downstream MCP server. Everything in front of the forwarding step - token introspection, the token exchange, the admission decision against the IKG, and audit - is identical in both modes.

### Three parties, three jobs

Before the details, the division of work. The gateway owns no users and issues no tokens; it sits between three parties and asks each one the question that party can answer:

| Party | What it does for the gateway |
| --- | --- |
| Your **external identity provider** (IdP) | Logs users in, tells the gateway whether a token is active (token introspection), gives each gateway its own client credentials token, and performs the **OAuth 2.0 token exchange** (RFC 8693) that turns "this user" plus "this gateway" into one **delegation token**: `sub` is the user, the nested `act` claims are the chain of gateway clients the request has passed. |
| **IndyKite** | Answers who the token's user is in the graph (ContX IQ `whoami`) and whether that user may reach the protected server through this delegation chain (one AuthZEN evaluation against a KBAC policy). |
| The **MCP server** | Receives the request once both have said yes. It needs no change and no knowledge of IndyKite. |

The demo runs on Curity as its IdP. Nothing in the gateway is tied to that product: any OAuth 2.0 provider that offers token introspection, the client credentials grant and a token exchange that nests the `act` claim hop by hop fits, and chapter 6 shows the handful of settings that point the gateways at yours.

### What the MCP proxy does

- **Serves one MCP endpoint** - the path of `service.base_url`, for the Drive gateway `/mcp`. Any MCP method on that path - `initialize`, the `notifications/initialized` notification, `tools/list`, `tools/call`, `resources/list`, `resources/read` - is forwarded after the checks pass, to exactly the server endpoint named in `protected_agent.base_url`. Session-teardown `DELETE` requests are forwarded too. Any other path answers `404` before the token is even read.
- **Enforces the protocol revision** - only revisions `2025-06-18`, `2025-11-25`, and `2026-07-28` are forwarded. An `initialize` naming another revision is forwarded with `protocolVersion` rewritten to `2025-11-25`; every other request must carry `Mcp-Protocol-Version` with a supported value, or it is refused with `400` (JSON-RPC `-32020` when the header is missing, `-32022` with the supported list when the revision is unknown). JSON-RPC batches (`400`, `-32600`), bodies with a `Content-Encoding` other than `identity` (`415`), and bodies over 4 MiB (`413`) are refused as well. Refusals are audited as `NOT_AUTHORIZED` and never reach the downstream.
- **Reads what each request names** - a `tools/call` must name its tool and a `prompts/get` its prompt in `params.name`, a `resources/read` its resource in `params.uri`. A body that is not exactly one JSON-RPC message, a key that could be read in more than one way (for example both `name` and `Name` in `params`), a missing tool name, or on revision `2026-07-28` an `Mcp-Method` or `Mcp-Name` header that disagrees with the body, is refused with `400` before authorization. The exact codes and messages are in the [Agent Gateway guide](/guides/guide-agent-gateway#http).
- **Decides who gets in (admission)** - one AuthZEN evaluation per request: may this user reach this MCP server through this delegation chain? The answer comes from a KBAC policy over the graph you model in chapter 5.
- **Decides what the caller may use (capability checks)** - a second decision, on by default: the gateway reads from the graph which tools, resources and prompts the caller may use, filters `tools/list`, `resources/list` and `prompts/list` to that set, and refuses a call outside it with `403` and the JSON-RPC error `-31403`. The demo switches this off for the Drive gateway, for a reason chapter 6 explains, and shows how to turn it on.
- **Passes the session through untouched** - the `Mcp-Session-Id` header is forwarded in both directions without translation. The session the downstream server mints during `initialize` is the session the caller uses on every follow-up.
- **Streams SSE responses** - the downstream response body is streamed to the caller and flushed per SSE message, so long-running responses are not buffered or truncated.
- **Swaps the credentials** - the caller's `Authorization` header is removed and replaced with the delegation token the IdP minted for this hop. Chapter 2 covers what this means for the downstream server.
- **Tells MCP clients where to get a token** - the gateway serves OAuth 2.0 Protected Resource Metadata (RFC 9728) at `/.well-known/oauth-protected-resource/mcp` without a token, naming your IdP's issuer as the authorization server, and every `401` links it in a `WWW-Authenticate` header.

### What the MCP proxy does not do

- It does **not inspect tool arguments**. The gateway decides on who calls, through which chain, and - with capability checks on - on the name of the tool, resource or prompt. What a tool does with its arguments stays the server's business.
- It is **not a generic HTTP reverse proxy**. The downstream must speak MCP Streamable HTTP, and only its one MCP endpoint is reachable through the gateway.
- It does **not check the intent of a prompt in this demo**. Intent-based access control (`ibac.enabled`) is off here, the gateway's default. Its checks need the intent of a prompt in the delegation token, which only the IndyKite Token Service writes; this demo exchanges tokens at the identity provider, so its delegation tokens carry no intent, and admission and the capability checks are what the gateways decide. The [intent tutorial](/tutorials/tutorial-intent-ibac-gateway) shows the gateway with the Token Service and the Intent Agent.

### Downstream-agnostic by design

Nothing in MCP proxy mode is specific to IndyKite's own MCP server. The [iag-mcp-demo](https://github.com/indykite/developer-hub/tree/master/a2a/iag-mcp-demo) proves this with three protected MCP downstreams:

- `mcp-iag` (port `8886`) protects the **IndyKite MCP server** - the demo agents reach ContX IQ and AuthZEN tools through it.
- `drive-mcp-iag` (port `8887`) protects a **Google Drive MCP server** - a third-party server that knows nothing about IndyKite. This is the pair this tutorial builds.
- `erp-mcp-iag` (port `8889`, compose profile `erp`) protects a **Postgres-backed ERP MCP server** whose rows are pre-filtered per caller by the AuthZEN search/resource API before any SQL runs - the same recipe as Drive, applied to a database-backed server.

### Mental model

```text
millicent (user token from your IdP)
   │  MCP Streamable HTTP: initialize / tools/list / tools/call
   ▼
drive-mcp-iag:8887/mcp
   │  ── is the token active?                     ──>  external IdP (introspection)
   │  ── user token + gateway token → delegation  ──>  external IdP (token exchange)
   │  ── who is this user in the graph?           ──>  IndyKite ContX IQ (whoami)
   │  ── may User/millicent reach Agent/indykiteagent-drive
   │     through the chain [indykiteagent-drive]? ──>  IndyKite AuthZEN (KBAC over the IKG)
   │  ── AUTHORIZED / NOT_AUTHORIZED              ──>  audit stream
   │  Authorization header replaced with the delegation token,
   │  Mcp-Session-Id and SSE streamed through untouched
   ▼
drive-mcp:8000/mcp  ──>  Google Drive API (server's own Google credentials)
```

### What comes next

Chapter 2 follows one MCP request through the gateway and lists the exact HTTP responses callers can get back.

## Chapter 2: How the gateway handles an MCP request

The runtime path of one MCP call through IAG, the token exchange at the external identity provider, the credential swap, and every HTTP response a caller can receive.

## Chapter 2: How the gateway handles an MCP request

Take one call - `tools/call` with the Drive server's `search` tool - sent to `http://localhost:8887/mcp` with a user's Bearer token. The gateway runs the same sequence for every request in the session. Steps 2 to 4 talk to your identity provider, steps 5 and 6 to IndyKite:

1. **Extract the Bearer token.** No `Authorization: Bearer` header means an immediate `401`.
2. **Introspect the token at the IdP.** The token must be active and carry a subject.
3. **Get the gateway's own token.** With the client credentials grant, using the client configured for this instance (`indykiteagent-drive`). The gateway keeps and reuses this token until shortly before it expires.
4. **Exchange both for a delegation token.** The IdP's token exchange (RFC 8693) takes the caller's token as the subject and the gateway's token as the actor, and returns one token: `sub` is still the user, and `act` names this gateway's client. When the caller's token was itself a delegation token from an earlier gateway, the IdP nests that token's `act` inside the new one, so the chain grows by one client per hop. A request straight from millicent gives the chain `[indykiteagent-drive]`; the same request arriving through the analyst gives `[indykiteagent-4, indykiteagent-drive]`.
5. **Resolve the subject with ContX IQ `whoami`.** The gateway sends the Bearer token to `GET /contx-iq/v1/whoami` with its AppAgent credentials token and gets back the user's IKG node, for millicent `{"type": "User", "id": "millicent"}`. The `type` is the `ikg_node_type` of the project's Token Introspect configuration whose `jwt_matcher` matches the token's issuer and audience; without such a configuration the request ends in `401`. Chapter 5 creates these configurations for your IdP.
6. **Ask AuthZEN for the admission decision.** One `POST /access/v1/evaluation`: subject `User`/`millicent`, action `CAN_TRIGGER`, resource `Agent`/`indykiteagent-drive` - the gateway's own client, the newest hop of the chain. The delegation token travels on that call in `X-IK-Token`, so the KBAC policy reads the chain as `$ik_token.act_chain` and compares it with the workflows in the graph (chapter 5). The gateway itself compares nothing: `decision: false` means `403`. With capability checks on, a request that lists or names a tool, resource or prompt gets the capability decision in place of this one (chapter 6).
7. **Audit the decision.** One record per decision, written before forwarding, on the configured audit stream (chapter 8).
8. **Swap the credential and forward.** The gateway **replaces** the caller's `Authorization` header with the delegation token from step 4 and forwards the request to the server's endpoint - same query, same body, `Mcp-Session-Id` untouched. The downstream's status code, headers, and (streamed) body go back to the caller as-is.

The decision of step 6 is kept per subject and chain for a configurable time, so follow-up requests of a session do not each cost a platform call. Introspection and the token exchange run on every request.

### The credential swap, and what it means for your MCP server

Because the gateway always replaces the `Authorization` header, the protected MCP server never sees the caller's token - it sees the delegation token: the user as `sub`, the chain of gateway clients as `act`. Two consequences:

- An MCP server that requires the **caller's own upstream credential** (for example a hosted MCP endpoint that expects the caller's Google OAuth access token) will not work behind the gateway.
- The downstream must hold **its own credentials** for whatever backend it talks to. The Google Drive server in this tutorial holds its own Google OAuth material (chapter 3) and simply ignores the incoming Bearer token. A server that wants to know who the request is for can read the delegation token instead - the ERP server of chapter 8 does.

### Responses a caller can receive

| Status | Body / meaning |
| --- | --- |
| `200` / `202` | Authorized and forwarded; this is the downstream MCP server's own response (JSON or SSE). With capability checks on, a list answer is filtered to what the caller may use. |
| `400`, `413`, `415` | A JSON-RPC error from the gateway: the request is not one readable MCP message on a supported protocol revision (chapter 1). |
| `401` | `{"message":"Missing bearer token"}` when no token is sent. `{"message":"Unauthorized","errors":["identity provider: the token is not active"]}` when the IdP reports the token expired or unknown. `{"message":"Unauthorized","errors":["ContX IQ whoami failed"]}` when no Token Introspect configuration in the project matches the token, or the token fails its validation (step 5). Every `401` carries `WWW-Authenticate: Bearer resource_metadata="…"`, the address of the gateway's OAuth protected resource metadata. |
| `403` | `{"message":"Authorization check failed"}` - the caller is authenticated but the admission policy answered no: no workflow this subject can trigger has the request's delegation chain as its path of agents. With capability checks on (chapter 6), also a JSON-RPC error under the request's id, `-31403` `Forbidden: the caller may not use the named tool` (or `resource`, `prompt`): the call names a capability outside the caller's permitted set. |
| `404` | `{"message":"Not Found"}` - the request went to a path other than the gateway's one MCP endpoint. |
| `500` | `{"message":"Internal Server Error"}` - the IdP or IndyKite could not be reached or timed out. |
| `502` | `{"message":"Bad Gateway","errors":[…]}` - the downstream MCP server could not be reached. |

A `401` or `403` that the IdP or IndyKite itself answers is passed through with an `errors` entry naming the service, for example `["identity provider: token exchange failed - …"]`, so a wrong client secret or an invalid AppAgent credential is told apart from a denial; the audit record then says `ERROR`, not `NOT_AUTHORIZED`.

The `401`-with-no-token response doubles as a liveness probe: an unauthenticated `POST` to the gateway's endpoint answering `{"message":"Missing bearer token"}` proves the instance is up and enforcing. Chapter 7 uses exactly this check.

### What comes next

Chapter 3 sets up the Google side: a Google Cloud project, the Drive API, and the OAuth material the Drive MCP server needs.

## Chapter 3: Set up Google Drive access

Create the Google Cloud OAuth client and mint the credentials the Drive MCP server uses to search Google Drive.

## Chapter 3: Set up Google Drive access

The Drive MCP server talks to the Google Drive API with **its own** Google OAuth credentials (chapter 2 explains why the caller's token never reaches it). This chapter produces the two credential files the server needs. Work from the demo directory:

```bash
cd a2a/iag-mcp-demo
```

### 1. Create a Google Cloud project and enable the Drive API

1. Go to [console.cloud.google.com](https://console.cloud.google.com). A personal Google account is easiest: it can create projects freely, and the demo then searches that account's Drive.
2. Create a project (for example `iag-drive-demo`) and switch to it.
3. Search for **Google Drive API** and click **Enable**.

### 2. Configure the OAuth consent screen

Under **APIs & Services → OAuth consent screen**: choose type *External*, fill the required fields, and under **Test users** add the Google account you will authorize with. While the app is in *Testing* status only test users can authenticate - anyone else gets "Access blocked: app has not completed verification".

### 3. Create the OAuth client and download the keys

1. **APIs & Services → Credentials → Create credentials → OAuth client ID** → application type **Desktop app** → Create → **Download JSON**.
2. Save the download as `drive_mcp/.gdrive/gcp-oauth.keys.json` inside the demo directory. This path is git-ignored.

### 4. Authorize once (browser flow)

Run the one-time auth bootstrap on the host. It opens a browser and writes the refresh-token credentials file next to the keys:

```bash
cd drive_mcp
GDRIVE_OAUTH_PATH=$PWD/.gdrive/gcp-oauth.keys.json \
GDRIVE_CREDENTIALS_PATH=$PWD/.gdrive/.gdrive-server-credentials.json \
npx -y @modelcontextprotocol/server-gdrive auth
cd ..
```

In the browser: pick the account (the project owner or a test user) → on the "Google hasn't verified this app" warning click **Advanced** → **Go to <app> (unsafe)** (it is your own app) → **Allow** read access to Drive. The granted scope is read-only (`https://www.googleapis.com/auth/drive.readonly`).

### 5. Verify the credential files

```bash
ls -A drive_mcp/.gdrive/
# expect both files (next to the repo's committed .gitkeep):
#   gcp-oauth.keys.json
#   .gdrive-server-credentials.json
```

Both files must come from the **same** OAuth client. If you ever replace `gcp-oauth.keys.json`, re-run step 4 - mismatched files fail later with `invalid_request` on the first Drive call.

### 6. Seed some content

Put a few files in that Google account's Drive so searches return something. The Drive server's `search` tool is **full-text over file contents**, so a reliable trick is to create a Google Doc containing a unique word (for example `canbank-test-fixture`) - searching for that word then always returns exactly that document.

### What comes next

Chapter 4 packages the Drive MCP server as a container the gateway can protect.

## Chapter 4: The Google Drive MCP server container

Wrap the reference stdio Drive MCP server into MCP Streamable HTTP so the gateway can proxy it.

## Chapter 4: The Google Drive MCP server container

The gateway proxies **MCP Streamable HTTP**, but the reference Google Drive MCP server speaks **stdio**. The demo bridges the two and exposes it as a stateful Streamable HTTP endpoint. This is a general recipe: any stdio MCP server can be put behind IAG the same way.

### The image

The `drive_mcp/Dockerfile` in the demo installs [supergateway](https://github.com/supercorp-ai/supergateway), a wrapper that serves a stdio MCP server over Streamable HTTP, and the Drive server vendored under `drive_mcp/vendor/` - the reference `server-gdrive` extended with two demo-friendly touches: `search` results include the file ID, and **PDF files are text-extracted on read** instead of returned as opaque base64 (the reference server only exports Google-native docs as text). The wrapper runs with:

- MCP endpoint: `http://drive-mcp:8000/mcp`. This full URL is what the gateway forwards to (`protected_agent.base_url`, chapter 6).
- `--stateful`: the wrapper keeps one Drive server process per MCP session and mints an `Mcp-Session-Id` per `initialize`; the gateway passes it through both ways.
- Health check: `GET /healthz`.

### The compose service

```yaml
drive-mcp:
  image: drive-mcp:latest
  profiles: ["drive"]
  ports:
    - "${DRIVE_MCP_PORT:-8000}:8000"
  networks:
    - drive-mcp-iag-network
  environment:
    # Paths to the mounted Google OAuth material (values are paths, not secrets).
    GDRIVE_OAUTH_PATH: /gdrive/gcp-oauth.keys.json
    GDRIVE_CREDENTIALS_PATH: /gdrive/.gdrive-server-credentials.json
  volumes:
    - ./drive_mcp/.gdrive:/gdrive:ro
```

The credential files from chapter 3 are mounted read-only. The server refreshes its Google access token from them automatically; the Bearer token the gateway injects on forwarded requests is simply ignored - exactly the arrangement chapter 2 requires. To put another Streamable HTTP Drive MCP server behind the gateway, set the gateway's `JARVIS_PROTECTED_AGENT_BASE_URL` to that server's full endpoint URL: scheme, host, port and path. Changing `DRIVE_MCP_HOST` alone is enough only when the replacement also serves HTTP on port `8000` at `/mcp`.

### What the server exposes

| Capability | Behavior |
| --- | --- |
| Tool `search` | Full-text search over file *contents* in the authorized account's Drive; returns up to 10 matches, one `<fileId> <name> (<mimeType>)` line each. |
| `resources/list` | Lists Drive files as resources with `gdrive:///<fileId>` URIs. |
| `resources/read` | Reads one file by URI. Google-native files (Docs, Sheets, Slides) are exported as text, and PDFs are text-extracted by the vendored server (an encrypted or scanned-image PDF falls back to base64). Other binaries (`.doc`, video, …) come back base64-encoded, so point read prompts at Google-native or PDF copies. |

### Build it

```bash
make new-drive-mcp     # builds the drive-mcp image from ./drive_mcp
```

### What comes next

The server is ready but nothing authorizes access to it yet. Chapter 5 models who may reach it, and through which chain, in the IKG.

## Chapter 5: Model the wf-drive workflow in the IKG

The IdP client, the Token Introspect configurations, the Workflow and Agent nodes, the CAN_TRIGGER grant, the INVOKES chain and the one admission policy that authorize Google Drive access - plus one workflow per call shape.

## Chapter 5: Model the wf-drive workflow in the IKG

The gateway admits an MCP request only when a workflow the subject can trigger has **exactly the request's delegation chain** as its path of agents. The chain comes from your identity provider's token exchange (chapter 2); the workflows, the agents and the grant live in the Identity Knowledge Graph (IKG); one KBAC policy compares the two. This chapter adds all of it for the Drive downstream. If you provision with instant-stack, everything here is already in your project - read the chapter to understand it, then jump to the [shortcut](#provisioning-shortcut).

### 1. Register the client at your IdP

Create a confidential machine-to-machine client `indykiteagent-drive` at your IdP, allowed to use the client credentials grant and the token exchange; it needs no redirect URI. The gateway authenticates as this client, so the client's name ends up in the delegation chain. **The value your IdP writes into `sub` for this client's token must exactly match the Agent node's `external_id`** - the admission policy compares the two. The demo's IdP uses the client ID, which is why the node is called `indykiteagent-drive` too.

### 2. Tell IndyKite which tokens of your IdP to accept

IndyKite reads a token only through a **Token Introspect configuration** whose `jwt_matcher` equals the token's `iss` and `aud`. Two kinds of token reach the platform from a gateway, and each issuer and audience pair needs its own configuration:

- The **Bearer token of the request**, sent to `whoami`. For a direct call to the Drive gateway that is millicent's login token, with the audience your IdP writes for the chatbot's login client (`chatbot-mcp` in the demo).
- The **delegation token** the IdP mints for this gateway, sent in `X-IK-Token` on the admission call. Its audience is the gateway's client, `indykiteagent-drive`.

On the longer chains, the Bearer token at the Drive gateway is the delegation token of the previous gateway, so those audiences (`indykiteagent`, `indykiteagent-4`) need a configuration as well. The canbank dataset carries one per audience. The `ikg_node_type` is the node type `whoami` answers with, and therefore the subject type of the policy in step 5. Created with Service Account credentials:

```json
POST /configs/v1/token-introspects
Authorization: Bearer <service-account-token>
{
  "project_id": "<PROJECT_GID>",
  "name": "canbank-delegated-indykiteagent-drive",
  "display_name": "CanBank delegated token (Drive MCP gateway)",
  "jwt_matcher": {
    "issuer": "<issuer of your IdP, exactly as in the iss claim>",
    "audience": "indykiteagent-drive"
  },
  "offline_validation": {},
  "ikg_node_type": "User"
}
```

Check a token the way the gateway will: `GET /contx-iq/v1/whoami` with the AppAgent credential in `X-IK-ClientKey` and `Authorization: Bearer $TOKEN`. The answer `{"type": "User", "id": "millicent"}` means the gateway will resolve it too; a `401` means no configuration matches that token.

### 3. Create the nodes

Via the Capture API (`POST /capture/v1/nodes`, AppAgent credential in `X-IK-ClientKey`) - one `Workflow` and one `Agent`. The user, `millicent`, is already in the canbank dataset as a `User` identity node whose `external_id` equals the `sub` of her token:

```json
{
  "nodes": [
    {
      "external_id": "wf-drive",
      "type": "Workflow",
      "is_identity": false,
      "properties": []
    },
    {
      "external_id": "indykiteagent-drive",
      "type": "Agent",
      "is_identity": false,
      "properties": []
    }
  ]
}
```

### 4. Create the relationships

Via `POST /capture/v1/relationships`. Two relationships matter: the **grant** (who may trigger the workflow) and the **chain** (which agent the workflow invokes). Every `INVOKES` relationship in a chain must carry a `workflow_name` property equal to the workflow's `external_id` - the admission policy filters on it at every hop, so a chain without it admits no request.

```json
{
  "relationships": [
    {
      "source": {
        "type": "User",
        "external_id": "millicent"
      },
      "target": {
        "type": "Workflow",
        "external_id": "wf-drive"
      },
      "properties": [],
      "type": "CAN_TRIGGER"
    },
    {
      "source": {
        "type": "Workflow",
        "external_id": "wf-drive"
      },
      "target": {
        "type": "Agent",
        "external_id": "indykiteagent-drive"
      },
      "properties": [
        {
          "type": "workflow_name",
          "value": "wf-drive"
        }
      ],
      "type": "INVOKES"
    }
  ]
}
```

In the demo dataset only `millicent` gets this grant. Every other user is denied at the gateway - that asymmetry is the demo.

### 5. Create the admission policy

One KBAC policy answers the gateway's question "may this subject reach this agent through this chain?". It is generic over all workflows and all gateways - if you already provisioned it for other gateway instances, there is nothing to add; `wf-drive` is covered the moment it exists in the graph. The demo names it `user-can-reach-agent`:

```json
{
  "meta": {
    "policy_version": "2.0-kbac"
  },
  "subject": {
    "type": "User"
  },
  "actions": [
    "CAN_TRIGGER"
  ],
  "resource": {
    "type": "Agent"
  },
  "condition": {
    "cypher": "MATCH (subject:User)-[:WORKS_IN|CAN_TRIGGER*..3]->(wf:Workflow) MATCH (wf)-[rels:INVOKES*]->(resource:Agent) WHERE ALL(r IN rels WHERE r.workflow_name = wf.external_id AND endNode(r):Agent) AND [r IN rels | endNode(r).external_id] = $ik_token.act_chain"
  }
}
```

Read the condition line by line:

- **First `MATCH`** - the subject can trigger a workflow, directly (`User -CAN_TRIGGER-> Workflow`, millicent's relationship from step 4) or through their department (`User -WORKS_IN-> Department -CAN_TRIGGER-> Workflow`).
- **Second `MATCH`** - that workflow's `INVOKES` path ends at the resource, the agent this gateway protects.
- **`WHERE`** - every hop of the path belongs to this workflow (`workflow_name`), and the agents on the path, in order, equal `$ik_token.act_chain`: the chain of the delegation token the gateway sent in `X-IK-Token`.

So the policy sees both worlds at once: the chain your IdP wrote into the token, and the chain you modelled in the graph. Create it with `POST /configs/v1/authorization-policies` (Service Account credentials; the policy above as a JSON string in `policy`, `status` `ACTIVE`). The policy's subject type must be the `ikg_node_type` of step 2: a user whose token matches a configuration with another type, such as `Person`, needs a policy for that type.

Replay the gateway's question by hand to test the model, with a delegation token of the Drive hop in `X-IK-Token`:

```json
POST /access/v1/evaluation
X-IK-ClientKey: <app-agent-credentials-token>
Authorization: Bearer <millicent's token>
X-IK-Token: <delegation token of the Drive hop>
{
  "subject": {
    "type": "User",
    "id": "millicent"
  },
  "action": {
    "name": "CAN_TRIGGER"
  },
  "resource": {
    "type": "Agent",
    "id": "indykiteagent-drive"
  }
}
```

```json
{
  "decision": true
}
```

Admission is not the dataset&#x27;s only policy. It also provisions `user-can-trigger-workflow` (subject `User`, action `CAN_TRIGGER`, resource `Workflow`, condition `MATCH (subject:User)-[:WORKS_IN|CAN_TRIGGER*..3]->(resource:Workflow)`), which the chatbot uses for the grant button of chapter 8, the capability policies `user-can-use-*` of chapter 6, and `user-can-retrieve-quote` (`2.0-kbac`): subject `User`, action `CAN_RETRIEVE`, resource `Quote` (id `stock_quote`), condition `MATCH (subject:User)-[:WORKS_IN]->(department:Department)-[:CAN_RETRIEVE]->(resource:Quote)`. Only the `trading` department holds the `CAN_RETRIEVE` relationship, and `millicent` works in both `support` and `trading` - this is what powers the stock-quote and AuthZEN prompts in chapter 7.

### One workflow per call shape

A workflow holds **exactly one agent chain**, and the policy wants the request's chain to equal it. If the same protected agent should be reachable through several different chains - directly, via another agent, via a console orchestrator - model each shape as its own workflow. The demo wires four:

| Workflow | Chain | Used by |
| --- | --- | --- |
| `wf-drive` | `indykiteagent-drive` | Direct MCP calls to the Drive gateway (chapter 7). |
| `wf-drive-analyst` | `indykiteagent-4 → indykiteagent-drive` | A prompt to the analyst agent, which calls Drive as an MCP backend. |
| `wf-drive-console` | `indykiteagent → indykiteagent-4 → indykiteagent-drive` | The chatbot console: orchestrator → analyst → Drive. |
| `wf3-console` | `indykiteagent → indykiteagent-4 → indykiteagent-mcp` | The console-routed analyst reaching the IndyKite MCP server. |

When two workflows share an agent-to-agent hop (for example `indykiteagent-4 → indykiteagent-drive` in both the analyst and console shapes), create **parallel `INVOKES` relationships** - one per workflow - and add a `discriminating_property` property with value `workflow_name` to each, so the relationships stay distinct per workflow:

```json
{
  "source": {
    "type": "Agent",
    "external_id": "indykiteagent-4"
  },
  "target": {
    "type": "Agent",
    "external_id": "indykiteagent-drive"
  },
  "properties": [
    {
      "type": "workflow_name",
      "value": "wf-drive-analyst"
    },
    {
      "type": "discriminating_property",
      "value": "workflow_name"
    }
  ],
  "type": "INVOKES"
}
```

Grant `CAN_TRIGGER` per shape as well - in the demo, `millicent` holds it on all three `wf-drive*` workflows. A token carries the chain, not a workflow name: admission asks only whether the resulting chain is the path of a workflow the subject can trigger. Workflows that share their first agents therefore share those hops - a request that passed the orchestrator and the analyst for `wf3-console` has the chain `[indykiteagent, indykiteagent-4]`, which is also the start of `wf-drive-console`, and continuing to the Drive gateway is admitted for a subject who can trigger that workflow. A chain that is the path of no workflow the subject can trigger is refused with `403`.

### Provisioning shortcut

The [instant-stack](https://github.com/indykite/developer-hub/tree/master/instant-stack) companion app provisions everything in this chapter - and the rest of the project - from the canbank dataset (`DATASET=canbank`). Its manifest covers the application and AppAgent (with credentials), the Token Introspect configurations (one per token audience), the MCP server configuration, the graph capture (nodes and relationships, including all the `wf-drive*` workflows and `indykiteagent-drive` with their `workflow_name` / `discriminating_property` relationships, and the `search` tool node of chapter 6), the KBAC policies (admission and capability policies included), the external data resolvers, and every ContX IQ policy and knowledge query. The values it creates are where chapter 7's env values come from. A provisioning run creates what is missing and upserts the graph; it does not rewrite a configuration that already exists in the project. To change an existing policy or Token Introspect configuration, such as its `jwt_matcher.issuer`, update it through the Config API (`PUT /configs/v1/token-introspects/{id}`, `PUT /configs/v1/authorization-policies/{id}`). The Drive data is inert while the `drive` compose profile is off, so the same provisioning serves the base demo too.

The Token Introspect configurations of the dataset name the issuer of the demo's IdP. Running against your own provider, set `jwt_matcher.issuer` to your issuer and the audiences to the ones your provider writes, as in step 2.

The demo repo also carries the same data request-by-request as a Bruno collection (`bruno/iag-demo`: Token Introspect under `token-introspect`, workflow graph under `ingest/agent-workflow`, policies under `authzen`) - useful as a manual alternative or for debugging a single element.

### What comes next

Chapter 6 configures the gateway instance that enforces all of this: `drive-mcp-iag`.

## Chapter 6: Configure the drive-mcp-iag gateway

The shared settings that point every gateway at your identity provider and at IndyKite, the per-instance settings that switch IAG into MCP proxy mode in front of the Drive server, and how capability checks apply to it.

## Chapter 6: Configure the drive-mcp-iag gateway

The gateway takes its configuration from a YAML file passed with `--config`, from environment variables, or both. Every config path maps to an environment variable with the fixed `JARVIS_` prefix: uppercase the path and replace dots with underscores, so `protected_agent.protocol` becomes `JARVIS_PROTECTED_AGENT_PROTOCOL`. The demo splits the settings in two: a shared base service (`iag-base-docker.yaml`) holds what is the same for every gateway - the image, your identity provider, IndyKite - and each instance in `docker-compose.yaml` adds only what is its own.

### The image

The gateway is published as `indykite/agent-gateway` by [IndyKite on Docker Hub](https://hub.docker.com/u/indykite). All gateways of the demo share one image, named once in the env file (chapter 7):

```bash
AGENT_GATEWAY_IMAGE=indykite/agent-gateway:<version>
```

To move to a newer release, change the tag and run `docker compose pull`. On Apple Silicon, add `platform: linux/amd64` to the `iag-base` service if Docker reports a platform mismatch.

### The shared base: your IdP and IndyKite

These settings are inherited by every gateway. The first block is where an external identity provider plugs in: one base URL, three endpoint paths under it, and the issuer.

```yaml
iag-base:
  image: ${AGENT_GATEWAY_IMAGE}
  environment:
    # Your identity provider: introspects the bearer token, issues each gateway
    # its client credentials token, and mints the delegation token (RFC 8693).
    JARVIS_IDENTITY_PROVIDER_BASE_URL: "${IDP_BASE_URL}"
    JARVIS_IDENTITY_PROVIDER_INTROSPECT_ENDPOINT: "<introspection path>"
    JARVIS_IDENTITY_PROVIDER_CLIENT_CREDENTIAL_ENDPOINT: "<token path>"
    JARVIS_IDENTITY_PROVIDER_EXCHANGE_ENDPOINT: "<token path>"
    # The issuer, exactly as in the iss claim of the IdP's tokens. MCP gateways
    # name it as the authorization server in their protected resource metadata.
    JARVIS_IDENTITY_PROVIDER_ISSUER: "${IDP_ISSUER}"
    JARVIS_IDENTITY_PROVIDER_OPENID_CONFIGURATION_URL: "${IDP_ISSUER}/.well-known/openid-configuration"
    # IndyKite: whoami resolves the subject, AuthZEN takes the admission decision.
    JARVIS_CONTX_IQ_BASE_URL: ${INDYKITE_BASE_URL}/contx-iq/v1
    JARVIS_CONTX_IQ_APP_AGENT_CREDENTIALS_TOKEN: ${APP_AGENT_CREDENTIALS_TOKEN}
    JARVIS_AUTHZEN_BASE_URL: ${INDYKITE_BASE_URL}/access/v1
    JARVIS_AUTHZEN_ACTION: CAN_TRIGGER
    # Capability checks, on by default; the Drive gateway overrides this below.
    JARVIS_AUTHZEN_CAPABILITIES_ENABLED: ${IAG_CAPABILITY_CHECKS:-true}
    # How long a decision is kept per subject and chain.
    JARVIS_AUTHZEN_CACHE_TTL: ${IAG_AUTHZEN_CACHE_TTL:-30s}
    JARVIS_AUTHZEN_CACHE_UPDATE_AFTER: ${IAG_AUTHZEN_CACHE_TTL:-30s}
```

The repo's file carries the endpoint paths and default URLs of the demo's own IdP. With another provider, set `IDP_BASE_URL` and `IDP_ISSUER` in the env file and replace the three endpoint paths with your provider's; the gateway authenticates to all three with HTTP Basic client authentication. Two more places name the provider. The chatbot's login: its `ID_SERVER_AUTHORIZE_ENDPOINT` and `ID_SERVER_TOKEN_ENDPOINT` in `docker-compose.yaml`, and the logout address it builds in `chatbot/app.py`, which is the demo provider's own. And the project's Token Introspect configurations, whose issuer and audiences must be your provider's (chapter 5). Note what is **not** here: no workflow setting and no subject type. The subject type comes from `whoami`, and which workflows a gateway serves is decided by the admission policy alone.

### The compose service

```yaml
drive-mcp-iag:
  extends:
    service: iag-base
    file: iag-base-docker.yaml
  profiles: ["drive"]
  ports:
    - "${IAG_DRIVE_MCP_PORT:-8887}:${IAG_DRIVE_MCP_PORT:-8887}"
  networks:
    - drive-mcp-iag-network
  environment:
    JARVIS_SERVICE_NAME: drive-mcp-iag
    JARVIS_SERVICE_PORT: ${IAG_DRIVE_MCP_PORT:-8887}
    # Switch from the default "a2a" proxy into MCP proxy mode.
    JARVIS_PROTECTED_AGENT_PROTOCOL: mcp
    # The public MCP endpoint at the gateway, and the MCP endpoint of the
    # Drive server it forwards to. Both are full URLs, path included.
    JARVIS_SERVICE_BASE_URL: http://${IAG_DRIVE_MCP_HOST:-drive-mcp-iag}:${IAG_DRIVE_MCP_PORT:-8887}/mcp
    JARVIS_PROTECTED_AGENT_BASE_URL: http://${DRIVE_MCP_HOST:-drive-mcp}:8000/mcp
    # Admission only on this gateway; see "Capability checks" below.
    JARVIS_AUTHZEN_CAPABILITIES_ENABLED: ${IAG_DRIVE_CAPABILITY_CHECKS:-false}
    JARVIS_PROTECTED_AGENT_AUTHENTICATION_CLIENT_ID: ${DRIVE_MCP_IDP_CLIENT_ID:-indykiteagent-drive}
    JARVIS_PROTECTED_AGENT_AUTHENTICATION_CLIENT_SECRET: ${DRIVE_MCP_IDP_CLIENT_SECRET:-}
  # Audit delivery is configured per instance via a mounted config file.
  volumes:
    - ./audit-config.yaml:/app/.configs/audit-config.yaml
  command: ["--config=/app/.configs/audit-config.yaml"]
```

### The per-instance fields

| Setting | Value for this instance |
| --- | --- |
| `service.name` | `drive-mcp-iag` - also stamped on every audit record. |
| `service.port` | `8887`. |
| `protected_agent.protocol` | `mcp`. |
| `service.base_url` | `http://drive-mcp-iag:8887/mcp` - the public URL of the MCP endpoint at the gateway. Its path, `/mcp`, is the one path the gateway serves; every other path answers `404`. It is also the `resource` of the gateway's OAuth protected resource metadata. |
| `protected_agent.base_url` | `http://drive-mcp:8000/mcp` - the full URL of the Drive server's MCP endpoint, not its address alone. |
| `protected_agent.authentication.client_id` / `client_secret` | The `indykiteagent-drive` IdP client from chapter 5. |
| `authzen.capabilities.enabled` | `false` through `IAG_DRIVE_CAPABILITY_CHECKS`: this gateway decides on admission alone. |

A gateway in MCP mode does not start without `service.base_url`, `protected_agent.base_url` and `identity_provider.issuer`; when one is missing or invalid, the gateway's log names it. **Audit delivery** comes from the mounted `audit-config.yaml` shown above - the same file every gateway in the demo mounts; without an `audit` section in a config file the instance writes no audit records, and chapter 8 has nothing to read.

**Decision caching:** each gateway keeps its admission decisions and permitted sets per subject and delegation chain for `authzen.cache_ttl`, which the demo sets to 30 seconds through `IAG_AUTHZEN_CACHE_TTL`. The practical consequence: a `CAN_TRIGGER` relationship added or removed in the graph (chapter 8's grant/revoke flow) reaches a gateway's decisions within that window - or immediately after restarting the affected gateways (`docker compose restart orchestrator-iag analyst-iag drive-mcp-iag`). The platform's own AuthZEN answers change at once; only the gateway cache lags.

### .env entries

These go into the usecase's env file, `.env.canbank` - the demo keeps one complete env file per usecase and symlinks `.env` to the active one (chapter 7).

```bash
# The gateway image for all gateways.
AGENT_GATEWAY_IMAGE=indykite/agent-gateway:<version>
# Your identity provider: base URL of its OAuth endpoints, and its issuer
# exactly as written into the iss claim of its tokens.
IDP_BASE_URL=<idp-base-url>
IDP_ISSUER=<idp-issuer>
# Include the two drive services in a plain `docker compose up`
# (equivalent to `docker compose --profile drive up`); leave empty for the base demo.
COMPOSE_PROFILES=drive
# IdP client for drive-mcp-iag's client-credentials / token-exchange flow.
DRIVE_MCP_IDP_CLIENT_ID=indykiteagent-drive
DRIVE_MCP_IDP_CLIENT_SECRET=<secret from your IdP>
# Capability checks of the Drive gateway; false = admission only (see below).
IAG_DRIVE_CAPABILITY_CHECKS=false
# Optional: how long a gateway keeps a decision before asking IndyKite again,
# i.e. how fast a grant or revoke reaches the gateways (default 30s).
IAG_AUTHZEN_CACHE_TTL=30s
# Read by the chatbot only, for its "why?" cards; leave empty for Drive.
DRIVE_WORKFLOW_ID=
# Give the analyst agent both MCP backends (alias=url pairs). Write the
# project gid unencoded (gid:..., not gid%3A...).
# Tool names get prefixed per backend: indykite_ciq_execute, drive_search, ...
ANALYST_MCP_SERVER_URLS=indykite=http://mcp-iag:8886/mcp/v1/<PROJECT_GID>,drive=http://drive-mcp-iag:8887/mcp
# Optional: enable the chatbot's grant/revoke buttons on DENY cards (chapter 8).
# Per gateway, the workflows one click grants (colon-separated); empty = buttons off.
# Only the chatbot reads this - the gateways take no workflow setting.
GRANT_WORKFLOW_MAP=drive-mcp-iag=wf-drive:wf-drive-analyst:wf-drive-console
# Optional: enable the "why?" buttons on audit cards (chapter 8) - the GIDs of the
# two explain queries provisioned with the canbank dataset.
EXPLAIN_STAFF_QUERY_ID=<gid-of-explain-staff-workflow-access>
EXPLAIN_DIRECT_QUERY_ID=<gid-of-explain-direct-workflow-access>
```

The env file holds secrets - client secrets, the AppAgent credentials token, an LLM key. It is gitignored in the demo; keep it out of commits, images and screenshots.

### Capability checks: off for Drive, and how to turn them on

In front of an MCP server the gateway makes a second decision beside admission, on by default: **capability checks**. It reads which tools, resources and prompts the caller may use, with one AuthZEN resource search per kind (action `CAN_USE`, resource types `Tool`, `McpResource` and `Prompt`), filters `tools/list`, `resources/list` and `prompts/list` to that permitted set, and refuses a `tools/call`, `resources/read` or `prompts/get` outside it with `403` and the JSON-RPC error `-31403`, without calling the server. Such a request gets the capability decision in place of the admission decision. The [Agent Gateway guide](/guides/guide-agent-gateway#capability-checks) has the full contract.

#### Why the demo runs Drive with the checks off

The Drive server lists its files as resources with `gdrive:///<fileId>` URIs, a set that changes with the account's Drive. With the checks on, each file a user may read would have to exist in the graph as an `McpResource` node named by that URI, or `resources/list` stays empty and `resources/read` is refused. So `IAG_DRIVE_CAPABILITY_CHECKS` defaults to `false`: admission decides who reaches Drive, and an admitted user may use everything the server offers. The audit trail of chapter 8 is unchanged by this setting. The demo's other MCP gateways, `mcp-iag` and `erp-mcp-iag`, keep the checks on.

#### Turning them on: only `search` passes

Set `IAG_DRIVE_CAPABILITY_CHECKS=true` and recreate the gateway (`docker compose up -d --force-recreate drive-mcp-iag`) to see the checks at work. The canbank dataset already models the one tool the walkthrough calls: a `Tool` node `search`, whose `external_id` is the tool name exactly as the protocol carries it, attached to `indykiteagent-drive` with one `HAS` relationship per workflow shape. Each carries the `workflow_name` that confines it to that shape and, like the parallel `INVOKES` relationships of chapter 5, a `discriminating_property` naming it, so that Capture keeps the three relationships apart instead of overwriting one with the next:

```json
POST /capture/v1/nodes
{
  "nodes": [
    {
      "external_id": "search",
      "type": "Tool",
      "is_identity": false,
      "properties": []
    }
  ]
}
```

```json
POST /capture/v1/relationships
{
  "relationships": [
    {
      "source": { "type": "Agent", "external_id": "indykiteagent-drive" },
      "target": { "type": "Tool", "external_id": "search" },
      "properties": [
        { "type": "workflow_name", "value": "wf-drive" },
        { "type": "discriminating_property", "value": "workflow_name" }
      ],
      "type": "HAS"
    },
    {
      "source": { "type": "Agent", "external_id": "indykiteagent-drive" },
      "target": { "type": "Tool", "external_id": "search" },
      "properties": [
        { "type": "workflow_name", "value": "wf-drive-analyst" },
        { "type": "discriminating_property", "value": "workflow_name" }
      ],
      "type": "HAS"
    },
    {
      "source": { "type": "Agent", "external_id": "indykiteagent-drive" },
      "target": { "type": "Tool", "external_id": "search" },
      "properties": [
        { "type": "workflow_name", "value": "wf-drive-console" },
        { "type": "discriminating_property", "value": "workflow_name" }
      ],
      "type": "HAS"
    }
  ]
}
```

The dataset's KBAC policy for the `Tool` type, `user-can-use-tool`, has the action `CAN_USE`. Its condition repeats the admission condition and ends at the tool, so a non-empty set proves admission too:

```json
{
  "meta": {
    "policy_version": "2.0-kbac"
  },
  "subject": {
    "type": "User"
  },
  "actions": [
    "CAN_USE"
  ],
  "resource": {
    "type": "Tool"
  },
  "condition": {
    "cypher": "MATCH (subject:User)-[:WORKS_IN|CAN_TRIGGER*..3]->(wf:Workflow) MATCH (wf)-[rels:INVOKES*]->(agent:Agent)-[h:HAS]->(resource:Tool) WHERE ALL(r IN rels WHERE r.workflow_name = wf.external_id AND endNode(r):Agent) AND [r IN rels | endNode(r).external_id] = $ik_token.act_chain AND h.workflow_name = wf.external_id"
  }
}
```

With the checks on, `tools/list` shows `search` to millicent and an empty list to a user without the grant, a `tools/call` of any other name is refused with `403` and `-31403` before it reaches the server, and chapter 8's trail gains a `DISCOVERY` record per list and an `INVOCATION` record per call, each with the permitted set or the tool it named. `resources/list` comes back empty and `resources/read` is refused, for millicent too: no Drive file is modelled. To allow file reads under the checks, model the files a user may read as `McpResource` nodes with their `gdrive:///<fileId>` URIs as `external_id`, attached the same way; the dataset's `user-can-use-mcp-resource` policy then covers them.

### What comes next

Chapter 7 starts the stack and runs a Google Drive search through the gateway.

## Chapter 7: Run a Google Drive search through the gateway

Start the stack, establish an MCP session against drive-mcp-iag, and execute the full-text search - by script, by hand, and by prompt.

## Chapter 7: Run a Google Drive search through the gateway

### 1. Configure the usecase env file

The demo keeps one **complete env file per usecase** (`.env.canbank`, gitignored) and `.env` is a symlink to the active one - so a switch always swaps the platform bindings, the domain vocabulary, and the agent skills together. First run only: bootstrap `.env.canbank` from the committed template and fill in the base values per the repo README, then add the entries from chapter 6 (including `AGENT_GATEWAY_IMAGE` and `COMPOSE_PROFILES=drive`). Take the project-specific values from the instant-stack provisioning output (chapter 5).

| Where it comes from | Variables |
| --- | --- |
| Your IndyKite project | `INDYKITE_BASE_URL` (the API URL of your region), `APP_AGENT_CREDENTIALS_TOKEN`, and `MCP_SERVER_ORIGIN` / `MCP_SERVER_PATH` / `MCP_SERVER_URL` for the IndyKite MCP server, with the path `/mcp/v1/<PROJECT_GID>` and the gid written unencoded (`gid:...`, not `gid%3A...`). |
| Your identity provider | `IDP_BASE_URL`, `IDP_ISSUER`, and one client ID and secret per client: `CHATBOT_IDP_*` (`console`), `ORCHESTRATOR_IDP_*`, `RETRIEVER_IDP_*`, `WEATHER_IDP_*`, `ANALYST_IDP_*`, `MCP_IDP_*` and `DRIVE_MCP_IDP_*`. The redirect URL of the `console` client must be exactly `http://localhost:3000/auth/callback`. |
| Your choice | `USECASE=canbank`, `AUTHZEN_SUBJECT_TYPES=User` (read by the chatbot, not by the gateways), an LLM for the agents (`GEMINI_ENABLED=true` with `GEMINI_API_KEY`, or a local Ollama through `OLLAMA_HOST`), and a fresh `FLASK_SECRET_KEY`. |

```bash
cd a2a/iag-mcp-demo
cp .example.env .env.canbank
# edit .env.canbank: base demo values per the repo README + the chapter 6 entries
ln -sf .env.canbank .env      # .env is a symlink to the active usecase's file
```

Later, `./switch-usecase.sh canbank` does the same relink and recreates whatever changed in one step. `USECASE=canbank` selects the usecase bundle `usecases/canbank/`: its `usecase.env` feeds every agent the CanBank vocabulary (org name, knowledge-query names such as `get-stock-quote` and `get-hq-weather`, the weather HQ keywords), and its `skills/<agent>` folders are mounted read-only into the orchestrator, retriever, and analyst - including the dataset-specific `canbank-authz` skill with the exact KBAC vocabulary.

Two optional `.env` entries tune the agents. `MCP_SESSION_TTL` is how long, in seconds, an agent reuses each user&#x27;s MCP session against the gateway before rebuilding it - keep it below the access-token lifetime, or set `0` for a fresh session per request. `LIB_LOG_LEVEL` sets the log level of the agents&#x27; third-party libraries independently of `LOG_LEVEL` - keep it at `INFO` or `WARNING` for readable agent logs, or set `DEBUG` to see the SDK events as one-line breadcrumbs.

### 2. Build and start the stack

```bash
make                   # builds the chatbot and agent images
make new-drive-mcp     # builds the drive-mcp image (chapter 4)
docker compose pull    # fetches indykite/agent-gateway from Docker Hub
docker compose up -d   # COMPOSE_PROFILES=drive in .env.canbank adds the two drive services
docker compose ps
```

The chatbot, agent and Drive server images are built locally and never pushed; only the gateway image comes from [IndyKite on Docker Hub](https://hub.docker.com/u/indykite). A change to the env file reaches a container only when it is recreated (`docker compose up -d --force-recreate <service>`); `docker compose restart` does not re-read it.

With the `drive` profile enabled expect **12 containers** - the 10 base services plus the `drive-mcp` / `drive-mcp-iag` pair; fewer means the profile didn't activate. (The demo's other optional profiles, `crm` and `erp`, add further containers - chapter 8's "Beyond Drive" section covers what they do.) Confirm the drive pair and prove the gateway is enforcing:

```bash
docker compose logs drive-mcp | tail        # the wrapped server is listening on :8000, endpoint /mcp
docker compose logs drive-mcp-iag | tail    # the gateway is listening on :8887
curl -s -X POST http://localhost:8887/mcp -H "Content-Type: application/json" -d '{}'
# {"message":"Missing bearer token"}   <- alive and enforcing (chapter 2)
curl -s http://localhost:8887/.well-known/oauth-protected-resource/mcp
# {"resource":"http://drive-mcp-iag:8887/mcp","authorization_servers":["<idp-issuer>"],"bearer_methods_supported":["header"]}
```

The second call needs no token: it is the gateway's OAuth protected resource metadata, and `authorization_servers` must show the issuer of **your** IdP. A gateway that exited at start names the missing or invalid setting in its log.

### 3. Get an authorized user token

Open `http://localhost:3000` (use `localhost`, not `127.0.0.1`) in a fresh incognito window and log in as **millicent** - the one user granted `CAN_TRIGGER` on `wf-drive` in chapter 5. The chatbot sends you to your IdP's login page and comes back with an access token. She must exist as a login user in your IdP, with a token `sub` equal to her node's `external_id`; if she does not, either create her there or grant your own login user the `CAN_TRIGGER` relationships instead. The demo's test scripts extract the logged-in user's access token from the chatbot session automatically; for the manual calls below, export it as `TOKEN`. Tokens are short-lived, so run the calls soon after logging in.

### 4. The script version

```bash
./test-drive.sh                       # initialize → tools/list → resources/list → search, as millicent
DRIVE_QUERY=budget ./test-drive.sh    # different search term
./test-drive.sh <user>                # as a different logged-in user
```

### 5. The manual version

An MCP session against the gateway, step by step. All requests go to the **gateway** (`:8887/mcp`), never to the Drive server directly:

```bash
DRIVE="http://localhost:8887/mcp"
H=(-H "Authorization: Bearer $TOKEN" -H "Content-Type: application/json" \
   -H "Accept: application/json, text/event-stream")
# 1. initialize - capture the MCP session id from the response headers
SID=$(curl -s -D - -o /dev/null "${H[@]}" -X POST $DRIVE \
  -d '{
  "jsonrpc": "2.0",
  "id": 1,
  "method": "initialize",
  "params": {
    "protocolVersion": "2025-11-25",
    "capabilities": {},
    "clientInfo": {
      "name": "demo",
      "version": "1.0"
    }
  }
}' \
  | grep -i mcp-session-id | tr -d '\r' | awk '{print $2}')
echo "session: $SID"      # a UUID; empty means check the token or the gateway logs
# every request after initialize must name the negotiated revision
S=(-H "Mcp-Session-Id: $SID" -H "Mcp-Protocol-Version: 2025-11-25")
# 2. initialized notification (expect HTTP 202)
curl -s -o /dev/null -w "initialized -> HTTP %{http_code}\n" "${H[@]}" "${S[@]}" -X POST $DRIVE \
  -d '{
  "jsonrpc": "2.0",
  "method": "notifications/initialized",
  "params": {}
}'
# 3. list the Drive server's tools (expect: search)
curl -s "${H[@]}" "${S[@]}" -X POST $DRIVE \
  -d '{
  "jsonrpc": "2.0",
  "id": 2,
  "method": "tools/list",
  "params": {}
}'
# 4. the search - full-text over the authorized account's Drive
curl -s -m 45 "${H[@]}" "${S[@]}" -X POST $DRIVE \
  -d '{
  "jsonrpc": "2.0",
  "id": 3,
  "method": "tools/call",
  "params": {
    "name": "search",
    "arguments": {
      "query": "canbank"
    }
  }
}'
```

The gateway forwards only MCP protocol revisions `2025-06-18`, `2025-11-25`, and `2026-07-28`. The Drive reference server does not speak the stateless `2026-07-28` revision (it rejects `server/discover`), so this walkthrough uses `2025-11-25`, the newest revision an `initialize` handshake can agree on; an `initialize` naming an older revision is forwarded with `2025-11-25` instead. Every request after the handshake must carry `Mcp-Protocol-Version`, or the gateway refuses it with `400` and the JSON-RPC error `Header mismatch: Mcp-Protocol-Version header is missing`. That is why the `S` array above carries the header on every call.

What steps 3 and 4 answer depends on `IAG_DRIVE_CAPABILITY_CHECKS` (chapter 6). With the checks off, the demo's default, admission alone decides every request: millicent gets the server's own answers, and anyone else gets `403` from the first call on. With the checks on, the list holds `search` only for a user admitted on the chain and is empty otherwise, and a `tools/call` naming anything else answers `403` with the JSON-RPC error `-31403` without reaching the server.

Expected result of the search - lines of `<fileId> <name> (<mimeType>)`; your files will differ, and matches are files whose *content* mentions the query; for example:

```text
Found 3 files:
1AbC...xYz Financial report (application/vnd.google-apps.document)
1DeF...uVw Retail campaign (application/vnd.google-apps.document)
1GhI...rSt video1.mp4 (video/mp4)
```

Cross-check: open drive.google.com as the authorized Google account and type the same query into the search bar - same files. Between steps, note what just happened: the gateway had your IdP introspect millicent's token and exchange it for a delegation token with the chain `[indykiteagent-drive]`, asked IndyKite whether `User/millicent` may reach `Agent/indykiteagent-drive` through that chain, audited the decision, swapped in the delegation token, and streamed the Drive server's response back - while the `Mcp-Session-Id` minted downstream flowed through untouched.

### 6. The prompt versions (optional)

The same authorization guards the longer chains modeled in chapter 5:

- **Via the analyst** (`wf-drive-analyst`): with `ANALYST_MCP_SERVER_URLS` set (chapter 6), send the analyst gateway (`:8885`) an A2A `message/send` with a prompt like *"Search Google Drive for canbank"* - the analyst then calls Drive as one of its MCP backends. Cross-backend prompts work too: *"Search Google Drive for canbank, then check which internal policy documents mention the same topics."* (The repo's `./demo-analyst-drive.sh` is a related smoke test: it sends the analyst a hello message and then runs the *direct* Drive search from step 5.)
- **Via the chatbot console** (`wf-drive-console`): as millicent, type *"Search Google Drive for canbank and list the matching files"* at `http://localhost:3000`. Mentioning **"Google Drive"** (or "Drive") in the prompt is what routes it to the orchestrator's `query_drive` tool instead of the retriever - a prompt like *"search my files for canbank"* silently goes to the retriever. Every hop - orchestrator, analyst, Drive - passes its own gateway and leaves its own audit record.

Prompt tips: Drive search is full-text, so to target a specific file prefer listing then reading (*"Read the file 'X' from Google Drive and summarize it"*), and point read prompts at Google-native documents or PDFs - the only formats that come back as readable text (chapter 4). For workflow prompts, **name the agent** (*"Use the retriever to …"*, *"Ask the retriever for …"*) so the orchestrator actually delegates instead of answering itself. Stock-quote prompts fetch live market data; an occasional `429 Too Many Requests` is upstream rate-limiting, not an authorization failure - retry after a few minutes.

### 7. Prompts by persona

The graph gives every demo user different access, so the same prompt can succeed for one login and be denied - or return nothing - for another. That asymmetry *is* the demo. Switch personas with a fresh incognito window per user. The repo's scripted tour of these prompts lives in `usecases/canbank/DEMO_SCRIPT.md`. Chatbot console prompts:

| Persona (access) | Prompts that work | What is denied |
| --- | --- | --- |
| `millicent` - support + trading depts; `wf1`, `wf3`, all `wf-drive*` | Everything leslie can, plus the star turn: *"Search Google Drive for canbank and list the matching files."*, *"List the files in my Google Drive."*, *"Read the file 'X' from Google Drive and summarize it."* Trading membership adds stock and AuthZEN prompts: *"What is the price of META?"*, *"Am I allowed to retrieve a stock quote? Check with authzen."* (decision `true`). | Asking authzen about a *different* user (e.g. subject `roy`) returns `false` by design - see the note below the table. |
| `leslie` - support dept → `wf1`, `wf2` | *"Use the retriever to find internal policy documents about refunds."*, *"Ask the retriever which past decisions incorporated the refund_policy document."*, *"What's the weather in London?"* | Drive and analyst calls → `403`; stock prompts return nothing, and *"Am I allowed to retrieve a stock quote?"* answers `false` - support holds no `CAN_RETRIEVE` relationship. |
| `roy` - trading dept → `wf1` | *"Use the retriever to get the NVDA stock price."*, *"Ask the retriever how many shares of NVDA the customer rebecca can purchase."*, *"Am I allowed to retrieve a stock quote? Check with authzen."* (decision `true`). | Drive and analyst calls → `403` - which makes roy the demo's grant-flow persona: chapter 8's deny → remediate → allow beat grants him Drive access with one click and revokes it again. |
| `carol` - `wf1` only | Normal `wf1` prompts (as leslie). | The designated deny persona: millicent's exact analyst and Drive requests with carol's token → `403`. The "same request, different user, different outcome" money shot. |
| `jane` - `wf2` only | Weather prompts: *"What's the weather in London?"*, *"What's the weather at CanBank HQ?"* The HQ variant goes through the `get-hq-weather` knowledge query and its weather resolvers only when `CIQ_QUERY_HQ_WEATHER` and that setup exist; otherwise weather prompts fall back to direct Open-Meteo. | All `wf1` flows → `403` - she cannot trigger the orchestrator workflow. |
| `joe` - plain `wf1` | Baseline `wf1` prompts; handy as the default subject for a direct AuthZEN `CAN_TRIGGER` evaluation. | Analyst and Drive → `403`. |

Note the three kinds of "no" in the table: a `403` is a **gateway** refusing admission, because no workflow that user can trigger has the request's chain; an empty result is **data-level** scoping inside an authorized workflow (the retriever's queries respect department reach); an AuthZEN decision of `false` is a **policy** answer delivered inside an authorized workflow - leslie asking about the stock quote gets a clean `false`, not an error. One more `false` is by design rather than policy: evaluations through the chatbot carry the logged-in user's token, and the platform binds them to that token's subject - asking about a *different* user always returns `false`, regardless of that user's real permissions. Evaluate other subjects from a service context instead (the repo's Bruno `authzen` folder, `X-IK-ClientKey` app token).

When writing your own AuthZEN prompts or agents, use the policy vocabulary exactly: types, actions, and ids are case-sensitive graph terms (`User`, `CAN_RETRIEVE`, `Quote`, `stock_quote`). A guessed value such as `user`, `view`, or `stock` evaluates to a `false` indistinguishable from a real denial, and the MCP server's `list_resources` returns only knowledge queries, not policy vocabulary - so the demo agents carry the exact triples as agent skills; give your own agents the vocabulary the same explicit way.

The customer in the stock prompts, `rebecca`, is data in the graph, not a login. Which personas can actually *log in* depends on your IdP - the graph side comes from the chapter 5 ingest; if a persona cannot log in, create them in the IdP or grant your login user the equivalent relationships.

### What comes next

A successful search is only half the story. Chapter 8 proves the denials and reads the audit trail.

## Chapter 8: Verify denials and read the audit trail

Force NOT_AUTHORIZED outcomes on purpose, read the audit records, and fix the common failure modes.

## Chapter 8: Verify denials and read the audit trail

Confidence in an enforcement point comes from watching it say no. Tail the gateway while you test:

```bash
docker compose logs -f drive-mcp-iag
```

### The money shot: same request, different user

Log in as any user other than millicent (fresh incognito window) and repeat chapter 7's calls - `./test-drive.sh leslie`, or the manual sequence with that user's token. Every request now returns:

```json
HTTP 403
{
  "message": "Authorization check failed"
}
```

Only millicent holds `CAN_TRIGGER` on `wf-drive` in the graph. Nothing else changed: same gateway, same MCP server, same request body - different subject, different decision. The identity provider did its part for both users alike: the token was active and the exchange succeeded. The refusal is IndyKite's answer about the graph. (With `IAG_DRIVE_CAPABILITY_CHECKS=true`, the same user gets an empty `tools/list` and the JSON-RPC error `-31403` on the `tools/call` instead - chapter 6.)

### Other denial paths worth forcing once

- **Arrive through the wrong agents** - call the Drive gateway with a delegation token that passed an agent no Drive workflow contains, for example one from the retriever hop, with the chain `[indykiteagent, indykiteagent-2]`: the exchange appends the Drive client, and `[indykiteagent, indykiteagent-2, indykiteagent-drive]` is the path of no workflow → `403`. A token whose chain is the start of a Drive workflow, such as `[indykiteagent, indykiteagent-4]`, is not a denial case: it continues along `wf-drive-console` for a subject who can trigger it.
- **Break the model** - remove the `workflow_name` property from the `INVOKES` relationship: the admission policy no longer matches the path → `403`.
- **Revoke the grant** - delete the `CAN_TRIGGER` relationship: AuthZEN answers no → `403`, once the gateway's cached decision expires.
- **Call another path** - `POST http://localhost:8887/` instead of `/mcp` → `404` `{"message":"Not Found"}`, before the token is read.

### Deny → remediate → allow: the grant button

Authorization is data, and the demo makes that literal. With `GRANT_WORKFLOW_MAP` set (chapter 6), a red **NOT AUTHORIZED** card from the Drive gateway in the chatbot's audit terminal carries a button that depends on who is looking: the denied person sees **request access** on their own card, people who can grant see **grant access** on other people's cards. Every console receives every audit card, so keep millicent logged in and open a second browser as roy. The scripted beat:

1. roy: *"List the files in my Google Drive."* → red NOT AUTHORIZED card from `drive-mcp-iag`, in both consoles.
2. roy clicks **request access** on his card → the request lands in millicent's access requests inbox on the Support page. He cannot self-serve: the grant is guarded by a live AuthZEN self-check (policy `user-can-trigger-workflow`, chapter 5) - it only proceeds when the *logged-in* user can `CAN_TRIGGER` every workflow in the bundle themselves, and answers `403` to anyone else.
3. millicent clicks **grant access** on the same card in her console, or **Grant** on the inbox item (she holds the drive workflows) → a Capture API upsert writes `roy -CAN_TRIGGER-> wf-drive*` relationships, and the why? graph shows the new path immediately.
4. roy repeats the prompt → **green**, the real Drive listing - once the gateways' cached decisions expire (about 30 seconds with the demo's `IAG_AUTHZEN_CACHE_TTL`, or restart the gateways: `docker compose restart orchestrator-iag analyst-iag drive-mcp-iag`).
5. millicent clicks **revoke access** (a Capture delete of the same relationships) → after the same cache window, roy is red again. The beat is repeatable.

Nothing but graph relationships changed between the red and green runs - same gateways, same MCP server, same prompt.

### Explain the decision: the why? cards

With `EXPLAIN_STAFF_QUERY_ID` and `EXPLAIN_DIRECT_QUERY_ID` set (chapter 6), every AUTHORIZED / NOT AUTHORIZED card also carries a **why?** button that renders the authorization path behind the decision, live from the graph: the staff leg (`Subject -WORKS_IN-> Department -CAN_TRIGGER-> Workflow`) and the direct leg (`Subject -CAN_TRIGGER-> Workflow`). A denial renders as the two nodes with *no connecting path* - the graph shows why not. The two explain queries ship with the canbank dataset; because they run live, a grant or revoke changes the picture on the next click. An audit record names the delegation chain, not a workflow, so the chatbot takes the workflow to explain from the gateway's grant bundle (`GRANT_WORKFLOW_MAP`).

Each gateway card also shows what the record says: a tag with the action (`admission`, `discovery`, `invocation`, or `refused early`), a **chain** line with the delegation chain, the reason, and a TOKEN card with the delegation token your IdP minted for that hop - the user as subject, the gateway clients as actors.

### Reading the audit records

Every decision emits one record on the audit stream configured in the mounted audit config (chapter 6), written before the request is forwarded: delivered either to a **webhook** (`audit.delivery: webhook` plus the target URL and auth) or to a **file** (`audit.delivery: file` with a storage path, `csv`/`json`/`txt` format, and size- or time-based rotation). The demo posts records to a webhook on the chatbot, which displays them live. millicent's direct search of chapter 7 leaves this record:

```json
{
  "decision": "AUTHORIZED",
  "reason": "subject User/millicent may reach Agent/indykiteagent-drive through the delegation chain",
  "subject": "millicent",
  "actor": "indykiteagent-drive",
  "action": "ADMISSION",
  "service": "drive-mcp-iag",
  "timestamp": "2026-09-30T09:12:00.123456789Z",
  "traceID": "4bf92f3577b34da6a3ce929d0e0e4736",
  "cached": {
    "admission": false
  },
  "actorsChain": [
    "indykiteagent-drive"
  ]
}
```

| Field | Meaning |
| --- | --- |
| `action` | The question the record answers. `ADMISSION`: may the subject reach the protected server through the delegation chain. `DISCOVERY` and `INVOCATION`: the capability decisions for a list and for a call, written only with capability checks on. `noop`: the request was refused before any question was asked, for example for a missing token. |
| `decision` | `AUTHORIZED`, `NOT_AUTHORIZED` for every refusal including an MCP refusal, or `ERROR` when the identity provider or IndyKite could not be consulted, so an outage is never counted as a denial. |
| `reason` | Human-readable explanation. On admission, `subject User/millicent may reach Agent/indykiteagent-drive through the delegation chain`, or on denial `subject User/leslie may not reach Agent/indykiteagent-drive through the delegation chain`. The reason names the subject `whoami` resolved and the chain, never a workflow. Refusals before the decision read `no bearer token`, `cannot introspect the subject token`, `cannot resolve the subject of the access token`, or `MCP request refused: <message>`. |
| `subject` | The end user the request acts for (e.g. `millicent`). |
| `actor` / `actorsChain` | The last agent of the chain and the full ordered delegation chain from the token's `act` claim, oldest first. |
| `cached` | Whether the answer came from the gateway's cache or from IndyKite during the request. |
| `permittedSet`, `discovery`, `capabilities` | Only on capability records: the set a list was filtered to, how many entries the server listed and the caller kept, and the tool or resource a call named. |
| `service` | The gateway instance that decided (`drive-mcp-iag`) - how you tell the hops apart in a multi-gateway chain. |
| `timestamp` / `traceID` | RFC 3339 UTC time and the trace ID also found in the gateway's logs. |

On a console-path request (chapter 7, `wf-drive-console`) you should see `AUTHORIZED` records from every gateway the request traversed - orchestrator, analyst, and Drive - each with an `actorsChain` one client longer: `[indykiteagent]`, `[indykiteagent, indykiteagent-4]`, `[indykiteagent, indykiteagent-4, indykiteagent-drive]`. The full record contract is in the [Agent Gateway guide](/guides/guide-agent-gateway#audit).

### Troubleshooting

| Symptom | Cause / fix |
| --- | --- |
| `401 Missing bearer token` on your own calls | Token missing or expired - tokens are short-lived; log in again and re-export `TOKEN`. |
| `401` with `"errors": ["identity provider: the token is not active"]` | The IdP reports the token expired or unknown. Log in again; if it persists, check that the chatbot and the gateways use the same IdP instance (`IDP_BASE_URL`) and the introspection path in `iag-base-docker.yaml`. |
| `401` or `403` with `"errors": ["identity provider: client credentials grant failed - …"]` or `["identity provider: token exchange failed - …"]` | The IdP refused the gateway's own client: a wrong `DRIVE_MCP_IDP_CLIENT_SECRET`, or the `indykiteagent-drive` client is not allowed the client credentials grant or the token exchange (chapter 5). The audit record says `ERROR`. |
| `401` with `"errors": ["ContX IQ whoami failed"]` | No Token Introspect configuration matches the issuer and audience of the token the gateway received - at a gateway behind an agent, that can be the IdP's delegation token rather than the login token. Call `GET /contx-iq/v1/whoami` with the same token and add the missing configuration (chapter 5). |
| `403` for a user you expected to pass | The admission policy answered no. Compare the record's `actorsChain` with the workflow's `INVOKES` path in the graph: the agents' `external_id` must equal the client names your IdP writes into the chain, every hop needs its `workflow_name`, and the subject needs a `CAN_TRIGGER` path to that workflow - re-run the ingest from chapter 5. A chain shorter than expected means the IdP's token exchange does not nest the previous `act` claim. Also check the type in the audit reason (`subject <type>/<id> ...`): it comes from the Token Introspect configuration, and a KBAC policy for another type never matches. Replay the evaluation of chapter 5 by hand to see the platform's answer. |
| `401` or `403` with `"errors": ["evaluating admission through AuthZEN failed"]` | IndyKite refused the AppAgent credential, or cannot read the delegation token in `X-IK-Token`: no Token Introspect configuration matches its issuer and the audience `indykiteagent-drive` (chapter 5). The audit record says `ERROR`. |
| Empty `tools/list`, or `403` with JSON-RPC `-31403` on `tools/call`, for a user you expected to pass | Capability checks are on (`IAG_DRIVE_CAPABILITY_CHECKS=true`) and the Drive server's tool is not in the caller's permitted set: nothing is modelled, the `HAS` relationship lacks the `workflow_name` of the shape in use, or the `CAN_USE` policy for `Tool` is missing. See chapter 6, or set the variable back to `false`; the `DISCOVERY` record in the audit trail shows the `permittedSet` the gateway worked from. |
| AuthZEN decision `false` when you expected `true` | Check the vocabulary casing (`User`, `CAN_RETRIEVE`, `Quote` - a mistyped type or action evaluates `false` with no error) and the subject: evaluations carrying a user token are bound to that token's subject, so another subject always evaluates `false` - evaluate other users from a service context (`X-IK-ClientKey`). |
| Empty `Mcp-Session-Id` after `initialize` | Check `docker compose logs drive-mcp-iag drive-mcp` - usually the graph ingest or the IdP client for `indykiteagent-drive` is missing. |
| `404` on MCP methods | The client calls a path other than the gateway's one MCP endpoint, `/mcp` (chapter 6). |
| A gateway exits at start | A setting is missing or invalid, and the gateway's log names it - typically `IDP_ISSUER`, or a percent-encoded project gid in `MCP_SERVER_PATH` (write `gid:...`). |
| `manifest unknown` when pulling the gateway image | The image named in `AGENT_GATEWAY_IMAGE` does not exist for your platform. Use `indykite/agent-gateway:<version>` and, on Apple Silicon, add `platform: linux/amd64` to the `iag-base` service. |
| `pull access denied for agent-gateway` when starting the stack | The image the gateways are told to run is not on Docker Hub: it is a name that exists only where the image was loaded locally. It comes either from `AGENT_GATEWAY_IMAGE` in your shell or env file, or, when that is not set, from the demo's default. Set `AGENT_GATEWAY_IMAGE=indykite/agent-gateway:<version>` (chapter 6) and run `docker compose up -d` again. |
| A change in the env file has no effect | `docker compose restart` does not re-read it - recreate the service: `docker compose up -d --force-recreate <service>`. |
| A grant or revoke seems to have no effect | Each gateway keeps its decisions per subject and chain (30 seconds in the demo, `IAG_AUTHZEN_CACHE_TTL`, chapter 6) - wait out the window or restart the affected gateways to clear the cache. The graph and AuthZEN answers change immediately; only the gateway cache lags. |
| Search fails with `invalid_request` or credential errors | The two Google files in `drive_mcp/.gdrive/` come from different OAuth clients or are missing - redo chapter 3 step 4. |
| File reads answer "binary document" | Only Google-native files and PDFs come back as text (chapter 4); an encrypted or scanned-image PDF also falls back to base64 - convert the file to a Google Doc. |

### Beyond Drive: two more protected downstreams

The demo extends the same enforcement pattern in two optional directions. Neither is required for this tutorial, but both show where the recipe leads.

#### Graph-filtered ERP rows (compose profile `erp`)

A second non-IndyKite MCP server behind its own gateway - this time a plain **Postgres "ERP"** (one invoices table) whose rows are pre-filtered per caller by the knowledge graph before any SQL runs. Where Drive showcased MCP proxying, ERP showcases the **AuthZEN search/resource API** (enumeration) alongside the evaluate API (yes/no) used everywhere else:

```text
console → orchestrator ──query_erp──> analyst ──erp_list_invoices──> erp-mcp-iag:8889 → erp-mcp
                                                                                        │  AuthZEN search/resource:
                                                                                        │  which Invoice ids may this subject CAN_VIEW?
                                                                                        └─> SELECT ... WHERE external_id = ANY(<allowed ids>)  @ erp-db
```

The graph decides through `Department -SERVES-> Customer -HAS_INVOICE-> Invoice` (staff) and the direct `HAS_INVOICE` relationship (customers), backed by the `staff-can-view-invoice` KBAC policy. The payoff prompt is *"Show me the invoices"*: **same prompt, three row counts** - millicent (support + trading) sees all 9, leslie (support) 6, roy (trading) 3. The database knows nothing about the graph; connecting to Postgres directly shows every row unfiltered.

- **Everything ships in the canbank dataset**: the `Invoice` nodes, `SERVES`/`HAS_INVOICE` relationships, the KBAC policy, and the `wf-erp` / `wf-erp-analyst` / `wf-erp-console` workflow chains - provisioned by the same instant-stack run as chapter 5.
- **To enable**: create the `indykiteagent-erp` IdP client, then in `.env.canbank` add `erp` to `COMPOSE_PROFILES`, append `,erp=http://erp-mcp-iag:8889/mcp` to `ANALYST_MCP_SERVER_URLS`, set `ERP_TOOL_ENABLED=true` and the `ERP_MCP_IDP_CLIENT_SECRET`, and build with `make new-erp-mcp`.
- **Trust boundary**: `erp-mcp` and `erp-db` are not published to the host - only `erp-mcp-iag` reaches them. The server reads the subject from the gateway-minted delegation token; exposing it directly would let a self-crafted token read other subjects' rows.

#### Delegation into a real SaaS: Salesforce cases (compose profile `crm`)

The `crm` profile completes the picture for any usecase: the delegation chain the gateways verify can land in a **real third-party SaaS**. A staff login asks the console to open a case; the CRM agent (an A2A agent behind `crm-iag`, workflow `wf-crm`, in the demo's insurance usecase) reads the `sub` and `act` chain from the gateway-minted delegation token, exchanges a signed JWT Bearer assertion (RFC 7523) for a Salesforce access token, and creates the Case with *"Filed on behalf of <subject> via agent chain …"* in its description. `wf-crm` is staff-only, so the same prompt from a customer login ends in the familiar red DENY - and the audit terminal shows two TOKEN cards per run: the delegation token from the IdP and the (redacted) Salesforce token. Like the ERP pair, the CRM agent's port is not published to the host - only `crm-iag` reaches it, so the on-behalf-of attribution written into Salesforce always rests on a gateway-verified token.

To enable it: provision the `wf-crm` workflow in your dataset, create the `indykiteagent-crm` IdP client, set up a Salesforce Connected App with the JWT Bearer flow (digital signatures, `api` + `refresh_token/offline_access` scopes, pre-authorized profile), and fill the CRM entries in the usecase env file (`CRM_IDP_CLIENT_ID/SECRET`, `IAG_CRM_HOST`, `SF_CONSUMER_KEY`, `SF_USERNAME`, `crm` in `COMPOSE_PROFILES`). The orchestrator registers its `query_crm` tool when `CRM_HOST` is set. The repo's usecase `DEMO_SCRIPT.md` files carry the full setup walkthrough.

### Where you are now

A third-party MCP server is running behind the Agent Gateway with per-user, graph-backed authorization and a full audit trail - and the MCP server itself never changed. The same recipe applies to any MCP Streamable HTTP server: wrap it if it speaks stdio (chapter 4), model who may reach it and through which chain (chapter 5), and point one gateway instance at it (chapter 6).

---

Source: https://developer.indykite.com/tutorials/tutorial-agent-gateway-mcp