返回 CodeWhale
mcp.ts
1 /** Tier-0 SDK protocol owner. Rust owns launch, every operation grant,
2 * pipes, catalog admission, keys, credentials, cancellation and teardown. */
3 import { Client, SSEClientTransport, StreamableHTTPClientTransport, parseJSONRPCMessage, type JSONRPCMessage, type RequestMethod, type Transport } from '@modelcontextprotocol/client'
4 import type { OwnerRef } from '../protocol.generated.ts'
5
6 export interface BrokerRpc {
7 request<T>(method: string, params: unknown, signal?: AbortSignal): Promise<T>
8 }
9 export interface OperationGrant {
10 ticket: string
11 operation_id: string
12 method: string
13 wire_id?: string
14 params: Record<string, unknown>
15 }
16 export interface OpenParams {
17 owner: OwnerRef
18 session_id: string
19 launch_ticket: string
20 transport?: 'stdio' | 'http' | 'sse'
21 discover_grant?: OperationGrant
22 initialize_grant: OperationGrant
23 initialized_grant: OperationGrant
24 client_version: string
25 deadline_ms: number
26 }
27 export interface RequestParams {
28 owner: OwnerRef
29 session_id: string
30 grant: OperationGrant
31 deadline_ms: number
32 }
33 const MAX_FRAME_BYTES = 16 * 1024 * 1024
34 const MAX_SESSIONS = 64
35 const MAX_PENDING = 256
36 const MAX_DEPTH = 128
37 function requestMethod(value: string): RequestMethod {
38 switch (value) {
39 case 'tools/list': case 'resources/list': case 'resources/templates/list': case 'prompts/list':
40 case 'tools/call': case 'resources/read': case 'prompts/get': return value
41 default: throw new Error('MCP request method is unavailable')
42 }
43 }
44 const EXTENSION_METHODS = new Set(['skills/list', 'skills/get'])
45 const brokerValidated = { '~standard': { version: 1, vendor: 'codewhale', validate: (value: unknown) => ({ value }) } } as const
46 const SUPPORTED = ['2026-07-28', '2025-06-18', '2025-11-25', '2025-03-26', '2024-11-05']
47 function identity(owner: OwnerRef): string {
48 return JSON.stringify([owner.plugin_id, owner.generation, owner.owner_token])
49 }
50 function jsonEqual(a: unknown, b: unknown, depth = 0): boolean {
51 if (depth > MAX_DEPTH) throw new Error('MCP operation nesting exceeds the bound')
52 if (a === b) return true
53 if (typeof a !== typeof b || a === null || b === null) return false
54 if (Array.isArray(a) || Array.isArray(b)) {
55 return Array.isArray(a) && Array.isArray(b) && a.length === b.length && a.every((value, i) => jsonEqual(value, b[i], depth + 1))
56 }
57 if (typeof a !== 'object') return false
58 const first = Object.keys(a as object), second = Object.keys(b as object)
59 if (first.length !== second.length) return false
60 return first.every(key => Object.hasOwn(b as object, key) && jsonEqual((a as Record<string, unknown>)[key], (b as Record<string, unknown>)[key], depth + 1))
61 }
62 function frameSize(value: unknown): number {
63 return Buffer.byteLength(JSON.stringify(value), 'utf8')
64 }
65 function deadline(value: number): number {
66 if (!Number.isSafeInteger(value) || value < 1 || value > 24 * 60 * 60 * 1000) throw new Error('invalid MCP request deadline')
67 return value
68 }
69
70 interface AdmittedFrame { frame: JSONRPCMessage; ticket?: string; operation_id?: string }
71 /** Real SDK IDs stay internal. Rust-issued string IDs and exact grants reach peers. */
72 class OperationFrames {
73 private readonly grants = new Map<string, OperationGrant>()
74 private readonly pending = new Map<string, { operation: string; wire: string; sdk: string | number }>()
75 private readonly wireToSdk = new Map<string, string>()
76 private readonly replied = new Set<string>()
77 grant(value: OperationGrant): void {
78 if (this.grants.size >= MAX_PENDING || this.grants.has(value.method)) throw new Error('MCP grant slot unavailable')
79 if (value.wire_id !== undefined && (!value.wire_id || value.wire_id.length > 256)) throw new Error('invalid Rust wire ID')
80 this.grants.set(value.method, structuredClone(value))
81 }
82 incoming(value: unknown): JSONRPCMessage {
83 const frame = parseJSONRPCMessage(value)
84 if ('id' in frame && !('method' in frame)) {
85 const sdkKey = this.wireToSdk.get(JSON.stringify(frame.id))
86 if (sdkKey === undefined) throw new Error('MCP reply has no admitted wire ID')
87 const binding = this.pending.get(sdkKey)!
88 this.pending.delete(sdkKey); this.wireToSdk.delete(JSON.stringify(frame.id))
89 if (this.replied.size >= MAX_PENDING) throw new Error('MCP completed exchange bound exceeded')
90 this.replied.add(binding.operation)
91 frame.id = binding.sdk
92 }
93 return frame
94 }
95 outgoing(value: JSONRPCMessage): AdmittedFrame {
96 const frame = structuredClone(value)
97 if (!('method' in frame)) {
98 const refusal = 'error' in frame && frame.error.code === -32601
99 const ping = 'result' in frame && Object.keys(frame.result).length === 0
100 if (!refusal && !ping) throw new Error('MCP server request requires Rust authority')
101 return { frame }
102 }
103 if (frame.method === 'notifications/cancelled') {
104 const params = frame.params as Record<string, unknown> | undefined
105 const binding = this.pending.get(JSON.stringify(params?.requestId))
106 if (!binding || !params) throw new Error('MCP cancellation has no admitted request')
107 params.requestId = binding.wire
108 return { frame, operation_id: binding.operation }
109 }
110 const grant = this.grants.get(frame.method)
111 if (!grant || !jsonEqual(frame.params ?? {}, grant.params)) throw new Error('MCP frame has no exact operation grant')
112 if ('id' in frame) {
113 if (grant.wire_id === undefined || this.pending.size >= MAX_PENDING || this.wireToSdk.has(JSON.stringify(grant.wire_id))) throw new Error('MCP wire ID is not admitted')
114 const sdk = frame.id, key = JSON.stringify(sdk)
115 if (this.pending.has(key)) throw new Error('duplicate SDK request ID')
116 this.pending.set(key, { operation: grant.operation_id, wire: grant.wire_id, sdk })
117 this.wireToSdk.set(JSON.stringify(grant.wire_id), key)
118 frame.id = grant.wire_id
119 } else if (grant.wire_id !== undefined) throw new Error('notification cannot redeem a request grant')
120 this.grants.delete(frame.method)
121 return { frame, ticket: grant.ticket, operation_id: grant.operation_id }
122 }
123 takeReply(operation: string): boolean { const found = this.replied.has(operation); this.replied.delete(operation); return found }
124 clear(): void { this.grants.clear(); this.pending.clear(); this.wireToSdk.clear(); this.replied.clear() }
125 }
126 interface GrantedTransport extends Transport { grant(value: OperationGrant): void; takeReply(operation: string): boolean }
127 class BrokerTransport implements GrantedTransport {
128 onclose?: () => void
129 onerror?: (error: Error) => void
130 onmessage?: Transport['onmessage']
131 private readonly stop = new AbortController()
132 private readonly frames = new OperationFrames()
133 private started = false
134 private closed = false
135 constructor(private readonly rpc: BrokerRpc, private readonly owner: OwnerRef, private readonly session: string, private readonly launch: string) {}
136 takeReply(operation: string): boolean { return this.frames.takeReply(operation) }
137 grant(value: OperationGrant): void { if (this.closed) throw new Error('MCP transport closed'); this.frames.grant(value) }
138 async start(): Promise<void> {
139 if (this.started || this.closed) throw new Error('MCP transport already started or closed')
140 this.started = true
141 await this.rpc.request('proc/launch', { owner: this.owner, session_id: this.session, ticket: this.launch }, this.stop.signal)
142 void this.readLoop().catch(async error => { if (!this.closed) this.onerror?.(error); await this.close().catch(() => undefined) })
143 }
144 private async readLoop(): Promise<void> {
145 while (!this.closed) {
146 const result = await this.rpc.request<{ frame?: unknown; closed?: boolean }>('proc/read', { owner: this.owner, session_id: this.session }, this.stop.signal)
147 if (result.closed) { this.finish(); return }
148 if (result.frame === undefined || frameSize(result.frame) > MAX_FRAME_BYTES) throw new Error('MCP broker frame exceeds the bound')
149 this.onmessage?.(this.frames.incoming(result.frame))
150 }
151 }
152 async send(message: JSONRPCMessage): Promise<void> {
153 if (this.closed || !this.started || frameSize(message) > MAX_FRAME_BYTES) throw new Error('MCP broker write unavailable')
154 const { frame, ticket, operation_id } = this.frames.outgoing(message)
155 try {
156 await this.rpc.request('proc/write', { owner: this.owner, session_id: this.session, frame, ...(ticket === undefined ? {} : { ticket }), ...(operation_id === undefined ? {} : { operation_id }) }, this.stop.signal)
157 } catch (error) { await this.close().catch(() => undefined); throw error }
158 }
159 private finish(): void { if (this.closed) return; this.closed = true; this.stop.abort(); this.frames.clear(); this.onclose?.() }
160 async close(): Promise<void> { if (this.closed) return; this.finish(); await this.rpc.request('proc/close', { owner: this.owner, session_id: this.session }) }
161 }
162 /** Official HTTP/SSE framing with an opaque Rust-authorized FetchProxy. */
163 class HttpBrokerTransport implements GrantedTransport {
164 onclose?: () => void
165 onerror?: (error: Error) => void
166 onmessage?: Transport['onmessage']
167 private readonly stop = new AbortController()
168 private readonly frames = new OperationFrames()
169 private readonly writes = new Map<string, AdmittedFrame>()
170 private inner: SSEClientTransport | StreamableHTTPClientTransport
171 private negotiation?: OperationGrant
172 private legacyHandshake = false
173 private legacy: boolean
174 private started = false
175 private closed = false
176 constructor(private readonly rpc: BrokerRpc, private readonly owner: OwnerRef, private readonly session: string, private readonly launch: string, legacy: boolean) {
177 this.legacy = legacy
178 this.inner = this.createInner(legacy)
179 }
180 private createInner(legacy: boolean): SSEClientTransport | StreamableHTTPClientTransport {
181 const url = new URL(`https://mcp-proxy.invalid/${this.session}`)
182 const fetcher = this.fetch.bind(this)
183 const inner = legacy ? new SSEClientTransport(url, { fetch: fetcher }) : new StreamableHTTPClientTransport(url, { fetch: fetcher, onInsufficientScope: 'throw', reconnectionOptions: { maxRetries: 0, initialReconnectionDelay: 0, maxReconnectionDelay: 0, reconnectionDelayGrowFactor: 1 } })
184 inner.onmessage = value => { try { this.onmessage?.(this.frames.incoming(value)) } catch (error) { this.fail(error) } }
185 inner.onclose = () => { if (!this.closed) this.fail(new Error('MCP HTTP channel closed')) }
186 inner.onerror = error => { if (!this.negotiation && !this.legacyHandshake) this.fail(error) }
187 return inner
188 }
189 private fail(error: unknown): void { if (!this.closed) this.onerror?.(error instanceof Error ? error : new Error('MCP HTTP failed')); void this.close().catch(() => undefined) }
190 takeReply(operation: string): boolean { return this.frames.takeReply(operation) }
191 grant(value: OperationGrant): void { if (this.closed) throw new Error('MCP transport closed'); this.frames.grant(value) }
192 async start(): Promise<void> {
193 if (this.started || this.closed) throw new Error('MCP HTTP already started or closed')
194 this.started = true
195 await this.rpc.request('net/start', { owner: this.owner, session_id: this.session, ticket: this.launch }, this.stop.signal)
196 await this.inner.start()
197 }
198 setProtocolVersion(version: string): void { this.inner.setProtocolVersion(version) }
199 async send(message: JSONRPCMessage, options?: Parameters<StreamableHTTPClientTransport['send']>[1]): Promise<void> {
200 if (!this.started || this.closed || frameSize(message) > MAX_FRAME_BYTES) throw new Error('MCP HTTP write unavailable')
201 const admitted = this.frames.outgoing(message), key = JSON.stringify(admitted.frame)
202 if (this.writes.size >= MAX_PENDING || this.writes.has(key)) throw new Error('MCP HTTP write slot unavailable')
203 this.writes.set(key, admitted)
204 try {
205 try { if (this.inner instanceof SSEClientTransport) await this.inner.send(admitted.frame); else await this.inner.send(admitted.frame, options) }
206 catch (error) {
207 const replacement = this.negotiation
208 if (!replacement || this.legacy || this.closed || this.stop.signal.aborted) throw error
209 this.negotiation = undefined
210 const original = admitted.frame
211 if (!('method' in original) || original.method !== 'initialize' || replacement.method !== original.method || replacement.operation_id !== admitted.operation_id
212 || replacement.wire_id !== ('id' in original ? original.id : undefined) || !jsonEqual(replacement.params, original.params ?? {})) throw new Error('MCP negotiation grant mismatch')
213 // Only Rust's explicit refusal issued this fresh, single-use grant.
214 // The original numeric SDK request remains pending; peer IDs stay exact.
215 this.inner.onclose = undefined; this.inner.onerror = undefined; this.inner.onmessage = undefined
216 await this.inner.close()
217 this.legacy = true
218 this.inner = this.createInner(true)
219 await this.inner.start()
220 this.writes.set(key, { frame: original, ticket: replacement.ticket, operation_id: replacement.operation_id })
221 await this.inner.send(original)
222 }
223 } catch (error) { if (!this.legacyHandshake) await this.close().catch(() => undefined); this.legacyHandshake = false; throw error }
224 finally { this.writes.delete(key) }
225 }
226 private async fetch(input: string | URL | Request, init?: RequestInit): Promise<Response> {
227 if (this.closed || this.stop.signal.aborted) throw new Error('MCP HTTP session closed')
228 const url = input instanceof Request ? input.url : String(input)
229 const method = init?.method ?? 'GET'
230 const signal = init?.signal ? AbortSignal.any([this.stop.signal, init.signal]) : this.stop.signal
231 let admitted: AdmittedFrame | undefined
232 if (method === 'POST') {
233 if (typeof init?.body !== 'string' || Buffer.byteLength(init.body) > MAX_FRAME_BYTES) throw new Error('MCP HTTP body unavailable')
234 admitted = this.writes.get(JSON.stringify(JSON.parse(init.body)))
235 if (!admitted) throw new Error('MCP HTTP body has no exact admitted frame')
236 this.writes.delete(JSON.stringify(admitted.frame)) // one fetch, no SDK replay
237 }
238 const headers: Record<string, string> = {}
239 for (const [name, value] of new Headers(init?.headers)) {
240 if (!['accept', 'content-type', 'mcp-session-id', 'mcp-protocol-version', 'mcp-method', 'mcp-name'].includes(name) || value.length > 8192) throw new Error('MCP framing header unavailable')
241 headers[name.replaceAll('-', '_')] = value
242 }
243 const reply = await this.rpc.request<{ response_id?: string; status: number; headers: Record<string, string>; legacy_grant?: OperationGrant; legacy_handshake?: boolean }>('net/fetch', { owner: this.owner, session_id: this.session, url, method, headers, ...(admitted ?? {}) }, signal)
244 if (reply.legacy_handshake === true) {
245 if (!admitted || !('method' in admitted.frame) || admitted.frame.method !== 'server/discover'
246 || reply.response_id !== undefined || ![400, 404, 405, 406, 415].includes(reply.status)) throw new Error('MCP handshake refusal unavailable')
247 this.legacyHandshake = true
248 }
249 if (reply.legacy_grant !== undefined) {
250 if (!admitted || this.legacy || this.negotiation || reply.response_id !== undefined
251 || ![400, 404, 405, 406, 415, 501].includes(reply.status)
252 || typeof reply.legacy_grant.ticket !== 'string' || !reply.legacy_grant.ticket) throw new Error('MCP negotiation unavailable')
253 this.negotiation = reply.legacy_grant
254 throw new Error('Rust admitted legacy MCP negotiation')
255 }
256 if (reply.response_id === undefined) return new Response(null, { status: reply.status, headers: reply.headers })
257 const response_id = reply.response_id
258 let done = false
259 const cancel = async () => { if (done) return; done = true; await this.rpc.request('net/release', { owner: this.owner, session_id: this.session, response_id }).catch(() => undefined) }
260 const body = new ReadableStream<Uint8Array>({
261 pull: async controller => { try {
262 if (signal.aborted) throw new Error('MCP HTTP body cancelled')
263 const next = await this.rpc.request<{ data: number[]; done: boolean }>('net/read', { owner: this.owner, session_id: this.session, response_id }, signal)
264 if (!Array.isArray(next.data) || next.data.length > 32768 || next.data.some(b => !Number.isInteger(b) || b < 0 || b > 255)) throw new Error('MCP HTTP chunk exceeds bound')
265 if (next.data.length) controller.enqueue(Uint8Array.from(next.data))
266 if (next.done) { await cancel(); controller.close() }
267 } catch (error) { await cancel(); controller.error(error); this.fail(error) } },
268 cancel,
269 }, { highWaterMark: 0 })
270 signal.addEventListener('abort', () => { void cancel() }, { once: true })
271 return new Response(body, { status: reply.status, headers: reply.headers })
272 }
273 async close(): Promise<void> {
274 if (this.closed) return
275 this.closed = true; this.stop.abort(); this.frames.clear(); this.writes.clear()
276 await this.inner.close().catch(() => undefined)
277 await this.rpc.request('net/close', { owner: this.owner, session_id: this.session }).catch(() => undefined)
278 this.onclose?.()
279 }
280 }
281 interface Session {
282 client: Client
283 transport: GrantedTransport
284 tail: Promise<unknown>
285 }
286 export class McpModule {
287 private readonly sessions = new Map<string, Session>()
288 private disposed = false
289 constructor(private readonly rpc: BrokerRpc, private readonly owner: OwnerRef) {}
290 private check(owner: OwnerRef): void {
291 if (this.disposed || identity(owner) !== identity(this.owner)) throw new Error('MCP builtin owner is no longer live')
292 }
293 async open(params: OpenParams, signal: AbortSignal): Promise<unknown> {
294 this.check(params.owner)
295 const timeout = deadline(params.deadline_ms)
296 if (params.transport !== undefined && !['stdio', 'http', 'sse'].includes(params.transport)) throw new Error('MCP transport selector unavailable')
297 if (this.sessions.size >= MAX_SESSIONS || this.sessions.has(params.session_id)) throw new Error('MCP session slot unavailable')
298 const transport: GrantedTransport = params.transport === undefined || params.transport === 'stdio'
299 ? new BrokerTransport(this.rpc, this.owner, params.session_id, params.launch_ticket)
300 : new HttpBrokerTransport(this.rpc, this.owner, params.session_id, params.launch_ticket, params.transport === 'sse')
301 const client = new Client({ name: 'codewhale-tui', version: params.client_version }, { capabilities: {}, supportedProtocolVersions: SUPPORTED, versionNegotiation: { mode: params.discover_grant === undefined ? 'legacy' : 'auto', probe: { timeoutMs: timeout, maxRetries: 0 } }, inputRequired: { autoFulfill: false }, listMaxPages: 64 })
302 const session: Session = { client, transport, tail: Promise.resolve() }
303 this.sessions.set(params.session_id, session)
304 if (params.discover_grant !== undefined) transport.grant(params.discover_grant)
305 transport.grant(params.initialize_grant)
306 transport.grant(params.initialized_grant)
307 const abort = () => { void transport.close().catch(() => undefined) }
308 signal.addEventListener('abort', abort, { once: true })
309 const timer = setTimeout(abort, timeout)
310 timer.unref()
311 try {
312 if (signal.aborted) throw new Error('MCP open cancelled')
313 await client.connect(transport, { signal, timeout })
314 if (params.discover_grant !== undefined) transport.takeReply(params.discover_grant.operation_id)
315 transport.takeReply(params.initialize_grant.operation_id)
316 this.check(params.owner)
317 return { protocolVersion: client.getNegotiatedProtocolVersion(), serverInfo: client.getServerVersion(), capabilities: client.getServerCapabilities(), instructions: client.getInstructions() }
318 } catch (error) {
319 this.sessions.delete(params.session_id)
320 await transport.close().catch(() => undefined)
321 throw error
322 } finally { clearTimeout(timer); signal.removeEventListener('abort', abort) }
323 }
324 async request(params: RequestParams, signal: AbortSignal): Promise<unknown> {
325 this.check(params.owner)
326 const timeout = deadline(params.deadline_ms)
327 const extension = EXTENSION_METHODS.has(params.grant.method)
328 const method = extension ? params.grant.method : requestMethod(params.grant.method)
329 const session = this.sessions.get(params.session_id)
330 if (!session) throw new Error('MCP session is no longer live')
331 const run = session.tail.then(async () => {
332 this.check(params.owner)
333 if (this.sessions.get(params.session_id) !== session || signal.aborted) throw new Error('MCP operation cancelled or stale')
334 session.transport.grant(params.grant)
335 // Generic request preserves per-page cursors. listTools/listResources /
336 // listPrompts convenience methods would auto-aggregate into an SDK cache.
337 try {
338 const options = { signal, timeout, resetTimeoutOnProgress: false, allowInputRequired: true }
339 return extension
340 ? await session.client.request({ method, params: params.grant.params }, brokerValidated, options)
341 : await session.client.request({ method: method as RequestMethod, params: params.grant.params }, options)
342 } catch (error) {
343 // A correlated reply completed the exchange, even if the SDK's
344 // stricter result schema rejected a legacy malformed catalog item.
345 // Rust receives the original bytes and applies its shared admission.
346 // Every failure without that receipt retires before queued work runs.
347 if (!session.transport.takeReply(params.grant.operation_id)) {
348 this.sessions.delete(params.session_id)
349 await session.transport.close().catch(() => undefined)
350 }
351 throw error
352 } finally { session.transport.takeReply(params.grant.operation_id) }
353 })
354 session.tail = run.catch(() => undefined)
355 return run
356 }
357 async close(owner: OwnerRef, sessionId: string): Promise<void> {
358 this.check(owner)
359 const session = this.sessions.get(sessionId)
360 this.sessions.delete(sessionId)
361 await session?.client.close()
362 }
363 async dispose(): Promise<void> {
364 if (this.disposed) return
365 this.disposed = true
366 const sessions = [...this.sessions.values()]
367 this.sessions.clear()
368 await Promise.allSettled(sessions.map(session => session.client.close()))
369 }
370 }
371 export function createMcpModule(rpc: BrokerRpc, owner: OwnerRef): McpModule {
372 if (owner.plugin_id !== 'host:mcp') throw new Error('MCP protocol owner must be the pinned builtin')
373 return new McpModule(rpc, Object.freeze(structuredClone(owner)))
374 }
375
375 lines TYPESCRIPT