Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion plugins/glean/.claude-plugin/plugin.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "glean-vnext",
"version": "0.2.50",
"version": "0.2.51",
"description": "Glean plugin for discovering skills and running tools.",
"author": {
"name": "Glean"
Expand Down
2 changes: 1 addition & 1 deletion plugins/glean/.codex-plugin/plugin.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "glean-vnext",
"version": "0.2.50",
"version": "0.2.51",
"description": "Glean Codex plugin for discovering skills and running tools.",
"author": {
"name": "Glean"
Expand Down
2 changes: 1 addition & 1 deletion plugins/glean/.cursor-plugin/plugin.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "glean-vnext",
"displayName": "Glean vNext",
"version": "0.2.50",
"version": "0.2.51",
"description": "Search and act across your company's apps — Jira, Slack, Salesforce, Google Workspace, and more — without leaving Cursor.",
"author": {
"name": "Glean"
Expand Down
69 changes: 61 additions & 8 deletions plugins/glean/dist/index.js

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

51 changes: 48 additions & 3 deletions src/auth-provider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,21 @@ import type {
OAuthTokens,
} from "@modelcontextprotocol/sdk/shared/auth.js";
import { execFile, spawn } from "node:child_process";
import { setTimeout as sleep } from "node:timers/promises";
import { platform } from "node:os";
import { getCallbackUrl, setExpectedState } from "./auth-callback-server.js";
import { clearCredentials, loadCredentials, saveCredentials } from "./token-store.js";
import {
clearCredentials,
loadCredentials,
saveCredentials,
} from "./token-store.js";

export type InvalidationScope = "all" | "client" | "tokens" | "verifier";

// Grace window for a sibling's in-flight refresh to land on disk.
const ROTATION_GRACE_MS = 2000;
const ROTATION_POLL_MS = 100;

/**
* Open `url` in the user's default browser. Used for the self-open sign-in
* path when the client does not support URL-mode elicitation (where the client
Expand Down Expand Up @@ -47,7 +56,6 @@ export class GleanOAuthClientProvider implements OAuthClientProvider {
// explicitly invalidating. Used to detect when a previous auth URL didn't
// complete — likely because the server rejected the (stale) client_id.
private _authUrlPending = false;

authorizationUrl: string | undefined;

/**
Expand All @@ -66,6 +74,33 @@ export class GleanOAuthClientProvider implements OAuthClientProvider {
}
}

// Re-read the shared store on every token access so a sibling's rotated
// grant is used instead of a stale in-memory copy.
private syncTokensFromDisk(): void {
Comment thread
pragati-agrawal-glean marked this conversation as resolved.
Resolved
const stored = loadCredentials();
if (!stored) return;
if (stored.tokens) {
this._tokens = stored.tokens as OAuthTokens;
}
if (stored.clientInfo) {
this._clientInfo = stored.clientInfo as OAuthClientInformationMixed;
}
}

// Wait for a sibling's refresh to land on disk. Returns true once a
// different access token is available for adoption/retry.
async waitForSiblingRefresh(
Comment thread
pragati-agrawal-glean marked this conversation as resolved.
Resolved
previousAccessToken: string | undefined,
): Promise<boolean> {
const deadline = Date.now() + ROTATION_GRACE_MS;
for (;;) {
const current = this.tokens()?.access_token;
if (current && current !== previousAccessToken) return true;
if (Date.now() >= deadline) return false;
await sleep(ROTATION_POLL_MS);
}
}

get redirectUrl(): string {
return getCallbackUrl();
}
Expand All @@ -87,6 +122,7 @@ export class GleanOAuthClientProvider implements OAuthClientProvider {
}

tokens(): OAuthTokens | undefined {
this.syncTokensFromDisk();
return this._tokens;
}

Expand All @@ -112,10 +148,19 @@ export class GleanOAuthClientProvider implements OAuthClientProvider {
this._clientInfo = undefined;
saveCredentials(this._tokens, undefined);
break;
case "tokens":
case "tokens": {
// Usually a sibling's rotation — try adopting before clearing.
const previousAccessToken = this._tokens?.access_token;
if (
this._tokens?.refresh_token &&
(await this.waitForSiblingRefresh(previousAccessToken))
) {
return;
}
this._tokens = undefined;
saveCredentials(undefined, this._clientInfo);
break;
}
case "verifier":
this._codeVerifier = "";
break;
Expand Down
49 changes: 46 additions & 3 deletions src/remote-client.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
import { UnauthorizedError } from "@modelcontextprotocol/sdk/client/auth.js";
import { OAuthError } from "@modelcontextprotocol/sdk/server/auth/errors.js";
import type { CallToolResult } from "@modelcontextprotocol/sdk/types.js";
import type { GleanOAuthClientProvider } from "./auth-provider.js";
import { pluginVersionString } from "./version.js";
Expand Down Expand Up @@ -146,6 +147,7 @@ export async function createRemoteClient(
serverUrl: string,
opts: RemoteClientOptions,
chatSessionId?: string,
authRetry = false,
): Promise<Client> {
const authProvider = opts.authProvider;

Expand Down Expand Up @@ -191,21 +193,62 @@ export async function createRemoteClient(
{ capabilities: {} },
);

// Snapshot to detect a sibling's refresh between connect and failure.
const accessTokenAtConnect = authProvider?.tokens()?.access_token;

const transport = buildTransport(serverUrl, opts, chatSessionId);

try {
await client.connect(transport);
} catch (error) {
if (error instanceof UnauthorizedError && authProvider?.authorizationUrl) {
pendingTransport = transport;
throw new AuthRequiredError(authProvider.authorizationUrl);
if (error instanceof UnauthorizedError && authProvider) {
const refreshedAccessToken = authProvider.tokens()?.access_token;
if (
!authRetry &&
refreshedAccessToken &&
refreshedAccessToken !== accessTokenAtConnect
) {
console.error(
"[auth] Auth failed but a newer token is on disk " +
"(sibling refresh) — retrying once",
);
return createRemoteClient(serverUrl, opts, chatSessionId, true);
}
if (authProvider.authorizationUrl) {
pendingTransport = transport;
throw new AuthRequiredError(authProvider.authorizationUrl);
}
}
// Concurrent-refresh losers are reported with structured OAuth errors
// (typically invalid_request); retry once if a sibling's grant lands in the
// grace window.
if (
authProvider &&
!authRetry &&
isRefreshOAuthError(error) &&
(await authProvider.waitForSiblingRefresh(accessTokenAtConnect))
) {
console.error(
"[auth] Refresh failed but a sibling refreshed — retrying with its token",
);
return createRemoteClient(serverUrl, opts, chatSessionId, true);
}
throw error;
}

return client;
}

// Restrict recovery to OAuth errors that can indicate a refresh race. The SDK
// preserves the response's machine-readable error code.
function isRefreshOAuthError(error: unknown): boolean {
return (
error instanceof OAuthError &&
(error.errorCode === "invalid_request" ||
error.errorCode === "invalid_grant")
);
}

export async function callRemoteTool(
client: Client,
name: string,
Expand Down
7 changes: 5 additions & 2 deletions src/token-store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,11 +31,14 @@ export function saveCredentials(tokens: unknown, clientInfo: unknown): void {
fs.mkdirSync(dir, { recursive: true, mode: DIR_MODE });
fs.chmodSync(dir, DIR_MODE);
const data: StoredCredentials = { tokens, clientInfo };
fs.writeFileSync(filePath, JSON.stringify(data, null, 2), {
// Temp-file + rename: concurrent readers never see a half-written store.
const tmpPath = `${filePath}.${process.pid}.tmp`;
fs.writeFileSync(tmpPath, JSON.stringify(data, null, 2), {
encoding: "utf-8",
mode: FILE_MODE,
});
fs.chmodSync(filePath, FILE_MODE);
Comment thread
pragati-agrawal-glean marked this conversation as resolved.
Resolved
fs.chmodSync(tmpPath, FILE_MODE);
fs.renameSync(tmpPath, filePath);
} catch (err) {
const msg = err instanceof Error ? err.message : String(err);
console.error(`[auth] Failed to persist credentials: ${msg}`);
Expand Down
Loading
Loading