Skip to content

Open-source Grok Bot alternative for named AI teammates. Local-first desktop, web, and mobile clients with per-bot tools, instructions, and memory. Independent fork of T3 Code.

fix(plugins): renew stale Hoplite OAuth registrations (#192)

Leod4ab489a738d
diff --git a/docs/user/plugins.md b/docs/user/plugins.md
index fd7e3abe0..58a7fdf3d 100644
--- a/docs/user/plugins.md
+++ b/docs/user/plugins.md
@@ -24,6 +24,11 @@ connection works. A routine can require an enabled connector.
A plugin waiting for publisher approval stays visible, but **Connect** remains disabled. A plugin
removed from the public directory stays under **Installed** until you remove it.
+If a service adds permissions after you first connected, select **Reconnect**. Akeru renews an
+outdated automatic OAuth client registration before opening sign-in, so services such as Hoplite
+can request their current permissions. You may need to approve those permissions again. Manually
+configured OAuth clients keep their existing registration.
+
## Enable tools for a bot
Akeru enables a new plugin for every bot by default. Open the bot's **Tools** setting to disable it
diff --git a/patches/@[email protected] b/patches/@[email protected]
index dc68a4363..7c928a223 100644
--- a/patches/@[email protected]
+++ b/patches/@[email protected]
@@ -1,5 +1,5 @@
diff --git a/dist/client/client.d.ts b/dist/client/client.d.ts
-index a0b93c5ad5d7f0d62c2fb2798b28ca2ffa6ead0d..f52cc4235ad06dc247b6b3649db2f47b390b1bb6 100644
+index a0b93c5ad5d7f0d62c2fb2798b28ca2ffa6ead0d..29952876bb2402017afdef7f57dc67da300c93c6 100644
--- a/dist/client/client.d.ts
+++ b/dist/client/client.d.ts
@@ -187,7 +187,7 @@ export declare class InternalMastraMCPClient extends MastraBase {
@@ -12,7 +12,7 @@ index a0b93c5ad5d7f0d62c2fb2798b28ca2ffa6ead0d..f52cc4235ad06dc247b6b3649db2f47b
private reconnectPromise;
private lifecycleGeneration;
diff --git a/dist/client/oauth-callback-server.d.ts b/dist/client/oauth-callback-server.d.ts
-index 1a724587cf4f4ca4383e005423afda2bc178b8bc..cd89f063b6d8953a8411476a4b2f641a53bf1e26 100644
+index 1a724587cf4f4ca4383e005423afda2bc178b8bc..01a54efeae4c9fceb33bf7a1ed43b926536aa7a8 100644
--- a/dist/client/oauth-callback-server.d.ts
+++ b/dist/client/oauth-callback-server.d.ts
@@ -44,6 +44,10 @@ export interface OAuthCallbackResult {
@@ -26,8 +26,20 @@ index 1a724587cf4f4ca4383e005423afda2bc178b8bc..cd89f063b6d8953a8411476a4b2f641a
}
/**
* A running loopback OAuth callback server.
+diff --git a/dist/client/oauth-provider.d.ts b/dist/client/oauth-provider.d.ts
+index 254aca0a8e959a84f0ee9e6807850f7e491616eb..d5126bae9a27144eb97b52fdb7e0fec66650f558 100644
+--- a/dist/client/oauth-provider.d.ts
++++ b/dist/client/oauth-provider.d.ts
+@@ -131,6 +131,7 @@ export declare class MCPOAuthClientProvider implements OAuthClientProvider {
+ private readonly onRedirect?;
+ private readonly generateState;
+ private _clientInfo?;
++ private readonly _hasConfiguredClientInformation;
+ private _sessionState?;
+ private _sessionRedirectUrl?;
+ constructor(options: MCPOAuthClientProviderOptions);
diff --git a/dist/index.cjs b/dist/index.cjs
-index 38a6c5e70d3fb6603ce6c40b443088eaeb8cf695..65821cdff5135c8f7e7dfa0590f52e3fb0da0e39 100644
+index 38a6c5e70d3fb6603ce6c40b443088eaeb8cf695..e9e3b511d8effb268dfaf80c19a2bfa499b35320 100644
--- a/dist/index.cjs
+++ b/dist/index.cjs
@@ -21759,12 +21759,12 @@ var InternalMastraMCPClient = class extends _mastra_core_base.MastraBase {
@@ -55,7 +67,40 @@ index 38a6c5e70d3fb6603ce6c40b443088eaeb8cf695..65821cdff5135c8f7e7dfa0590f52e3f
} });
});
const hostname = candidates[0].hostname.replace(/^\[|\]$/g, "");
-@@ -23646,8 +23647,8 @@ onListChanged: async (serverName, handler) => {
+@@ -22587,12 +22588,14 @@ var MCPOAuthClientProvider = class {
+ onRedirect;
+ generateState;
+ _clientInfo;
++ _hasConfiguredClientInformation;
+ _sessionState;
+ _sessionRedirectUrl;
+ constructor(options) {
+ this._redirectUrl = options.redirectUrl;
+ this._clientMetadata = options.clientMetadata;
+ this._clientInfo = options.clientInformation;
++ this._hasConfiguredClientInformation = options.clientInformation !== void 0;
+ this.storage = options.storage ?? new InMemoryOAuthStorage();
+ this.onRedirect = options.onRedirectToAuthorization;
+ this.generateState = options.stateGenerator ?? (() => crypto.randomUUID());
+@@ -22701,6 +22704,17 @@ var MCPOAuthClientProvider = class {
+ * Invoked to redirect the user agent to the authorization URL.
+ */
+ async redirectToAuthorization(authorizationUrl) {
++ if (!this._hasConfiguredClientInformation) {
++ const clientInfo = await this.clientInformation();
++ const requestedScope = authorizationUrl.searchParams.get("scope");
++ if (typeof clientInfo?.scope === "string" && requestedScope) {
++ const registeredScopes = new Set(clientInfo.scope.split(/\s+/).filter(Boolean));
++ if (requestedScope.split(/\s+/).filter(Boolean).some((scope) => !registeredScopes.has(scope))) {
++ // The SDK retries invalid_client once with fresh registration and tokens.
++ throw new _modelcontextprotocol_client.OAuthError(_modelcontextprotocol_client.OAuthErrorCode.InvalidClient, "OAuth client registered scopes do not include the requested scopes. Reconnect to register this client again.");
++ }
++ }
++ }
+ if (this.onRedirect) await this.onRedirect(authorizationUrl);
+ else console.info(`Authorization required. Please visit: ${authorizationUrl.toString()}`);
+ }
+@@ -23646,8 +23660,8 @@ onListChanged: async (serverName, handler) => {
} catch (error) {
if (!(error instanceof _modelcontextprotocol_client.UnauthorizedError)) throw this.handleConnectError(serverName, error);
}
@@ -67,9 +112,18 @@ index 38a6c5e70d3fb6603ce6c40b443088eaeb8cf695..65821cdff5135c8f7e7dfa0590f52e3f
await client.connect();
} catch (error) {
diff --git a/dist/index.js b/dist/index.js
-index 5d71441f80773dc594cfd49a8d7bf6159629edd7..dde1b30b13d2be892c8c72d05b9bfc43e98d14c0 100644
+index 5d71441f80773dc594cfd49a8d7bf6159629edd7..4f92927e6b2d90319cb7eaf54ab64f97d4115046 100644
--- a/dist/index.js
+++ b/dist/index.js
+@@ -3,7 +3,7 @@ import { AsyncLocalStorage } from "async_hooks";
+ import { MastraBase } from "@mastra/core/base";
+ import { ErrorCategory, ErrorDomain, MastraError } from "@mastra/core/error";
+ import { createTool, isValidationError } from "@mastra/core/tools";
+-import { Client, DEFAULT_REQUEST_TIMEOUT_MSEC, ProtocolErrorCode, SSEClientTransport, SdkHttpError, StreamableHTTPClientTransport, UnauthorizedError, auth, buildDiscoveryUrls, discoverAuthorizationServerMetadata, discoverOAuthMetadata, discoverOAuthProtectedResourceMetadata, exchangeAuthorization, extractResourceMetadataUrl, parseErrorResponse, refreshAuthorization, registerClient, selectResourceURL, startAuthorization } from "@modelcontextprotocol/client";
++import { Client, DEFAULT_REQUEST_TIMEOUT_MSEC, OAuthError, OAuthErrorCode, ProtocolErrorCode, SSEClientTransport, SdkHttpError, StreamableHTTPClientTransport, UnauthorizedError, auth, buildDiscoveryUrls, discoverAuthorizationServerMetadata, discoverOAuthMetadata, discoverOAuthProtectedResourceMetadata, exchangeAuthorization, extractResourceMetadataUrl, parseErrorResponse, refreshAuthorization, registerClient, selectResourceURL, startAuthorization } from "@modelcontextprotocol/client";
+ import { StdioClientTransport, getDefaultEnvironment } from "@modelcontextprotocol/client/stdio";
+ import { asyncExitHook, gracefulExit } from "exit-hook";
+ import { createHash, randomUUID, timingSafeEqual } from "crypto";
@@ -21738,12 +21738,12 @@ var InternalMastraMCPClient = class extends MastraBase {
*
* @internal
@@ -95,7 +149,40 @@ index 5d71441f80773dc594cfd49a8d7bf6159629edd7..dde1b30b13d2be892c8c72d05b9bfc43
} });
});
const hostname = candidates[0].hostname.replace(/^\[|\]$/g, "");
-@@ -23625,8 +23626,8 @@ onListChanged: async (serverName, handler) => {
+@@ -22566,12 +22567,14 @@ var MCPOAuthClientProvider = class {
+ onRedirect;
+ generateState;
+ _clientInfo;
++ _hasConfiguredClientInformation;
+ _sessionState;
+ _sessionRedirectUrl;
+ constructor(options) {
+ this._redirectUrl = options.redirectUrl;
+ this._clientMetadata = options.clientMetadata;
+ this._clientInfo = options.clientInformation;
++ this._hasConfiguredClientInformation = options.clientInformation !== void 0;
+ this.storage = options.storage ?? new InMemoryOAuthStorage();
+ this.onRedirect = options.onRedirectToAuthorization;
+ this.generateState = options.stateGenerator ?? (() => crypto.randomUUID());
+@@ -22680,6 +22683,17 @@ var MCPOAuthClientProvider = class {
+ * Invoked to redirect the user agent to the authorization URL.
+ */
+ async redirectToAuthorization(authorizationUrl) {
++ if (!this._hasConfiguredClientInformation) {
++ const clientInfo = await this.clientInformation();
++ const requestedScope = authorizationUrl.searchParams.get("scope");
++ if (typeof clientInfo?.scope === "string" && requestedScope) {
++ const registeredScopes = new Set(clientInfo.scope.split(/\s+/).filter(Boolean));
++ if (requestedScope.split(/\s+/).filter(Boolean).some((scope) => !registeredScopes.has(scope))) {
++ // The SDK retries invalid_client once with fresh registration and tokens.
++ throw new OAuthError(OAuthErrorCode.InvalidClient, "OAuth client registered scopes do not include the requested scopes. Reconnect to register this client again.");
++ }
++ }
++ }
+ if (this.onRedirect) await this.onRedirect(authorizationUrl);
+ else console.info(`Authorization required. Please visit: ${authorizationUrl.toString()}`);
+ }
+@@ -23625,8 +23639,8 @@ onListChanged: async (serverName, handler) => {
} catch (error) {
if (!(error instanceof UnauthorizedError)) throw this.handleConnectError(serverName, error);
}
diff --git a/patches/@[email protected] b/patches/@[email protected]
new file mode 100644
index 000000000..05ef1389f
--- /dev/null
+++ b/patches/@[email protected]
@@ -0,0 +1,78 @@
+diff --git a/dist/index.cjs b/dist/index.cjs
+index 635f1c0134274c89e7efbcae2adf3d9ecba575ee..76ccc3a0f027ecd3f31182cdc41c208467a4e88e 100644
+--- a/dist/index.cjs
++++ b/dist/index.cjs
+@@ -611,20 +611,21 @@ async function parseErrorResponse(input) {
+ * instead of linking together the other lower-level functions in this module.
+ */
+ async function auth(provider, options) {
+- try {
+- return await authInternal(provider, options);
+- } catch (error) {
+- if (error instanceof require_src.OAuthError) {
+- if (error.code === require_src.OAuthErrorCode.InvalidClient || error.code === require_src.OAuthErrorCode.UnauthorizedClient) {
+- await provider.invalidateCredentials?.("client");
+- await provider.invalidateCredentials?.("tokens");
+- return await authInternal(provider, options);
+- } else if (error.code === require_src.OAuthErrorCode.InvalidGrant) {
+- await provider.invalidateCredentials?.("tokens");
+- return await authInternal(provider, options);
+- }
++ const recoveredCredentials = new Set();
++ for (;;) {
++ try {
++ return await authInternal(provider, options);
++ } catch (error) {
++ if (!(error instanceof require_src.OAuthError)) throw error;
++ const recovery = error.code === require_src.OAuthErrorCode.InvalidClient || error.code === require_src.OAuthErrorCode.UnauthorizedClient
++ ? "client"
++ : error.code === require_src.OAuthErrorCode.InvalidGrant ? "tokens" : void 0;
++ if (!recovery || recoveredCredentials.has(recovery)) throw error;
++ // An expired token must not consume the stale client's registration retry.
++ recoveredCredentials.add(recovery);
++ if (recovery === "client") await provider.invalidateCredentials?.("client");
++ await provider.invalidateCredentials?.("tokens");
+ }
+- throw error;
+ }
+ }
+ /**
+diff --git a/dist/index.mjs b/dist/index.mjs
+index f02ce3ca394e826fc27c9848dbe9a214bf6ba7a9..ebca1ee168c609501cfe8dc51cb0b80a64faac3b 100644
+--- a/dist/index.mjs
++++ b/dist/index.mjs
+@@ -608,20 +608,21 @@ async function parseErrorResponse(input) {
+ * instead of linking together the other lower-level functions in this module.
+ */
+ async function auth(provider, options) {
+- try {
+- return await authInternal(provider, options);
+- } catch (error) {
+- if (error instanceof OAuthError) {
+- if (error.code === OAuthErrorCode.InvalidClient || error.code === OAuthErrorCode.UnauthorizedClient) {
+- await provider.invalidateCredentials?.("client");
+- await provider.invalidateCredentials?.("tokens");
+- return await authInternal(provider, options);
+- } else if (error.code === OAuthErrorCode.InvalidGrant) {
+- await provider.invalidateCredentials?.("tokens");
+- return await authInternal(provider, options);
+- }
++ const recoveredCredentials = new Set();
++ for (;;) {
++ try {
++ return await authInternal(provider, options);
++ } catch (error) {
++ if (!(error instanceof OAuthError)) throw error;
++ const recovery = error.code === OAuthErrorCode.InvalidClient || error.code === OAuthErrorCode.UnauthorizedClient
++ ? "client"
++ : error.code === OAuthErrorCode.InvalidGrant ? "tokens" : void 0;
++ if (!recovery || recoveredCredentials.has(recovery)) throw error;
++ // An expired token must not consume the stale client's registration retry.
++ recoveredCredentials.add(recovery);
++ if (recovery === "client") await provider.invalidateCredentials?.("client");
++ await provider.invalidateCredentials?.("tokens");
+ }
+- throw error;
+ }
+ }
+ /**
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index af66c4ad2..b57938820 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -71,7 +71,8 @@ patchedDependencies:
'@expo/[email protected]': 8cb08b5bb7051ed9d2dbe46a2c293c5a1e17f1bd6ddf30de27909e18c921ff46
'@ff-labs/[email protected]': ab9ff544009e1891cfe3930105862d3699007f38922a79f3c98d90018deca368
'@legendapp/[email protected]': 064530db83875fa671559a81ae42dc159726dc2dd6ec4c982da44ff7c7a74706
- '@mastra/[email protected]': 016edd26ea06f6ebcde74dc84648bb45937a3dc5c6876407c2474c4525f91871
+ '@mastra/[email protected]': 9b6d63569c5225bf2803a5ce1bbf1e470192f3fc21af9e2a4dd321d64dc9cbc4
+ '@modelcontextprotocol/[email protected]': 26c067f6d379f934223521f228d8db1557c64cf2a9206d9dc020a0fa59013ebc
'@pierre/[email protected]': 7ef7cb0cbabb17c15cdb137554068b36f15f6f5265e73fb51452aa3380db91aa
'@react-native-menu/[email protected]': c7f66d121c726ade4f5c4e1aed11a691e5711d244c544084e289ac26132a0045
'@react-native/[email protected]': c1b594a16e682d621b6a960926f8ce13fc92edfb397884cfe7fcb0518996a784
@@ -1020,6 +1021,12 @@ importers:
'@effect/vitest':
specifier: 4.0.0-beta.103
version: 4.0.0-beta.103(patch_hash=a16b1e870d8c29e4a98b17cc4c638a4ff471753d8ca3487f78a22b759caf951b)([email protected](patch_hash=af36b7948b6f9c56623074662b51dade5699880c1a7c71245de73e13c3185fb6))
+ '@mastra/mcp':
+ specifier: 1.17.2
+ '@modelcontextprotocol/client':
+ specifier: 2.0.0
+ version: 2.0.0(patch_hash=26c067f6d379f934223521f228d8db1557c64cf2a9206d9dc020a0fa59013ebc)
'@types/pngjs':
specifier: 6.0.5
version: 6.0.5
@@ -16960,7 +16967,7 @@ snapshots:
'@mastra/fastembed': 1.3.0
@@ -17073,10 +17080,10 @@ snapshots:
- bufferutil
- utf-8-validate
dependencies:
- '@modelcontextprotocol/client': 2.0.0
+ '@modelcontextprotocol/client': 2.0.0(patch_hash=26c067f6d379f934223521f228d8db1557c64cf2a9206d9dc020a0fa59013ebc)
'@modelcontextprotocol/core': 2.0.0
'@modelcontextprotocol/ext-apps': 1.7.5(@modelcontextprotocol/[email protected]([email protected]))([email protected]([email protected]))([email protected])([email protected])
'@modelcontextprotocol/node': 2.0.0(@modelcontextprotocol/[email protected])([email protected])
@@ -17173,7 +17180,7 @@ snapshots:
dependencies:
'@chevrotain/types': 11.1.2
- '@modelcontextprotocol/[email protected]':
+ '@modelcontextprotocol/[email protected](patch_hash=26c067f6d379f934223521f228d8db1557c64cf2a9206d9dc020a0fa59013ebc)':
dependencies:
'@modelcontextprotocol/core': 2.0.0
cross-spawn: 7.0.6
diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml
index 6b853d0ff..dbb359749 100644
--- a/pnpm-workspace.yaml
+++ b/pnpm-workspace.yaml
@@ -122,6 +122,7 @@ patchedDependencies:
"@legendapp/[email protected]": patches/@[email protected]
+ "@modelcontextprotocol/[email protected]": patches/@[email protected]
"@pierre/[email protected]": patches/@pierre%[email protected]
"@react-native-menu/[email protected]": patches/@[email protected]
"@react-native/[email protected]": patches/@[email protected]
diff --git a/scripts/mastra-mcp-oauth-patch.test.ts b/scripts/mastra-mcp-oauth-patch.test.ts
index ab98ae00e..3aa0c8827 100644
--- a/scripts/mastra-mcp-oauth-patch.test.ts
+++ b/scripts/mastra-mcp-oauth-patch.test.ts
@@ -2,17 +2,185 @@
import * as NodeFS from "node:fs";
import * as NodeModule from "node:module";
import * as NodePath from "node:path";
-import { describe, expect, it } from "vite-plus/test";
+import { InMemoryOAuthStorage, MCPOAuthClientProvider } from "@mastra/mcp";
+import { auth } from "@modelcontextprotocol/client";
+import { describe, expect, it, vi } from "vite-plus/test";
-const packageEntry = NodeModule.createRequire(
- new URL("../node_modules/.pnpm/node_modules/resolve.cjs", import.meta.url),
-).resolve("@mastra/mcp");
+const requirePackage = NodeModule.createRequire(import.meta.url);
+const packageEntry = requirePackage.resolve("@mastra/mcp");
const packageRoot = NodePath.dirname(NodePath.dirname(packageEntry));
function readPackageFile(path: string): string {
return NodeFS.readFileSync(NodePath.join(packageRoot, path), "utf8");
}
+const commonJsMcp = requirePackage("@mastra/mcp") as typeof import("@mastra/mcp");
+const commonJsClient = requirePackage(
+ "@modelcontextprotocol/client",
+) as typeof import("@modelcontextprotocol/client");
+const runtimes = [
+ { name: "ESM", InMemoryOAuthStorage, MCPOAuthClientProvider, auth },
+ { name: "CommonJS", ...commonJsMcp, auth: commonJsClient.auth },
+];
+
+const issuer = "https://oauth.example.test";
+const resourceUrl = "https://mcp.example.test/mcp";
+const redirectUrl = "http://127.0.0.1:1458/oauth/callback";
+const oldScope = "openid offline_access thread:read";
+const currentScope = `${oldScope} thread:update`;
+
+function oauthFixture(options: {
+ registeredScope?: string | undefined;
+ staticClient?: boolean;
+ registrationScope?: string;
+ expiredRefreshToken?: boolean;
+ runtime: (typeof runtimes)[number];
+}) {
+ const storage = new options.runtime.InMemoryOAuthStorage();
+ const clientMetadata = {
+ redirect_uris: [redirectUrl],
+ client_name: "Akeru OAuth test",
+ grant_types: ["authorization_code", "refresh_token"],
+ response_types: ["code"],
+ token_endpoint_auth_method: "none",
+ };
+ const clientInformation = {
+ ...clientMetadata,
+ client_id: "cached-client",
+ issuer,
+ ...(options.registeredScope === undefined ? {} : { scope: options.registeredScope }),
+ };
+ storage.set("client_info", JSON.stringify(clientInformation));
+ if (options.expiredRefreshToken) {
+ storage.set(
+ "tokens",
+ JSON.stringify({
+ access_token: "expired-access-token",
+ refresh_token: "expired-refresh-token",
+ token_type: "Bearer",
+ issuer,
+ }),
+ );
+ }
+ const onRedirectToAuthorization = vi.fn<(url: URL) => void>();
+ const provider = new options.runtime.MCPOAuthClientProvider({
+ redirectUrl,
+ clientMetadata,
+ storage,
+ ...(options.staticClient ? { clientInformation } : {}),
+ onRedirectToAuthorization,
+ });
+ const registrations: Record<string, unknown>[] = [];
+ const fetchFn: typeof fetch = async (input, init) => {
+ const url = String(input);
+ if (url === `${resourceUrl}/metadata`) {
+ return Response.json({
+ resource: resourceUrl,
+ authorization_servers: [issuer],
+ scopes_supported: currentScope.split(" "),
+ });
+ }
+ if (url === `${issuer}/.well-known/oauth-authorization-server`) {
+ return Response.json({
+ issuer,
+ authorization_endpoint: `${issuer}/authorize`,
+ token_endpoint: `${issuer}/token`,
+ registration_endpoint: `${issuer}/register`,
+ response_types_supported: ["code"],
+ code_challenge_methods_supported: ["S256"],
+ scopes_supported: currentScope.split(" "),
+ });
+ }
+ if (url === `${issuer}/token` && options.expiredRefreshToken) {
+ return Response.json({ error: "invalid_grant" }, { status: 400 });
+ }
+ if (url === `${issuer}/register`) {
+ const metadata = JSON.parse(String(init?.body)) as Record<string, unknown>;
+ registrations.push(metadata);
+ return Response.json(
+ {
+ ...metadata,
+ client_id: "new-client",
+ ...(options.registrationScope === undefined ? {} : { scope: options.registrationScope }),
+ },
+ { status: 201 },
+ );
+ }
+ throw new Error(`Unexpected OAuth request: ${url}`);
+ };
+ const authorize = () =>
+ options.runtime.auth(provider, {
+ serverUrl: resourceUrl,
+ resourceMetadataUrl: new URL(`${resourceUrl}/metadata`),
+ fetchFn,
+ });
+ return { provider, storage, registrations, onRedirectToAuthorization, authorize };
+}
+
+describe.each(runtimes)("@mastra/mcp OAuth registration scopes ($name)", (runtime) => {
+ it("re-registers a cached client before requesting a newly advertised scope", async () => {
+ const fixture = oauthFixture({ runtime, registeredScope: oldScope });
+ await fixture.storage.set(
+ "tokens",
+ JSON.stringify({ access_token: "old-access-token", token_type: "Bearer", issuer }),
+ );
+ const state = await fixture.provider.beginAuthorizationSession();
+ await expect(fixture.authorize()).resolves.toBe("REDIRECT");
+ expect(await fixture.provider.tokens()).toBeUndefined();
+ expect(await fixture.provider.state()).toBe(state);
+ expect(fixture.registrations).toHaveLength(1);
+ expect(fixture.registrations[0]?.scope).toBe(currentScope);
+ expect(fixture.onRedirectToAuthorization).toHaveBeenCalledOnce();
+ const url = fixture.onRedirectToAuthorization.mock.calls[0]?.[0];
+ expect(url?.searchParams.get("client_id")).toBe("new-client");
+ expect(url?.searchParams.get("scope")).toBe(currentScope);
+ expect(url?.searchParams.get("code_challenge_method")).toBe("S256");
+ expect((await fixture.provider.clientInformation())?.client_id).toBe("new-client");
+ expect(JSON.parse(String(await fixture.storage.get("client_info"))).scope).toBe(currentScope);
+ });
+
+ it("recovers a stale registration even after an expired refresh token", async () => {
+ const fixture = oauthFixture({ runtime, registeredScope: oldScope, expiredRefreshToken: true });
+ await expect(fixture.authorize()).resolves.toBe("REDIRECT");
+ expect(fixture.registrations).toHaveLength(1);
+ expect(fixture.onRedirectToAuthorization).toHaveBeenCalledOnce();
+ expect((await fixture.provider.clientInformation())?.client_id).toBe("new-client");
+ expect(await fixture.provider.tokens()).toBeUndefined();
+ });
+
+ it.each([currentScope, `${currentScope} project:read`, undefined])(
+ "preserves compatible or unspecified registered scopes: %s",
+ async (registeredScope) => {
+ const fixture = oauthFixture({ runtime, registeredScope });
+ await expect(fixture.authorize()).resolves.toBe("REDIRECT");
+ expect(fixture.registrations).toHaveLength(0);
+ expect(fixture.onRedirectToAuthorization).toHaveBeenCalledOnce();
+ },
+ );
+
+ it("leaves explicitly configured clients under their owner's control", async () => {
+ const fixture = oauthFixture({ runtime, registeredScope: oldScope, staticClient: true });
+ await expect(fixture.authorize()).resolves.toBe("REDIRECT");
+ expect(fixture.registrations).toHaveLength(0);
+ expect((await fixture.provider.clientInformation())?.client_id).toBe("cached-client");
+ });
+
+ it.each([false, true])(
+ "stops after one rejected registration retry with expired refresh token: %s",
+ async (expiredRefreshToken) => {
+ const fixture = oauthFixture({
+ runtime,
+ registeredScope: oldScope,
+ registrationScope: oldScope,
+ expiredRefreshToken,
+ });
+ await expect(fixture.authorize()).rejects.toThrow("registered scopes");
+ expect(fixture.registrations).toHaveLength(1);
+ expect(fixture.onRedirectToAuthorization).not.toHaveBeenCalled();
+ },
+ );
+});
+
describe("@mastra/mcp OAuth issuer patch", () => {
it("forwards the authorization issuer from the callback to the MCP transport", () => {
for (const bundle of ["dist/index.js", "dist/index.cjs"]) {
diff --git a/scripts/package.json b/scripts/package.json
index 6e61fb308..ab294a18e 100644
--- a/scripts/package.json
+++ b/scripts/package.json
@@ -19,6 +19,8 @@
},
"devDependencies": {
"@effect/vitest": "catalog:",
+ "@mastra/mcp": "1.17.2",
+ "@modelcontextprotocol/client": "2.0.0",
"@types/pngjs": "6.0.5",
"vite-plus": "catalog:"
}