Skip to content

Open-source Grok Bot alternative with a virtual machine that bots can use

fix(mcp): request advertised offline access

David Neyra89bc1d3469a3
diff --git a/server/mcp-oauth-discovery.test.ts b/server/mcp-oauth-discovery.test.ts
index b734f8442a..520efff559 100644
--- a/server/mcp-oauth-discovery.test.ts
+++ b/server/mcp-oauth-discovery.test.ts
@@ -34,6 +34,18 @@ describe("resourceMetadataUrl", () => {
});
describe("discoverMcpAuth", () => {
+ it.each([
+ [["read"], ["read", "offline_access"], ["read", "offline_access"]],
+ [["read", "offline_access"], ["offline_access"], ["read", "offline_access"]],
+ [["read"], ["read"], ["read"]],
+ [[], ["offline_access"], undefined],
+ ])("combines advertised offline access without changing unspecified or duplicate scopes", async (resourceScopes, authScopes, expected) => {
+ const { impl } = stubFetch({
+ "https://mcp.example.com/.well-known/oauth-protected-resource/mcp": { authorization_servers: ["https://auth.example.com"], scopes_supported: resourceScopes },
+ "https://auth.example.com/.well-known/oauth-authorization-server": { ...AS, scopes_supported: authScopes },
+ });
+ expect((await discoverMcpAuth("https://mcp.example.com/mcp", null, { fetch: impl }))?.scopes).toEqual(expected);
+ });
it("follows the header hint to the authorization server", async () => {
const { impl } = stubFetch({
"https://mcp.example.com/prm": { resource: "https://mcp.example.com/mcp", authorization_servers: ["https://auth.example.com"], scopes_supported: ["read", "write"] },
diff --git a/server/mcp-oauth-discovery.ts b/server/mcp-oauth-discovery.ts
index 2b86459eaf..77679985c4 100644
--- a/server/mcp-oauth-discovery.ts
+++ b/server/mcp-oauth-discovery.ts
@@ -199,7 +199,11 @@ export async function discoverMcpAuth(
const optionalEndpoint = (value: unknown) => typeof value === "string" && isAllowedDiscoveryUrl(value, trustedOrigin) ? value : undefined;
const registrationEndpoint = optionalEndpoint(metadata.registration_endpoint);
const revocationEndpoint = optionalEndpoint(metadata.revocation_endpoint);
- const scopes = stringList(resource?.scopes_supported);
+ const resourceScopes = stringList(resource?.scopes_supported);
+ const authorizationScopes = stringList(metadata.scopes_supported);
+ const scopes = resourceScopes?.length && authorizationScopes?.includes("offline_access") && !resourceScopes.includes("offline_access")
+ ? [...resourceScopes, "offline_access"]
+ : resourceScopes;
const tokenEndpointAuthMethods = stringList(metadata.token_endpoint_auth_methods_supported);
target.hash = "";
return {
diff --git a/server/mcp-oauth.test.ts b/server/mcp-oauth.test.ts
index aae72a440f..2f3786924a 100644
--- a/server/mcp-oauth.test.ts
+++ b/server/mcp-oauth.test.ts
@@ -135,6 +135,14 @@ describe("McpOAuthManager tokens", () => {
await settled("docs", started.flowId);
}
+ it("requests offline access advertised by the authorization server and refreshes the resulting token", async () => {
+ await signedIn({ expiresIn: 60, offlineAccess: true });
+ expect(oauth.lastAuthorize?.get("scope")).toBe("mcp offline_access");
+ expect(oauth.isValid(`Bearer ${await manager.accessToken("docs", mcp.url)}`)).toBe(true);
+ expect(oauth.counts.refresh).toBe(1);
+ expect(manager.authState("docs", mcp.url)).toBe("signed-in");
+ });
+
it("refreshes a token about to expire, once for concurrent callers", async () => {
await signedIn({ expiresIn: 60 });
const [a, b] = await Promise.all([manager.accessToken("docs", mcp.url), manager.accessToken("docs", mcp.url)]);
@@ -347,6 +355,13 @@ describe("a sign-in app registered in advance", () => {
expect(oauth.isValid(`Bearer ${await manager.accessToken("docs", mcp.url)}`)).toBe(true);
});
+ it("preserves explicitly configured scopes when offline access is advertised", async () => {
+ await setup({ noRegistration: true, preRegistered: { "read-only": null }, offlineAccess: true });
+ registered = { clientId: "read-only", scopes: ["mcp"] };
+ const started = await manager.start("docs", mcp.url);
+ expect(new URL(started.authorizationUrl!).searchParams.get("scope")).toBe("mcp");
+ });
+
it("uses the app in place of registration even when the server offers it", async () => {
await setup({ preRegistered: { mine: null } });
registered = { clientId: "mine" };
diff --git a/server/testing/fake-oauth-server.ts b/server/testing/fake-oauth-server.ts
index d38dd9926f..135d7c2830 100644
--- a/server/testing/fake-oauth-server.ts
+++ b/server/testing/fake-oauth-server.ts
@@ -32,6 +32,8 @@ export interface FakeOAuthOptions {
preRegistered?: Record<string, string | null>;
/** advertised token_endpoint_auth_methods_supported */
tokenAuthMethods?: string[];
+ /** Require offline_access to issue a refresh token and advertise it only on the authorization server. */
+ offlineAccess?: boolean;
}
export interface FakeClientAuth {
@@ -65,7 +67,7 @@ function readBody(req: IncomingMessage): Promise<string> {
}
export async function startFakeOAuth(options: FakeOAuthOptions = {}): Promise<FakeOAuth> {
- const codes = new Map<string, { challenge: string; clientId: string; redirectUri: string }>();
+ const codes = new Map<string, { challenge: string; clientId: string; redirectUri: string; offline: boolean }>();
const access = new Set<string>();
const refresh = new Set<string>();
const clients = new Set<string>();
@@ -100,12 +102,12 @@ export async function startFakeOAuth(options: FakeOAuthOptions = {}): Promise<Fa
return clients.has(auth.clientId) && secret === null ? auth.clientId : null;
};
- const issue = () => {
+ const issue = (offline = true) => {
const token = `at_${randomBytes(12).toString("hex")}`;
const refreshToken = `rt_${randomBytes(12).toString("hex")}`;
access.add(token);
refresh.add(refreshToken);
- return { access_token: token, token_type: "Bearer", expires_in: options.expiresIn ?? 3600, refresh_token: refreshToken, scope: "mcp" };
+ return { access_token: token, token_type: "Bearer", expires_in: options.expiresIn ?? 3600, ...(offline ? { refresh_token: refreshToken } : {}), scope: offline && options.offlineAccess ? "mcp offline_access" : "mcp" };
};
const json = (res: import("node:http").ServerResponse, status: number, body: unknown) =>
res.writeHead(status, { "content-type": "application/json" }).end(JSON.stringify(body));
@@ -124,6 +126,7 @@ export async function startFakeOAuth(options: FakeOAuthOptions = {}): Promise<Fa
...(options.noRegistration ? {} : { registration_endpoint: `${issuer}/register` }),
revocation_endpoint: `${issuer}/revoke`,
code_challenge_methods_supported: ["S256"],
+ ...(options.offlineAccess ? { scopes_supported: ["mcp", "offline_access"] } : {}),
...(options.tokenAuthMethods ? { token_endpoint_auth_methods_supported: options.tokenAuthMethods } : {}),
});
}
@@ -152,6 +155,7 @@ export async function startFakeOAuth(options: FakeOAuthOptions = {}): Promise<Fa
challenge: url.searchParams.get("code_challenge") ?? "",
clientId: url.searchParams.get("client_id") ?? "",
redirectUri: url.searchParams.get("redirect_uri") ?? "",
+ offline: !options.offlineAccess || (url.searchParams.get("scope") ?? "").split(" ").includes("offline_access"),
});
redirect.searchParams.set("code", code);
}
@@ -173,7 +177,7 @@ export async function startFakeOAuth(options: FakeOAuthOptions = {}): Promise<Fa
&& entry.clientId === client
&& entry.redirectUri === form.get("redirect_uri")
&& createHash("sha256").update(verifier).digest("base64url") === entry.challenge;
- return ok ? json(res, 200, issue()) : json(res, 400, { error: "invalid_grant" });
+ return ok ? json(res, 200, issue(entry.offline)) : json(res, 400, { error: "invalid_grant" });
}
if (form.get("grant_type") === "refresh_token") {
counts.refresh += 1;