Skip to content

Refresh OAuth token before expiry instead of fetching once at startup - #4

Open
stefangordon wants to merge 1 commit into
bengineer19:mainfrom
stefangordon:fix-token-refresh
Open

stefangordon wants to merge 1 commit into
bengineer19:mainfrom
stefangordon:fix-token-refresh

Conversation

@stefangordon

Copy link
Copy Markdown

Problem

The access token is fetched exactly once at module load and stored in a global that is never refreshed:

access_token = get_access_token()  # runs once at import

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:

API error: 401 - ...

…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

  • Track expiry: cache the token alongside its expires_at and refresh on demand ~60s before it lapses (_valid_token() / get_access_token()).
  • Retry safety net: if a request still returns 401 (e.g. early revocation / clock skew), force a refresh and retry the request once.

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

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>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant