|
| 1 | +#!/usr/bin/env python3 |
| 2 | +""" |
| 3 | +MCP OAuth conformance test client. |
| 4 | +
|
| 5 | +This client is designed to work with the MCP conformance test framework. |
| 6 | +It automatically handles OAuth flows without user interaction by programmatically |
| 7 | +fetching the authorization URL and extracting the auth code from the redirect. |
| 8 | +
|
| 9 | +Usage: |
| 10 | + python -m mcp_conformance_auth_client <server-url> |
| 11 | +""" |
| 12 | + |
| 13 | +import asyncio |
| 14 | +import logging |
| 15 | +import sys |
| 16 | +from datetime import timedelta |
| 17 | +from urllib.parse import ParseResult, parse_qs, urlparse |
| 18 | + |
| 19 | +import httpx |
| 20 | +from mcp import ClientSession |
| 21 | +from mcp.client.auth import OAuthClientProvider, TokenStorage |
| 22 | +from mcp.client.streamable_http import streamablehttp_client |
| 23 | +from mcp.shared.auth import OAuthClientInformationFull, OAuthClientMetadata, OAuthToken |
| 24 | +from pydantic import AnyUrl |
| 25 | + |
| 26 | +# Set up logging to stderr (stdout is for conformance test output) |
| 27 | +logging.basicConfig( |
| 28 | + level=logging.DEBUG, |
| 29 | + format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", |
| 30 | + stream=sys.stderr, |
| 31 | +) |
| 32 | +logger = logging.getLogger(__name__) |
| 33 | + |
| 34 | + |
| 35 | +class InMemoryTokenStorage(TokenStorage): |
| 36 | + """Simple in-memory token storage for conformance testing.""" |
| 37 | + |
| 38 | + def __init__(self): |
| 39 | + self._tokens: OAuthToken | None = None |
| 40 | + self._client_info: OAuthClientInformationFull | None = None |
| 41 | + |
| 42 | + async def get_tokens(self) -> OAuthToken | None: |
| 43 | + return self._tokens |
| 44 | + |
| 45 | + async def set_tokens(self, tokens: OAuthToken) -> None: |
| 46 | + self._tokens = tokens |
| 47 | + |
| 48 | + async def get_client_info(self) -> OAuthClientInformationFull | None: |
| 49 | + return self._client_info |
| 50 | + |
| 51 | + async def set_client_info(self, client_info: OAuthClientInformationFull) -> None: |
| 52 | + self._client_info = client_info |
| 53 | + |
| 54 | + |
| 55 | +class ConformanceOAuthCallbackHandler: |
| 56 | + """ |
| 57 | + OAuth callback handler that automatically fetches the authorization URL |
| 58 | + and extracts the auth code, without requiring user interaction. |
| 59 | +
|
| 60 | + This mimics the behavior of the TypeScript ConformanceOAuthProvider. |
| 61 | + """ |
| 62 | + |
| 63 | + def __init__(self): |
| 64 | + self._auth_code: str | None = None |
| 65 | + self._state: str | None = None |
| 66 | + |
| 67 | + async def handle_redirect(self, authorization_url: str) -> None: |
| 68 | + """ |
| 69 | + Fetch the authorization URL and extract the auth code from the redirect. |
| 70 | +
|
| 71 | + The conformance test server returns a redirect with the auth code, |
| 72 | + so we can capture it programmatically. |
| 73 | + """ |
| 74 | + logger.debug(f"Fetching authorization URL: {authorization_url}") |
| 75 | + |
| 76 | + async with httpx.AsyncClient() as client: |
| 77 | + response = await client.get( |
| 78 | + authorization_url, |
| 79 | + follow_redirects=False, # Don't follow redirects automatically |
| 80 | + ) |
| 81 | + |
| 82 | + # Check for redirect response |
| 83 | + if response.status_code in (301, 302, 303, 307, 308): |
| 84 | + location = response.headers.get("location") |
| 85 | + if location: |
| 86 | + redirect_url: ParseResult = urlparse(location) |
| 87 | + query_params: dict[str, list[str]] = parse_qs(redirect_url.query) |
| 88 | + |
| 89 | + if "code" in query_params: |
| 90 | + self._auth_code = query_params["code"][0] |
| 91 | + state_values = query_params.get("state") |
| 92 | + self._state = state_values[0] if state_values else None |
| 93 | + logger.debug(f"Got auth code from redirect: {self._auth_code[:10]}...") |
| 94 | + return |
| 95 | + else: |
| 96 | + raise RuntimeError(f"No auth code in redirect URL: {location}") |
| 97 | + else: |
| 98 | + raise RuntimeError(f"No redirect location received from {authorization_url}") |
| 99 | + else: |
| 100 | + raise RuntimeError(f"Expected redirect response, got {response.status_code} from {authorization_url}") |
| 101 | + |
| 102 | + async def handle_callback(self) -> tuple[str, str | None]: |
| 103 | + """Return the captured auth code and state, then clear them for potential reuse.""" |
| 104 | + if self._auth_code is None: |
| 105 | + raise RuntimeError("No authorization code available - was handle_redirect called?") |
| 106 | + auth_code = self._auth_code |
| 107 | + state = self._state |
| 108 | + # Clear the stored values so the next auth flow gets fresh ones |
| 109 | + self._auth_code = None |
| 110 | + self._state = None |
| 111 | + return auth_code, state |
| 112 | + |
| 113 | + |
| 114 | +async def run_client(server_url: str) -> None: |
| 115 | + """ |
| 116 | + Run the conformance test client against the given server URL. |
| 117 | +
|
| 118 | + This function: |
| 119 | + 1. Connects to the MCP server with OAuth authentication |
| 120 | + 2. Initializes the session |
| 121 | + 3. Lists available tools |
| 122 | + 4. Calls a test tool |
| 123 | + """ |
| 124 | + logger.debug(f"Starting conformance auth client for {server_url}") |
| 125 | + |
| 126 | + # Create callback handler that will automatically fetch auth codes |
| 127 | + callback_handler = ConformanceOAuthCallbackHandler() |
| 128 | + |
| 129 | + # Create OAuth authentication handler |
| 130 | + oauth_auth = OAuthClientProvider( |
| 131 | + server_url=server_url, |
| 132 | + client_metadata=OAuthClientMetadata( |
| 133 | + client_name="conformance-auth-client", |
| 134 | + redirect_uris=[AnyUrl("http://localhost:3000/callback")], |
| 135 | + grant_types=["authorization_code", "refresh_token"], |
| 136 | + response_types=["code"], |
| 137 | + ), |
| 138 | + storage=InMemoryTokenStorage(), |
| 139 | + redirect_handler=callback_handler.handle_redirect, |
| 140 | + callback_handler=callback_handler.handle_callback, |
| 141 | + ) |
| 142 | + |
| 143 | + # Connect using streamable HTTP transport with OAuth |
| 144 | + async with streamablehttp_client( |
| 145 | + url=server_url, |
| 146 | + auth=oauth_auth, |
| 147 | + timeout=timedelta(seconds=30), |
| 148 | + sse_read_timeout=timedelta(seconds=60), |
| 149 | + ) as (read_stream, write_stream, _): |
| 150 | + async with ClientSession(read_stream, write_stream) as session: |
| 151 | + # Initialize the session |
| 152 | + await session.initialize() |
| 153 | + logger.debug("Successfully connected and initialized MCP session") |
| 154 | + |
| 155 | + # List tools |
| 156 | + tools_result = await session.list_tools() |
| 157 | + logger.debug(f"Listed tools: {[t.name for t in tools_result.tools]}") |
| 158 | + |
| 159 | + # Call test tool (expected by conformance tests) |
| 160 | + try: |
| 161 | + result = await session.call_tool("test-tool", {}) |
| 162 | + logger.debug(f"Called test-tool, result: {result}") |
| 163 | + except Exception as e: |
| 164 | + logger.debug(f"Tool call result/error: {e}") |
| 165 | + |
| 166 | + logger.debug("Connection closed successfully") |
| 167 | + |
| 168 | + |
| 169 | +def main() -> None: |
| 170 | + """Main entry point for the conformance auth client.""" |
| 171 | + if len(sys.argv) != 2: |
| 172 | + print(f"Usage: {sys.argv[0]} <server-url>", file=sys.stderr) |
| 173 | + sys.exit(1) |
| 174 | + |
| 175 | + server_url = sys.argv[1] |
| 176 | + |
| 177 | + try: |
| 178 | + asyncio.run(run_client(server_url)) |
| 179 | + except Exception: |
| 180 | + logger.exception("Client failed") |
| 181 | + sys.exit(1) |
| 182 | + |
| 183 | + |
| 184 | +if __name__ == "__main__": |
| 185 | + main() |
0 commit comments