Refresh OAuth token before expiry instead of fetching once at startup - #4
Open
stefangordon wants to merge 1 commit into
Open
stefangordon wants to merge 1 commit into
stefangordon wants to merge 1 commit into
Conversation
The access token was fetched a single time at module load and stored in a global that was never refreshed. DigiKey client-credentials tokens expire after ~600s (expires_in), so after ~10 minutes every request returned 401 until the server was restarted. Cache the token together with its expiry and refresh on demand ~60s before it lapses, and add a one-time refresh-and-retry on any 401 as a safety net for early revocation. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Problem
The access token is fetched exactly once at module load and stored in a global that is never refreshed:
DigiKey's client-credentials tokens are short-lived — the token response reports
expires_in≈600(10 minutes). Once that window passes, every tool call returns:…and stays broken until the server process is restarted. Users report "it works for a while, then starts 401ing," which matches the token lifetime exactly.
Fix
expires_atand refresh on demand ~60s before it lapses (_valid_token()/get_access_token()).Behavior is unchanged for callers —
_get_headers()now transparently uses a valid token.Verification
With this change the startup log shows
Successfully obtained access token (expires in 599s), and requests made after the original 10-minute window succeed instead of 401ing (a fresh token is fetched automatically).🤖 Generated with Claude Code