test(mcp): the factory guard of the handler and the logged error name (#202)

Two guards of the endpoint had no test of their own:
- the factory builds no server for a request that does not carry the
  account the route writes in authInfo (the SDK handler verifies nothing);
- the server log keeps of an exception its class name only when that name
  reads as one.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
le king fu 2026-11-15 08:01:39 -05:00
commit 18fa391bf6

View file

@ -42,7 +42,7 @@ const { POST } = route;
const { createAgentToken, revokeAgentToken } = await import('@/lib/agentTokens');
const { rateLimit, rateLimitDelay } = await import('@/lib/rateLimit');
const { loadAccountTags } = await import('@/lib/taskQueries');
const { TOOL_ERROR_MESSAGES } = await import('@/lib/mcp/errors');
const { TOOL_ERROR_MESSAGES, errorName } = await import('@/lib/mcp/errors');
const { instructionsFor, mcpHandler } = await import('@/lib/mcp/server');
const SITE = 'https://liste.lacompagniemaximus.com';
@ -624,6 +624,52 @@ describe('authentication', () => {
it('exports POST and nothing else', () => {
expect(Object.keys(route)).toEqual(['POST']);
});
// The SDK handler verifies nothing and passes `authInfo` through: the route
// is its only caller. Should another one appear, the factory builds no
// server for a request that does not carry what the route writes.
it.each([
['no authInfo', undefined],
['an authInfo without the account', { token: '', clientId: 'client', scopes: ['read'] }],
['an empty account', { userId: '', scope: 'read', tokenId: null, tokenName: 'Assistant' }],
['an unknown scope', { userId: 'user-of-the-test', scope: 'admin', tokenId: null, tokenName: 'Assistant' }],
['a token id that is not a string', { userId: 'user-of-the-test', scope: 'read', tokenId: 7, tokenName: 'Assistant' }],
['no token name', { userId: 'user-of-the-test', scope: 'read', tokenId: null }],
])('the handler builds no server for %s', async (_label, extra) => {
const authInfo = extra === undefined || 'clientId' in extra
? extra
: { token: '', clientId: 'client', scopes: ['read'], extra };
for (const era of ERAS) {
const legacy = era === 'legacy';
const request = new Request(`${CONTAINER}/api/mcp`, {
method: 'POST',
headers: legacy
? { 'content-type': 'application/json', ...LEGACY_ACCEPT }
: { 'content-type': 'application/json', 'mcp-protocol-version': MODERN, 'mcp-method': 'tools/list' },
body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'tools/list', ...(legacy ? {} : { params: { _meta: ENVELOPE } }) }),
});
const refusedAnswer = await answer(await mcpHandler.fetch(request, authInfo === undefined ? undefined : { authInfo: authInfo as never }));
expect(refusedAnswer.status).toBe(500);
expect(refusedAnswer.message).toEqual({ jsonrpc: '2.0', id: 1, error: { code: -32603, message: 'Internal server error' } });
}
expect(logLines()).toEqual([{ at: 'mcp-sdk', error: 'Error' }, { at: 'mcp-sdk', error: 'Error' }]);
});
it('the handler serves the account its authInfo names, with a null token id', async () => {
const account = await newAccount();
const own = await newTask(account);
const request = new Request(`${CONTAINER}/api/mcp`, {
method: 'POST',
headers: { 'content-type': 'application/json', 'mcp-protocol-version': MODERN, 'mcp-method': 'tools/call', 'mcp-name': 'list_tasks' },
body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'tools/call', params: { name: 'list_tasks', arguments: {}, _meta: ENVELOPE } }),
});
const served = await answer(await mcpHandler.fetch(request, {
authInfo: { token: '', clientId: '', scopes: ['read'], extra: { userId: account.userId, scope: 'read', tokenId: null, tokenName: 'Assistant' } },
}));
const result = resultOf(served) as { structuredContent: { tasks: ShapedTask[] } };
expect(result.structuredContent.tasks.map((task) => task.id)).toEqual([own]);
expect(logLines('mcp-tool')).toEqual([{ at: 'mcp-tool', tool: 'list_tasks', outcome: 'ok', ms: expect.any(Number), token: null }]);
});
});
describe('the two generations of the protocol', () => {
@ -1313,6 +1359,20 @@ describe('errors', () => {
expect(logLines()).toEqual([{ at: 'mcp', status: 500, ms: expect.any(Number), error: expect.stringMatching(/^[A-Za-z]+$/) }]);
});
it('keeps of an exception its class name, and only when it reads as one', () => {
class QueryError extends Error {
name = 'QueryError';
}
expect(errorName(new QueryError('Failed query: select 1'))).toBe('QueryError');
expect(errorName(new TypeError('x'))).toBe('TypeError');
expect(errorName(new Error('x'))).toBe('Error');
// A name is a property anyone can set: a sentence is not kept.
expect(errorName(Object.assign(new Error('x'), { name: 'Failed query: select * from sl_tasks' }))).toBe('Error');
expect(errorName(Object.assign(new Error('x'), { name: 'x'.repeat(65) }))).toBe('Error');
expect(errorName(Object.assign(new Error('x'), { name: '' }))).toBe('Error');
for (const thrown of ['a string', { name: 'NotAnError' }, null, undefined, 42]) expect(errorName(thrown)).toBe('Error');
});
it('no result of any tool carries the account', async () => {
const a = await connected();
const tag = await newTag(a);