-
Notifications
You must be signed in to change notification settings - Fork 36
Keycloak integration #12
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
17 commits
Select commit
Hold shift + click to select a range
a0b7d12
Add Keycloak OAuth authentication for MCP server
madebygps d6663a3
feat: use DCR dynamically and add multi-stage Dockerfile build
madebygps d234dc4
refactor: apply Bicep best practices and fix token issuer mismatch
madebygps 7448490
ran ruff
madebygps 0df8485
remove unused keycloak setup script
madebygps 49d490d
Update infra/Dockerfile.keycloak
madebygps 5a52481
Update agents/langchainv1_keycloak.py
madebygps 23be967
Update servers/keycloak_deployed_mcp.py
madebygps 9dc7be8
fix: improve error messages and fix formatting issues
madebygps 1504037
Merge main into keycloak-integration with auth updates
madebygps 637805e
fix: format keycloak_deployed_mcp.py
madebygps 74f2e6d
chore: remove unused Dockerfile.noauth
madebygps 8627170
addresses feedback from Pamela
madebygps bf6ec60
Format keycloak_auth.py
madebygps ccb5afa
Update README: use agentframework_http.py for Keycloak testing
madebygps 51b3969
README: simplify expected output for agent test
madebygps 2c25546
README: add deployed_mcp.py to servers table
madebygps File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,33 +1,33 @@ | ||
| { | ||
| "servers": { | ||
| "expenses-mcp": { | ||
| "type": "stdio", | ||
| "command": "uv", | ||
| "cwd": "${workspaceFolder}", | ||
| "args": [ | ||
| "run", | ||
| "servers/basic_mcp_stdio.py" | ||
| ] | ||
| }, | ||
| "expenses-mcp-http": { | ||
| "type": "http", | ||
| "url": "http://localhost:8000/mcp" | ||
| }, | ||
| "expenses-mcp-debug": { | ||
| "type": "stdio", | ||
| "command": "uv", | ||
| "cwd": "${workspaceFolder}", | ||
| "args": [ | ||
| "run", | ||
| "--", | ||
| "python", | ||
| "-m", | ||
| "debugpy", | ||
| "--listen", | ||
| "0.0.0.0:5678", | ||
| "servers/basic_mcp_stdio.py" | ||
| ] | ||
| } | ||
| }, | ||
| "inputs": [] | ||
| } | ||
| "servers": { | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. What's the whitespace diff from? Pre-commit? (I did add precommit btw if you want to install it) |
||
| "expenses-mcp": { | ||
| "type": "stdio", | ||
| "command": "uv", | ||
| "cwd": "${workspaceFolder}", | ||
| "args": [ | ||
| "run", | ||
| "servers/basic_mcp_stdio.py" | ||
| ] | ||
| }, | ||
| "expenses-mcp-http": { | ||
| "type": "http", | ||
| "url": "http://localhost:8000/mcp" | ||
| }, | ||
| "expenses-mcp-debug": { | ||
| "type": "stdio", | ||
| "command": "uv", | ||
| "cwd": "${workspaceFolder}", | ||
| "args": [ | ||
| "run", | ||
| "--", | ||
| "python", | ||
| "-m", | ||
| "debugpy", | ||
| "--listen", | ||
| "0.0.0.0:5678", | ||
| "servers/basic_mcp_stdio.py" | ||
| ] | ||
| }, | ||
| }, | ||
| "inputs": [] | ||
madebygps marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,120 @@ | ||
| """ | ||
| Keycloak authentication helpers for MCP agents. | ||
|
|
||
| Provides OAuth2 client credentials flow authentication via Keycloak's | ||
| Dynamic Client Registration (DCR) endpoint. | ||
|
|
||
| Usage: | ||
| from keycloak_auth import get_auth_headers | ||
|
|
||
| headers = await get_auth_headers(keycloak_realm_url) | ||
| # Returns {"Authorization": "Bearer <token>"} or None if no URL provided | ||
| """ | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| import logging | ||
| from datetime import datetime | ||
|
|
||
| import httpx | ||
|
|
||
| logger = logging.getLogger(__name__) | ||
|
|
||
|
|
||
| async def register_client_via_dcr(keycloak_realm_url: str, client_name_prefix: str = "agent") -> tuple[str, str]: | ||
| """ | ||
| Register a new client dynamically using Keycloak's DCR endpoint. | ||
|
|
||
| Args: | ||
| keycloak_realm_url: The Keycloak realm URL (e.g., http://localhost:8080/realms/myrealm) | ||
| client_name_prefix: Prefix for the generated client name | ||
|
|
||
| Returns: | ||
| Tuple of (client_id, client_secret) | ||
|
|
||
| Raises: | ||
| RuntimeError: If DCR registration fails | ||
| """ | ||
| dcr_url = f"{keycloak_realm_url}/clients-registrations/openid-connect" | ||
| logger.info("📝 Registering client via DCR...") | ||
|
|
||
| async with httpx.AsyncClient() as http_client: | ||
| response = await http_client.post( | ||
| dcr_url, | ||
| json={ | ||
| "client_name": f"{client_name_prefix}-{datetime.now().strftime('%Y%m%d-%H%M%S')}", | ||
| "grant_types": ["client_credentials"], | ||
| "token_endpoint_auth_method": "client_secret_basic", | ||
| }, | ||
| headers={"Content-Type": "application/json"}, | ||
| ) | ||
|
|
||
| if response.status_code not in (200, 201): | ||
| raise RuntimeError( | ||
| f"DCR registration failed at {dcr_url}: status={response.status_code}, response={response.text}" | ||
| ) | ||
|
|
||
| data = response.json() | ||
| logger.info(f"✅ Registered client: {data['client_id'][:20]}...") | ||
| return data["client_id"], data["client_secret"] | ||
|
|
||
|
|
||
| async def get_keycloak_token(keycloak_realm_url: str, client_id: str, client_secret: str) -> str: | ||
| """ | ||
| Get an access token from Keycloak using client_credentials grant. | ||
|
|
||
| Args: | ||
| keycloak_realm_url: The Keycloak realm URL | ||
| client_id: The OAuth client ID | ||
| client_secret: The OAuth client secret | ||
|
|
||
| Returns: | ||
| The access token string | ||
|
|
||
| Raises: | ||
| RuntimeError: If token request fails | ||
| """ | ||
| token_url = f"{keycloak_realm_url}/protocol/openid-connect/token" | ||
| logger.info("🔑 Getting access token from Keycloak...") | ||
|
|
||
| async with httpx.AsyncClient() as http_client: | ||
| response = await http_client.post( | ||
| token_url, | ||
| data={ | ||
| "grant_type": "client_credentials", | ||
| "client_id": client_id, | ||
| "client_secret": client_secret, | ||
| }, | ||
| headers={"Content-Type": "application/x-www-form-urlencoded"}, | ||
| ) | ||
|
|
||
| if response.status_code != 200: | ||
| raise RuntimeError( | ||
| f"Token request failed at {token_url}: status={response.status_code}, response={response.text}" | ||
| ) | ||
|
|
||
| token_data = response.json() | ||
| logger.info(f"✅ Got access token (expires in {token_data.get('expires_in', '?')}s)") | ||
| return token_data["access_token"] | ||
|
|
||
|
|
||
| async def get_auth_headers(keycloak_realm_url: str | None, client_name_prefix: str = "agent") -> dict[str, str] | None: | ||
| """ | ||
| Get authorization headers if Keycloak is configured. | ||
|
|
||
| This is the main entry point for agents that need OAuth authentication. | ||
| It handles the full flow: DCR registration -> token acquisition -> headers. | ||
|
|
||
| Args: | ||
| keycloak_realm_url: The Keycloak realm URL, or None to skip auth | ||
| client_name_prefix: Prefix for the dynamically registered client name | ||
|
|
||
| Returns: | ||
| {"Authorization": "Bearer <token>"} if keycloak_realm_url is set, None otherwise | ||
| """ | ||
| if not keycloak_realm_url: | ||
| return None | ||
|
|
||
| client_id, client_secret = await register_client_via_dcr(keycloak_realm_url, client_name_prefix) | ||
| access_token = await get_keycloak_token(keycloak_realm_url, client_id, client_secret) | ||
| return {"Authorization": f"Bearer {access_token}"} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The
.dockerignorefile excludesinfra/keycloak-realm.jsonbut this file is needed by the Keycloak Dockerfile (see line 4 ofDockerfile.keycloak). This will cause the Docker build to fail with a "file not found" error.To fix this, add an exception to allow the keycloak-realm.json file: