Skip to content

Commit 1a8194c

Browse files
committed
add conformance auth client
1 parent 5489e8b commit 1a8194c

File tree

5 files changed

+314
-0
lines changed

5 files changed

+314
-0
lines changed
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
# MCP Conformance Auth Client
2+
3+
A Python OAuth client designed for use with the MCP conformance test framework.
4+
5+
## Overview
6+
7+
This client implements OAuth authentication for MCP and is designed to work automatically with the conformance test framework without requiring user interaction. It programmatically fetches authorization URLs and extracts auth codes from redirects.
8+
9+
## Installation
10+
11+
```bash
12+
cd examples/clients/conformance-auth-client
13+
uv sync
14+
```
15+
16+
## Usage with Conformance Tests
17+
18+
Run the auth conformance tests against this Python client:
19+
20+
```bash
21+
# From the conformance repository
22+
npx @modelcontextprotocol/conformance client \
23+
--command "uv run --directory /path/to/python-sdk/examples/clients/conformance-auth-client python -m mcp_conformance_auth_client" \
24+
--scenario auth/basic-dcr
25+
```
26+
27+
Available auth test scenarios:
28+
- `auth/basic-dcr` - Tests OAuth Dynamic Client Registration flow
29+
- `auth/basic-metadata-var1` - Tests OAuth with authorization metadata
30+
31+
## How It Works
32+
33+
Unlike interactive OAuth clients that open a browser for user authentication, this client:
34+
35+
1. Receives the authorization URL from the OAuth provider
36+
2. Makes an HTTP request to that URL directly (without following redirects)
37+
3. Extracts the authorization code from the redirect response
38+
4. Uses the code to complete the OAuth token exchange
39+
40+
This allows the conformance test framework's mock OAuth server to automatically provide auth codes without human interaction.
41+
42+
## Direct Usage
43+
44+
You can also run the client directly:
45+
46+
```bash
47+
uv run python -m mcp_conformance_auth_client http://localhost:3000/mcp
48+
```
Lines changed: 187 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,187 @@
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 parse_qs, urlparse
18+
19+
import httpx
20+
from pydantic import AnyUrl
21+
22+
from mcp import ClientSession
23+
from mcp.client.auth import OAuthClientProvider, TokenStorage
24+
from mcp.client.streamable_http import streamablehttp_client
25+
from mcp.shared.auth import OAuthClientInformationFull, OAuthClientMetadata, OAuthToken
26+
27+
# Set up logging to stderr (stdout is for conformance test output)
28+
logging.basicConfig(
29+
level=logging.DEBUG,
30+
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
31+
stream=sys.stderr,
32+
)
33+
logger = logging.getLogger(__name__)
34+
35+
36+
class InMemoryTokenStorage(TokenStorage):
37+
"""Simple in-memory token storage for conformance testing."""
38+
39+
def __init__(self):
40+
self._tokens: OAuthToken | None = None
41+
self._client_info: OAuthClientInformationFull | None = None
42+
43+
async def get_tokens(self) -> OAuthToken | None:
44+
return self._tokens
45+
46+
async def set_tokens(self, tokens: OAuthToken) -> None:
47+
self._tokens = tokens
48+
49+
async def get_client_info(self) -> OAuthClientInformationFull | None:
50+
return self._client_info
51+
52+
async def set_client_info(self, client_info: OAuthClientInformationFull) -> None:
53+
self._client_info = client_info
54+
55+
56+
class ConformanceOAuthCallbackHandler:
57+
"""
58+
OAuth callback handler that automatically fetches the authorization URL
59+
and extracts the auth code, without requiring user interaction.
60+
61+
This mimics the behavior of the TypeScript ConformanceOAuthProvider.
62+
"""
63+
64+
def __init__(self):
65+
self._auth_code: str | None = None
66+
self._state: str | None = None
67+
68+
async def handle_redirect(self, authorization_url: str) -> None:
69+
"""
70+
Fetch the authorization URL and extract the auth code from the redirect.
71+
72+
The conformance test server returns a redirect with the auth code,
73+
so we can capture it programmatically.
74+
"""
75+
logger.debug(f"Fetching authorization URL: {authorization_url}")
76+
77+
async with httpx.AsyncClient() as client:
78+
response = await client.get(
79+
authorization_url,
80+
follow_redirects=False, # Don't follow redirects automatically
81+
)
82+
83+
# Check for redirect response
84+
if response.status_code in (301, 302, 303, 307, 308):
85+
location = response.headers.get("location")
86+
if location:
87+
redirect_url = urlparse(location)
88+
query_params = parse_qs(redirect_url.query)
89+
90+
if "code" in query_params:
91+
self._auth_code = query_params["code"][0]
92+
self._state = query_params.get("state", [None])[0]
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(
101+
f"Expected redirect response, got {response.status_code} from {authorization_url}"
102+
)
103+
104+
async def handle_callback(self) -> tuple[str, str | None]:
105+
"""Return the captured auth code and state, then clear them for potential reuse."""
106+
if self._auth_code is None:
107+
raise RuntimeError("No authorization code available - was handle_redirect called?")
108+
auth_code = self._auth_code
109+
state = self._state
110+
# Clear the stored values so the next auth flow gets fresh ones
111+
self._auth_code = None
112+
self._state = None
113+
return auth_code, state
114+
115+
116+
async def run_client(server_url: str) -> None:
117+
"""
118+
Run the conformance test client against the given server URL.
119+
120+
This function:
121+
1. Connects to the MCP server with OAuth authentication
122+
2. Initializes the session
123+
3. Lists available tools
124+
4. Calls a test tool
125+
"""
126+
logger.debug(f"Starting conformance auth client for {server_url}")
127+
128+
# Create callback handler that will automatically fetch auth codes
129+
callback_handler = ConformanceOAuthCallbackHandler()
130+
131+
# Create OAuth authentication handler
132+
oauth_auth = OAuthClientProvider(
133+
server_url=server_url,
134+
client_metadata=OAuthClientMetadata(
135+
client_name="conformance-auth-client",
136+
redirect_uris=[AnyUrl("http://localhost:3000/callback")],
137+
grant_types=["authorization_code", "refresh_token"],
138+
response_types=["code"],
139+
),
140+
storage=InMemoryTokenStorage(),
141+
redirect_handler=callback_handler.handle_redirect,
142+
callback_handler=callback_handler.handle_callback,
143+
)
144+
145+
# Connect using streamable HTTP transport with OAuth
146+
async with streamablehttp_client(
147+
url=server_url,
148+
auth=oauth_auth,
149+
timeout=timedelta(seconds=30),
150+
sse_read_timeout=timedelta(seconds=60),
151+
) as (read_stream, write_stream, get_session_id):
152+
async with ClientSession(read_stream, write_stream) as session:
153+
# Initialize the session
154+
await session.initialize()
155+
logger.debug("Successfully connected and initialized MCP session")
156+
157+
# List tools
158+
tools_result = await session.list_tools()
159+
logger.debug(f"Listed tools: {[t.name for t in tools_result.tools]}")
160+
161+
# Call test tool (expected by conformance tests)
162+
try:
163+
result = await session.call_tool("test-tool", {})
164+
logger.debug(f"Called test-tool, result: {result}")
165+
except Exception as e:
166+
logger.debug(f"Tool call result/error: {e}")
167+
168+
logger.debug("Connection closed successfully")
169+
170+
171+
def main() -> None:
172+
"""Main entry point for the conformance auth client."""
173+
if len(sys.argv) != 2:
174+
print(f"Usage: {sys.argv[0]} <server-url>", file=sys.stderr)
175+
sys.exit(1)
176+
177+
server_url = sys.argv[1]
178+
179+
try:
180+
asyncio.run(run_client(server_url))
181+
except Exception as e:
182+
logger.exception(f"Client failed: {e}")
183+
sys.exit(1)
184+
185+
186+
if __name__ == "__main__":
187+
main()
Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
"""Allow running the module with python -m."""
2+
3+
from mcp_conformance_auth_client import main
4+
5+
if __name__ == "__main__":
6+
main()
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
[project]
2+
name = "mcp-conformance-auth-client"
3+
version = "0.1.0"
4+
description = "OAuth conformance test client for MCP"
5+
readme = "README.md"
6+
requires-python = ">=3.10"
7+
authors = [{ name = "Anthropic" }]
8+
keywords = ["mcp", "oauth", "client", "auth", "conformance", "testing"]
9+
license = { text = "MIT" }
10+
classifiers = [
11+
"Development Status :: 4 - Beta",
12+
"Intended Audience :: Developers",
13+
"License :: OSI Approved :: MIT License",
14+
"Programming Language :: Python :: 3",
15+
"Programming Language :: Python :: 3.10",
16+
]
17+
dependencies = ["mcp", "httpx>=0.28.1"]
18+
19+
[project.scripts]
20+
mcp-conformance-auth-client = "mcp_conformance_auth_client:main"
21+
22+
[build-system]
23+
requires = ["hatchling"]
24+
build-backend = "hatchling.build"
25+
26+
[tool.hatch.build.targets.wheel]
27+
packages = ["mcp_conformance_auth_client"]
28+
29+
[tool.pyright]
30+
include = ["mcp_conformance_auth_client"]
31+
venvPath = "."
32+
venv = ".venv"
33+
34+
[tool.ruff.lint]
35+
select = ["E", "F", "I"]
36+
ignore = []
37+
38+
[tool.ruff]
39+
line-length = 120
40+
target-version = "py310"
41+
42+
[dependency-groups]
43+
dev = ["pyright>=1.1.379", "pytest>=8.3.3", "ruff>=0.6.9"]

uv.lock

Lines changed: 30 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

0 commit comments

Comments
 (0)