|
| 1 | +#!/usr/bin/env python3 |
| 2 | +""" |
| 3 | +Client credentials conformance test client. |
| 4 | +
|
| 5 | +This client handles the auth/client-credentials-jwt and auth/client-credentials-basic |
| 6 | +scenarios from the MCP conformance test suite. |
| 7 | +
|
| 8 | +Usage: |
| 9 | + MCP_CONFORMANCE_SCENARIO=auth/client-credentials-jwt \ |
| 10 | + MCP_CONFORMANCE_CONTEXT='{"name":"auth/client-credentials-jwt","client_id":"...","private_key_pem":"...","signing_algorithm":"ES256"}' \ |
| 11 | + python client_credentials_client.py http://localhost:12345/mcp |
| 12 | +""" |
| 13 | + |
| 14 | +import asyncio |
| 15 | +import json |
| 16 | +import os |
| 17 | +import sys |
| 18 | +import time |
| 19 | +from uuid import uuid4 |
| 20 | + |
| 21 | +import httpx |
| 22 | +import jwt |
| 23 | + |
| 24 | + |
| 25 | +async def get_oauth_metadata(client: httpx.AsyncClient, server_url: str) -> dict: |
| 26 | + """Fetch OAuth authorization server metadata.""" |
| 27 | + from urllib.parse import urljoin, urlparse |
| 28 | + |
| 29 | + parsed = urlparse(server_url) |
| 30 | + base_url = f"{parsed.scheme}://{parsed.netloc}" |
| 31 | + |
| 32 | + # First try the protected resource metadata |
| 33 | + prm_url = urljoin(base_url, f"/.well-known/oauth-protected-resource{parsed.path}") |
| 34 | + resp = await client.get(prm_url) |
| 35 | + if resp.status_code == 200: |
| 36 | + prm = resp.json() |
| 37 | + auth_server = prm.get("authorization_servers", [base_url])[0] |
| 38 | + else: |
| 39 | + auth_server = base_url |
| 40 | + |
| 41 | + # Fetch authorization server metadata |
| 42 | + metadata_url = urljoin(auth_server, "/.well-known/oauth-authorization-server") |
| 43 | + resp = await client.get(metadata_url) |
| 44 | + resp.raise_for_status() |
| 45 | + return resp.json() |
| 46 | + |
| 47 | + |
| 48 | +def create_jwt_assertion( |
| 49 | + client_id: str, |
| 50 | + private_key_pem: str, |
| 51 | + algorithm: str, |
| 52 | + audience: str, |
| 53 | +) -> str: |
| 54 | + """Create a JWT client assertion.""" |
| 55 | + now = int(time.time()) |
| 56 | + claims = { |
| 57 | + "iss": client_id, |
| 58 | + "sub": client_id, |
| 59 | + "aud": audience, |
| 60 | + "exp": now + 300, |
| 61 | + "iat": now, |
| 62 | + "jti": str(uuid4()), |
| 63 | + } |
| 64 | + return jwt.encode(claims, private_key_pem, algorithm=algorithm) |
| 65 | + |
| 66 | + |
| 67 | +async def run_client_credentials_jwt(server_url: str, context: dict) -> None: |
| 68 | + """Run client credentials flow with private_key_jwt authentication.""" |
| 69 | + client_id = context["client_id"] |
| 70 | + private_key_pem = context["private_key_pem"] |
| 71 | + signing_algorithm = context.get("signing_algorithm", "ES256") |
| 72 | + |
| 73 | + async with httpx.AsyncClient() as client: |
| 74 | + # Get OAuth metadata |
| 75 | + metadata = await get_oauth_metadata(client, server_url) |
| 76 | + token_endpoint = metadata["token_endpoint"] |
| 77 | + issuer = metadata["issuer"] |
| 78 | + |
| 79 | + # Create JWT assertion |
| 80 | + assertion = create_jwt_assertion( |
| 81 | + client_id=client_id, |
| 82 | + private_key_pem=private_key_pem, |
| 83 | + algorithm=signing_algorithm, |
| 84 | + audience=issuer, |
| 85 | + ) |
| 86 | + |
| 87 | + # Request token |
| 88 | + token_response = await client.post( |
| 89 | + token_endpoint, |
| 90 | + data={ |
| 91 | + "grant_type": "client_credentials", |
| 92 | + "client_assertion": assertion, |
| 93 | + "client_assertion_type": "urn:ietf:params:oauth:client-assertion-type:jwt-bearer", |
| 94 | + }, |
| 95 | + ) |
| 96 | + token_response.raise_for_status() |
| 97 | + tokens = token_response.json() |
| 98 | + access_token = tokens["access_token"] |
| 99 | + |
| 100 | + # Connect to MCP server |
| 101 | + mcp_headers = { |
| 102 | + "Authorization": f"Bearer {access_token}", |
| 103 | + "Content-Type": "application/json", |
| 104 | + "Accept": "application/json, text/event-stream", |
| 105 | + } |
| 106 | + |
| 107 | + init_response = await client.post( |
| 108 | + server_url, |
| 109 | + headers=mcp_headers, |
| 110 | + json={ |
| 111 | + "jsonrpc": "2.0", |
| 112 | + "id": 1, |
| 113 | + "method": "initialize", |
| 114 | + "params": { |
| 115 | + "protocolVersion": "2024-11-05", |
| 116 | + "capabilities": {}, |
| 117 | + "clientInfo": {"name": "conformance-python-client", "version": "1.0.0"}, |
| 118 | + }, |
| 119 | + }, |
| 120 | + ) |
| 121 | + init_response.raise_for_status() |
| 122 | + |
| 123 | + # List tools |
| 124 | + tools_response = await client.post( |
| 125 | + server_url, |
| 126 | + headers=mcp_headers, |
| 127 | + json={ |
| 128 | + "jsonrpc": "2.0", |
| 129 | + "id": 2, |
| 130 | + "method": "tools/list", |
| 131 | + "params": {}, |
| 132 | + }, |
| 133 | + ) |
| 134 | + tools_response.raise_for_status() |
| 135 | + |
| 136 | + print("Successfully connected with private_key_jwt auth", file=sys.stderr) |
| 137 | + |
| 138 | + |
| 139 | +async def run_client_credentials_basic(server_url: str, context: dict) -> None: |
| 140 | + """Run client credentials flow with client_secret_basic authentication.""" |
| 141 | + client_id = context["client_id"] |
| 142 | + client_secret = context["client_secret"] |
| 143 | + |
| 144 | + async with httpx.AsyncClient() as client: |
| 145 | + # Get OAuth metadata |
| 146 | + metadata = await get_oauth_metadata(client, server_url) |
| 147 | + token_endpoint = metadata["token_endpoint"] |
| 148 | + |
| 149 | + # Request token with Basic auth |
| 150 | + token_response = await client.post( |
| 151 | + token_endpoint, |
| 152 | + auth=(client_id, client_secret), |
| 153 | + data={"grant_type": "client_credentials"}, |
| 154 | + ) |
| 155 | + token_response.raise_for_status() |
| 156 | + tokens = token_response.json() |
| 157 | + access_token = tokens["access_token"] |
| 158 | + |
| 159 | + # Connect to MCP server |
| 160 | + mcp_headers = { |
| 161 | + "Authorization": f"Bearer {access_token}", |
| 162 | + "Content-Type": "application/json", |
| 163 | + "Accept": "application/json, text/event-stream", |
| 164 | + } |
| 165 | + |
| 166 | + init_response = await client.post( |
| 167 | + server_url, |
| 168 | + headers=mcp_headers, |
| 169 | + json={ |
| 170 | + "jsonrpc": "2.0", |
| 171 | + "id": 1, |
| 172 | + "method": "initialize", |
| 173 | + "params": { |
| 174 | + "protocolVersion": "2024-11-05", |
| 175 | + "capabilities": {}, |
| 176 | + "clientInfo": {"name": "conformance-python-client", "version": "1.0.0"}, |
| 177 | + }, |
| 178 | + }, |
| 179 | + ) |
| 180 | + init_response.raise_for_status() |
| 181 | + |
| 182 | + # List tools |
| 183 | + tools_response = await client.post( |
| 184 | + server_url, |
| 185 | + headers=mcp_headers, |
| 186 | + json={ |
| 187 | + "jsonrpc": "2.0", |
| 188 | + "id": 2, |
| 189 | + "method": "tools/list", |
| 190 | + "params": {}, |
| 191 | + }, |
| 192 | + ) |
| 193 | + tools_response.raise_for_status() |
| 194 | + |
| 195 | + print("Successfully connected with client_secret_basic auth", file=sys.stderr) |
| 196 | + |
| 197 | + |
| 198 | +async def main() -> None: |
| 199 | + """Main entry point.""" |
| 200 | + if len(sys.argv) < 2: |
| 201 | + print("Usage: client_credentials_client.py <server-url>", file=sys.stderr) |
| 202 | + sys.exit(1) |
| 203 | + |
| 204 | + server_url = sys.argv[1] |
| 205 | + |
| 206 | + context_str = os.environ.get("MCP_CONFORMANCE_CONTEXT") |
| 207 | + if not context_str: |
| 208 | + print("MCP_CONFORMANCE_CONTEXT not set", file=sys.stderr) |
| 209 | + sys.exit(1) |
| 210 | + |
| 211 | + context = json.loads(context_str) |
| 212 | + scenario_name = context.get("name") |
| 213 | + |
| 214 | + if scenario_name == "auth/client-credentials-jwt": |
| 215 | + await run_client_credentials_jwt(server_url, context) |
| 216 | + elif scenario_name == "auth/client-credentials-basic": |
| 217 | + await run_client_credentials_basic(server_url, context) |
| 218 | + else: |
| 219 | + print(f"Unknown scenario: {scenario_name}", file=sys.stderr) |
| 220 | + sys.exit(1) |
| 221 | + |
| 222 | + |
| 223 | +if __name__ == "__main__": |
| 224 | + asyncio.run(main()) |
0 commit comments