| 1 | // Real official SDK HTTP/SSE transports in the committed builtin bundle. |
| 2 | // FetchProxy network/ticket authority is simulated here; Rust acceptance tests |
| 3 | // separately run the real broker and guarded McpHttpClient against loopback. |
| 4 | import { test } from 'node:test' |
| 5 | import assert from 'node:assert/strict' |
| 6 | import { randomUUID } from 'node:crypto' |
| 7 | import { createMcpModule } from '../dist/builtin/mcp.mjs' |
| 8 | import { validateMessage } from '../dist/protocol.mjs' |
| 9 | |
| 10 | const owner = { plugin_id: 'host:mcp', generation: 1, owner_token: 'builtin-test-token' } |
| 11 | const initParams = { protocolVersion: '2025-06-18', capabilities: {}, clientInfo: { name: 'codewhale-tui', version: '0.10.1' } } |
| 12 | const metadata = { 'io.modelcontextprotocol/protocolVersion': '2026-07-28', 'io.modelcontextprotocol/clientInfo': initParams.clientInfo, 'io.modelcontextprotocol/clientCapabilities': {} } |
| 13 | class FakeFetchProxy { |
| 14 | session = randomUUID() |
| 15 | grants = new Map() |
| 16 | bodies = new Map() |
| 17 | frames = [] |
| 18 | fetches = [] |
| 19 | closed = false |
| 20 | modern = false |
| 21 | sequence = 0 |
| 22 | failWrite = false |
| 23 | status = undefined |
| 24 | silent = false |
| 25 | constructor(legacy = false, ssePost = false) { this.legacy = legacy; this.ssePost = ssePost } |
| 26 | grant(method, params) { |
| 27 | if (this.modern && !['initialize', 'notifications/initialized'].includes(method)) params = { ...params, _meta: metadata } |
| 28 | const grant = { ticket: randomUUID(), operation_id: randomUUID(), method, ...(method.startsWith('notifications/') ? {} : { wire_id: String(this.sequence++) }), params: structuredClone(params) } |
| 29 | this.grants.set(grant.ticket, structuredClone(grant)); return grant |
| 30 | } |
| 31 | body(bytes, open = false) { const id = randomUUID(); this.bodies.set(id, { bytes: Array.from(Buffer.from(bytes)), open, waiting: undefined }); return id } |
| 32 | append(id, bytes) { const body = this.bodies.get(id); if (!body) return; body.bytes.push(...Buffer.from(bytes)); if (body.waiting) { const take = body.waiting; body.waiting = undefined; take() } } |
| 33 | async request(method, params, signal) { |
| 34 | assert.deepEqual(params.owner, owner); assert.equal(params.session_id, this.session) |
| 35 | if (method === 'net/start') { assert.equal(params.ticket, 'launch-once'); return {} } |
| 36 | if (method === 'net/close') { this.closed = true; for (const body of this.bodies.values()) body.waiting?.(); this.bodies.clear(); return {} } |
| 37 | if (method === 'net/release') { this.bodies.delete(params.response_id); return {} } |
| 38 | if (method === 'net/read') { |
| 39 | const body = this.bodies.get(params.response_id); assert.ok(body) |
| 40 | if (!body.bytes.length && body.open) await new Promise((resolve, reject) => { |
| 41 | const abort = () => { body.waiting = undefined; reject(new Error('fake response cancelled')) } |
| 42 | body.waiting = () => { signal?.removeEventListener('abort', abort); resolve() } |
| 43 | if (signal?.aborted) abort(); else signal?.addEventListener('abort', abort, { once: true }) |
| 44 | }) |
| 45 | if (this.closed) throw new Error('fake response closed') |
| 46 | const data = body.bytes.splice(0, 32768); return { data, done: !body.open && !body.bytes.length } |
| 47 | } |
| 48 | assert.equal(method, 'net/fetch') |
| 49 | this.fetches.push(structuredClone(params)) |
| 50 | assert.equal(new URL(params.url).origin, 'https://mcp-proxy.invalid') |
| 51 | assert.ok(Object.keys(params.headers).every(key => ['accept', 'content_type', 'mcp_session_id', 'mcp_protocol_version', 'mcp_method', 'mcp_name'].includes(key))) |
| 52 | if (params.method === 'GET') { |
| 53 | assert.equal(params.url, `https://mcp-proxy.invalid/${this.session}`) |
| 54 | if (!this.legacy) return { status: 405, headers: {} } |
| 55 | this.stream = this.body(this.holdEndpoint ? '' : `event: endpoint\ndata: https://mcp-proxy.invalid/${this.session}/endpoint\n\n`, true) |
| 56 | return { status: 200, headers: { 'content-type': 'text/event-stream' }, response_id: this.stream } |
| 57 | } |
| 58 | assert.equal(params.method, 'POST') |
| 59 | assert.equal(params.url, `https://mcp-proxy.invalid/${this.session}${this.legacy ? '/endpoint' : ''}`) |
| 60 | const frame = params.frame, grant = this.grants.get(params.ticket) |
| 61 | assert.ok(grant, 'operation grant is single-use') |
| 62 | assert.equal(params.operation_id, grant.operation_id); assert.equal(frame.method, grant.method) |
| 63 | assert.deepEqual(frame.params ?? {}, grant.params) |
| 64 | if (grant.wire_id !== undefined) assert.equal(frame.id, grant.wire_id) |
| 65 | this.grants.delete(params.ticket); this.frames.push(structuredClone(frame)) |
| 66 | if (this.negotiate && !this.legacy) { |
| 67 | this.legacy = true |
| 68 | const replacement = { ...structuredClone(grant), ticket: randomUUID() } |
| 69 | if (this.mutateNegotiation) replacement.params = { forged: true } |
| 70 | this.grants.set(replacement.ticket, replacement) |
| 71 | return { status: 405, headers: {}, legacy_grant: replacement } |
| 72 | } |
| 73 | if (this.failWrite && frame.method === 'tools/call') throw new Error('fake unknown partial HTTP write') |
| 74 | if (this.status !== undefined && frame.method !== 'initialize') return { status: this.status, headers: {} } |
| 75 | if (!Object.hasOwn(frame, 'id')) return { status: 202, headers: {} } |
| 76 | assert.equal(typeof frame.id, 'string', 'real numeric SDK IDs must not reach the peer') |
| 77 | const result = this.customResult?.(frame.method) ?? (frame.method === 'server/discover' ? { resultType: 'complete', ttlMs: 0, cacheScope: 'private', supportedVersions: ['2026-07-28'], capabilities: { tools: {} } } : frame.method === 'initialize' ? { protocolVersion: '2025-06-18', capabilities: { tools: {}, resources: {}, prompts: {} }, serverInfo: { name: 'fetch-fixture', version: '1' } } |
| 78 | : frame.method === 'tools/list' ? { ...(this.modern ? { ttlMs: 0, cacheScope: 'private' } : {}), tools: [{ name: 'echo', inputSchema: { type: 'object' } }], nextCursor: 'next-page' } |
| 79 | : { content: [{ type: 'text', text: 'ok' }] }) |
| 80 | const response = JSON.stringify({ jsonrpc: '2.0', id: frame.id, result: this.modern ? { resultType: 'complete', ...result } : result }) |
| 81 | if (this.legacy) { |
| 82 | if (!this.silent) this.append(this.stream, `event: message\ndata: ${response}\n\n`) |
| 83 | return { status: 202, headers: {} } |
| 84 | } |
| 85 | const headers = { 'content-type': this.ssePost ? 'text/event-stream' : 'application/json', ...(frame.method === 'initialize' ? { 'mcp-session-id': 'rust-observed-session' } : {}) } |
| 86 | return { status: 200, headers, response_id: this.body(this.silent ? '' : this.ssePost ? `event: message\ndata: ${response}\n\n` : response, this.silent) } |
| 87 | } |
| 88 | } |
| 89 | async function fixture(legacy = false, ssePost = false, modern = false) { |
| 90 | const broker = new FakeFetchProxy(legacy, ssePost), module = createMcpModule(broker, owner) |
| 91 | broker.modern = modern |
| 92 | const open = { owner, session_id: broker.session, transport: legacy ? 'sse' : 'http', launch_ticket: 'launch-once', initialize_grant: broker.grant('initialize', initParams), initialized_grant: broker.grant('notifications/initialized', {}), client_version: '0.10.1', deadline_ms: 1000 } |
| 93 | if (modern) open.discover_grant = broker.grant('server/discover', {}) |
| 94 | const signal = new AbortController().signal |
| 95 | await module.open(open, signal); return { broker, module, open, signal } |
| 96 | } |
| 97 | for (const [name, legacy, ssePost, modern] of [['modern HTTP JSON', false, false, true], ['HTTP SSE response', false, true, false], ['legacy SSE', true, false, false]]) { |
| 98 | test(`official ${name} transport uses opaque FetchProxy and one exact per-page Rust wire ID`, async () => { |
| 99 | const f = await fixture(legacy, ssePost, modern) |
| 100 | try { |
| 101 | const grant = f.broker.grant('tools/list', { cursor: 'one-page' }) |
| 102 | const result = await f.module.request({ owner, session_id: f.open.session_id, grant, deadline_ms: 1000 }, f.signal) |
| 103 | assert.equal(result.nextCursor, 'next-page') |
| 104 | assert.equal(f.broker.frames.filter(frame => frame.method === 'tools/list').length, 1) |
| 105 | assert.equal(f.broker.frames.find(frame => frame.method === 'tools/list').id, grant.wire_id) |
| 106 | assert.ok(f.broker.frames.filter(frame => Object.hasOwn(frame, 'id')).every(frame => typeof frame.id === 'string')) |
| 107 | if (!legacy && !modern) assert.equal(f.broker.fetches.find(params => params.frame?.method === 'tools/list').headers.mcp_session_id, 'rust-observed-session') |
| 108 | if (modern) { |
| 109 | assert.equal(f.broker.frames.some(frame => frame.method === 'initialize'), false) |
| 110 | await f.module.request({ owner, session_id: f.open.session_id, grant: f.broker.grant('tools/call', { name: 'echo', arguments: {} }), deadline_ms: 1000 }, f.signal) |
| 111 | for (const request of f.broker.fetches.filter(p => p.frame)) { |
| 112 | assert.deepEqual(request.frame.params._meta, metadata) |
| 113 | assert.equal(request.headers.mcp_protocol_version, '2026-07-28') |
| 114 | assert.equal(request.headers.mcp_method, request.frame.method) |
| 115 | assert.equal(request.headers.mcp_name, request.frame.method === 'tools/call' ? 'echo' : undefined) |
| 116 | assert.equal(request.headers.mcp_session_id, undefined) |
| 117 | } |
| 118 | } |
| 119 | } finally { await f.module.dispose() } |
| 120 | assert.equal(f.broker.closed, true) |
| 121 | }) |
| 122 | } |
| 123 | |
| 124 | test('HTTP decoded grant mismatch fails before a FetchProxy write and closes the session', async () => { |
| 125 | const f = await fixture() |
| 126 | const grant = f.broker.grant('tools/call', { name: 'echo', arguments: {} }) |
| 127 | grant.params.arguments = { forged: true } |
| 128 | await assert.rejects(f.module.request({ owner, session_id: f.open.session_id, grant, deadline_ms: 1000 }, f.signal), /exact|Connection closed/) |
| 129 | assert.equal(f.broker.frames.some(frame => frame.method === 'tools/call'), false) |
| 130 | assert.equal(f.broker.closed, true); await f.module.dispose() |
| 131 | }) |
| 132 | test('unknown partial HTTP write retires once and never replays', async () => { |
| 133 | const f = await fixture(); f.broker.failWrite = true |
| 134 | await assert.rejects(f.module.request({ owner, session_id: f.open.session_id, grant: f.broker.grant('tools/call', { name: 'echo', arguments: {} }), deadline_ms: 1000 }, f.signal), /partial HTTP write|Connection closed/) |
| 135 | assert.equal(f.broker.frames.filter(frame => frame.method === 'tools/call').length, 1) |
| 136 | assert.equal(f.broker.closed, true); await f.module.dispose() |
| 137 | }) |
| 138 | test('401 cannot make SDK fetch replay a consumed operation', async () => { |
| 139 | const f = await fixture(); f.broker.status = 401 |
| 140 | await assert.rejects(f.module.request({ owner, session_id: f.open.session_id, grant: f.broker.grant('tools/list', {}), deadline_ms: 1000 }, f.signal)) |
| 141 | assert.equal(f.broker.frames.filter(frame => frame.method === 'tools/list').length, 1) |
| 142 | assert.equal(f.broker.closed, true); await f.module.dispose() |
| 143 | }) |
| 144 | test('plugin tier cannot redeem any FetchProxy frame', () => { |
| 145 | const rows = [['net/start', { ticket: 't' }], ['net/fetch', { url: 'https://mcp-proxy.invalid/s', method: 'GET', headers: {} }], ['net/read', { response_id: 'r' }], ['net/release', { response_id: 'r' }], ['net/close', {}]] |
| 146 | for (const [method, rest] of rows) { |
| 147 | const frame = { jsonrpc: '2.0', id: 1, method, params: { owner, session_id: 's', ...rest } } |
| 148 | assert.throws(() => validateMessage(frame, 'host_to_core', 'plugin'), /not allowed/) |
| 149 | validateMessage(frame, 'host_to_core', 'builtin') |
| 150 | } |
| 151 | }) |
| 152 | test('cancelled HTTP body releases its response and refuses queued work', async () => { |
| 153 | const f = await fixture(); f.broker.silent = true |
| 154 | const first = f.module.request({ owner, session_id: f.open.session_id, grant: f.broker.grant('tools/list', {}), deadline_ms: 20 }, f.signal) |
| 155 | const queued = f.module.request({ owner, session_id: f.open.session_id, grant: f.broker.grant('prompts/list', {}), deadline_ms: 1000 }, f.signal) |
| 156 | const firstResult = assert.rejects(first, /timed out|closed|cancelled/) |
| 157 | const queuedResult = assert.rejects(queued, /closed|cancelled|stale/) |
| 158 | await firstResult; await queuedResult |
| 159 | assert.equal(f.broker.frames.filter(frame => frame.method === 'tools/list').length, 1) |
| 160 | assert.equal(f.broker.frames.some(frame => frame.method === 'prompts/list'), false) |
| 161 | assert.equal(f.broker.closed, true); assert.equal(f.broker.bodies.size, 0) |
| 162 | await f.module.dispose() |
| 163 | }) |
| 164 | |
| 165 | // Actual official Streamable HTTP -> SSE transport change; the FetchProxy |
| 166 | // simulates one explicit Rust refusal and a fresh exact single-use grant. |
| 167 | async function negotiatedFixture(options = {}) { |
| 168 | const broker = new FakeFetchProxy(), module = createMcpModule(broker, owner) |
| 169 | Object.assign(broker, { negotiate: true }, options) |
| 170 | const open = { owner, session_id: broker.session, transport: 'http', launch_ticket: 'launch-once', initialize_grant: broker.grant('initialize', initParams), initialized_grant: broker.grant('notifications/initialized', {}), client_version: '0.10.1', deadline_ms: 100 } |
| 171 | return { broker, module, open } |
| 172 | } |
| 173 | test('official SDK negotiates legacy SSE only with a fresh exact Rust grant and original wire ID', async () => { |
| 174 | const f = await negotiatedFixture() |
| 175 | try { |
| 176 | await f.module.open(f.open, new AbortController().signal) |
| 177 | const attempts = f.broker.fetches.filter(p => p.frame?.method === 'initialize') |
| 178 | assert.equal(attempts.length, 2) |
| 179 | assert.equal(attempts[0].frame.id, f.open.initialize_grant.wire_id) |
| 180 | assert.deepEqual(attempts[0].frame, attempts[1].frame) |
| 181 | assert.notEqual(attempts[0].ticket, attempts[1].ticket) |
| 182 | assert.equal(attempts[0].operation_id, attempts[1].operation_id) |
| 183 | assert.equal(new URL(attempts[1].url).pathname.endsWith('/endpoint'), true) |
| 184 | assert.equal(f.broker.frames.filter(p => p.method === 'notifications/initialized').length, 1) |
| 185 | } finally { await f.module.dispose() } |
| 186 | }) |
| 187 | test('changed negotiation params refuse before SDK opens legacy channel or rewrites a request', async () => { |
| 188 | const f = await negotiatedFixture({ mutateNegotiation: true }) |
| 189 | await assert.rejects(f.module.open(f.open, new AbortController().signal), /mismatch|closed/) |
| 190 | assert.equal(f.broker.fetches.some(p => p.method === 'GET'), false) |
| 191 | assert.equal(f.broker.frames.filter(p => p.method === 'initialize').length, 1) |
| 192 | assert.equal(f.broker.closed, true); await f.module.dispose() |
| 193 | }) |
| 194 | test('cancellation during negotiated endpoint discovery releases body without replaying the admitted request', async () => { |
| 195 | const f = await negotiatedFixture({ holdEndpoint: true }) |
| 196 | await assert.rejects(f.module.open(f.open, new AbortController().signal), /closed|cancelled/) |
| 197 | assert.equal(f.broker.frames.filter(p => p.method === 'initialize').length, 1) |
| 198 | assert.equal(f.broker.closed, true); assert.equal(f.broker.bodies.size, 0) |
| 199 | await f.module.dispose() |
| 200 | }) |
| 201 | |
| 202 | test('correlated malformed catalog reply preserves SDK session for Rust per-item admission and the next page', async () => { |
| 203 | const f = await fixture() |
| 204 | f.broker.customResult = method => method === 'tools/list' ? { tools: [{ description: 'missing name', inputSchema: { type: 'object' } }, { name: 'valid', inputSchema: { type: 'object' } }], nextCursor: 'next' } : undefined |
| 205 | await assert.rejects(f.module.request({ owner, session_id: f.open.session_id, grant: f.broker.grant('tools/list', {}), deadline_ms: 1000 }, f.signal)) |
| 206 | assert.equal(f.broker.closed, false, 'the exact correlated reply is available to Rust; schema refusal is not an unknown write') |
| 207 | f.broker.customResult = undefined |
| 208 | const result = await f.module.request({ owner, session_id: f.open.session_id, grant: f.broker.grant('tools/list', { cursor: 'next' }), deadline_ms: 1000 }, f.signal) |
| 209 | assert.equal(result.nextCursor, 'next-page') |
| 210 | assert.equal(f.broker.frames.filter(p => p.method === 'tools/list').length, 2) |
| 211 | await f.module.dispose() |
| 212 | }) |
| 213 |