Skip to content

Open source alternative to Semrush and Ahrefs

Tell MCP clients to sign in again when their OAuth grant is gone (EVE-454) (#1000)

Carter Smith5051fdb6924d
diff --git a/src/server/mcp/oauth-errors.ts b/src/server/mcp/oauth-errors.ts
new file mode 100644
index 00000000..38756d17
--- /dev/null
+++ b/src/server/mcp/oauth-errors.ts
@@ -0,0 +1,46 @@
+// The provider's refresh-token failures that only a new sign-in can fix: the
+// grant sat idle past its 30-day window or was revoked. The bare provider text
+// ("Grant not found") doesn't tell the agent or the user what to do next.
+const DEAD_GRANT_REASONS = new Set([
+ "grant_not_found",
+ "refresh_token_mismatch",
+]);
+const REAUTHORIZE_DESCRIPTION =
+ "Your OpenSEO sign-in has expired or was revoked. Reconnect OpenSEO in your agent and approve the sign-in again: https://openseo.so/docs/agent-setup";
+
+export function handleOAuthError(error: {
+ code: string;
+ description: string;
+ status: number;
+ headers: Record<string, string>;
+ internal: { category: string; reason: string };
+}) {
+ // 401s here are the standard OAuth discovery handshake, not failures: an
+ // unauthenticated /mcp hit returns `invalid_token` (which triggers the
+ // client's .well-known discovery), and stale client registrations draw
+ // `invalid_client` until the client re-registers. Log those at debug so
+ // they stop masquerading as errors; keep 5xx at error and everything else
+ // (bad client metadata, etc.) at warn.
+ const line = `[oauth] ${error.status} ${error.code}: ${error.description}`;
+ if (error.status === 401) {
+ console.debug(line);
+ } else if (error.status >= 500) {
+ console.error(line);
+ } else {
+ console.warn(line);
+ }
+
+ // Keep the invalid_grant code so clients still start a new authorization.
+ if (
+ error.internal.category === "refresh-token-grant" &&
+ DEAD_GRANT_REASONS.has(error.internal.reason)
+ ) {
+ return Response.json(
+ { error: error.code, error_description: REAUTHORIZE_DESCRIPTION },
+ { status: error.status, headers: error.headers },
+ );
+ }
+
+ // Returning void delegates the standards-compliant body, bearer challenge,
+ // and CORS headers to workers-oauth-provider.
+}
diff --git a/src/server/mcp/oauth-provider.ts b/src/server/mcp/oauth-provider.ts
index 91a704f8..8dab7b34 100644
--- a/src/server/mcp/oauth-provider.ts
+++ b/src/server/mcp/oauth-provider.ts
@@ -28,6 +28,7 @@ import {
MCP_ROUTE,
workersOAuthMcpPropsSchema,
} from "@/server/mcp/context";
+import { handleOAuthError } from "@/server/mcp/oauth-errors";
import { normalizeClientRegistrationRequest } from "@/server/mcp/oauth-registration";
import { getPublicOrigin } from "@/server/mcp/public-origin";
import { resolveHostedContext } from "@/middleware/ensure-user/hosted";
@@ -107,30 +108,6 @@ function jsonResponse(body: unknown, init?: ResponseInit) {
});
}
-function logOAuthError(error: {
- code: string;
- description: string;
- status: number;
-}) {
- // 401s here are the standard OAuth discovery handshake, not failures: an
- // unauthenticated /mcp hit returns `invalid_token` (which triggers the
- // client's .well-known discovery), and stale client registrations draw
- // `invalid_client` until the client re-registers. Log those at debug so
- // they stop masquerading as errors; keep 5xx at error and everything else
- // (bad client metadata, etc.) at warn.
- const line = `[oauth] ${error.status} ${error.code}: ${error.description}`;
- if (error.status === 401) {
- console.debug(line);
- } else if (error.status >= 500) {
- console.error(line);
- } else {
- console.warn(line);
- }
-
- // Returning void delegates the standards-compliant body, bearer challenge,
- // and CORS headers to workers-oauth-provider.
-}
-
function csrfProtected(request: Request) {
const origin = request.headers.get("Origin");
return origin === getPublicOrigin(request);
@@ -429,7 +406,7 @@ function createProvider(appFetch: AppFetch, resource: string) {
}),
};
},
- onError: logOAuthError,
+ onError: handleOAuthError,
});
}
diff --git a/src/server/mcp/oauth-refresh.e2e.test.ts b/src/server/mcp/oauth-refresh.e2e.test.ts
index e3c94b1f..6f17e638 100644
--- a/src/server/mcp/oauth-refresh.e2e.test.ts
+++ b/src/server/mcp/oauth-refresh.e2e.test.ts
@@ -57,8 +57,8 @@ vi.mock("@/server/mcp/transport", () => ({
): Promise<Response> => Promise.resolve(Response.json({ props })),
}));
-// Minimal in-memory KVNamespace honoring expirationTtl against Date.now(), so
-// vi.setSystemTime drives token/grant expiry.
+// Minimal in-memory KVNamespace honoring expiration/expirationTtl against
+// Date.now(), so vi.setSystemTime drives token/grant expiry.
function createKvFake() {
const store = new Map<
string,
@@ -87,15 +87,21 @@ function createKvFake() {
put(
key: string,
value: string,
- options?: { expirationTtl?: number; metadata?: unknown },
+ options?: {
+ expiration?: number;
+ expirationTtl?: number;
+ metadata?: unknown;
+ },
) {
store.set(key, {
value,
metadata: options?.metadata,
expiresAt:
- options?.expirationTtl !== undefined
- ? Date.now() + options.expirationTtl * 1000
- : undefined,
+ options?.expiration !== undefined
+ ? options.expiration * 1000
+ : options?.expirationTtl !== undefined
+ ? Date.now() + options.expirationTtl * 1000
+ : undefined,
});
return Promise.resolve();
},
@@ -334,8 +340,12 @@ describe("Codex-style OAuth token refresh (real workers-oauth-provider)", () =>
vi.setSystemTime(startedAt + 62 * day);
const expired = await refresh(client.client_id, rotated.refresh_token);
expect(expired.status).toBe(400);
- expect(tokenErrorSchema.parse(await expired.json()).error).toBe(
- "invalid_grant",
+ const body = tokenErrorSchema
+ .extend({ error_description: z.string() })
+ .parse(await expired.json());
+ expect(body.error).toBe("invalid_grant");
+ expect(body.error_description).toContain(
+ "https://openseo.so/docs/agent-setup",
);
});