Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
166 changes: 166 additions & 0 deletions src/app/[transport]/route.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,166 @@
import { afterEach, beforeEach, describe, expect, mock, test } from "bun:test";
import type { McpConnectionScopeFailureAnalytics } from "@/lib/mcp/analytics";
import { defaultMcpDependencies } from "@/lib/mcp/dependencies";

process.env.CLERK_SECRET_KEY ??= "test-clerk-secret";

// after() needs a Next request scope only the server provides. The route uses
// it to flush analytics, which these tests observe directly instead.
const nextServer = await import("next/server");
mock.module("next/server", () => ({ ...nextServer, after: () => {} }));

// Scope resolution runs before the instrumented McpServer exists, so this
// capture is the only record of it. Record the calls and delegate, so the
// module stays intact for anything else exercising it.
const captured: McpConnectionScopeFailureAnalytics[] = [];
const analytics = await import("@/lib/mcp/analytics");
const captureMcpConnectionScopeFailure =
analytics.captureMcpConnectionScopeFailure;
mock.module("@/lib/mcp/analytics", () => ({
...analytics,
captureMcpConnectionScopeFailure: (
...args: Parameters<typeof analytics.captureMcpConnectionScopeFailure>
) => {
captured.push(args[0]);
return captureMcpConnectionScopeFailure(...args);
},
}));

const originalCreateKernelClient = defaultMcpDependencies.createKernelClient;
const { POST, connectionScopeFailureResponse } = await import("./route");

function initializeRequest(token = "sk_opaque_key") {
return new Request("https://mcp.example.test/sse", {
method: "POST",
headers: {
Authorization: `Bearer ${token}`,
"Content-Type": "application/json",
Accept: "application/json, text/event-stream",
},
body: JSON.stringify({
jsonrpc: "2.0",
id: 1,
method: "initialize",
params: {
protocolVersion: "2025-06-18",
capabilities: {},
clientInfo: { name: "route-test", version: "0" },
},
}),
}) as never;
}

function failingAuthContext(error: unknown) {
defaultMcpDependencies.createKernelClient = () =>
({
auth: {
context: {
retrieve: async () => {
throw error;
},
},
},
}) as never;
}

beforeEach(() => {
captured.length = 0;
});
Comment thread
cursor[bot] marked this conversation as resolved.

afterEach(() => {
defaultMcpDependencies.createKernelClient = originalCreateKernelClient;
});

describe("connection scope failures through the handler", () => {
test("answers a refused credential with 401 rather than a server error", async () => {
failingAuthContext(Object.assign(new Error("revoked"), { status: 401 }));

const response = await POST(initializeRequest());

expect(response.status).toBe(401);
expect(await response.json()).toEqual({
error: "invalid_token",
error_description: "The Kernel API rejected this credential",
});
expect(captured).toEqual([
{
outcome: "rejected",
credentialType: "api_key",
upstreamStatusCode: 401,
},
]);
});

test("keeps a credential scoped to another project usable", async () => {
failingAuthContext(
Object.assign(new Error("other project"), { status: 403 }),
);

const response = await POST(initializeRequest());

expect(response.status).toBe(403);
expect((await response.json()).error).toBe("insufficient_scope");
expect(captured[0]?.upstreamStatusCode).toBe(403);
});

test("answers an upstream outage with a retryable 503", async () => {
failingAuthContext(
Object.assign(new Error("unavailable"), { status: 502 }),
);

const response = await POST(initializeRequest());

expect(response.status).toBe(503);
expect(response.headers.get("Retry-After")).toBe("1");
expect(captured).toEqual([
{
outcome: "unavailable",
credentialType: "api_key",
upstreamStatusCode: 502,
},
]);
});

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",
);
expect(captured).toEqual([
{
outcome: "invalid",
credentialType: "api_key",
upstreamStatusCode: undefined,
},
]);
});
});

describe("connectionScopeFailureResponse", () => {
test("names an inactive project instead of blaming the credential", async () => {
const response = connectionScopeFailureResponse({
status: "rejected",
statusCode: 404,
});

expect(response.status).toBe(404);
expect(response.headers.get("WWW-Authenticate")).toBeNull();
expect(await response.json()).toEqual({
error: "project_not_found",
error_description:
"The Kernel project for this connection was not found or is inactive",
});
});

test("challenges a refused credential so clients re-authenticate", () => {
const response = connectionScopeFailureResponse({
status: "rejected",
statusCode: 401,
});

expect(response.headers.get("WWW-Authenticate")).toContain(
'error="invalid_token"',
);
});
});
93 changes: 75 additions & 18 deletions src/app/[transport]/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,15 @@ import { verifyToken } from "@clerk/nextjs/server";
import { after, NextRequest } from "next/server";
import { isValidJwtFormat } from "@/lib/auth-utils";
import {
captureMcpConnectionScopeFailure,
flushMcpAnalytics,
instrumentMcpAnalytics,
isMcpAnalyticsEnabled,
} from "@/lib/mcp/analytics";
import {
connectionAnalyticsFromContext,
resolveMcpConnectionContext,
type McpConnectionContextFailure,
} from "@/lib/mcp/auth-context";
import { mcpAppsAuthSubject } from "@/lib/mcp-apps-marker";
import { requestUsesMcpApps } from "@/lib/mcp-apps-request";
Expand All @@ -36,26 +38,67 @@ export async function OPTIONS(_req: NextRequest): Promise<Response> {
});
}

const CORS_HEADERS = {
"Content-Type": "application/json",
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "GET, POST, OPTIONS",
"Access-Control-Allow-Headers": "Content-Type, Authorization",
};

function errorResponse(
status: number,
error: string,
description: string,
headers: Record<string, string> = {},
): Response {
return new Response(
JSON.stringify({ error, error_description: description }),
{ status, headers: { ...CORS_HEADERS, ...headers } },
);
}

// Helper function to create authentication error response
function createAuthErrorResponse(
error: string = "invalid_token",
description: string = "Missing or invalid access token",
): Response {
return new Response(
JSON.stringify({
error,
error_description: description,
}),
{
status: 401,
headers: {
"WWW-Authenticate": `Bearer realm="OAuth", error="${error}", error_description="${description}"`,
"Content-Type": "application/json",
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "GET, POST, OPTIONS",
"Access-Control-Allow-Headers": "Content-Type, Authorization",
},
},
return errorResponse(401, error, description, {
"WWW-Authenticate": `Bearer realm="OAuth", error="${error}", error_description="${description}"`,
});
}

export function connectionScopeFailureResponse(
failure: Exclude<McpConnectionContextFailure, { status: "invalid" }>,
): Response {
if (failure.status === "rejected") {
switch (failure.statusCode) {
case 403:
return errorResponse(
403,
"insufficient_scope",
"This credential is not scoped to the requested Kernel project",
{
"WWW-Authenticate": `Bearer realm="OAuth", error="insufficient_scope"`,
},
);
case 404:
return errorResponse(
404,
"project_not_found",
"The Kernel project for this connection was not found or is inactive",
);
case 401:
return createAuthErrorResponse(
"invalid_token",
"The Kernel API rejected this credential",
);
}
}
return errorResponse(
503,
"temporarily_unavailable",
"Unable to resolve Kernel connection scope",
{ "Retry-After": "1" },
);
}

Expand Down Expand Up @@ -83,6 +126,7 @@ async function handleMcpRequestWithIdentity({
authSubject,
scopes,
authInfoExtra,
credentialType,
transportSessionId,
connectionContextCacheIdentity,
observeConnection,
Expand All @@ -92,11 +136,12 @@ async function handleMcpRequestWithIdentity({
authSubject: string;
scopes: string[];
authInfoExtra: AuthInfoExtra;
credentialType: "api_key" | "oauth";
transportSessionId: string | null;
connectionContextCacheIdentity?: string;
observeConnection: boolean;
}) {
const [mcpApps, connectionContext] = await Promise.all([
const [mcpApps, connection] = await Promise.all([
requestUsesMcpApps(req, {
authSubject,
transportSessionId,
Expand All @@ -108,9 +153,19 @@ async function handleMcpRequestWithIdentity({
cacheIdentity: connectionContextCacheIdentity,
}),
]);
if (!connectionContext) {
throw new Error("Unable to resolve Kernel connection scope");
if (connection.status !== "ok") {
captureMcpConnectionScopeFailure({
outcome: connection.status,
credentialType,
upstreamStatusCode:
connection.status === "invalid" ? undefined : connection.statusCode,
});
if (connection.status === "invalid") {
throw new Error("Unable to resolve Kernel connection scope");
}
return connectionScopeFailureResponse(connection);
}
const connectionContext = connection.context;
const connectionAnalytics =
observeConnection && isMcpAnalyticsEnabled()
? connectionAnalyticsFromContext(connectionContext)
Expand Down Expand Up @@ -161,6 +216,7 @@ async function handleAuthenticatedRequest(
authSubject: mcpAppsAuthSubject({ token }),
scopes: ["apikey"],
authInfoExtra: { userId: null, clerkToken: null },
credentialType: "api_key",
transportSessionId,
observeConnection,
});
Expand Down Expand Up @@ -194,6 +250,7 @@ async function handleAuthenticatedRequest(
authSubject,
scopes: ["openid"],
authInfoExtra: { userId, clerkToken: token },
credentialType: "oauth",
transportSessionId,
connectionContextCacheIdentity: transportSessionId
? `${authSubject}\0${transportSessionId}`
Expand Down
42 changes: 42 additions & 0 deletions src/lib/mcp/analytics.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,11 @@ import {
PostHogMCPAnalyticsProperty,
} from "@posthog/mcp";
import {
captureMcpConnectionScopeFailure,
captureOAuthTokenExchange,
enrichMcpAnalyticsEvent,
instrumentMcpAnalytics,
MCP_CONNECTION_SCOPE_FAILURE_EVENT,
OAUTH_TOKEN_EXCHANGE_EVENT,
sanitizeMcpAnalyticsEvent,
} from "@/lib/mcp/analytics";
Expand Down Expand Up @@ -328,6 +330,46 @@ describe("captureOAuthTokenExchange", () => {
});
});

describe("captureMcpConnectionScopeFailure", () => {
test("records the outcome without the credential it was resolving", () => {
const captured: unknown[] = [];
const fakePosthog = {
capture: (event: unknown) => captured.push(event),
} as unknown as PostHog;

captureMcpConnectionScopeFailure(
{
outcome: "rejected",
credentialType: "api_key",
upstreamStatusCode: 403,
},
fakePosthog,
);

expect(captured).toEqual([
{
distinctId: "mcp-connection-scope",
event: MCP_CONNECTION_SCOPE_FAILURE_EVENT,
properties: {
$process_person_profile: false,
connection_scope_outcome: "rejected",
connection_credential_type: "api_key",
upstream_status_code: 403,
},
},
]);
});

test("is a no-op without a configured client", () => {
expect(() =>
captureMcpConnectionScopeFailure(
{ outcome: "unavailable", credentialType: "oauth" },
null,
),
).not.toThrow();
});
});

describe("instrumentMcpAnalytics (SDK integration)", () => {
const ORG = "org_integration";

Expand Down
Loading
Loading