diff --git a/src/app/[transport]/route.test.ts b/src/app/[transport]/route.test.ts index 18cb884..1d2ab22 100644 --- a/src/app/[transport]/route.test.ts +++ b/src/app/[transport]/route.test.ts @@ -147,6 +147,7 @@ describe("native OAuth credentials", () => { let kernelTokens: string[]; let kernelPaths: string[]; let browsersRequested: () => void; + let credentialProjectId: string | null; let fetchSpy: ReturnType>; beforeEach(async () => { @@ -156,6 +157,7 @@ describe("native OAuth credentials", () => { kernelTokens = []; kernelPaths = []; browsersRequested = () => {}; + credentialProjectId = "proj_123"; defaultMcpDependencies.createKernelClient = (token) => { kernelTokens.push(token); return new Kernel({ @@ -184,7 +186,7 @@ describe("native OAuth credentials", () => { principal: { type: "user", id: "user_123" }, organization: { id: "org_123" }, authorization: { - credential_scope: { project_id: "proj_123" }, + credential_scope: { project_id: credentialProjectId }, effective_scope: { project_id: "proj_123" }, }, }); @@ -430,11 +432,38 @@ describe("native OAuth credentials", () => { ]); }); - test("post-authentication bugs propagate as server errors", async () => { - failingAuthContext(new Error("unaccountable")); - await expect(POST(mcpRequest(await issuer.parent()))).rejects.toThrow( - "Unable to resolve Kernel connection scope", + // A grant limited to one non-default project names no credential project; + // the API runs its requests in that project. + test("fix a grant's implicit project as the connection scope", async () => { + credentialProjectId = null; + const response = await POST( + mcpRequest(await issuer.parent(), "tools/call", { + name: "get_connection_context", + arguments: {}, + }), ); + expect(response.status).toBe(200); + const text = await response.text(); + const event = text.split("\n").find((line) => line.startsWith("data: ")); + const result = JSON.parse(event ? event.slice(6) : text).result; + expect(result.isError).not.toBe(true); + expect(JSON.parse(result.content[0].text).connection_scope).toEqual({ + kind: "project", + organization_id: "org_123", + project_id: "proj_123", + source: "credential", + project_id_required: false, + }); + }); + + test("answer post-authentication bugs with a JSON server error", async () => { + failingAuthContext(new Error("unaccountable")); + const response = await POST(mcpRequest(await issuer.parent())); + expect(response.status).toBe(500); + expect(await response.json()).toEqual({ + error: "server_error", + error_description: "Unable to resolve Kernel connection scope", + }); }); describe("end with the exchanged token", () => { @@ -705,17 +734,57 @@ describe("connection scope failures through the handler", () => { test("still surfaces an unaccountable failure as a server error", async () => { failingAuthContext(new TypeError("cannot read properties of undefined")); - await expect(POST(initializeRequest())).rejects.toThrow( - "Unable to resolve Kernel connection scope", - ); + const response = await POST(initializeRequest()); + + expect(response.status).toBe(500); + expect(response.headers.get("Access-Control-Allow-Origin")).toBe("*"); + expect(await response.json()).toEqual({ + error: "server_error", + error_description: "Unable to resolve Kernel connection scope", + }); expect(captured).toEqual([ { stage: "scope", outcome: "invalid", credentialType: "api_key", + upstreamStatusCode: undefined, + responseStatusCode: 500, }, ]); }); + + test("answers an inconsistent connection scope with a server error", async () => { + defaultMcpDependencies.createKernelClient = () => + ({ + auth: { + context: { + retrieve: async () => ({ + authentication: { + method: "api_key", + source: "api_key", + credential_id: "key_123", + }, + principal: { type: "api_key", id: "key_123" }, + organization: { id: "org_123" }, + authorization: { + credential_scope: { project_id: "proj_1" }, + effective_scope: { project_id: "proj_2" }, + }, + }), + }, + }, + }) as never; + + const response = await POST(initializeRequest()); + + expect(response.status).toBe(500); + expect((await response.json()).error).toBe("server_error"); + expect(captured[0]).toMatchObject({ + stage: "scope", + outcome: "invalid", + responseStatusCode: 500, + }); + }); }); describe("capability routing", () => { diff --git a/src/app/[transport]/route.ts b/src/app/[transport]/route.ts index 74a313c..e18ab21 100644 --- a/src/app/[transport]/route.ts +++ b/src/app/[transport]/route.ts @@ -138,8 +138,15 @@ function createAuthErrorResponse( export function connectionScopeFailureResponse( req: Request, - failure: Exclude, + failure: McpConnectionContextFailure, ): Response { + if (failure.status === "invalid") { + return errorResponse( + 500, + "server_error", + "Unable to resolve Kernel connection scope", + ); + } if (failure.status === "rejected") { switch (failure.statusCode) { case 403: @@ -202,19 +209,17 @@ function refuseConnection( failure: McpConnectionContextFailure, ): Response { if (failure.status === "invalid") { - captureMcpConnectionScopeFailure({ - stage, - outcome: failure.status, - credentialType, - }); - throw new Error("Unable to resolve Kernel connection scope"); + console.error(`Unable to resolve Kernel connection scope at ${stage}`); } const response = connectionScopeFailureResponse(req, failure); captureMcpConnectionScopeFailure({ stage, outcome: failure.status, credentialType, - upstreamStatusCode: stage === "scope" ? failure.statusCode : undefined, + upstreamStatusCode: + stage === "scope" && "statusCode" in failure + ? failure.statusCode + : undefined, responseStatusCode: response.status, }); return response; diff --git a/src/lib/mcp/analytics.ts b/src/lib/mcp/analytics.ts index c871cff..38ea698 100644 --- a/src/lib/mcp/analytics.ts +++ b/src/lib/mcp/analytics.ts @@ -96,7 +96,7 @@ export type McpConnectionScopeFailureAnalytics = { credentialType: McpCredentialType; // Status the Kernel API returned from /auth/context. Only set for "scope". upstreamStatusCode?: number; - // Status this server answered with. Unset for "invalid", which throws. + // Status this server answered with. responseStatusCode?: number; }; diff --git a/src/lib/mcp/auth-context.test.ts b/src/lib/mcp/auth-context.test.ts index 79a1be2..4832817 100644 --- a/src/lib/mcp/auth-context.test.ts +++ b/src/lib/mcp/auth-context.test.ts @@ -286,6 +286,39 @@ describe("resolveMcpConnectionContext", () => { }); }); + describe("OAuth grants", () => { + const grant = (effectiveProjectId: string | null) => + response({ + method: "jwt", + source: "oauth", + principalType: "user", + principalId: "user_123", + effectiveProjectId, + }); + + // The API runs a single-project grant's requests in its project, and + // reports a non-default one as the effective scope. + test("fixes a single non-default project grant to that project", () => { + expect(connectionScopeFromAuthContext(grant("project_granted"))).toEqual({ + kind: "project", + organizationId: "org_123", + projectId: "project_granted", + source: "credential", + }); + }); + + // The API reports neither a default-project grant nor an all-projects + // grant with an effective project, so both stay organization-wide. + test("keeps default-project and all-projects grants organization-wide", () => { + expect(connectionScopeFromAuthContext(grant(null))).toEqual({ + kind: "organization", + organizationId: "org_123", + projectId: null, + source: "credential", + }); + }); + }); + test("rejects inconsistent credential, effective, and server scope", () => { expect( connectionScopeFromAuthContext( @@ -297,7 +330,7 @@ describe("resolveMcpConnectionContext", () => { ).toBeNull(); expect( connectionScopeFromAuthContext( - response({ effectiveProjectId: "project_1" }), + response({ credentialProjectId: "project_1" }), ), ).toBeNull(); expect( @@ -306,6 +339,15 @@ describe("resolveMcpConnectionContext", () => { "project_2", ), ).toBeNull(); + expect( + connectionScopeFromAuthContext( + response({ + credentialProjectId: "project_1", + effectiveProjectId: "project_1", + }), + "project_2", + ), + ).toBeNull(); }); test("reuses normalized scope across token refreshes in one session", async () => { diff --git a/src/lib/mcp/auth-context.ts b/src/lib/mcp/auth-context.ts index 3b23efc..1b36e90 100644 --- a/src/lib/mcp/auth-context.ts +++ b/src/lib/mcp/auth-context.ts @@ -188,7 +188,16 @@ export function connectionScopeFromAuthContext( }; } - if (effectiveProjectId) return null; + // A credential whose grant is limited to one project runs requests that + // name none in that project, so the API reports it as the effective scope. + if (effectiveProjectId) { + return { + kind: "project", + organizationId, + projectId: effectiveProjectId, + source: "credential", + }; + } return { kind: "organization", organizationId,