chore: import upstream snapshot with attribution
Deploy Docs / deploy-docs (push) Failing after 1s
Conformance Tests / client-conformance (push) Failing after 3s
Conformance Tests / server-conformance (push) Failing after 1s
GitHub Actions Security Analysis / zizmor (push) Failing after 1s
CI / checks (push) Failing after 59m20s
CI / all-green (push) Waiting to run
Deploy Docs / deploy-docs (push) Failing after 1s
Conformance Tests / client-conformance (push) Failing after 3s
Conformance Tests / server-conformance (push) Failing after 1s
GitHub Actions Security Analysis / zizmor (push) Failing after 1s
CI / checks (push) Failing after 59m20s
CI / all-green (push) Waiting to run
This commit is contained in:
@@ -0,0 +1,78 @@
|
||||
# oauth-client-credentials
|
||||
|
||||
OAuth 2.0 **`client_credentials`** grant — machine-to-machine MCP auth, no
|
||||
browser. A backend service authenticates *as itself* by presenting a
|
||||
pre-registered `client_id`/`client_secret` directly to the AS token endpoint;
|
||||
the SDK's `ClientCredentialsOAuthProvider` handles 401-challenge → PRM/AS
|
||||
discovery → token POST → Bearer attachment automatically.
|
||||
|
||||
## Run it
|
||||
|
||||
```bash
|
||||
# HTTP — the client self-hosts the server, runs the grant, then tears it down.
|
||||
# Self-hosting uses this story's fixed :8000 (the AS metadata pins it), so
|
||||
# :8000 must be free.
|
||||
uv run python -m stories.oauth_client_credentials.client --http
|
||||
# same, against the lowlevel-API server variant
|
||||
uv run python -m stories.oauth_client_credentials.client --http --server server_lowlevel
|
||||
|
||||
# against a server you run yourself (real uvicorn on :8000 — auth is HTTP-only)
|
||||
uv run python -m stories.oauth_client_credentials.server --port 8000 &
|
||||
SERVER_PID=$!
|
||||
uv run python -m stories.oauth_client_credentials.client --http http://127.0.0.1:8000/mcp
|
||||
kill "$SERVER_PID"
|
||||
```
|
||||
|
||||
OAuth is an HTTP-layer concern; stdio servers receive credentials via the
|
||||
environment per the spec, so there is no stdio leg. The port must be **8000**:
|
||||
the demo AS metadata (`_shared/auth.py` `BASE_URL`) is pinned to it on both
|
||||
the client and server side.
|
||||
|
||||
## What to look at
|
||||
|
||||
- `client.py` `main` — opens with `async with Client(target, mode=mode) as
|
||||
client:` and that's the whole program. `target` is a transport that already
|
||||
carries the OAuth `httpx.Auth`; the body never touches a token.
|
||||
- `client.py` `build_auth` — five lines of `ClientCredentialsOAuthProvider`
|
||||
config is all the caller writes; the SDK does RFC 9728 PRM →
|
||||
RFC 8414 AS-metadata discovery and token exchange on the first 401.
|
||||
- `server.py` `token_endpoint` — the *entire* AS for this grant: validate
|
||||
HTTP-Basic `client_id:client_secret`, mint a token, return RFC 6749 JSON.
|
||||
The SDK's built-in `auth_server_provider=` only routes
|
||||
`authorization_code`/`refresh_token`, so M2M servers mount their own `/token`.
|
||||
- `server.py` `whoami` — `get_access_token()` is how a tool reads the
|
||||
authenticated principal (`client_id`, `scopes`) from the request context.
|
||||
- `server_lowlevel.py` — identical auth wiring via
|
||||
`Server.streamable_http_app(auth=..., token_verifier=...,
|
||||
custom_starlette_routes=[...])`; only the tool registration differs.
|
||||
|
||||
## Caveats
|
||||
|
||||
- `Client(url, auth=build_auth(http))` is the ergonomic the SDK is missing —
|
||||
`Client(url)` has no `auth=` passthrough. Until it lands, the authed
|
||||
`httpx.AsyncClient` → `streamable_http_client(url, http_client=hc)` chain has
|
||||
to be built *outside* `main` and handed in as `target`; both `run_client`
|
||||
(the standalone `--http` run) and the test harness do that from the
|
||||
`build_auth` export.
|
||||
- `transport_security=NO_DNS_REBIND` — DNS-rebinding protection is on by
|
||||
default for localhost binds; the harness disables it because the in-process
|
||||
httpx client sends no `Origin` header. Drop the kwarg for a real deployment.
|
||||
- `OAuthMetadata.authorization_endpoint` is a required field even though a
|
||||
`client_credentials`-only AS has no authorize endpoint; the server sets a
|
||||
dummy URL.
|
||||
|
||||
## `private_key_jwt`
|
||||
|
||||
Swap `ClientCredentialsOAuthProvider` for `PrivateKeyJWTOAuthProvider` to
|
||||
authenticate the token request with a signed assertion (RFC 7523 §2.2) instead
|
||||
of a shared secret. Not exercised here because the demo AS only validates
|
||||
`client_secret_basic`.
|
||||
|
||||
## Spec
|
||||
|
||||
[Authorization](https://modelcontextprotocol.io/specification/2025-11-25/basic/authorization)
|
||||
|
||||
## See also
|
||||
|
||||
`oauth/` (interactive `authorization_code` + PKCE — user-facing flow) ·
|
||||
`bearer_auth/` (static token, no AS — simplest gating).
|
||||
@@ -0,0 +1,46 @@
|
||||
"""HTTP-only: ``build_auth`` returns a ``ClientCredentialsOAuthProvider``; ``whoami`` round-trips client_id + scopes."""
|
||||
|
||||
import httpx
|
||||
|
||||
from mcp.client import Client
|
||||
from mcp.client.auth.extensions.client_credentials import ClientCredentialsOAuthProvider
|
||||
from stories._harness import Target, run_client
|
||||
|
||||
# MCP_URL pins the resource to :8000, and the server side builds its PRM/AS metadata from
|
||||
# the same constant — run the server on 8000 or the discovery chain points at the wrong origin.
|
||||
from stories._shared.auth import MCP_URL, InMemoryTokenStorage
|
||||
|
||||
from .server import DEMO_CLIENT_ID, DEMO_CLIENT_SECRET, DEMO_SCOPE
|
||||
|
||||
|
||||
def build_auth(_http: httpx.AsyncClient) -> httpx.Auth:
|
||||
"""The ``httpx.Auth`` for the ``client_credentials`` grant — five lines of provider config.
|
||||
|
||||
The SDK then handles 401 → RFC 9728 PRM → RFC 8414 AS-metadata discovery → token POST →
|
||||
Bearer attachment automatically. ``Client(url)`` has no ``auth=`` passthrough yet, so the
|
||||
harness threads this onto the transport's ``httpx.AsyncClient`` and hands ``main`` the
|
||||
already-authed ``target``.
|
||||
"""
|
||||
return ClientCredentialsOAuthProvider(
|
||||
server_url=MCP_URL,
|
||||
storage=InMemoryTokenStorage(),
|
||||
client_id=DEMO_CLIENT_ID,
|
||||
client_secret=DEMO_CLIENT_SECRET,
|
||||
scopes=DEMO_SCOPE,
|
||||
)
|
||||
|
||||
|
||||
async def main(target: Target, *, mode: str = "auto") -> None:
|
||||
async with Client(target, mode=mode) as client:
|
||||
listed = await client.list_tools()
|
||||
assert [t.name for t in listed.tools] == ["whoami"]
|
||||
|
||||
result = await client.call_tool("whoami", {})
|
||||
assert not result.is_error
|
||||
assert result.structured_content is not None
|
||||
assert result.structured_content["client_id"] == DEMO_CLIENT_ID, result
|
||||
assert DEMO_SCOPE in result.structured_content["scopes"]
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run_client(main)
|
||||
@@ -0,0 +1,77 @@
|
||||
"""Bearer-gated resource server + a minimal in-process ``client_credentials`` AS, one app; exports ``build_app()``."""
|
||||
|
||||
import base64
|
||||
import secrets
|
||||
|
||||
from pydantic import AnyHttpUrl, BaseModel
|
||||
from starlette.applications import Starlette
|
||||
from starlette.requests import Request
|
||||
from starlette.responses import JSONResponse
|
||||
|
||||
from mcp.server.auth.middleware.auth_context import get_access_token
|
||||
from mcp.server.auth.provider import AccessToken
|
||||
from mcp.server.mcpserver import MCPServer
|
||||
from mcp.shared.auth import OAuthMetadata, OAuthToken
|
||||
from stories._hosting import NO_DNS_REBIND, run_app_from_args
|
||||
from stories._shared.auth import BASE_URL, auth_settings
|
||||
|
||||
# DEMO ONLY — never hard-code real credentials.
|
||||
DEMO_CLIENT_ID = "demo-m2m-client"
|
||||
DEMO_CLIENT_SECRET = "demo-m2m-secret"
|
||||
DEMO_SCOPE = "mcp:tools"
|
||||
|
||||
|
||||
class Whoami(BaseModel):
|
||||
client_id: str
|
||||
scopes: list[str]
|
||||
|
||||
|
||||
def build_app() -> Starlette:
|
||||
issued: dict[str, AccessToken] = {}
|
||||
|
||||
class _Verifier:
|
||||
async def verify_token(self, token: str) -> AccessToken | None:
|
||||
return issued.get(token)
|
||||
|
||||
mcp = MCPServer(
|
||||
"oauth-client-credentials-example",
|
||||
token_verifier=_Verifier(),
|
||||
auth=auth_settings(required_scopes=[DEMO_SCOPE]),
|
||||
)
|
||||
|
||||
@mcp.tool(description="Return the authenticated client_id and granted scopes.")
|
||||
def whoami() -> Whoami:
|
||||
token = get_access_token()
|
||||
assert token is not None
|
||||
return Whoami(client_id=token.client_id, scopes=token.scopes)
|
||||
|
||||
@mcp.custom_route("/.well-known/oauth-authorization-server", methods=["GET"])
|
||||
async def as_metadata(request: Request) -> JSONResponse:
|
||||
meta = OAuthMetadata(
|
||||
issuer=AnyHttpUrl(BASE_URL),
|
||||
authorization_endpoint=AnyHttpUrl(f"{BASE_URL}/authorize"), # unused; required
|
||||
token_endpoint=AnyHttpUrl(f"{BASE_URL}/token"),
|
||||
grant_types_supported=["client_credentials"],
|
||||
token_endpoint_auth_methods_supported=["client_secret_basic"],
|
||||
scopes_supported=[DEMO_SCOPE],
|
||||
)
|
||||
return JSONResponse(meta.model_dump(by_alias=True, mode="json", exclude_none=True))
|
||||
|
||||
@mcp.custom_route("/token", methods=["POST"])
|
||||
async def token_endpoint(request: Request) -> JSONResponse:
|
||||
form = await request.form()
|
||||
if form.get("grant_type") != "client_credentials":
|
||||
return JSONResponse({"error": "unsupported_grant_type"}, status_code=400)
|
||||
creds = base64.b64decode(request.headers.get("authorization", "").removeprefix("Basic ")).decode()
|
||||
if creds != f"{DEMO_CLIENT_ID}:{DEMO_CLIENT_SECRET}":
|
||||
return JSONResponse({"error": "invalid_client"}, status_code=401)
|
||||
access = f"access_{secrets.token_hex(16)}"
|
||||
issued[access] = AccessToken(token=access, client_id=DEMO_CLIENT_ID, scopes=[DEMO_SCOPE], expires_at=None)
|
||||
body = OAuthToken(access_token=access, token_type="Bearer", expires_in=3600, scope=DEMO_SCOPE)
|
||||
return JSONResponse(body.model_dump(exclude_none=True), headers={"cache-control": "no-store"})
|
||||
|
||||
return mcp.streamable_http_app(transport_security=NO_DNS_REBIND)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run_app_from_args(build_app)
|
||||
@@ -0,0 +1,82 @@
|
||||
"""Bearer-gated MCP resource server (lowlevel API) + the same minimal ``client_credentials`` AS."""
|
||||
|
||||
import base64
|
||||
import json
|
||||
import secrets
|
||||
from typing import Any
|
||||
|
||||
import mcp_types as types
|
||||
from pydantic import AnyHttpUrl
|
||||
from starlette.applications import Starlette
|
||||
from starlette.requests import Request
|
||||
from starlette.responses import JSONResponse
|
||||
from starlette.routing import Route
|
||||
|
||||
from mcp.server.auth.middleware.auth_context import get_access_token
|
||||
from mcp.server.auth.provider import AccessToken
|
||||
from mcp.server.context import ServerRequestContext
|
||||
from mcp.server.lowlevel import Server
|
||||
from mcp.shared.auth import OAuthMetadata, OAuthToken
|
||||
from stories._hosting import NO_DNS_REBIND, run_app_from_args
|
||||
from stories._shared.auth import BASE_URL, auth_settings
|
||||
|
||||
from .server import DEMO_CLIENT_ID, DEMO_CLIENT_SECRET, DEMO_SCOPE
|
||||
|
||||
|
||||
def build_app() -> Starlette:
|
||||
issued: dict[str, AccessToken] = {}
|
||||
|
||||
class _Verifier:
|
||||
async def verify_token(self, token: str) -> AccessToken | None:
|
||||
return issued.get(token)
|
||||
|
||||
async def list_tools(
|
||||
ctx: ServerRequestContext[Any], params: types.PaginatedRequestParams | None
|
||||
) -> types.ListToolsResult:
|
||||
return types.ListToolsResult(tools=[types.Tool(name="whoami", input_schema={"type": "object"})])
|
||||
|
||||
async def call_tool(ctx: ServerRequestContext[Any], params: types.CallToolRequestParams) -> types.CallToolResult:
|
||||
assert params.name == "whoami"
|
||||
token = get_access_token()
|
||||
assert token is not None
|
||||
payload = {"client_id": token.client_id, "scopes": token.scopes}
|
||||
return types.CallToolResult(content=[types.TextContent(text=json.dumps(payload))], structured_content=payload)
|
||||
|
||||
server = Server("oauth-client-credentials-example", on_list_tools=list_tools, on_call_tool=call_tool)
|
||||
|
||||
async def as_metadata(request: Request) -> JSONResponse:
|
||||
meta = OAuthMetadata(
|
||||
issuer=AnyHttpUrl(BASE_URL),
|
||||
authorization_endpoint=AnyHttpUrl(f"{BASE_URL}/authorize"), # unused; required
|
||||
token_endpoint=AnyHttpUrl(f"{BASE_URL}/token"),
|
||||
grant_types_supported=["client_credentials"],
|
||||
token_endpoint_auth_methods_supported=["client_secret_basic"],
|
||||
scopes_supported=[DEMO_SCOPE],
|
||||
)
|
||||
return JSONResponse(meta.model_dump(by_alias=True, mode="json", exclude_none=True))
|
||||
|
||||
async def token_endpoint(request: Request) -> JSONResponse:
|
||||
form = await request.form()
|
||||
if form.get("grant_type") != "client_credentials":
|
||||
return JSONResponse({"error": "unsupported_grant_type"}, status_code=400)
|
||||
creds = base64.b64decode(request.headers.get("authorization", "").removeprefix("Basic ")).decode()
|
||||
if creds != f"{DEMO_CLIENT_ID}:{DEMO_CLIENT_SECRET}":
|
||||
return JSONResponse({"error": "invalid_client"}, status_code=401)
|
||||
access = f"access_{secrets.token_hex(16)}"
|
||||
issued[access] = AccessToken(token=access, client_id=DEMO_CLIENT_ID, scopes=[DEMO_SCOPE], expires_at=None)
|
||||
body = OAuthToken(access_token=access, token_type="Bearer", expires_in=3600, scope=DEMO_SCOPE)
|
||||
return JSONResponse(body.model_dump(exclude_none=True), headers={"cache-control": "no-store"})
|
||||
|
||||
return server.streamable_http_app(
|
||||
auth=auth_settings(required_scopes=[DEMO_SCOPE]),
|
||||
token_verifier=_Verifier(),
|
||||
custom_starlette_routes=[
|
||||
Route("/.well-known/oauth-authorization-server", as_metadata, methods=["GET"]),
|
||||
Route("/token", token_endpoint, methods=["POST"]),
|
||||
],
|
||||
transport_security=NO_DNS_REBIND,
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run_app_from_args(build_app)
|
||||
Reference in New Issue
Block a user