OAuthProvider
Tool-level OAuth 2.0 Authorization Code flow via MCP elicitation.
OAuthProvider
OAuthProvider(
name: str,
build_auth_url: Callable[[str, str], str],
exchange_code: Callable[
..., Coroutine[Any, Any, ExchangeResult]
],
redirect_uri: str,
user_context: ContextVar[dict | None],
token_store: TokenStore | None = None,
pending_store: PendingStore | None = None,
refresh_token_fn: Callable[
..., Coroutine[Any, Any, ExchangeResult]
]
| None = None,
token_timeout: float = 120.0,
)
Generic MCP OAuth elicitation provider (MCP spec 2025-11-25).
Gates MCP tools behind a third-party OAuth flow. Handles the complete token lifecycle: first-time elicitation, expiry checking, silent refresh, and reactive invalidation.
Token lifecycle
- First call — no token → URL mode elicitation → browser OAuth → callback → token stored → tool proceeds.
- Next calls — token valid → tool proceeds immediately.
- Expiry known (expires_in provided) — silent refresh via refresh_token_fn if available; else re-elicitation.
- Revocation — tool detects API 401, calls
await provider.invalidate_token(sub)and returns an error string → next call triggers re-elicitation.
Elicitation modes
require_token(fail_fast=False) [default] Calls ctx.elicit_url(); the tool call stays open and waits for the OAuth callback via PendingStore. After the callback fires, send_elicit_complete notifies the client (spec §3.4).
require_token(fail_fast=True) Raises UrlElicitationRequiredError (JSON-RPC -32042, spec §3.5) immediately. The client retries the tool call after the OAuth flow.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
|
required |
build_auth_url
|
Callable[[str, str], str]
|
|
required |
exchange_code
|
Callable[..., Coroutine[Any, Any, ExchangeResult]]
|
|
required |
redirect_uri
|
str
|
|
required |
user_context
|
ContextVar[dict | None]
|
|
required |
token_store
|
TokenStore | None
|
|
None
|
pending_store
|
PendingStore | None
|
|
None
|
refresh_token_fn
|
Callable[..., Coroutine[Any, Any, ExchangeResult]] | None
|
|
None
|
token_timeout
|
float
|
|
120.0
|
Initialise the provider; see class docstring for parameter descriptions.
Source code in mcpauthkit/providers/oauth_provider.py
149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 | |
from_standard_oauth2
classmethod
from_standard_oauth2(
*,
name: str,
authorization_url: str,
token_url: str,
client_id: str,
client_secret: str,
scope: str,
redirect_uri: str,
user_context: ContextVar[dict | None],
token_store: TokenStore | None = None,
pending_store: PendingStore | None = None,
refresh_token_fn: Callable[
..., Coroutine[Any, Any, ExchangeResult]
]
| None = None,
token_timeout: float = 120.0,
http_verify: bool | SSLContext | str = True,
extra_authorize_params: dict[str, str] | None = None,
) -> OAuthProvider
Convenience factory for any standard OAuth2 Authorization Code provider (GitHub, Google, Jira, Entra, Okta, etc.).
Builds build_auth_url and exchange_code internally from standard
OAuth2 endpoints so the caller only needs to supply configuration::
github = OAuthProvider.from_standard_oauth2(
name="github",
authorization_url="https://github.com/login/oauth/authorize",
token_url="https://github.com/login/oauth/access_token",
client_id=settings.github_client_id,
client_secret=settings.github_client_secret,
scope="read:user repo",
redirect_uri="http://localhost:8005/github/callback",
user_context=current_user,
http_verify=_SSL_CTX,
)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
authorization_url
|
str
|
Full URL of the provider's authorization endpoint. |
required |
token_url
|
str
|
Full URL of the provider's token endpoint. |
required |
client_id
|
str
|
OAuth2 client ID. |
required |
client_secret
|
str
|
OAuth2 client secret. |
required |
scope
|
str
|
Space-separated scope string. |
required |
http_verify
|
bool | SSLContext | str
|
Passed as |
True
|
extra_authorize_params
|
dict[str, str] | None
|
Optional extra query parameters appended to every authorization URL.
Use this for provider-specific routing hints that are not part of the
standard OAuth2 spec. For example, Okta supports an
These parameters are merged into the standard ones
( |
None
|
token_store
|
TokenStore | None
|
Optional persistent store override. |
None
|
pending_store
|
PendingStore | None
|
Optional pending store override. |
None
|
name
|
str
|
Same as |
required |
redirect_uri
|
str
|
Same as |
required |
user_context
|
str
|
Same as |
required |
refresh_token_fn
|
str
|
Same as |
required |
token_timeout
|
str
|
Same as |
required |
Source code in mcpauthkit/providers/oauth_provider.py
194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 | |
get_token
get_token() -> str | None
Return the access token for the current tool invocation. Only meaningful inside a @require_token()-decorated function.
Source code in mcpauthkit/providers/oauth_provider.py
332 333 334 335 | |
invalidate_token
async
invalidate_token(sub: str) -> None
Remove the cached token for a user, forcing re-elicitation on the next tool invocation.
Call this when the downstream API returns 401::
token = provider.get_token()
resp = await _api_get("/path", token)
if resp.status_code == 401:
await provider.invalidate_token(current_user.get()["sub"])
return "Authorization expired — please retry."
Source code in mcpauthkit/providers/oauth_provider.py
337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 | |
require_token
require_token(*, fail_fast: bool = False) -> Callable
Decorator factory that gates an async MCP tool behind OAuth.
Apply AFTER @mcp.tool()::
@mcp.tool(description="...")
@provider.require_token()
async def my_tool(ctx: Context, arg: str) -> str:
token = provider.get_token() # guaranteed non-None here
...
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
fail_fast
|
bool
|
False (default): tool call stays open during the OAuth flow. True: raises UrlElicitationRequiredError; client must retry. |
False
|
Source code in mcpauthkit/providers/oauth_provider.py
353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 | |
register
register(app: FastAPI) -> None
Register the OAuth callback GET route on a FastAPI app.
Call this before mounting the MCP sub-app (app.mount("/", ...)).
The callback path must also be in open_paths so the auth middleware
does not reject the unauthenticated redirect. Use
provider.callback_path to reference the path dynamically.
Source code in mcpauthkit/providers/oauth_provider.py
404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 | |
Provider-specific routing hints
Some providers require extra query parameters on the authorization URL that are
not part of the standard OAuth 2.0 spec. Pass them via extra_authorize_params
— they are merged into every authorization URL built by the factory.
Okta — routing to an external Identity Provider
Okta supports an idp parameter that bypasses its own login page and routes
users directly to a configured external Identity Provider (e.g. Microsoft Entra,
Google Workspace, a SAML IdP). The value is the IdP ID visible in the Okta
Admin Console under Security → Identity Providers.
okta = OAuthProvider.from_standard_oauth2(
name="okta",
authorization_url="https://your-org.okta.com/oauth2/default/v1/authorize",
token_url="https://your-org.okta.com/oauth2/default/v1/token",
client_id=settings.okta_client_id,
client_secret=settings.okta_client_secret,
scope="openid profile email",
redirect_uri=f"{settings.server_base_url}/okta/callback",
user_context=current_user,
extra_authorize_params={"idp": "0oaz2r21a8RBmZyOL0h7"},
)
The resulting authorization URL will include &idp=0oaz2r21a8RBmZyOL0h7 in
addition to the standard parameters. Standard parameters (client_id,
redirect_uri, scope, state, response_type) always take precedence and
cannot be overridden via extra_authorize_params.
Helper types
_parse_token_data
_parse_token_data(
result: ExchangeResult, stored_at: float
) -> TokenData | None
Normalise an exchange_code / refresh_token_fn result into a TokenData entry.
Source code in mcpauthkit/providers/oauth_provider.py
85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 | |