askrobots / dbbasic-browser
Public
A desktop browser with x402 built in: when a page asks for payment, it pays in stablecoins and shows the content.
danq9
site icons (favicons) in tabs, address bar suggestions and the bookmarks panel
7249579
15 hours, 50 minutes ago
History
mcp-client.ts · 6.1 KB · 141 lines
| 1 | /** |
| 2 | * A small client for MCP servers over HTTP (the "streamable HTTP" transport): JSON-RPC in a POST, answered either as |
| 3 | * JSON or as a short event stream. It lists a server's tools and calls them; that is all the chat needs. |
| 4 | * Main process only. The access token comes from `getToken` on every request, so a refresh in between is picked up. |
| 5 | */ |
| 6 | |
| 7 | import type { Fetch } from "./mcp-oauth.js"; |
| 8 | |
| 9 | export class McpAuthError extends Error { |
| 10 | constructor(message = "the server wants a fresh sign-in") { |
| 11 | super(message); |
| 12 | this.name = "McpAuthError"; |
| 13 | } |
| 14 | } |
| 15 | |
| 16 | export interface McpTool { |
| 17 | name: string; |
| 18 | description?: string; |
| 19 | inputSchema?: Record<string, unknown>; |
| 20 | /** The server's own hints (MCP tool annotations). Hints only: what a tool may do is still decided here, not by them. */ |
| 21 | annotations?: { readOnlyHint?: boolean; destructiveHint?: boolean }; |
| 22 | } |
| 23 | export interface McpResult { |
| 24 | text: string; |
| 25 | isError: boolean; |
| 26 | } |
| 27 | |
| 28 | const PROTOCOL = "2025-03-26"; |
| 29 | const MAX_RESPONSE = 4_000_000; |
| 30 | |
| 31 | /** Pick the JSON-RPC reply with our id out of a text/event-stream body. */ |
| 32 | export function parseEventStream(body: string, id: number): Record<string, unknown> | null { |
| 33 | for (const block of body.split(/\r?\n\r?\n/)) { |
| 34 | const data = block |
| 35 | .split(/\r?\n/) |
| 36 | .filter((l) => l.startsWith("data:")) |
| 37 | .map((l) => l.slice(5).replace(/^ /, "")) |
| 38 | .join("\n"); |
| 39 | if (!data) continue; |
| 40 | try { |
| 41 | const j = JSON.parse(data) as Record<string, unknown>; |
| 42 | if (j.id === id) return j; |
| 43 | } catch { |
| 44 | /* not JSON: skip */ |
| 45 | } |
| 46 | } |
| 47 | return null; |
| 48 | } |
| 49 | |
| 50 | export class McpClient { |
| 51 | private nextId = 1; |
| 52 | private session: string | null = null; |
| 53 | private ready = false; |
| 54 | |
| 55 | constructor( |
| 56 | private url: string, |
| 57 | private getToken: () => Promise<string>, |
| 58 | private f: Fetch, |
| 59 | private info = { name: "dbbasic-browser", version: "1" }, |
| 60 | ) {} |
| 61 | |
| 62 | private async post(body: Record<string, unknown>, expectReply: boolean): Promise<Record<string, unknown> | null> { |
| 63 | const headers: Record<string, string> = { |
| 64 | "content-type": "application/json", |
| 65 | accept: "application/json, text/event-stream", |
| 66 | authorization: `Bearer ${await this.getToken()}`, |
| 67 | "mcp-protocol-version": PROTOCOL, |
| 68 | ...(this.session ? { "mcp-session-id": this.session } : {}), |
| 69 | }; |
| 70 | const res = await this.f(this.url, { method: "POST", headers, body: JSON.stringify(body), signal: AbortSignal.timeout(45_000) }); |
| 71 | const sid = res.headers.get("mcp-session-id"); |
| 72 | if (sid) this.session = sid; |
| 73 | if (res.status === 401) throw new McpAuthError(); |
| 74 | if (res.status === 404 && this.session) { |
| 75 | this.session = null; |
| 76 | this.ready = false; |
| 77 | throw new Error("the server forgot this session; try again"); |
| 78 | } |
| 79 | const text = await res.text(); |
| 80 | if (text.length > MAX_RESPONSE) throw new Error("the server's reply is too large"); |
| 81 | if (!res.ok) throw new Error(`the server answered ${res.status}`); |
| 82 | if (!expectReply) return null; |
| 83 | const type = (res.headers.get("content-type") ?? "").toLowerCase(); |
| 84 | const j = type.includes("text/event-stream") ? parseEventStream(text, body.id as number) : (JSON.parse(text) as Record<string, unknown>); |
| 85 | if (!j) throw new Error("the server sent no reply"); |
| 86 | return j; |
| 87 | } |
| 88 | |
| 89 | private async rpc(method: string, params: Record<string, unknown> = {}): Promise<Record<string, unknown>> { |
| 90 | await this.init(); |
| 91 | return this.call(method, params); |
| 92 | } |
| 93 | |
| 94 | private async call(method: string, params: Record<string, unknown>): Promise<Record<string, unknown>> { |
| 95 | const id = this.nextId++; |
| 96 | const j = (await this.post({ jsonrpc: "2.0", id, method, params }, true)) as Record<string, unknown>; |
| 97 | const err = j.error as { message?: string; code?: number } | undefined; |
| 98 | if (err) { |
| 99 | if (err.code === -32000 && /authenticat/i.test(String(err.message))) throw new McpAuthError(); |
| 100 | throw new Error(String(err.message ?? "the server returned an error").slice(0, 300)); |
| 101 | } |
| 102 | return (j.result ?? {}) as Record<string, unknown>; |
| 103 | } |
| 104 | |
| 105 | private async init(): Promise<void> { |
| 106 | if (this.ready) return; |
| 107 | await this.call("initialize", { protocolVersion: PROTOCOL, capabilities: {}, clientInfo: this.info }); |
| 108 | this.ready = true; |
| 109 | try { |
| 110 | await this.post({ jsonrpc: "2.0", method: "notifications/initialized" }, false); |
| 111 | } catch (e) { |
| 112 | if (e instanceof McpAuthError) throw e; // anything else about this courtesy message is not worth failing for |
| 113 | } |
| 114 | } |
| 115 | |
| 116 | async listTools(): Promise<McpTool[]> { |
| 117 | const out: McpTool[] = []; |
| 118 | let cursor: string | undefined; |
| 119 | for (let page = 0; page < 20; page++) { |
| 120 | const r = await this.rpc("tools/list", cursor ? { cursor } : {}); |
| 121 | const tools = Array.isArray(r.tools) ? (r.tools as Array<Record<string, unknown>>) : []; |
| 122 | for (const t of tools) { |
| 123 | if (typeof t.name !== "string") continue; |
| 124 | const a = t.annotations && typeof t.annotations === "object" ? (t.annotations as Record<string, unknown>) : null; |
| 125 | const annotations = a ? { ...(typeof a.readOnlyHint === "boolean" ? { readOnlyHint: a.readOnlyHint } : {}), ...(typeof a.destructiveHint === "boolean" ? { destructiveHint: a.destructiveHint } : {}) } : null; |
| 126 | out.push({ name: t.name, ...(typeof t.description === "string" ? { description: t.description } : {}), ...(t.inputSchema && typeof t.inputSchema === "object" ? { inputSchema: t.inputSchema as Record<string, unknown> } : {}), ...(annotations && Object.keys(annotations).length ? { annotations } : {}) }); |
| 127 | } |
| 128 | cursor = typeof r.nextCursor === "string" && r.nextCursor ? r.nextCursor : undefined; |
| 129 | if (!cursor) break; |
| 130 | } |
| 131 | return out; |
| 132 | } |
| 133 | |
| 134 | async callTool(name: string, args: Record<string, unknown>): Promise<McpResult> { |
| 135 | const r = await this.rpc("tools/call", { name, arguments: args }); |
| 136 | const content = Array.isArray(r.content) ? (r.content as Array<Record<string, unknown>>) : []; |
| 137 | const parts = content.map((c) => (c.type === "text" && typeof c.text === "string" ? c.text : `[${String(c.type ?? "content")} not shown]`)); |
| 138 | if (!parts.length && r.structuredContent !== undefined) parts.push(JSON.stringify(r.structuredContent)); |
| 139 | return { text: parts.join("\n"), isError: r.isError === true }; |
| 140 | } |
| 141 | } |