Level: Advanced ยท Stack: Python, Docker, Keycloak, AgentGateway

What you'll build

A locally-runnable security demo with three moving pieces: an MCP server exposing one safe tool and one destructive tool, Keycloak issuing OAuth2 access tokens with realm roles baked in, and AgentGateway sitting in front of the MCP server validating every token and enforcing tool-level RBAC - before a single request reaches your server code.

You'll run the exact same AI agent twice with two different identities and watch the gateway make two different decisions:

Learning objectives

By the end you'll be able to:

sequenceDiagram participant A as AI Agent (agent_demo.py) participant K as Keycloak (:8080) participant G as AgentGateway (:3000) participant M as MCP Server (:9000) A->>K: 1. POST /token (client_credentials grant) K-->>A: JWT access token (realm_access.roles) A->>G: 2. POST /mcp + Bearer JWT (get_customer_summary) Note over G: 3. Validate JWT via JWKS and check RBAC rules G->>M: 4. Forward tools/call: get_customer_summary("cust_8819") M-->>G: Customer summary result G-->>A: 200 OK (Active status, standard tier) A->>G: 5. POST /mcp + Bearer JWT (delete_customer_account) Note over G: Deny rule matches (missing mcp_admin role) G-->>A: Blocked ("unknown tool" - never reaches MCP Server)
View diagram source
sequenceDiagram
    participant A as AI Agent (agent_demo.py)
    participant K as Keycloak (:8080)
    participant G as AgentGateway (:3000)
    participant M as MCP Server (:9000)

    A->>K: 1. POST /token (client_credentials grant)
    K-->>A: JWT access token (realm_access.roles)
    A->>G: 2. POST /mcp + Bearer JWT (get_customer_summary)
    Note over G: 3. Validate JWT via JWKS and check RBAC rules
    G->>M: 4. Forward tools/call: get_customer_summary("cust_8819")
    M-->>G: Customer summary result
    G-->>A: 200 OK (Active status, standard tier)
    A->>G: 5. POST /mcp + Bearer JWT (delete_customer_account)
    Note over G: Deny rule matches (missing mcp_admin role)
    G-->>A: Blocked ("unknown tool" - never reaches MCP Server)

Think back to how a Workshop-1-style custom tool works: the agent process calls a Python function directly, in-process. There's no network hop, no identity to check - the tool trusts whatever called it, because "whatever called it" is the same process.

An MCP server breaks that assumption on purpose. Any MCP-compatible client - your agent, a teammate's agent, someone probing the port - can connect and ask tools/list. If authorization logic lives inside the tool's own function body, every tool author has to get it right, every time, and a single missed check anywhere in the server is a hole.

This demo moves that responsibility to a dedicated enforcement point in front of the server:

Auth logic in the tool

Auth logic at the gateway

Enforced by

Every tool author, individually

One shared policy, applied uniformly

Server trusts

The caller's claims, unchecked

Nothing - the gateway already validated the caller

Add a new tool

Must remember to add the check

Inherits existing rules automatically

Blast radius of a mistake

One missed if and the tool is wide open

Gateway config is the single place to audit

You need three things on your machine:

Dependency

Notes

Docker (or Podman)

Runs Keycloak as a container

AgentGateway

This demo was built against v1.3.1 - install the binary from the AgentGateway project releases and confirm it on your PATH

Python 3

A virtual environment with mcp, httpx

Confirm the gateway binary resolves before going further:

agentgateway --version

Grab the demo code and set up a virtual environment:

git clone https://github.com/adityajoshi12/ai-workshop-add
cd ai-workshop-add/secure-mcp-keycloak-agentgateway

python3 -m venv .venv
source .venv/bin/activate
pip install mcp httpx

Open server.py. This is the whole file:

from mcp.server.mcpserver import MCPServer

mcp = MCPServer("CustomerOps")

@mcp.tool()
def get_customer_summary(customer_id: str) -> str:
    """Safe operation: available to standard readers."""
    return f"Customer {customer_id}: Active status, standard tier."

@mcp.tool()
def delete_customer_account(customer_id: str) -> str:
    """Privileged operation: requires admin clearance."""
    return f"SUCCESS: Customer {customer_id} has been fully purged from the DB."

if __name__ == "__main__":
    mcp.run(transport="sse", host="0.0.0.0", port=9000)

Notice what's missing: no token parsing, no role check, no if user.is_admin. Both tools are defined identically from the server's point of view - delete_customer_account only becomes privileged because of a rule you're about to write somewhere else entirely.

setup_keycloak.sh automates the Keycloak side end-to-end over its REST admin API, so you never touch the admin console by hand. Skim through what it creates:

  1. Realm ai-mesh - an isolated tenant, separate from Keycloak's master realm
  2. Realm roles mcp_reader and mcp_admin
  3. Client agent-core-client - a confidential, service-account-only client assigned the mcp_reader role
  4. Client adminuser - a second service-account client assigned mcp_admin
  5. Audience mapper on both clients, adding account to the JWT's aud claim

That last point trips people up the first time, so it's worth calling out on its own. AgentGateway validates the token's audience against the list it's configured to accept - if aud doesn't contain an entry the gateway recognizes, every request gets rejected with 401 regardless of how correct the roles are. The mapper is what makes that claim show up at all:

curl -sf -X POST "$KEYCLOAK_URL/admin/realms/$REALM/clients/$uuid/protocol-mappers/models" \
  -H "$AUTH" -H "Content-Type: application/json" \
  -d '{
    "name": "audience-account",
    "protocol": "openid-connect",
    "protocolMapper": "oidc-audience-mapper",
    "config": {
      "included.client.audience": "account",
      "id.token.claim": "false",
      "access.token.claim": "true"
    }
  }'

You don't need to run this script by hand yet - start.sh calls it for you in the next step. It's worth reading first so the gateway config in the next section makes sense: the roles end up on the token as realm_access.roles, which is exactly the claim path config.yaml's authorization rule checks against.

Open config.yaml. It has three jobs: terminate CORS for a browser-based client, validate incoming JWTs against Keycloak, and enforce which roles can call which tools.

Authentication - who is allowed to even send a request:

mcpAuthentication:
  issuer: http://localhost:8080/realms/ai-mesh
  audiences:
  - account
  jwks:
    url: http://localhost:8080/realms/ai-mesh/protocol/openid-connect/certs
  provider:
    keycloak: {}
  resourceMetadata:
    resource: http://localhost:3000/mcp
    scopesSupported:
    - read:all
    bearerMethodsSupported:
    - header

The gateway fetches Keycloak's public signing keys from the jwks.url, verifies every token's signature against them, confirms the issuer matches, and confirms account is present in aud - the exact claim the mapper from the previous step added.

Authorization - who is allowed to call which tool:

mcpAuthorization:
  rules:
      - deny: 'mcp.tool.name == "delete_customer_account" && !("mcp_admin" in jwt.realm_access.roles)'

Read that rule as: deny this call if the tool being invoked is

delete_customer_account

and the caller's token does not contain the

mcp_admin

role. Everything not matched by a deny rule is allowed by default - there's no explicit allow-list for get_customer_summary because it doesn't need one.

Finally, the gateway needs to know where to actually forward allowed calls:

targets:
- name: customer-ops-server
  sse:
    host: localhost
    port: 9000
    path: /sse

This points at the MCP server's SSE endpoint from the previous step - the thing that never had to know any of the above existed.

start.sh brings up all three services in order and prints ready-to-copy commands when it's done:

bash start.sh

It does, in sequence: start the Keycloak container, run setup_keycloak.sh to configure the ai-mesh realm, launch server.py in the background on port 9000, then launch agentgateway -f config.yaml on port 3000. Leave this terminal running - it's holding the processes.

If you've already run it once and just want faster restarts without rotating all the client secrets, reuse the existing Keycloak container:

bash start.sh --keep

When it prints All Services Ready, it also prints the exact agent_demo.py commands for both the reader and admin identities, each with its real client secret already filled in. Keep this terminal visible - you'll copy from it in the next two steps.

Open a second terminal in the same folder. Source the secrets file start.sh just wrote so you can reference the reader's real client ID and secret without retyping them:

source .demo-secrets
python3 agent_demo.py --client-id "$READER_CLIENT_ID" --client-secret "$READER_SECRET"

Watch what agent_demo.py does, step by step:

  1. Fetches a token via a client_credentials grant straight from Keycloak's token endpoint - no browser, no user interaction, exactly how a backend agent would authenticate.
  2. Decodes the token's payload locally (just to print the roles for you) and shows Effective roles: ['mcp_reader'].
  3. Connects to the gateway at http://localhost:3000/mcp with the token as a Bearer header and lists the tools it can see.
  4. Calls get_customer_summary - succeeds, because no deny rule matches it.
  5. Calls delete_customer_account - fails, and agent_demo.py specifically checks for an "unknown tool" error to print a friendly BLOCKED BY GATEWAY message instead of a raw stack trace.

You should see something close to:

 SUCCESS: Customer cust_8819: Active status, standard tier.

 AGENT ACTION: delete_customer_account('cust_8819')
  BLOCKED BY GATEWAY: delete_customer_account
   (Reason: token lacks 'mcp_admin' role - gateway hides the tool entirely)

Same agent code, same gateway, same server - only the identity changes:

python3 agent_demo.py --client-id "$ADMIN_CLIENT_ID" --client-secret "$ADMIN_SECRET"

This time the printed roles include mcp_admin, and the delete call goes all the way through:

 AGENT ACTION: delete_customer_account('cust_8819')
 ALLOWED: SUCCESS: Customer cust_8819 has been fully purged from the DB.

Nothing in server.py, agent_demo.py's tool-calling logic, or the network path changed between the two runs - only the role claim inside the JWT did. That's the entire point of pushing authorization to the gateway: identity changes behavior, code does not.

Re-running both scenarios by hand before a demo or a deploy is exactly the kind of thing that should be scripted instead. e2e.sh does the whole loop for you - starts fresh infrastructure, runs both agent identities, asserts on their output, and runs a third scenario with intentionally bad credentials:

bash e2e.sh

It checks, with real assertions rather than eyeballing output:

It exits non-zero if any assertion fails and tears down Keycloak, the MCP server, and the gateway on the way out - safe to wire into CI or to run right before walking on stage.

Two deliberate choices in this demo are worth internalizing beyond this one repo:

Authorization lives in exactly one place. config.yaml's mcpAuthorization rules are the single source of truth for who can call what. Add a tenth tool to server.py tomorrow and it inherits sane allow-by-default behavior automatically - no new code in the tool itself, no second place to remember to update.

A denied tool call doesn't tell the caller it exists. AgentGateway responds to a blocked delete_customer_account call as an "unknown tool," not a 403 Forbidden. A 403 confirms the tool is real and simply off-limits to you right now - useful information to an attacker probing what capabilities a compromised reader credential might unlock later. "Unknown tool" gives up nothing: a reader credential can't even confirm a destructive tool exists on the other end of the gateway.

Symptom

Likely cause

Fix

401 Unauthorized on every call

Token missing account in aud

Confirm the audience mapper exists on the client in Keycloak; re-check audiences: [account] in config.yaml

AgentGateway fails to start

Keycloak wasn't ready when the gateway tried to fetch JWKS

Re-run bash start.sh; inspect cat agentgateway.log

MCP server not responding

Port 9000 already bound by a leftover process

pkill -f server.py && bash start.sh

Client secret suddenly invalid

start.sh ran a fresh realm setup and rotated secrets

Use bash start.sh --keep to reuse the existing realm/clients

pip install -r requirements.txt fails

Stray httpx2==2.13.0 line in requirements.txt

Install mcp and httpx directly, or remove that line

Noisy ClosedResourceError tracebacks from the agent

Known MCP SDK internal logging noise on denied/closed sessions

Already suppressed in agent_demo.py via logging.getLogger("mcp").setLevel(CRITICAL) - safe to ignore if you see it elsewhere

start.sh holds the foreground terminal open - press Ctrl+C there to stop the gateway and server processes it started. Then remove the Keycloak container:

docker rm -f keycloak

If you ran e2e.sh instead, its own trap cleanup EXIT already stopped everything for you.

AgentGateway ProjectModel Context Protocol SpecKeycloak Documentation