|
| 1 | +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. |
| 2 | +// |
| 3 | +// `tools/list` pagination and the credential-rejection fault, measured against |
| 4 | +// REAL Streamable-HTTP servers through the SDK-backed default client. |
| 5 | +// |
| 6 | +// Nothing here injects a client: each case starts a dependency-free MCP server |
| 7 | +// on an ephemeral localhost port (JSON-RPC over POST, answered as plain JSON), |
| 8 | +// so what is asserted is what the MCP SDK's own transport and client do with |
| 9 | +// the server's answers — the cursor it really sends, the 401 it really raises. |
| 10 | + |
| 11 | +import { createServer, type IncomingMessage, type Server, type ServerResponse } from 'node:http'; |
| 12 | +import type { AddressInfo } from 'node:net'; |
| 13 | +import { afterEach, describe, expect, it } from 'vitest'; |
| 14 | +import { LiteKernel } from '@objectstack/core'; |
| 15 | +import { isConnectorUpstreamUnavailable } from '@objectstack/spec/integration'; |
| 16 | +import { AutomationServicePlugin, type AutomationEngine } from '@objectstack/service-automation'; |
| 17 | +import { ConnectorMcpPlugin } from './connector-mcp-plugin.js'; |
| 18 | +import { createMcpConnector, MCP_TOOLS_LIST_MAX_PAGES } from './mcp-connector.js'; |
| 19 | +import { createMcpProviderFactory } from './mcp-provider.js'; |
| 20 | + |
| 21 | +type JsonRpc = { jsonrpc: '2.0'; id?: number | string; method: string; params?: Record<string, unknown> }; |
| 22 | + |
| 23 | +interface Fixture { |
| 24 | + url: string; |
| 25 | + /** Every JSON-RPC message the server received, in order. */ |
| 26 | + received: JsonRpc[]; |
| 27 | + /** Every HTTP request the server received (method), in order. */ |
| 28 | + requests: string[]; |
| 29 | +} |
| 30 | + |
| 31 | +const servers: Server[] = []; |
| 32 | +afterEach(async () => { |
| 33 | + await Promise.all(servers.splice(0).map((s) => new Promise((r) => s.close(r)))); |
| 34 | +}); |
| 35 | + |
| 36 | +async function readBody(req: IncomingMessage): Promise<string> { |
| 37 | + let body = ''; |
| 38 | + for await (const chunk of req) body += chunk; |
| 39 | + return body; |
| 40 | +} |
| 41 | + |
| 42 | +/** |
| 43 | + * Start a fixture MCP server. `toolsList` answers one `tools/list` request |
| 44 | + * from its cursor; `reject` (when set) answers every request with that status. |
| 45 | + */ |
| 46 | +async function startServer(opts: { |
| 47 | + toolsList?: (cursor: string | undefined) => { tools: unknown[]; nextCursor?: string }; |
| 48 | + reject?: number; |
| 49 | +}): Promise<Fixture> { |
| 50 | + const fixture: Fixture = { url: '', received: [], requests: [] }; |
| 51 | + const server = createServer((req: IncomingMessage, res: ServerResponse) => { |
| 52 | + void (async () => { |
| 53 | + fixture.requests.push(req.method ?? ''); |
| 54 | + const body = await readBody(req); |
| 55 | + if (opts.reject !== undefined) { |
| 56 | + res.writeHead(opts.reject, { 'content-type': 'application/json' }); |
| 57 | + res.end(JSON.stringify({ error: 'invalid_token' })); |
| 58 | + return; |
| 59 | + } |
| 60 | + // No server-initiated SSE stream; DELETE (session end) is a no-op. |
| 61 | + if (req.method !== 'POST') { |
| 62 | + res.writeHead(req.method === 'GET' ? 405 : 200); |
| 63 | + res.end(); |
| 64 | + return; |
| 65 | + } |
| 66 | + const msg = JSON.parse(body) as JsonRpc; |
| 67 | + fixture.received.push(msg); |
| 68 | + if (msg.id === undefined) { |
| 69 | + res.writeHead(202); |
| 70 | + res.end(); |
| 71 | + return; |
| 72 | + } |
| 73 | + let result: unknown; |
| 74 | + if (msg.method === 'initialize') { |
| 75 | + result = { |
| 76 | + protocolVersion: msg.params?.protocolVersion, |
| 77 | + capabilities: { tools: {} }, |
| 78 | + serverInfo: { name: 'http-fixture', version: '1.0.0' }, |
| 79 | + }; |
| 80 | + } else if (msg.method === 'tools/list' && opts.toolsList) { |
| 81 | + result = opts.toolsList(msg.params?.cursor as string | undefined); |
| 82 | + } else { |
| 83 | + res.writeHead(200, { 'content-type': 'application/json' }); |
| 84 | + res.end(JSON.stringify({ jsonrpc: '2.0', id: msg.id, error: { code: -32601, message: 'method not found' } })); |
| 85 | + return; |
| 86 | + } |
| 87 | + res.writeHead(200, { 'content-type': 'application/json' }); |
| 88 | + res.end(JSON.stringify({ jsonrpc: '2.0', id: msg.id, result })); |
| 89 | + })(); |
| 90 | + }); |
| 91 | + servers.push(server); |
| 92 | + await new Promise<void>((r) => server.listen(0, '127.0.0.1', () => r())); |
| 93 | + fixture.url = `http://127.0.0.1:${(server.address() as AddressInfo).port}/mcp`; |
| 94 | + return fixture; |
| 95 | +} |
| 96 | + |
| 97 | +const tool = (name: string) => ({ name, description: `${name} tool`, inputSchema: { type: 'object' } }); |
| 98 | + |
| 99 | +/** Two pages: `alpha`, `beta` then (cursor `page-2`) `gamma`. */ |
| 100 | +const twoPages = (cursor: string | undefined) => |
| 101 | + cursor === undefined |
| 102 | + ? { tools: [tool('alpha'), tool('beta')], nextCursor: 'page-2' } |
| 103 | + : cursor === 'page-2' |
| 104 | + ? { tools: [tool('gamma')] } |
| 105 | + : { tools: [] }; |
| 106 | + |
| 107 | +describe('tools/list pagination — real Streamable-HTTP server', () => { |
| 108 | + it('follows nextCursor until exhausted: every tool on every page becomes an action', async () => { |
| 109 | + const server = await startServer({ toolsList: twoPages }); |
| 110 | + const bundle = await createMcpConnector({ name: 'paged', transport: { kind: 'http', url: server.url } }); |
| 111 | + try { |
| 112 | + expect(bundle.def.actions?.map((a) => a.key)).toEqual(['alpha', 'beta', 'gamma']); |
| 113 | + expect(Object.keys(bundle.handlers)).toEqual(['alpha', 'beta', 'gamma']); |
| 114 | + // The second request carried the server's cursor, and there was no third. |
| 115 | + const listCalls = server.received.filter((m) => m.method === 'tools/list'); |
| 116 | + expect(listCalls.map((m) => m.params?.cursor)).toEqual([undefined, 'page-2']); |
| 117 | + } finally { |
| 118 | + await bundle.close(); |
| 119 | + } |
| 120 | + }); |
| 121 | + |
| 122 | + it(`fails discovery loudly when the server still pages after ${MCP_TOOLS_LIST_MAX_PAGES} pages — never a truncated list`, async () => { |
| 123 | + let page = 0; |
| 124 | + const server = await startServer({ |
| 125 | + toolsList: () => ({ tools: [tool(`t_${page}`)], nextCursor: `c${++page}` }), |
| 126 | + }); |
| 127 | + await expect( |
| 128 | + createMcpConnector({ name: 'endless', transport: { kind: 'http', url: server.url } }), |
| 129 | + ).rejects.toThrow( |
| 130 | + `MCP server still returned a tools/list nextCursor after ${MCP_TOOLS_LIST_MAX_PAGES} pages ` + |
| 131 | + `(${MCP_TOOLS_LIST_MAX_PAGES} tools so far); refusing to build the connector from a truncated tool list.`, |
| 132 | + ); |
| 133 | + expect(server.received.filter((m) => m.method === 'tools/list')).toHaveLength(MCP_TOOLS_LIST_MAX_PAGES); |
| 134 | + }); |
| 135 | +}); |
| 136 | + |
| 137 | +describe('credential rejection — real Streamable-HTTP server', () => { |
| 138 | + it.each([401, 403])( |
| 139 | + 'an HTTP %i on the handshake is a plain configuration fault (not upstream-unavailable), sent once', |
| 140 | + async (status) => { |
| 141 | + const server = await startServer({ reject: status }); |
| 142 | + const factory = createMcpProviderFactory(); |
| 143 | + const materialized = factory({ |
| 144 | + name: 'vendor', |
| 145 | + label: 'Vendor', |
| 146 | + type: 'api', |
| 147 | + providerConfig: { transport: { kind: 'http', url: server.url } }, |
| 148 | + auth: { type: 'bearer', token: 'wrong-token' }, |
| 149 | + }); |
| 150 | + const err = await Promise.resolve(materialized).then( |
| 151 | + () => { throw new Error('expected rejection'); }, |
| 152 | + (e: unknown) => e, |
| 153 | + ); |
| 154 | + expect(err).toBeInstanceOf(Error); |
| 155 | + expect(isConnectorUpstreamUnavailable(err)).toBe(false); |
| 156 | + expect((err as Error).message).toContain( |
| 157 | + `connector-mcp provider: connector 'vendor' was refused by its MCP server (HTTP ${status})`, |
| 158 | + ); |
| 159 | + expect((err as Error).message).toContain('is not retried'); |
| 160 | + expect(server.requests).toEqual(['POST']); |
| 161 | + }, |
| 162 | + ); |
| 163 | + |
| 164 | + it('a declarative instance answered 401 fails the boot instead of degrading into a retry loop', async () => { |
| 165 | + const server = await startServer({ reject: 401 }); |
| 166 | + const declared = [ |
| 167 | + { |
| 168 | + name: 'vendor_mcp', |
| 169 | + label: 'Vendor MCP', |
| 170 | + type: 'api', |
| 171 | + provider: 'mcp', |
| 172 | + providerConfig: { transport: { kind: 'http', url: server.url } }, |
| 173 | + }, |
| 174 | + ]; |
| 175 | + const kernel = new LiteKernel({ logger: { level: 'silent' } } as never); |
| 176 | + kernel.use(new AutomationServicePlugin()); |
| 177 | + kernel.use({ |
| 178 | + name: 'test.connector-metadata', |
| 179 | + type: 'standard', |
| 180 | + version: '1.0.0', |
| 181 | + dependencies: ['com.objectstack.service-automation'], |
| 182 | + async init(ctx: { registerService(name: string, service: unknown): void }) { |
| 183 | + ctx.registerService('objectql', { |
| 184 | + registry: { listItems: (type: string) => (type === 'connector' ? declared : []) }, |
| 185 | + }); |
| 186 | + }, |
| 187 | + async start() {}, |
| 188 | + } as never); |
| 189 | + kernel.use(new ConnectorMcpPlugin()); |
| 190 | + try { |
| 191 | + await expect(kernel.bootstrap()).rejects.toThrow(/was refused by its MCP server \(HTTP 401\)/); |
| 192 | + const engine = kernel.getService('automation') as AutomationEngine; |
| 193 | + expect(engine.getConnectorDegradedReason('vendor_mcp')).toBeUndefined(); |
| 194 | + // Give a (wrongly) scheduled retry the chance to fire: none does. |
| 195 | + await new Promise((r) => setTimeout(r, 300)); |
| 196 | + expect(server.requests).toEqual(['POST']); |
| 197 | + } finally { |
| 198 | + await kernel.shutdown().catch(() => {}); |
| 199 | + } |
| 200 | + }); |
| 201 | +}); |
0 commit comments