René's URL Explorer Experiment


Title: Fix `token_expiry_time` upon context initialization for stored tokens. by keurcien · Pull Request #1784 · modelcontextprotocol/python-sdk · GitHub

Open Graph Title: Fix `token_expiry_time` upon context initialization for stored tokens. by keurcien · Pull Request #1784 · modelcontextprotocol/python-sdk

X Title: Fix `token_expiry_time` upon context initialization for stored tokens. by keurcien · Pull Request #1784 · modelcontextprotocol/python-sdk

Description: Partial fix for #1318. Motivation and Context When storing OAuth tokens in a persistent storage, the OAuthClientProvider context would never refresh tokens, because it would consider tokens valid (by is_token_valid()) and proceed with the expired access_token until it meets a 401 response from the MCP server, forcing users to start a new OAuth flow. The proposed change is small and only solve part of the problem. It's mainly inspired by the discussion from #1318 and the approach taken in the FastMCP library: https://github.com/jlowin/fastmcp/blob/main/src/fastmcp/client/auth/oauth.py This fix works in the case where token.expires_in returned by the TokenStorage is well calculated (which is not the case if we just simply store the OAuthToken as is, cf. below), and when the token endpoint is the default MCP_SERVER_URL/token. This PR could also be considered a draft, as it raises other questions about how client_metadata (in case where token endpoint is not obvious) and how or where token.expires_at values should be stored. How Has This Been Tested? Here's a sample script to test the proposed change (tested with Notion MCP and Linear MCP). It uses a StoredToken class to hold an extra expires_at value, to return a correct token.expires_in value in get_tokens (cf. PrefectHQ/fastmcp@f73b7b5) Steps: Run the script once to retrieve the OAuth token. Rerun the script when the token expires: current implementation would trigger the 401 error. New implementation would silently refresh the token. import asyncio import json from pathlib import Path from urllib.parse import parse_qs, urlparse import httpx from datetime import datetime, timezone, timedelta from pydantic import AnyUrl, BaseModel from mcp import ClientSession from mcp.client.auth import OAuthClientProvider, TokenStorage from mcp.client.streamable_http import streamable_http_client from mcp.shared.auth import OAuthClientInformationFull, OAuthClientMetadata, OAuthToken SERVER_URL = "https://mcp.notion.com/mcp" class StoredToken(BaseModel): token_payload: OAuthToken expires_at: datetime | None class FileTokenStorage(TokenStorage): """File-backed token storage.""" def __init__(self, tokens_file: Path = Path("tokens.json"), client_info_file: Path = Path("client_info.json")): self.tokens_file = tokens_file self.client_info_file = client_info_file async def get_tokens(self) -> OAuthToken | None: if not self.tokens_file.exists(): return None try: stored_token = StoredToken.model_validate_json(self.tokens_file.read_text()) except (OSError, json.JSONDecodeError): return None if stored_token.expires_at is not None: now = datetime.now(timezone.utc) if stored_token.token_payload.expires_in is not None: remaining = stored_token.expires_at - now stored_token.token_payload.expires_in = max(0, int(remaining.total_seconds())) return stored_token.token_payload async def set_tokens(self, tokens: OAuthToken) -> None: expires_at: datetime | None = None if tokens.expires_in is not None: expires_at = datetime.now(timezone.utc) + timedelta(seconds=tokens.expires_in) stored_token = StoredToken(token_payload=tokens, expires_at=expires_at) self.tokens_file.write_text(stored_token.model_dump_json()) async def get_client_info(self) -> OAuthClientInformationFull | None: if not self.client_info_file.exists(): return None try: return OAuthClientInformationFull.model_validate_json(self.client_info_file.read_text()) except (OSError, json.JSONDecodeError): return None async def set_client_info(self, client_info: OAuthClientInformationFull) -> None: self.client_info_file.write_text(client_info.model_dump_json()) async def handle_redirect(auth_url: str) -> None: print(f"Visit: {auth_url}") async def handle_callback() -> tuple[str, str | None]: callback_url = input("Paste callback URL: ") params = parse_qs(urlparse(callback_url).query) return params["code"][0], params.get("state", [None])[0] async def main(): """Run the OAuth client example.""" oauth_auth = OAuthClientProvider( server_url=SERVER_URL, client_metadata=OAuthClientMetadata( client_name="Example MCP Client", redirect_uris=[AnyUrl("http://localhost:3000/callback")], grant_types=["authorization_code", "refresh_token"], response_types=["code"], scope="user", ), storage=FileTokenStorage(), redirect_handler=handle_redirect, callback_handler=handle_callback, ) async with httpx.AsyncClient(auth=oauth_auth, follow_redirects=True) as custom_client: async with streamable_http_client(SERVER_URL, http_client=custom_client) as (read, write, _): async with ClientSession(read, write) as session: await session.initialize() tools = await session.list_tools() print(f"Available tools: {[tool.name for tool in tools.tools]}") resources = await session.list_resources() print(f"Available resources: {[r.uri for r in resources.resources]}") def run(): asyncio.run(main()) if __name__ == "__main__": run() Breaking Changes No breaking changes. Types of changes Bug fix (non-breaking change which fixes an issue) New feature (non-breaking change which adds functionality) Breaking change (fix or feature that would cause existing functionality to change) Documentation update Checklist I have read the MCP Documentation My code follows the repository's style guidelines New and existing tests pass locally I have added appropriate error handling I have added or updated documentation as needed Additional context The added tests complement the existing test_token_validity_check as it assumes the token_expiry_time gets set at initialization.

Open Graph Description: Partial fix for #1318. Motivation and Context When storing OAuth tokens in a persistent storage, the OAuthClientProvider context would never refresh tokens, because it would consider tokens valid (...

X Description: Partial fix for #1318. Motivation and Context When storing OAuth tokens in a persistent storage, the OAuthClientProvider context would never refresh tokens, because it would consider tokens valid (...

Opengraph URL: https://github.com/modelcontextprotocol/python-sdk/pull/1784

X: @github

direct link

Domain: github.com

react-profiling0
react-import-mapreact,react-dom,react-dom/client,react-dom/profiling,react-is,react/compiler-runtime,react/jsx-dev-runtime,react/jsx-runtime,scheduler@b8488ee2c322
route-pattern/:user_id/:repository/pull/:id/files(.:format)
route-controllerpull_requests
route-actionfiles
fetch-noncev2:a32bd0cd-df23-0fc5-e5c9-ee23a406ac0f
current-catalog-service-hashae870bc5e265a340912cde392f23dad3671a0a881730ffdadd82f2f57d81641b
request-id916C:2F9718:1471163:1B6E48F:6B013880
html-safe-nonce261451ec4890417a4c8b111c15c476806b225e688ed1ad4f786d51a1e7f22a58
visitor-payloadeyJyZWZlcnJlciI6IiIsInJlcXVlc3RfaWQiOiI5MTZDOjJGOTcxODoxNDcxMTYzOjFCNkU0OEY6NkIwMTM4ODAiLCJ2aXNpdG9yX2lkIjoiMjUxMDMzMjUzNzE4NDc5NDc1MiIsInJlZ2lvbl9lZGdlIjoiaWFkIiwicmVnaW9uX3JlbmRlciI6ImlhZCJ9
visitor-hmac007b720a8cdb2603dc04c4990164ee1d8c7590e6c410612351b53e5ed65e0313
hovercard-subject-tagpull_request:3097064176
github-keyboard-shortcutsrepository,pull-request-list,pull-request-conversation,pull-request-files-changed,copilot
google-site-verificationApib7-x98H0j5cPqHWwSMm6dNU4GmODRoqxLiDzdx9I
octolytics-urlhttps://collector.github.com/github/collect
analytics-location///pull_requests/show/files
fb:app_id1401488693436528
apple-itunes-appapp-id=1477376905, app-argument=https://github.com/modelcontextprotocol/python-sdk/pull/1784/files
twitter:imagehttps://avatars.githubusercontent.com/u/11570911?s=400&v=4
twitter:cardsummary_large_image
og:imagehttps://avatars.githubusercontent.com/u/11570911?s=400&v=4
og:image:altPartial fix for #1318. Motivation and Context When storing OAuth tokens in a persistent storage, the OAuthClientProvider context would never refresh tokens, because it would consider tokens valid (...
og:site_nameGitHub
og:typeobject
hostnamegithub.com
expected-hostnamegithub.com
Nonecc5dfdd32f62ebd3223cab3af3aa2b268d3605218237326a48a99d1efd89495c
turbo-cache-controlno-preview
diff-viewunified
go-importgithub.com/modelcontextprotocol/python-sdk git https://github.com/modelcontextprotocol/python-sdk.git
octolytics-dimension-user_id182288589
octolytics-dimension-user_loginmodelcontextprotocol
octolytics-dimension-repository_id862584018
octolytics-dimension-repository_nwomodelcontextprotocol/python-sdk
octolytics-dimension-repository_publictrue
octolytics-dimension-repository_is_forkfalse
octolytics-dimension-repository_network_root_id862584018
octolytics-dimension-repository_network_root_nwomodelcontextprotocol/python-sdk
turbo-body-classeslogged-out env-production page-responsive full-width
disable-turbotrue
browser-stats-urlhttps://api.github.com/_private/browser/stats
browser-errors-urlhttps://api.github.com/_private/browser/errors
release8c77c9e8439031ad54c75a250694842892f693e1
ui-targetfull
theme-color#1e2327
color-schemelight dark

Links:

Skip to contenthttps://github.com/modelcontextprotocol/python-sdk/pull/1784/files#start-of-content
https://github.com/
Sign inhttps://github.com/login?return_to=https%3A%2F%2Fgithub.com%2Fmodelcontextprotocol%2Fpython-sdk%2Fpull%2F1784%2Ffiles
GitHubRepository hosting, code review, and collaborationhttps://github.com/platform
CopilotAI coding agent for tasks, projects, and automated workhttps://github.com/features/copilot
ActionsCI/CD and automationhttps://github.com/features/actions
Code QualityQuality analysis, fixes, and enforcementhttps://github.com/features/code-quality
CodespacesCloud development environmentshttps://github.com/features/codespaces
Code SecurityVulnerability detection and remediationhttps://github.com/security/advanced-security/code-security
Secret ProtectionSecret scanning and leak preventionhttps://github.com/security/advanced-security/secret-protection
All Featureshttps://github.com/features
Documentationhttps://docs.github.com/en
Traininghttps://learn.github.com/skills
Certificationshttps://learn.github.com/credentials
Build with Copilothttps://github.com/features/ai
Customize Copilothttps://docs.github.com/en/copilot/how-tos/copilot-on-github/customize-copilot/customize-copilot-overview
Integrationshttps://github.com/marketplace
Trending reposhttps://github.com/trending
GitHub Sponsorshttps://github.com/open-source/sponsors
Developer articleshttps://github.com/resources/articles
ChangelogYour source for the latest features, improvements, and fixes across GitHub products, all in one place.https://github.blog/changelog/
Enterpriseshttps://github.com/enterprise
Teamhttps://github.com/team
Startupshttps://github.com/enterprise/startups
Nonprofitshttps://github.com/solutions/industry/nonprofits
Healthcarehttps://github.com/solutions/industry/healthcare
Financial serviceshttps://github.com/solutions/industry/financial-services
Manufacturinghttps://github.com/solutions/industry/manufacturing
Governmenthttps://github.com/solutions/industry/government
See all industrieshttps://github.com/solutions/industry
Why GitHubhttps://github.com/why-github
Customer Storieshttps://github.com/customer-stories
Business insightshttps://github.com/solutions/executive-insights
Trust Centerhttps://github.com/trust-center
GitHub Advanced SecurityEnterprise-grade code securityhttps://github.com/security/advanced-security
Copilot for businessEnterprise-grade AI featureshttps://github.com/features/copilot/copilot-business
Premium SupportEnterprise-grade 24/7 supporthttps://github.com/enterprise/premium-support
Documentationhttps://docs.github.com/en
Resource centerhttps://github.com/resources
Bloghttps://github.blog/
Events & webinarshttps://github.com/resources/events
Community Forumhttps://github.com/orgs/community/discussions
Customer Storieshttps://github.com/customer-stories
Integrationshttps://github.com/marketplace
Customer supporthttps://help.github.com/
Traininghttps://learn.github.com/skills
GitHub Statushttps://www.githubstatus.com/
Abouthttps://github.com/about
Partnershttps://github.com/partners
Changeloghttps://github.blog/changelog/
GitHub UniverseThe event for developers, by developers — talks, workshops, and what’s next for GitHub.https://githubuniverse.com/
Pricinghttps://github.com/pricing
Sign inhttps://github.com/login?return_to=https%3A%2F%2Fgithub.com%2Fmodelcontextprotocol%2Fpython-sdk%2Fpull%2F1784%2Ffiles
Sign uphttps://github.com/signup?ref_cta=Sign+up&ref_loc=header+logged+out&ref_page=%2F%3Cuser-name%3E%2F%3Crepo-name%3E%2Fpull_requests%2Fshow%2Ffiles&source=header-repo&source_repo=modelcontextprotocol%2Fpython-sdk
Reloadhttps://github.com/modelcontextprotocol/python-sdk/pull/1784/files
Reloadhttps://github.com/modelcontextprotocol/python-sdk/pull/1784/files
Reloadhttps://github.com/modelcontextprotocol/python-sdk/pull/1784/files
modelcontextprotocolhttps://github.com/modelcontextprotocol
python-sdkhttps://github.com/modelcontextprotocol/python-sdk
Codehttps://github.com/modelcontextprotocol/python-sdk
Issues315 (315)https://github.com/modelcontextprotocol/python-sdk/issues
Pull requests112 (112)https://github.com/modelcontextprotocol/python-sdk/pulls
Actionshttps://github.com/modelcontextprotocol/python-sdk/actions
Projectshttps://github.com/modelcontextprotocol/python-sdk/projects
Security and quality12 (12)https://github.com/modelcontextprotocol/python-sdk/security
Insightshttps://github.com/modelcontextprotocol/python-sdk/insights
Sign up for GitHub https://github.com/signup?return_to=%2Fmodelcontextprotocol%2Fpython-sdk%2Fissues%2Fnew%2Fchoose
terms of servicehttps://docs.github.com/terms
privacy statementhttps://docs.github.com/privacy
Sign inhttps://github.com/login?return_to=%2Fmodelcontextprotocol%2Fpython-sdk%2Fissues%2Fnew%2Fchoose
keurcienhttps://github.com/keurcien
modelcontextprotocol:mainhttps://github.com/modelcontextprotocol/python-sdk/tree/main
keurcien:fix/token-expiry-time-on-inithttps://github.com/keurcien/python-sdk/tree/fix/token-expiry-time-on-init
Conversation 3 https://github.com/modelcontextprotocol/python-sdk/pull/1784
Commits 6 https://github.com/modelcontextprotocol/python-sdk/pull/1784/commits
Checks 23 https://github.com/modelcontextprotocol/python-sdk/pull/1784/checks
Files changed https://github.com/modelcontextprotocol/python-sdk/pull/1784/files
Please reload this pagehttps://github.com/modelcontextprotocol/python-sdk/pull/1784/files
Fix token_expiry_time upon context initialization for stored tokens. https://github.com/modelcontextprotocol/python-sdk/pull/1784/files#top
Show all changes 6 commits https://github.com/modelcontextprotocol/python-sdk/pull/1784/files
c9cae41 Set token_expiry_time upon context initialization keurcien Dec 12, 2025 https://github.com/modelcontextprotocol/python-sdk/pull/1784/commits/c9cae41fec0dd99628e08722baf1b2ee36020859
31c1cd6 Add tests that complement test_token_validity_check keurcien Dec 12, 2025 https://github.com/modelcontextprotocol/python-sdk/pull/1784/commits/31c1cd6b9a963227a22301944432b55115b3b85a
f875a8f Check that expires_in is explicitly not None, can be 0 keurcien Dec 12, 2025 https://github.com/modelcontextprotocol/python-sdk/pull/1784/commits/f875a8f7addba38b262b341e2feb3778185c4cb5
fa48916 Fix format keurcien Dec 12, 2025 https://github.com/modelcontextprotocol/python-sdk/pull/1784/commits/fa489164e17d641b375f81508c098c8a664ba98c
3070654 Try fix Windows checks by setting expiry > 0 keurcien Dec 12, 2025 https://github.com/modelcontextprotocol/python-sdk/pull/1784/commits/30706541f1ebb273f8e7e6c4464c095bb18100fe
06a1eff Merge branch 'main' into fix/token-expiry-time-on-init keurcien Jan 18, 2026 https://github.com/modelcontextprotocol/python-sdk/pull/1784/commits/06a1effdb982b6c7b38eed42bed58fae3b03fad9
Clear filters https://github.com/modelcontextprotocol/python-sdk/pull/1784/files
Please reload this pagehttps://github.com/modelcontextprotocol/python-sdk/pull/1784/files
Please reload this pagehttps://github.com/modelcontextprotocol/python-sdk/pull/1784/files
oauth2.py https://github.com/modelcontextprotocol/python-sdk/pull/1784/files#diff-b7aaf2062da175cea9a532176d6eb78b659eaadb757cc48929f0bafccfdb8d98
test_auth.py https://github.com/modelcontextprotocol/python-sdk/pull/1784/files#diff-f083d075f463e8b1ecfa6b931c33288c3d09b00ee3af3e5f74df16b7e75c3ab1
src/mcp/client/auth/oauth2.pyhttps://github.com/modelcontextprotocol/python-sdk/pull/1784/files#diff-b7aaf2062da175cea9a532176d6eb78b659eaadb757cc48929f0bafccfdb8d98
View file https://github.com/modelcontextprotocol/python-sdk/blob/06a1effdb982b6c7b38eed42bed58fae3b03fad9/src/mcp/client/auth/oauth2.py
Open in desktop https://desktop.github.com
https://github.co/hiddenchars
https://github.com/modelcontextprotocol/python-sdk/pull/1784/{{ revealButtonHref }}
https://github.com/modelcontextprotocol/python-sdk/pull/1784/files#diff-b7aaf2062da175cea9a532176d6eb78b659eaadb757cc48929f0bafccfdb8d98
https://github.com/modelcontextprotocol/python-sdk/pull/1784/files#diff-b7aaf2062da175cea9a532176d6eb78b659eaadb757cc48929f0bafccfdb8d98
tests/client/test_auth.pyhttps://github.com/modelcontextprotocol/python-sdk/pull/1784/files#diff-f083d075f463e8b1ecfa6b931c33288c3d09b00ee3af3e5f74df16b7e75c3ab1
View file https://github.com/modelcontextprotocol/python-sdk/blob/06a1effdb982b6c7b38eed42bed58fae3b03fad9/tests/client/test_auth.py
Open in desktop https://desktop.github.com
https://github.co/hiddenchars
https://github.com/modelcontextprotocol/python-sdk/pull/1784/{{ revealButtonHref }}
https://github.com/modelcontextprotocol/python-sdk/pull/1784/files#diff-f083d075f463e8b1ecfa6b931c33288c3d09b00ee3af3e5f74df16b7e75c3ab1
https://github.com/modelcontextprotocol/python-sdk/pull/1784/files#diff-f083d075f463e8b1ecfa6b931c33288c3d09b00ee3af3e5f74df16b7e75c3ab1
https://github.com/modelcontextprotocol/python-sdk/pull/1784/files#diff-f083d075f463e8b1ecfa6b931c33288c3d09b00ee3af3e5f74df16b7e75c3ab1
https://github.com/modelcontextprotocol/python-sdk/pull/1784/files#diff-f083d075f463e8b1ecfa6b931c33288c3d09b00ee3af3e5f74df16b7e75c3ab1
Please reload this pagehttps://github.com/modelcontextprotocol/python-sdk/pull/1784/files
https://github.com
Termshttps://docs.github.com/site-policy/github-terms/github-terms-of-service
Privacyhttps://docs.github.com/site-policy/privacy-policies/github-privacy-statement
Securityhttps://github.com/security
Statushttps://www.githubstatus.com/
Communityhttps://github.community/
Docshttps://docs.github.com/
Contacthttps://support.github.com?tags=dotcom-footer

Viewport: width=device-width


URLs of crawlers that visited me.