Skip to content
Draft
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
56 changes: 52 additions & 4 deletions api/mcp.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,8 @@ type RequestLike = {

type JsonResponse = {
error: string | { code: number; message: string };
/** A fixed refusal code from RESOLVE_REFUSAL_MESSAGES. */
code?: string;
message?: string;
jsonrpc?: string;
id?: string | number | null;
Expand Down Expand Up @@ -112,6 +114,7 @@ type ConnectedClientResolutionResponse = {
};
};
error?: string;
code?: string;
};

type UnauthorizedReason = 'missing_credentials' | 'invalid_token';
Expand Down Expand Up @@ -168,19 +171,48 @@ function resolveEndpointUrl(): string {

type ResolveFailureKind = 'config' | 'invalid_token' | 'forbidden' | 'upstream';

/**
* Why Terminal49 refused to resolve a valid grant, keyed by the fixed `code`
* the resolve endpoint returns with a 403. The client sees this text, never
* the upstream message.
*/
const RESOLVE_REFUSAL_MESSAGES = {
billing_access_restricted:
'Terminal49 access for this account is paused because of a billing issue. An account manager can resolve it at https://app.terminal49.com/settings/billing, then retry.',
account_onboarding_incomplete:
'This Terminal49 account has not finished setup. Sign in at https://app.terminal49.com to complete account onboarding, then retry.',
} as const;

type ResolveRefusalCode = keyof typeof RESOLVE_REFUSAL_MESSAGES;

function resolveRefusalCode(
code: string | undefined,
): ResolveRefusalCode | undefined {
switch (code) {
case 'billing_access_restricted':
case 'account_onboarding_incomplete':
return code;
default:
return undefined;
}
}

class ConnectedClientResolveError extends Error {
readonly kind: ResolveFailureKind;
readonly upstreamStatus?: number;
readonly refusalCode?: ResolveRefusalCode;

constructor(
message: string,
kind: ResolveFailureKind,
upstreamStatus?: number,
refusalCode?: ResolveRefusalCode,
) {
super(message);
this.name = 'ConnectedClientResolveError';
this.kind = kind;
this.upstreamStatus = upstreamStatus;
this.refusalCode = refusalCode;
}
}

Expand Down Expand Up @@ -283,6 +315,7 @@ async function resolveConnectedClientToken(
`Terminal49 connected client resolve failed with ${response.status}`,
kind,
response.status,
kind === 'forbidden' ? resolveRefusalCode(payload.code) : undefined,
);
}

Expand Down Expand Up @@ -608,13 +641,18 @@ export default async function handler(
err instanceof ConnectedClientResolveError
? err.upstreamStatus
: undefined;
const refusalCode =
err instanceof ConnectedClientResolveError
? err.refusalCode
: undefined;
setCorsHeaders(res);
// Keep the detailed reason in the server log (correlated by request_id);
// return a generic, category-appropriate response so internals never leak.
logLifecycle('mcp.request.complete', requestId, {
reason: 'connected_client_resolve_failed',
kind,
upstream_status: upstreamStatus,
refusal_code: refusalCode,
message: err.message,
});
if (kind === 'invalid_token') {
Expand All @@ -624,10 +662,20 @@ export default async function handler(
message: 'Invalid or expired token.',
});
} else if (kind === 'forbidden') {
res.status(403).json({
error: 'Forbidden',
message: 'Terminal49 access is not enabled for this account.',
});
// A known refusal says what the account must do; anything else
// stays generic so upstream text never reaches the client.
res.status(403).json(
refusalCode
? {
error: 'Forbidden',
code: refusalCode,
message: RESOLVE_REFUSAL_MESSAGES[refusalCode],
}
: {
error: 'Forbidden',
message: 'Terminal49 access is not enabled for this account.',
},
);
} else if (kind === 'config') {
res.status(500).json({
error: 'Server misconfiguration',
Expand Down
78 changes: 78 additions & 0 deletions packages/mcp/tests/api-handler.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -612,6 +612,84 @@ describe('api/mcp handler lifecycle', () => {
expect(mockState.servers).toHaveLength(0);
});

it.each([
[
'billing_access_restricted',
'Terminal49 access for this account is paused because of a billing issue. An account manager can resolve it at https://app.terminal49.com/settings/billing, then retry.',
],
[
'account_onboarding_incomplete',
'This Terminal49 account has not finished setup. Sign in at https://app.terminal49.com to complete account onboarding, then retry.',
],
])(
'explains a %s resolver refusal without echoing upstream text',
async (code, message) => {
process.env.T49_MCP_AUTHKIT_ENABLED = 'true';
process.env.T49_CONNECTED_CLIENTS_RESOLVE_SECRET = 'resolve-secret';
process.env.WORKOS_MCP_RESOURCE = 'https://mcp.test';
process.env.WORKOS_AUTHORIZATION_SERVER_URL = 'https://auth.workos.test';
vi.stubGlobal(
'fetch',
vi.fn(
async () =>
new Response(
JSON.stringify({ error: 'internal upstream detail', code }),
{ status: 403 },
),
),
);

const { default: handler } = await import('../../../api/mcp.ts');
const req = createRequest({
headers: {
host: 'localhost',
authorization: 'Bearer valid-workos-mcp-token',
},
});
const res = new MockResponse();

await handler(req as any, res as any);

expect(res.statusCode).toBe(403);
expect(res.payload).toEqual({ error: 'Forbidden', code, message });
expect(res.headers['WWW-Authenticate']).toBeUndefined();
expect(mockState.servers).toHaveLength(0);
},
);

it('keeps an unknown resolver refusal code generic', async () => {
process.env.T49_MCP_AUTHKIT_ENABLED = 'true';
process.env.T49_CONNECTED_CLIENTS_RESOLVE_SECRET = 'resolve-secret';
process.env.WORKOS_MCP_RESOURCE = 'https://mcp.test';
process.env.WORKOS_AUTHORIZATION_SERVER_URL = 'https://auth.workos.test';
vi.stubGlobal(
'fetch',
vi.fn(
async () =>
new Response(JSON.stringify({ error: 'nope', code: 'toString' }), {
status: 403,
}),
),
);

const { default: handler } = await import('../../../api/mcp.ts');
const req = createRequest({
headers: {
host: 'localhost',
authorization: 'Bearer valid-workos-mcp-token',
},
});
const res = new MockResponse();

await handler(req as any, res as any);

expect(res.statusCode).toBe(403);
expect(res.payload).toEqual({
error: 'Forbidden',
message: 'Terminal49 access is not enabled for this account.',
});
});

it('omits resource_metadata from the 401 challenge when WorkOS is not configured', async () => {
// Token / client-secret deployment: no WORKOS_* env. Advertising OAuth
// discovery would send clients to a PRM endpoint that 500s.
Expand Down
Loading