Skip to content
Open
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
30 changes: 25 additions & 5 deletions src/app/api/mcp/route.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,7 @@ vi.mock('@/lib/rate-limit', async (importOriginal) => {
return { ...actual, chargeRateLimit: (...args: unknown[]) => consume(...args) };
});

const okResolution = {
ok: true,
const organizer = {
actor: {
kind: 'organizer',
id: 'org_1',
Expand All @@ -38,7 +37,12 @@ const okResolution = {
clientId: 'c',
defaultWorkspaceId: 'ws_1',
workspaces: [{ id: 'ws_1', slug: 'w', name: 'W', role: 'owner' }],
locale: null,
locale: null as string | null,
};

const okResolution = {
ok: true,
organizer,
authInfo: { token: 'tok', clientId: 'c', scopes: ['signups:read', 'signups:write'] },
};

Expand Down Expand Up @@ -137,6 +141,22 @@ describe('/api/mcp', () => {
expect(body.result.tools.map((t) => t.name)).toContain('list_workspaces');
});

it('gives the tools only the organizer fields and the database, never the auth info', async () => {
const { POST } = await import('./route');
toolContexts.mockClear();
// A field the seam might gain later, outside BearerOrganizer, must not reach tools.
resolve.mockResolvedValue({ ...okResolution, extra: 'not for tools' });
const r = await POST(post(rpc('tools/list')));
expect(r.status).toBe(200);
expect(toolContexts).toHaveBeenCalledOnce();
const ctx = toolContexts.mock.calls[0]?.[0] as Record<string, unknown>;
expect(Object.keys(ctx).sort()).toEqual(
['actor', 'clientId', 'db', 'defaultWorkspaceId', 'locale', 'scopes', 'workspaces'].sort(),
);
expect(ctx).not.toHaveProperty('authInfo');
expect(JSON.stringify({ ...ctx, db: undefined })).not.toContain('tok');
});

it.each([
['as saved', OTHER_LOCALE],
['null when the organizer saved none', null],
Expand All @@ -146,13 +166,13 @@ describe('/api/mcp', () => {
async (_name, locale) => {
const { POST } = await import('./route');
toolContexts.mockClear();
resolve.mockResolvedValue({ ...okResolution, locale });
resolve.mockResolvedValue({ ...okResolution, organizer: { ...organizer, locale } });
const r = await POST(post(rpc('tools/list')));
expect(r.status).toBe(200);
expect(toolContexts).toHaveBeenCalledOnce();
const ctx = toolContexts.mock.calls[0]?.[0] as ToolContext;
expect(ctx.locale).toBe(locale);
expect(ctx.actor).toEqual(okResolution.actor);
expect(ctx.actor).toEqual(organizer.actor);
},
);

Expand Down
14 changes: 4 additions & 10 deletions src/app/api/mcp/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -100,20 +100,14 @@ export async function POST(request: Request): Promise<Response> {
// a minute.
const organizerLimited = await meter(
RateLimits.mcpPerOrganizer,
auth.actor.id,
auth.organizer.actor.id,
Math.max(1, countToolCalls(parsedBody)),
);
if (organizerLimited) return organizerLimited;

const ctx: ToolContext = {
db: getDb(),
actor: auth.actor,
scopes: auth.scopes,
clientId: auth.clientId,
defaultWorkspaceId: auth.defaultWorkspaceId,
workspaces: auth.workspaces,
locale: auth.locale,
};
// Only what `BearerOrganizer` names reaches tools; the SDK's auth info,
// which carries the raw token, stays out.
const ctx: ToolContext = { db: getDb(), ...auth.organizer };
// The body is already consumed; the SDK never reads it when parsedBody is given.
return getMcpHandler().fetch(request, {
authInfo: attachContext(auth.authInfo, ctx),
Expand Down
119 changes: 65 additions & 54 deletions src/auth/bearer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,61 +22,82 @@ import { parseScopeString, type Scope } from '@/oauth/scopes';
import { loadOrganizerSessionById, toActor, type OrganizerSession } from './organizer-session';

/**
* The seam between the authorization server and the MCP layer.
*
* This is the only thing the MCP routes and tool handlers may know about
* authentication: give it the request, get back the same `Actor` a cookie
* session would produce plus the token's scopes, or a ready-made 401/403
* challenge to return as-is. Token format, keys, audience, issuer — all of
* that stays behind this function, so swapping the authorization server is
* a rewrite of one file.
*
* Scope checks sit *on top of* the policy layer, never instead of it: a
* token with `signups:write` still cannot write to a workspace where the
* organizer is a viewer, because the actor is the same one
* `requireWorkspaceWrite` already judges.
* What a token's organizer may act as. Every field here reaches every MCP
* tool's context, so anything new is added on purpose, and token material
* (the raw token, `AuthInfo`) never goes here.
*/
interface BearerWorkspace {
id: string;
slug: string;
name: string;
role: WorkspaceRole;
export interface BearerOrganizer {
actor: Extract<Actor, { kind: 'organizer' }>;
scopes: Scope[];
clientId: string;
/** The organizer's default workspace, for tools called without one. */
defaultWorkspaceId: string | null;
/** Every workspace the organizer belongs to, with names for display. */
workspaces: { id: string; slug: string; name: string; role: WorkspaceRole }[];
/**
* The organizer's saved language, raw (`OrganizerSession.locale`), for
* tool handlers, which may not query the database. Not on `actor`.
*/
locale: string | null;
}

export type BearerResolution =
| {
ok: true;
actor: Extract<Actor, { kind: 'organizer' }>;
scopes: Scope[];
clientId: string;
/** The organizer's default workspace, for tools called without one. */
defaultWorkspaceId: string | null;
/** Every workspace the organizer belongs to, with names for display. */
workspaces: BearerWorkspace[];
/**
* The organizer's saved language, raw (`OrganizerSession.locale`), for
* tool handlers, which may not query the database. Not on `actor`.
*/
locale: string | null;
organizer: BearerOrganizer;
/**
* What the SDK verified, for handing back to SDK code that wants it
* (the MCP handler's pass-through auth info). Carries the raw token;
* never log it.
* never log it, and never copy it into a tool's context.
*/
authInfo: AuthInfo;
}
| { ok: false; response: Response };

/** The organizer's memberships in the shape the MCP layer shows to a client. */
export function bearerWorkspaces(session: OrganizerSession): BearerWorkspace[] {
return session.memberships.map((m) => ({
id: m.workspaceId,
slug: m.workspaceSlug,
name: m.workspaceName,
role: m.role,
}));
/**
* What a token's organizer may act as, from their session: the one place
* this is built, so the MCP tests and evals run tools on the same context
* production does. Null when the session gives no organizer actor.
*/
export function bearerOrganizer(
session: OrganizerSession,
clientId: string,
scopes: Scope[],
): BearerOrganizer | null {
const actor = toActor(session);
// `toActor` gives an organizer for every session, so this only narrows the type.
if (actor.kind !== 'organizer') return null;
return {
// Spread rather than mutate: `toActor` is React-cached and the object may be shared.
actor: { ...actor, via: { clientId } },
scopes,
clientId,
defaultWorkspaceId: session.defaultWorkspaceId,
workspaces: session.memberships.map((m) => ({
id: m.workspaceId,
slug: m.workspaceSlug,
name: m.workspaceName,
role: m.role,
})),
locale: session.locale,
};
}

/**
* The seam between the authorization server and the MCP layer.
*
* This is the only thing the MCP routes and tool handlers may know about
* authentication: give it the request, get back the same `Actor` a cookie
* session would produce plus the token's scopes, or a ready-made 401/403
* challenge to return as-is. Token format, keys, audience, issuer — all of
* that stays behind this function, so swapping the authorization server is
* a rewrite of one file.
*
* Scope checks sit *on top of* the policy layer, never instead of it: a
* token with `signups:write` still cannot write to a workspace where the
* organizer is a viewer, because the actor is the same one
* `requireWorkspaceWrite` already judges.
*/
export async function resolveBearerActor(
request: Request,
opts: { requiredScopes?: Scope[] } = {},
Expand All @@ -92,11 +113,11 @@ export async function resolveBearerActor(

const organizerId = typeof auth.extra?.sub === 'string' ? auth.extra.sub : null;
const session = organizerId ? await loadOrganizerSessionById(getDb(), organizerId) : null;
const actor = session ? toActor(session) : null;
if (!session || actor?.kind !== 'organizer') {
const organizer = session
? bearerOrganizer(session, auth.clientId, parseScopeString(auth.scopes.join(' ')))
: null;
if (!organizer) {
// The organizer behind the token is gone; treat the token as invalid.
// `toActor` gives an organizer for every session, so the kind check only
// narrows the type for the return below.
return {
ok: false,
response: bearerAuthChallengeResponse(
Expand All @@ -107,17 +128,7 @@ export async function resolveBearerActor(
),
};
}
return {
ok: true,
// Spread rather than mutate: `toActor` is React-cached and the object may be shared.
actor: { ...actor, via: { clientId: auth.clientId } },
scopes: parseScopeString(auth.scopes.join(' ')),
clientId: auth.clientId,
defaultWorkspaceId: session.defaultWorkspaceId,
workspaces: bearerWorkspaces(session),
locale: session.locale,
authInfo: auth,
};
return { ok: true, organizer, authInfo: auth };
}

let verifier: OAuthTokenVerifier | null = null;
Expand Down
23 changes: 2 additions & 21 deletions src/mcp/context.ts
Original file line number Diff line number Diff line change
@@ -1,33 +1,14 @@
import type { BearerOrganizer } from '@/auth/bearer';
import type { Db } from '@/db/client';
import type { ServiceError } from '@/lib/errors';
import type { Actor, WorkspaceRole } from '@/lib/policy';
import type { Result } from '@/lib/result';
import { chooseWorkspaceId } from '@/lib/workspace-choice';
import type { Scope } from '@/oauth/scopes';

type OrganizerActor = Extract<Actor, { kind: 'organizer' }>;

interface ToolWorkspace {
id: string;
slug: string;
name: string;
role: WorkspaceRole;
}

/**
* Everything a tool handler may know about the request. Built once per
* request from the bearer seam's resolution; never shared across requests.
*/
export interface ToolContext {
db: Db;
actor: OrganizerActor;
scopes: Scope[];
clientId: string;
defaultWorkspaceId: string | null;
workspaces: ToolWorkspace[];
/** The organizer's saved language as stored, or null: the bearer seam's `locale`. */
locale: string | null;
}
export type ToolContext = BearerOrganizer & { db: Db };

/** The workspace a tool acts in: the argument if given, else the organizer's default. */
export function resolveWorkspaceId(
Expand Down
18 changes: 5 additions & 13 deletions src/mcp/testing/context.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { bearerWorkspaces } from '@/auth/bearer';
import { loadOrganizerSessionById, toActor } from '@/auth/organizer-session';
import { bearerOrganizer } from '@/auth/bearer';
import { loadOrganizerSessionById } from '@/auth/organizer-session';
import type { Db } from '@/db/client';
import type { Scope } from '@/oauth/scopes';
import type { ToolContext } from '../context';
Expand All @@ -13,15 +13,7 @@ export async function contextForOrganizer(
): Promise<ToolContext> {
const session = await loadOrganizerSessionById(db, organizerId);
if (!session) throw new Error(`no organizer ${organizerId}`);
const actor = toActor(session);
if (actor.kind !== 'organizer') throw new Error('not an organizer');
return {
db,
actor: { ...actor, via: { clientId } },
scopes,
clientId,
defaultWorkspaceId: session.defaultWorkspaceId,
workspaces: bearerWorkspaces(session),
locale: session.locale,
};
const organizer = bearerOrganizer(session, clientId, scopes);
if (!organizer) throw new Error('not an organizer');
return { db, ...organizer };
}
19 changes: 11 additions & 8 deletions src/oauth/flow.db.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -275,19 +275,19 @@ describe('authorization code flow on Postgres', () => {
expect(seam.ok).toBe(true);
if (seam.ok) {
// Same actor the cookie path builds, plus the app that carried it.
expect(seam.actor).toEqual({ ...organizerActor, via: { clientId: CLIENT } });
expect(seam.scopes).toEqual(['signups:read', 'signups:write']);
expect(seam.clientId).toBe(CLIENT);
expect(seam.defaultWorkspaceId).toBe(workspaceId);
expect(seam.workspaces).toEqual([
expect(seam.organizer.actor).toEqual({ ...organizerActor, via: { clientId: CLIENT } });
expect(seam.organizer.scopes).toEqual(['signups:read', 'signups:write']);
expect(seam.organizer.clientId).toBe(CLIENT);
expect(seam.organizer.defaultWorkspaceId).toBe(workspaceId);
expect(seam.organizer.workspaces).toEqual([
{ id: workspaceId, slug: organizerId.toLowerCase(), name: 'Flow', role: 'owner' },
]);
expect(seam.authInfo).toMatchObject({
token: tokens.access_token,
clientId: CLIENT,
scopes: ['signups:read', 'signups:write'],
});
expect(seam.locale).toBeNull();
expect(seam.organizer.locale).toBeNull();
}
// The organizer's saved language rides along raw, even one that names no
// language, and stays off the actor: the cookie path's actor still matches.
Expand All @@ -296,8 +296,11 @@ describe('authorization code flow on Postgres', () => {
const withLocale = await resolveBearerActor(bearer(tokens.access_token));
expect(withLocale.ok).toBe(true);
if (withLocale.ok) {
expect(withLocale.locale).toBe(saved);
expect(withLocale.actor).toEqual({ ...organizerActor, via: { clientId: CLIENT } });
expect(withLocale.organizer.locale).toBe(saved);
expect(withLocale.organizer.actor).toEqual({
...organizerActor,
via: { clientId: CLIENT },
});
}
expect(toActor(await loadOrganizerSessionById(db, organizerId))).toEqual(organizerActor);
}
Expand Down