Skip to content

Commit 7c03aa0

Browse files
authored
fix(ai-agents): tolerate a trailing slash between the MCP server URL and its advertised resource (#31088)
Closes #31085 (PROD-12223) Stacked on #31087. ## Problem OAuth sign-in to an external MCP server failed when the server's protected-resource metadata advertised `"resource": "https://host/mcp/"` but the server URL was entered as `https://host/mcp`. The SDK's `checkResourceAllowed` has an early return when the requested path is shorter than the configured one, so this direction failed with `Protected resource https://host/mcp/ does not match expected https://host/mcp (or origin)` while the reverse direction passed. Users cannot control what a gateway advertises. ## Change A `pnpm patch` on `@modelcontextprotocol/[email protected]` that removes the path-length early return from `checkResourceAllowed`, in both the CommonJS and ESM builds. The function already normalises both paths to a trailing slash before its prefix check, so `/mcp` now matches `/mcp/`, while `/mcp` against `/mcp123`, a different path, or a different origin are still rejected. The origin and path-prefix binding (RFC 8707) is unchanged. Why a patch rather than a `validateResourceURL` override (the first version of this PR): the SDK only sends the advertised resource string verbatim when no provider override is present. An override forces the SDK to serialise the override's return value through `URL.href`, which appends `/` to a pathless indicator and reintroduces modelcontextprotocol/typescript-sdk#1968. Keeping the SDK's own path avoids re-implementing resource selection and any workaround. - `checkResourceAllowed` is used only by the SDK's client auth path. Lightdash's own MCP server does not call it, so nothing server-side changes. - The patch is version-pinned. The next SDK bump fails install until the patch is re-applied or dropped once upstream has the fix. - The Dockerfiles already copy `patches/` before install (added for the existing `scim-patch` patch in #30682). - Upstream: modelcontextprotocol/typescript-sdk#3041 describes the asymmetry and proposes the same change. Upstream has an explicit test asserting the current one-directional behaviour, so I opened an issue rather than a PR to settle the "what" first, per their contributing guide. Drop this patch once the fix lands and the SDK is bumped. - Still client-only in 1.32.1: `checkResourceAllowed` is not used by the SDK's server-side bearer-auth check there either, so a bump to that line keeps the patch's blast radius unchanged. ## Tests `AiAgentMcpRuntimeClient.test.ts` now drives the SDK's real `auth()` through `PersistentMcpOAuthClientProvider` with a mocked fetch serving protected-resource and authorization-server metadata, and asserts on the `resource` query parameter of the authorization URL handed to `onAuthorizationUrl`: - metadata that adds a trailing slash is accepted and sent verbatim (fails without the patch, verified by temporarily restoring the SDK's original check); - metadata that drops the trailing slash is accepted; - a pathless resource is sent without a slash appended; - a different path is still rejected and no authorization URL is produced. The same test also covers the public-client flow from #31087 end to end: the configured client ID reaches the authorization URL with `code_challenge_method=S256`. 🤖 Generated with [Claude Code](https://claude.com/claude-code)
1 parent 8816ff5 commit 7c03aa0

4 files changed

Lines changed: 216 additions & 7 deletions

File tree

‎packages/backend/src/ee/services/ai/AiAgentMcpRuntimeClient.test.ts‎

Lines changed: 174 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,10 @@
11
import * as mcpSdk from '@ai-sdk/mcp';
22
import type { MCPClient } from '@ai-sdk/mcp';
33
/* eslint-disable import/extensions */
4-
import { UnauthorizedError } from '@modelcontextprotocol/sdk/client/auth.js';
4+
import {
5+
auth,
6+
UnauthorizedError,
7+
} from '@modelcontextprotocol/sdk/client/auth.js';
58
/* eslint-enable import/extensions */
69
import { asSchema, jsonSchema } from 'ai';
710
import dns from 'node:dns';
@@ -644,6 +647,176 @@ describe('PersistentMcpOAuthClientProvider', () => {
644647
});
645648
});
646649

650+
describe('MCP OAuth resource indicator', () => {
651+
// Drives the SDK's real auth() through our provider. The SDK's
652+
// checkResourceAllowed is patched (patches/@modelcontextprotocol__sdk) so
653+
// a server URL of /mcp accepts metadata that advertises /mcp/.
654+
const buildProvider = (onAuthorizationUrl: (url: URL) => void) => {
655+
const sharedCredential = {
656+
uuid: 'credential-uuid',
657+
mcpServerUuid: 'server-uuid',
658+
credentialScope: 'shared',
659+
userUuid: null,
660+
createdByUserUuid: 'creator-uuid',
661+
updatedByUserUuid: 'creator-uuid',
662+
createdAt: new Date(),
663+
updatedAt: new Date(),
664+
credentials: {
665+
type: 'oauth',
666+
credentialScope: 'shared',
667+
connectionStatus: 'not_connected',
668+
configuredClientId: 'public-client',
669+
},
670+
} satisfies AiMcpCredential;
671+
const aiAgentModel = {
672+
getCredential: vi
673+
.fn()
674+
.mockImplementation(
675+
async (_serverUuid: string, scope: string) =>
676+
scope === 'shared' ? sharedCredential : undefined,
677+
),
678+
upsertCredential: vi.fn(),
679+
} as unknown as AiAgentModel;
680+
const runtimeClient = new AiAgentMcpRuntimeClient({
681+
aiAgentModel,
682+
lightdashConfig: {
683+
siteUrl: 'https://lightdash.example.com',
684+
ai: {
685+
copilot: { mcpConnectionTimeoutMs: 20_000 },
686+
},
687+
} as LightdashConfig,
688+
});
689+
return (
690+
runtimeClient as unknown as {
691+
createMcpOAuthProvider: (args: {
692+
projectUuid: string;
693+
mcpServerUuid: string;
694+
credentialScope: 'user';
695+
userUuid: string;
696+
actorUserUuid: string;
697+
onAuthorizationUrl: (url: URL) => void;
698+
}) => Parameters<typeof auth>[0];
699+
}
700+
).createMcpOAuthProvider({
701+
projectUuid: 'project-uuid',
702+
mcpServerUuid: 'server-uuid',
703+
credentialScope: 'user',
704+
userUuid: 'user-uuid',
705+
actorUserUuid: 'user-uuid',
706+
onAuthorizationUrl,
707+
});
708+
};
709+
710+
const jsonResponse = (body: unknown) =>
711+
new Response(JSON.stringify(body), {
712+
status: 200,
713+
headers: { 'content-type': 'application/json' },
714+
});
715+
716+
const buildFetch = (advertisedResource: string) =>
717+
vi.fn(async (input: string | URL | Request) => {
718+
const url = new URL(
719+
input instanceof Request ? input.url : String(input),
720+
);
721+
if (
722+
url.host === 'mcp.example.com' &&
723+
url.pathname.startsWith('/.well-known/oauth-protected-resource')
724+
) {
725+
return jsonResponse({
726+
resource: advertisedResource,
727+
authorization_servers: ['https://auth.example.com'],
728+
});
729+
}
730+
if (
731+
url.href ===
732+
'https://auth.example.com/.well-known/oauth-authorization-server'
733+
) {
734+
return jsonResponse({
735+
issuer: 'https://auth.example.com',
736+
authorization_endpoint:
737+
'https://auth.example.com/authorize',
738+
token_endpoint: 'https://auth.example.com/token',
739+
response_types_supported: ['code'],
740+
code_challenge_methods_supported: ['S256'],
741+
});
742+
}
743+
return new Response('not found', { status: 404 });
744+
}) as unknown as typeof fetch;
745+
746+
it('accepts metadata that only adds a trailing slash and sends it verbatim', async () => {
747+
let authorizationUrl: URL | undefined;
748+
const provider = buildProvider((url) => {
749+
authorizationUrl = url;
750+
});
751+
752+
await expect(
753+
auth(provider, {
754+
serverUrl: 'https://mcp.example.com/mcp',
755+
fetchFn: buildFetch('https://mcp.example.com/mcp/'),
756+
}),
757+
).resolves.toBe('REDIRECT');
758+
759+
expect(authorizationUrl?.searchParams.get('resource')).toBe(
760+
'https://mcp.example.com/mcp/',
761+
);
762+
expect(authorizationUrl?.searchParams.get('client_id')).toBe(
763+
'public-client',
764+
);
765+
expect(
766+
authorizationUrl?.searchParams.get('code_challenge_method'),
767+
).toBe('S256');
768+
});
769+
770+
it('accepts metadata that only drops the trailing slash', async () => {
771+
let authorizationUrl: URL | undefined;
772+
const provider = buildProvider((url) => {
773+
authorizationUrl = url;
774+
});
775+
776+
await expect(
777+
auth(provider, {
778+
serverUrl: 'https://mcp.example.com/mcp/',
779+
fetchFn: buildFetch('https://mcp.example.com/mcp'),
780+
}),
781+
).resolves.toBe('REDIRECT');
782+
783+
expect(authorizationUrl?.searchParams.get('resource')).toBe(
784+
'https://mcp.example.com/mcp',
785+
);
786+
});
787+
788+
it('sends a pathless advertised resource without adding a slash', async () => {
789+
let authorizationUrl: URL | undefined;
790+
const provider = buildProvider((url) => {
791+
authorizationUrl = url;
792+
});
793+
794+
await expect(
795+
auth(provider, {
796+
serverUrl: 'https://mcp.example.com',
797+
fetchFn: buildFetch('https://mcp.example.com'),
798+
}),
799+
).resolves.toBe('REDIRECT');
800+
801+
expect(authorizationUrl?.searchParams.get('resource')).toBe(
802+
'https://mcp.example.com',
803+
);
804+
});
805+
806+
it('still rejects metadata that advertises a different path', async () => {
807+
const onAuthorizationUrl = vi.fn();
808+
const provider = buildProvider(onAuthorizationUrl);
809+
810+
await expect(
811+
auth(provider, {
812+
serverUrl: 'https://mcp.example.com/mcp',
813+
fetchFn: buildFetch('https://mcp.example.com/other/'),
814+
}),
815+
).rejects.toThrow(/does not match/);
816+
expect(onAuthorizationUrl).not.toHaveBeenCalled();
817+
});
818+
});
819+
647820
describe('resolveMcpTools', () => {
648821
const aiAgentModel = {
649822
updateMcpServerRuntimeState: vi.fn(),

‎patches/@[email protected]‎

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
diff --git a/dist/cjs/shared/auth-utils.js b/dist/cjs/shared/auth-utils.js
2+
index f2fe617344051e0b7a5ff4543af4bf435523092d..e9a78e027e590822151d16f60355b54e4d4f1abf 100644
3+
--- a/dist/cjs/shared/auth-utils.js
4+
+++ b/dist/cjs/shared/auth-utils.js
5+
@@ -31,10 +31,8 @@ function checkResourceAllowed({ requestedResource, configuredResource }) {
6+
if (requested.origin !== configured.origin) {
7+
return false;
8+
}
9+
- // Handle cases like requested=/foo and configured=/foo/
10+
- if (requested.pathname.length < configured.pathname.length) {
11+
- return false;
12+
- }
13+
+ // A single trailing slash is not a different resource: requested=/foo
14+
+ // matches configured=/foo/ once both paths are normalised below.
15+
// Check if the requested path starts with the configured path
16+
// Ensure both paths end with / for proper comparison
17+
// This ensures that if we have paths like "/api" and "/api/users",
18+
diff --git a/dist/esm/shared/auth-utils.js b/dist/esm/shared/auth-utils.js
19+
index 1883885e406491c6142127fd8d7a00f2d5d229a3..59044c55394b23d3f3abf6ddcc05d0471fb85a79 100644
20+
--- a/dist/esm/shared/auth-utils.js
21+
+++ b/dist/esm/shared/auth-utils.js
22+
@@ -27,10 +27,8 @@ export function checkResourceAllowed({ requestedResource, configuredResource })
23+
if (requested.origin !== configured.origin) {
24+
return false;
25+
}
26+
- // Handle cases like requested=/foo and configured=/foo/
27+
- if (requested.pathname.length < configured.pathname.length) {
28+
- return false;
29+
- }
30+
+ // A single trailing slash is not a different resource: requested=/foo
31+
+ // matches configured=/foo/ once both paths are normalised below.
32+
// Check if the requested path starts with the configured path
33+
// Ensure both paths end with / for proper comparison
34+
// This ensures that if we have paths like "/api" and "/api/users",

‎pnpm-lock.yaml‎

Lines changed: 7 additions & 6 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎pnpm-workspace.yaml‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -162,4 +162,5 @@ packageExtensions:
162162
ai:
163163
optional: true
164164
patchedDependencies:
165+
'@modelcontextprotocol/[email protected]': patches/@[email protected]
165166

0 commit comments

Comments
 (0)