import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"; import { CallToolRequestSchema, type CallToolResult, ListToolsRequestSchema, } from "@modelcontextprotocol/sdk/types.js"; import { dbg } from "./debug.js"; import type { KlausTool } from "./protocol.js"; interface PermissionCall { id: string; name: string; input: Record; } interface PendingCall extends PermissionCall { resolve(result: CallToolResult): void; reject(error: Error): void; } export interface PiToolResult { id: string; content: Array< | { type: "text"; text: string } | { type: "image"; data: string; mimeType: string } >; isError: boolean; } export const TOOL_ID_FIELD = "__klausToolUseID"; const originalName = (name: string): string => name.startsWith("mcp__klaus__") ? name.slice("mcp__klaus__".length) : name; function canonical(value: unknown): string { if (Array.isArray(value)) return `[${value.map(canonical).join(",")}]`; if (typeof value === "object" && value !== null) { return `{${Object.entries(value) .sort(([left], [right]) => left.localeCompare(right)) .map(([key, item]) => `${JSON.stringify(key)}:${canonical(item)}`) .join(",")}}`; } return JSON.stringify(value) ?? "undefined"; } const sameInput = ( left: Record, right: Record, ): boolean => canonical(left) === canonical(right); export class ToolBridge { readonly server: McpServer; readonly pending = new Map(); private readonly settled = new Set(); private permissions: PermissionCall[] = []; private tools = new Map(); private closed = false; private waiters: Array<() => void> = []; constructor( tools: KlausTool[], private readonly onActivity: () => void = () => undefined, ) { dbg?.("bridge.create", { toolNames: tools.map((tool) => tool.name) }); this.tools = new Map(tools.map((tool) => [tool.name, tool])); this.server = new McpServer( { name: "klaus", version: "1" }, { capabilities: { tools: {} } }, ); this.server.server.setRequestHandler(ListToolsRequestSchema, async () => { dbg?.("bridge.listTools", { toolNames: this.toolNames() }); this.onActivity(); return { tools: [...this.tools.values()].map((tool) => ({ name: tool.name, description: tool.description, inputSchema: tool.inputSchema, })), }; }); this.server.server.setRequestHandler( CallToolRequestSchema, async (request) => { dbg?.("bridge.callTool.start", { name: request.params.name, argumentKeys: Object.keys(request.params.arguments ?? {}), closed: this.closed, }); this.onActivity(); if (this.closed) return this.errorResult("Klaus query is closed."); const name = originalName(request.params.name); if (!this.tools.has(name)) return this.errorResult(`Tool ${name} is no longer active.`); const input = { ...(request.params.arguments ?? {}) }; const embeddedId = input[TOOL_ID_FIELD]; delete input[TOOL_ID_FIELD]; const permissionIndex = this.permissions.findIndex((call) => typeof embeddedId === "string" ? call.id === embeddedId && call.name === name : call.name === name && sameInput(call.input, input), ); const permission = permissionIndex < 0 ? undefined : this.permissions.splice(permissionIndex, 1)[0]; if (!permission) { return this.errorResult(`No Klaus tool identity for ${name}.`); } if (this.pending.has(permission.id)) { return this.errorResult( `Duplicate Klaus tool call ${permission.id}.`, ); } dbg?.("bridge.callTool.park", { id: permission.id, name: permission.name, }); return await new Promise((resolve, reject) => { const pending: PendingCall = { ...permission, resolve, reject }; this.pending.set(permission.id, pending); for (const notify of this.waiters.splice(0)) notify(); }); }, ); } allow(name: string, input: Record, id: string): void { dbg?.("bridge.allow", { name, id, inputKeys: Object.keys(input), }); this.onActivity(); this.permissions.push({ id, name: originalName(name), input }); } toolNames(): string[] { const names = [...this.tools.keys()]; dbg?.("bridge.toolNames", { names }); return names; } hasSchemaChange(tools: KlausTool[]): boolean { const changed = JSON.stringify([...this.tools.values()]) !== JSON.stringify(tools); dbg?.("bridge.hasSchemaChange", { changed }); return changed; } pendingIds(): string[] { const ids = [...this.pending.keys()]; dbg?.("bridge.pendingIds", { ids }); return ids; } async waitForPending(ids: string[], signal?: AbortSignal): Promise { dbg?.("bridge.waitForPending.start", { ids }); while (ids.some((id) => !this.pending.has(id))) { if (this.closed) throw new Error("Klaus query closed before tools parked."); if (signal?.aborted) throw new Error("Klaus tool wait aborted."); await new Promise((resolve, reject) => { const abort = () => reject(new Error("Klaus tool wait aborted.")); signal?.addEventListener("abort", abort, { once: true }); this.waiters.push(() => { signal?.removeEventListener("abort", abort); resolve(); }); }); } dbg?.("bridge.waitForPending.end", { ids }); } settle(result: PiToolResult): boolean { dbg?.("bridge.settle.start", { id: result.id, isError: result.isError, contentTypes: result.content.map((item) => item.type), }); this.onActivity(); if (this.settled.has(result.id)) return false; const pending = this.pending.get(result.id); if (!pending) return false; this.pending.delete(result.id); this.settled.add(result.id); pending.resolve({ content: result.content.map((item) => item.type === "text" ? { type: "text" as const, text: item.text } : { type: "image" as const, data: item.data, mimeType: item.mimeType, }, ), isError: result.isError, }); dbg?.("bridge.settle.end", { id: result.id }); return true; } async close(reason: string): Promise { dbg?.("bridge.close.start", { reason, alreadyClosed: this.closed, pendingCount: this.pending.size, }); if (this.closed) return; this.closed = true; const error = new Error(reason); for (const pending of this.pending.values()) pending.reject(error); this.pending.clear(); for (const notify of this.waiters.splice(0)) notify(); await this.server.close(); dbg?.("bridge.close.end", { reason }); } private errorResult(message: string): CallToolResult { dbg?.("bridge.errorResult", { message }); return { content: [{ type: "text", text: message }], isError: true }; } }