Level: Advanced ยท Stack: Python, Docker, Keycloak, AgentGateway
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:
mcp_reader agent can read customer data, but gets silently blocked - the tool is hidden, not just denied - when it tries to delete an account.mcp_admin agent gets the same tool call through without issue.By the end you'll be able to:
mcpAuthentication (JWT/JWKS validation) and mcpAuthorization (RBAC) rules403 Forbidden for a denied callsequenceDiagram
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 | 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 |
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:
ai-mesh - an isolated tenant, separate from Keycloak's master realmmcp_reader and mcp_adminagent-core-client - a confidential, service-account-only client assigned the mcp_reader roleadminuser - a second service-account client assigned mcp_adminaccount to the JWT's aud claimThat 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:
client_credentials grant straight from Keycloak's token endpoint - no browser, no user interaction, exactly how a backend agent would authenticate.Effective roles: ['mcp_reader'].http://localhost:3000/mcp with the token as a Bearer header and lists the tools it can see.get_customer_summary - succeeds, because no deny rule matches it.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:
mcp_reader, get_customer_summary succeeds, delete_customer_account is blockedmcp_admin, delete_customer_account succeeds, nothing was unexpectedly blocked401/UnauthorizedIt 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 |
| Token missing | Confirm the audience mapper exists on the client in Keycloak; re-check |
AgentGateway fails to start | Keycloak wasn't ready when the gateway tried to fetch JWKS | Re-run |
MCP server not responding | Port 9000 already bound by a leftover process |
|
Client secret suddenly invalid |
| Use |
| Stray | Install |
Noisy | Known MCP SDK internal logging noise on denied/closed sessions | Already suppressed in |
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.
realm_access.roles; a client's audience mapper must add the gateway's expected aud entry or every request gets a 401 regardless of roles.mcpAuthentication validates signature/issuer/audience against Keycloak's JWKS; mcpAuthorization rules then gate individual tool calls by role, default-allow-unless-denied.403 - don't leak the shape of your privileged surface to an under-privileged caller.e2e.sh's three scenarios) instead of manually re-checking "allowed" and "blocked" behavior before every demo or deploy.