@ractive-ch/tab-mcp-client 0.13.1 → 0.14.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +12 -5
- package/cdn/{connection-jk28y9f6.min.js → connection-dweyrdbn.min.js} +7 -7
- package/cdn/{connection-jk28y9f6.min.js.map → connection-dweyrdbn.min.js.map} +3 -3
- package/cdn/tab-mcp-client.min.js +3 -3
- package/cdn/tab-mcp-client.min.js.map +3 -3
- package/{connection-h2ct4x47.js → connection-eqsag07j.js} +13 -7
- package/connection-eqsag07j.js.map +15 -0
- package/index.d.ts +1 -1
- package/index.js +4 -4
- package/index.js.map +3 -3
- package/internal.d.ts +2 -2
- package/mcp.d.ts +7 -6
- package/package.json +1 -1
- package/types.d.ts +13 -4
- package/connection-h2ct4x47.js.map +0 -15
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../src/icons.ts", "../src/mcp.ts", "../src/mapping.ts", "../src/protocol.ts", "../src/address.ts", "../src/connection.ts"],
|
|
4
|
+
"sourcesContent": [
|
|
5
|
+
"/**\n * The page's icons for `serverInfo.icons` (MCP `Icon`): the AI app may show\n * them for this page's connector. Loaded with the connection, not the core.\n */\n\nimport type { Icon } from \"./types.ts\";\n\n/** At most this many icons; a URL up to 2 KiB, a `data:` URI up to 16 KiB. */\nconst MAX_ICONS = 8;\nconst MAX_URL = 2048;\nconst MAX_DATA = 16_384;\nconst SIZE = /^(?:\\d{1,4}x\\d{1,4}|any)$/;\n\n/**\n * An icon worth sending, with clean fields: an http(s) URL (rendering an SVG\n * safely is the AI app's job, as MCP says), or a raster `data:` URI; never\n * an inline SVG, which the app might put into its own page.\n */\nfunction clean(icon: Icon): Icon | undefined {\n\tconst { src, mimeType, sizes, theme } = icon;\n\tif (typeof src !== \"string\") return undefined;\n\tconst url = /^https?:/i.test(src) && src.length <= MAX_URL;\n\tconst data =\n\t\t/^data:image\\/(?:png|jpeg|gif|webp|x-icon|vnd\\.microsoft\\.icon)[;,]/i.test(\n\t\t\tsrc,\n\t\t) && src.length <= MAX_DATA;\n\tif (!url && !data) return undefined;\n\tconst out: Icon = { src };\n\tif (typeof mimeType === \"string\" && /^image\\/[\\w.+-]+$/i.test(mimeType)) {\n\t\tout.mimeType = mimeType.toLowerCase();\n\t}\n\tconst valid = Array.isArray(sizes)\n\t\t? sizes.map((s) => String(s).toLowerCase()).filter((s) => SIZE.test(s))\n\t\t: [];\n\tif (valid.length > 0) out.sizes = valid;\n\tif (theme === \"light\" || theme === \"dark\") out.theme = theme;\n\treturn out;\n}\n\n/** Icons as given (`server.icons`), cleaned and capped. */\nexport function cleanIcons(icons: readonly Icon[]): Icon[] {\n\tconst out: Icon[] = [];\n\tfor (const icon of icons) {\n\t\tconst c =\n\t\t\ttypeof icon === \"object\" && icon !== null ? clean(icon) : undefined;\n\t\tif (c !== undefined) out.push(c);\n\t\tif (out.length === MAX_ICONS) break;\n\t}\n\treturn out;\n}\n\n/**\n * The document's `<link rel=\"icon\">` and `<link rel=\"apple-touch-icon\">`,\n * with their `type`, `sizes` and a `prefers-color-scheme` media query as the\n * theme. Empty without a document.\n */\nexport function pageIcons(\n\tdoc: Document | undefined = globalThis.document,\n): Icon[] {\n\t// Icons are optional: whatever the document is, connecting goes on.\n\ttry {\n\t\tconst links = doc?.querySelectorAll<HTMLLinkElement>(\n\t\t\t'link[rel~=\"icon\" i], link[rel~=\"apple-touch-icon\" i]',\n\t\t);\n\t\treturn cleanIcons(\n\t\t\t// An empty href resolves to the page itself: no icon.\n\t\t\t[...(links ?? [])]\n\t\t\t\t.filter((link) => link.getAttribute(\"href\")?.trim())\n\t\t\t\t.map((link) => {\n\t\t\t\t\tconst icon: Icon = { src: link.href };\n\t\t\t\t\tif (link.type) icon.mimeType = link.type;\n\t\t\t\t\tconst sizes = link.getAttribute(\"sizes\");\n\t\t\t\t\tif (sizes) icon.sizes = sizes.trim().split(/\\s+/);\n\t\t\t\t\tconst scheme = /prefers-color-scheme:\\s*(light|dark)/i.exec(\n\t\t\t\t\t\tlink.media,\n\t\t\t\t\t);\n\t\t\t\t\tif (scheme) icon.theme = scheme[1]?.toLowerCase() as \"light\" | \"dark\";\n\t\t\t\t\treturn icon;\n\t\t\t\t}),\n\t\t);\n\t} catch {\n\t\treturn [];\n\t}\n}\n",
|
|
6
|
+
"/**\n * The tab's MCP server: the stateless 2026-07-28 subset tab-mcp needs\n * (DEC-049), written for the page instead of bundling the SDK. It answers\n * `server/discover`, `tools/list`, `tools/call` (as SSE, DEC-020) and\n * `subscriptions/listen`, and applies the request checks of the 2026-07-28\n * Streamable HTTP transport (content type, JSON-RPC shape, `_meta` envelope,\n * `MCP-Protocol-Version` / `Mcp-Method` / `Mcp-Name`). Status codes and error\n * codes follow the MCP TypeScript SDK's `createMcpHandler`; the conformance\n * tests compare the two.\n */\n\nimport {\n\tdereference,\n\ttype OutputUnit,\n\ttype Schema,\n\tvalidate as validateSchema,\n} from \"@cfworker/json-schema\";\nimport { cleanIcons } from \"./icons.ts\";\nimport {\n\tANNOTATIONS_META_KEY,\n\ttype CallToolResult,\n\terrorResult,\n\tmapAnnotations,\n\tthrownResult,\n\ttoCallToolResult,\n} from \"./mapping.ts\";\nimport type { GrantRef } from \"./protocol.ts\";\nimport type { RegisteredTool, ToolRegistry } from \"./registry.ts\";\nimport type {\n\tConfirmAnswer,\n\tConfirmRequest,\n\tServerInfo,\n\tToolCallClient,\n\tToolCallEnd,\n\tToolCallOutcome,\n\tToolCallStart,\n} from \"./types.ts\";\n\nexport const MCP_PROTOCOL_VERSION = \"2026-07-28\";\nconst META_VERSION = \"io.modelcontextprotocol/protocolVersion\";\nconst META_CAPABILITIES = \"io.modelcontextprotocol/clientCapabilities\";\nconst META_CLIENT_INFO = \"io.modelcontextprotocol/clientInfo\";\nconst META_SERVER_INFO = \"io.modelcontextprotocol/serverInfo\";\nconst META_SUBSCRIPTION = \"io.modelcontextprotocol/subscriptionId\";\n\nconst HEADER_MISMATCH = -32020;\nconst UNSUPPORTED_VERSION = -32022;\n\ntype Id = string | number;\ntype Json = Record<string, unknown>;\n\nexport interface ToolSource {\n\tlist(): RegisteredTool[];\n\tget(name: string): RegisteredTool | undefined;\n}\n\n/** What a tool call needs, through the relay or through WebMCP. */\nexport interface CallContext {\n\ttools: ToolSource;\n\t/** Ask the user before a consequential tool runs. */\n\tconfirm(request: ConfirmRequest): Promise<ConfirmAnswer>;\n\t/** Told about every call of a known tool, as it starts and as it ends. */\n\tobserve?: {\n\t\tstart(call: ToolCallStart): void;\n\t\tend(call: ToolCallEnd): void;\n\t};\n}\n\nexport interface McpHandlerOptions extends CallContext {\n\tserver: ServerInfo;\n\t/** The caller of a request, from its grant. */\n\tclient(grant: GrantRef): ToolCallClient;\n}\n\n/** Tool call ids, unique in the page. */\nlet lastCallId = 0;\n\n/** Checks arguments against a tool's input schema. */\nexport type ArgumentValidator = (args: unknown) => {\n\tvalid: boolean;\n\terrors: OutputUnit[];\n};\n\nconst compiled = new WeakMap<RegisteredTool, ArgumentValidator>();\n\n/**\n * The validator of a tool's input schema, built once per tool. Throws what\n * the validator would throw at call time: a `$ref` that does not resolve\n * (the validator resolves one only when an argument reaches it, against the\n * base of the nearest `$id`), an `$id` that is not a URL, a duplicate one.\n * `compileRegistry` makes the registry call it at registration (DEC-086).\n */\nexport function compileTool(tool: RegisteredTool): ArgumentValidator {\n\tconst known = compiled.get(tool);\n\tif (known !== undefined) return known;\n\tconst schema = tool.inputSchema as Schema;\n\tlet lookup: Record<string, Schema | boolean>;\n\ttry {\n\t\tlookup = dereference(schema);\n\t} catch (error) {\n\t\t// Only the first line: the validator appends the URIs it knows.\n\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\tthrow new Error(message.split(\"\\n\")[0]);\n\t}\n\tfor (const node of Object.values(lookup)) {\n\t\tif (typeof node !== \"object\" || node.$ref === undefined) continue;\n\t\tconst absolute = (node as { __absolute_ref__?: string }).__absolute_ref__;\n\t\tif (lookup[absolute ?? node.$ref] === undefined)\n\t\t\tthrow new Error(`$ref ${JSON.stringify(node.$ref)} does not resolve`);\n\t}\n\tconst validator: ArgumentValidator = (args) =>\n\t\tvalidateSchema(args, schema, \"2020-12\", lookup, false);\n\tcompiled.set(tool, validator);\n\treturn validator;\n}\n\nfunction schemaError(name: string, error: unknown, suffix = \"\"): TypeError {\n\tconst message = error instanceof Error ? error.message : String(error);\n\treturn new TypeError(\n\t\t`registerTool: the inputSchema of ${name}: ${message}${suffix}`,\n\t);\n}\n\n/**\n * The validator is loaded (on `connect()`): compile the schemas of the tools\n * registered so far, before any AI app lists them, and from now on at\n * registration, so that `registerTool` rejects a schema the validator cannot\n * use. A tool registered before that it refuses is unregistered; the errors\n * are for the page's `error` event.\n */\nexport function compileRegistry(registry: ToolRegistry): TypeError[] {\n\tconst refused: TypeError[] = [];\n\tfor (const tool of registry.list()) {\n\t\ttry {\n\t\t\tcompileTool(tool);\n\t\t} catch (error) {\n\t\t\tregistry.remove(tool);\n\t\t\trefused.push(\n\t\t\t\tschemaError(tool.name, error, \"; the tool was unregistered\"),\n\t\t\t);\n\t\t}\n\t}\n\tregistry.setCompiler((tool) => {\n\t\ttry {\n\t\t\tcompileTool(tool);\n\t\t} catch (error) {\n\t\t\tthrow schemaError(tool.name, error);\n\t\t}\n\t});\n\treturn refused;\n}\n\n/** A deep copy for an event; the value itself when it cannot be cloned. */\nfunction copy<T>(value: T): T {\n\ttry {\n\t\treturn structuredClone(value);\n\t} catch {\n\t\treturn value;\n\t}\n}\n\nexport interface McpRequestContext {\n\tgrant: GrantRef;\n\t/** The body as text when the caller already has it. */\n\tbody?: string;\n}\n\nexport interface McpHandler {\n\thandle(request: Request, context: McpRequestContext): Promise<Response>;\n\t/** The tool list changed: tell the listen streams. */\n\ttoolsChanged(): void;\n\t/** End every listen stream (the session is over). */\n\tclose(): void;\n}\n\nconst encoder = new TextEncoder();\n\nfunction isObject(v: unknown): v is Json {\n\treturn typeof v === \"object\" && v !== null && !Array.isArray(v);\n}\n\nfunction json(status: number, value: unknown): Response {\n\treturn new Response(JSON.stringify(value), {\n\t\tstatus,\n\t\theaders: { \"content-type\": \"application/json\" },\n\t});\n}\n\nfunction rpcError(\n\tstatus: number,\n\tid: Id | null,\n\tcode: number,\n\tmessage: string,\n\tdata?: unknown,\n): Response {\n\tconst error: Json = { code, message };\n\tif (data !== undefined) error[\"data\"] = data;\n\treturn json(status, { jsonrpc: \"2.0\", id, error });\n}\n\nfunction mismatch(id: Id | null, header: string, body: string): Response {\n\treturn rpcError(\n\t\t400,\n\t\tid,\n\t\tHEADER_MISMATCH,\n\t\t`Bad Request: the request headers and body disagree: ${body}`,\n\t\t{\n\t\t\tmismatch: { header, body },\n\t\t},\n\t);\n}\n\nfunction sseEvent(message: unknown): Uint8Array {\n\treturn encoder.encode(`event: message\\ndata: ${JSON.stringify(message)}\\n\\n`);\n}\n\nconst SSE_HEADERS = {\n\t\"content-type\": \"text/event-stream\",\n\t\"cache-control\": \"no-cache\",\n};\n\n/** `application/json`, with or without parameters. */\nfunction isJsonContentType(value: string | null): boolean {\n\treturn (\n\t\t(value ?? \"\").split(\";\")[0]?.trim().toLowerCase() === \"application/json\"\n\t);\n}\n\n/** Decode the `=?base64?…?=` sentinel of SEP-2243 headers; `undefined` if malformed. */\nexport function decodeHeaderValue(value: string): string | undefined {\n\tif (!(value.startsWith(\"=?base64?\") && value.endsWith(\"?=\"))) return value;\n\tconst b64 = value.slice(9, -2);\n\tif (\n\t\t!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(\n\t\t\tb64,\n\t\t)\n\t)\n\t\treturn undefined;\n\ttry {\n\t\tconst bin = atob(b64);\n\t\tconst bytes = Uint8Array.from(bin, (c) => c.charCodeAt(0));\n\t\treturn new TextDecoder(\"utf-8\", { fatal: true }).decode(bytes);\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\n/** The first problem of a 2026-07-28 `_meta` envelope, or `undefined`. */\nfunction envelopeIssue(\n\tmeta: Json,\n): { key: string; problem: string } | undefined {\n\tif (!(META_VERSION in meta)) return { key: META_VERSION, problem: \"missing\" };\n\tif (!(META_CAPABILITIES in meta))\n\t\treturn { key: META_CAPABILITIES, problem: \"missing\" };\n\tif (typeof meta[META_VERSION] !== \"string\") {\n\t\treturn { key: META_VERSION, problem: \"expected a protocol version string\" };\n\t}\n\tif (!isObject(meta[META_CAPABILITIES]))\n\t\treturn { key: META_CAPABILITIES, problem: \"expected an object\" };\n\tconst info = meta[META_CLIENT_INFO];\n\tif (\n\t\tinfo !== undefined &&\n\t\t!(\n\t\t\tisObject(info) &&\n\t\t\ttypeof info[\"name\"] === \"string\" &&\n\t\t\ttypeof info[\"version\"] === \"string\"\n\t\t)\n\t) {\n\t\treturn { key: META_CLIENT_INFO, problem: \"expected {name, version}\" };\n\t}\n\treturn undefined;\n}\n\n/** Listen streams honour only the tool list (the tab has nothing else). */\nfunction honoured(params: Json): Json {\n\tconst requested = params[\"notifications\"];\n\treturn isObject(requested) && requested[\"toolsListChanged\"] === true\n\t\t? { toolsListChanged: true }\n\t\t: {};\n}\n\nfunction validate(tool: RegisteredTool, args: Json): string | undefined {\n\tlet outcome: ReturnType<ArgumentValidator>;\n\ttry {\n\t\toutcome = compileTool(tool)(args);\n\t} catch (error) {\n\t\t// Refused at registration through `TabMcp`; this is for any other registry.\n\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\treturn `The input schema of tool ${tool.name} cannot be used: ${message}`;\n\t}\n\tif (outcome.valid) return undefined;\n\tconst detail = outcome.errors\n\t\t.filter((e) => e.keyword !== \"properties\" && e.keyword !== \"$ref\")\n\t\t.map((e) => `${e.instanceLocation} ${e.error}`)\n\t\t.slice(0, 5)\n\t\t.join(\"; \");\n\treturn `Input validation error: Invalid arguments for tool ${tool.name}: ${detail || \"the arguments do not match the schema\"}`;\n}\n\n/**\n * How a call ended. `stop`: why it did not run to its end: invalid\n * arguments, declined by the user, not answered by the user, cancelled, or\n * its tool gone. `returned`: what `execute` returned.\n */\nexport interface CallRun {\n\toutcome: ToolCallOutcome;\n\tresult: CallToolResult;\n\tstop?: \"invalid\" | \"declined\" | \"unanswered\" | \"cancelled\" | \"gone\";\n\treturned?: { value: unknown };\n}\n\n/**\n * One call of a known tool, from an AI app through the relay or from an\n * agent in the browser through WebMCP: the `toolcall` and `toolcallend`\n * events around the argument check, the confirmation of a consequential\n * tool and `execute`. The one path for both callers, so they cannot drift.\n */\nexport async function runCall(\n\tcontext: CallContext,\n\ttool: RegisteredTool,\n\traw: Json,\n\tsignal: AbortSignal,\n\tclient: ToolCallClient,\n): Promise<CallRun> {\n\t// Copies: a listener cannot change what the tool gets or the caller receives.\n\tconst call: ToolCallStart = {\n\t\tid: ++lastCallId,\n\t\ttool: tool.name,\n\t\targuments: copy(raw),\n\t\tclient: { ...client },\n\t};\n\tif (tool.title !== undefined) call.title = tool.title;\n\tconst started = Date.now();\n\tcontext.observe?.start(call);\n\t// Every start has its end, also when something fails outside the tool.\n\tlet run: CallRun = {\n\t\toutcome: \"error\",\n\t\tresult: errorResult(\"Internal error\"),\n\t};\n\ttry {\n\t\trun = await decideAndRun(context, tool, raw, signal, client);\n\t} finally {\n\t\tcontext.observe?.end({\n\t\t\tid: call.id,\n\t\t\ttool: tool.name,\n\t\t\tclient: { ...client },\n\t\t\toutcome: run.outcome,\n\t\t\tresult: copy(run.result),\n\t\t\tdurationMs: Date.now() - started,\n\t\t});\n\t}\n\treturn run;\n}\n\n/** What the AI app reads when the user was asked and did not answer. */\nconst UNANSWERED = \"The user was asked and did not answer.\";\n\n/** Validate, confirm and run one call. */\nasync function decideAndRun(\n\tcontext: CallContext,\n\ttool: RegisteredTool,\n\traw: Json,\n\tsignal: AbortSignal,\n\tclient: ToolCallClient,\n): Promise<CallRun> {\n\tconst stopped = (\n\t\toutcome: ToolCallOutcome,\n\t\tmessage: string,\n\t\tstop: NonNullable<CallRun[\"stop\"]>,\n\t): CallRun => ({ outcome, result: errorResult(message), stop });\n\tconst invalid = validate(tool, raw);\n\tif (invalid !== undefined) return stopped(\"error\", invalid, \"invalid\");\n\tif (tool.annotations.consequentialHint === true) {\n\t\tconst question: ConfirmRequest = {\n\t\t\ttool: { name: tool.name, description: tool.description },\n\t\t\targuments: raw,\n\t\t\tclient,\n\t\t\tsignal,\n\t\t};\n\t\tif (tool.title !== undefined) question.tool.title = tool.title;\n\t\tlet answer: ConfirmAnswer = false;\n\t\ttry {\n\t\t\tanswer = await context.confirm(question);\n\t\t} catch {\n\t\t\tanswer = false; // a failing question is a refusal\n\t\t}\n\t\tif (answer !== true) {\n\t\t\tif (signal.aborted)\n\t\t\t\treturn stopped(\"cancelled\", \"The user declined\", \"cancelled\");\n\t\t\treturn answer === \"unanswered\"\n\t\t\t\t? stopped(\"unanswered\", UNANSWERED, \"unanswered\")\n\t\t\t\t: stopped(\"declined\", \"The user declined\", \"declined\");\n\t\t}\n\t}\n\tif (signal.aborted) return stopped(\"cancelled\", \"Cancelled\", \"cancelled\");\n\t// Unregistered (or replaced) while the user was asked: not the tool\n\t// the user allowed, or one the page still offers.\n\tif (context.tools.get(tool.name) !== tool)\n\t\treturn stopped(\"error\", \"The tool is no longer available\", \"gone\");\n\tlet run: CallRun;\n\ttry {\n\t\tconst value = await tool.execute(raw, { signal, client });\n\t\trun = {\n\t\t\toutcome: \"ok\",\n\t\t\tresult: toCallToolResult(value),\n\t\t\treturned: { value },\n\t\t};\n\t} catch (error) {\n\t\trun = { outcome: \"error\", result: thrownResult(error) };\n\t}\n\t// Cancelled is cancelled, however the tool answered the abort.\n\tif (signal.aborted)\n\t\treturn { ...run, outcome: \"cancelled\", stop: \"cancelled\" };\n\tif (run.result.isError === true) run.outcome = \"error\";\n\treturn run;\n}\n\n/**\n * A call from an agent in the browser (WebMCP) of the mirrored `tool`: the\n * same path as an AI app's call (`runCall`), its outcome as WebMCP has it.\n * Resolves with what `execute` returned. Every failure the agent should read\n * resolves too, as `{ error: \"<message>\" }`: invalid arguments, \"Don't\n * allow\", a question not answered, a tool that is gone, what `execute`\n * threw, an `isError` result.\n * Chrome 156 turns a rejection into a bare `UnknownError`, so the agent\n * would learn neither why nor what to change (DEC-120). Only a call the\n * browser cancelled rejects (`AbortError`): its caller has gone already.\n */\nexport async function webMcpCall(\n\tcontext: CallContext,\n\ttool: RegisteredTool,\n\tinput: unknown,\n\tsignal: unknown,\n): Promise<unknown> {\n\tconst failed = (error: string) => ({ error });\n\tconst gone = `The tool ${tool.name} is no longer available.`;\n\t// Gone already, e.g. refused by the validator just loaded: no call.\n\tif (context.tools.get(tool.name) !== tool) return failed(gone);\n\tif (!isObject(input)) return failed(\"The input must be an object.\");\n\tconst run = await runCall(\n\t\tcontext,\n\t\ttool,\n\t\tinput,\n\t\tsignal instanceof AbortSignal ? signal : new AbortController().signal,\n\t\t{ kind: \"webmcp\" },\n\t);\n\tif (run.stop === \"cancelled\")\n\t\tthrow new DOMException(\"Cancelled\", \"AbortError\");\n\tif (run.stop === \"declined\")\n\t\treturn failed(`The user did not allow ${tool.name} to run.`);\n\tif (run.stop === \"unanswered\")\n\t\treturn failed(`The user did not answer whether ${tool.name} may run.`);\n\tif (run.stop === \"gone\") return failed(gone);\n\tif (run.result.isError === true)\n\t\treturn failed(resultText(run.result) || \"The tool failed.\");\n\treturn run.returned?.value;\n}\n\n/** The text blocks of a result, one per line. */\nfunction resultText(result: CallToolResult): string {\n\treturn result.content\n\t\t.map((block) =>\n\t\t\tisObject(block) &&\n\t\t\tblock[\"type\"] === \"text\" &&\n\t\t\ttypeof block[\"text\"] === \"string\"\n\t\t\t\t? block[\"text\"]\n\t\t\t\t: \"\",\n\t\t)\n\t\t.filter((text) => text !== \"\")\n\t\t.join(\"\\n\");\n}\n\nexport function createMcpHandler(options: McpHandlerOptions): McpHandler {\n\tconst { tools, server } = options;\n\tconst serverInfo: Json = { name: server.name, version: server.version };\n\tif (server.title !== undefined) serverInfo[\"title\"] = server.title;\n\t// The icons only in server/discover: every other result carries\n\t// serverInfo too, and the app needs them once.\n\tconst icons = cleanIcons(server.icons ?? []);\n\tconst discoverInfo: Json =\n\t\ticons.length > 0 ? { ...serverInfo, icons } : serverInfo;\n\tconst listeners = new Set<{\n\t\tid: Id;\n\t\tsend(message: unknown): void;\n\t\tend(): void;\n\t}>();\n\tlet changeQueued = false;\n\n\tconst resultMeta = (extra: Json = {}) => ({\n\t\t...extra,\n\t\t[META_SERVER_INFO]: serverInfo,\n\t});\n\n\tfunction result(id: Id, value: Json, meta: Json = resultMeta()): Json {\n\t\treturn {\n\t\t\tjsonrpc: \"2.0\",\n\t\t\tid,\n\t\t\tresult: { ...value, resultType: \"complete\", _meta: meta },\n\t\t};\n\t}\n\n\tfunction listTools(): Json[] {\n\t\treturn tools.list().map((tool) => {\n\t\t\tconst entry: Json = { name: tool.name };\n\t\t\tif (tool.title !== undefined) entry[\"title\"] = tool.title;\n\t\t\tentry[\"description\"] = tool.description;\n\t\t\tentry[\"inputSchema\"] = tool.inputSchema;\n\t\t\tconst { annotations, meta } = mapAnnotations(tool.annotations);\n\t\t\tif (annotations !== undefined) entry[\"annotations\"] = annotations;\n\t\t\tif (meta !== undefined) entry[\"_meta\"] = { [ANNOTATIONS_META_KEY]: meta };\n\t\t\treturn entry;\n\t\t});\n\t}\n\n\t/**\n\t * A call's outcome: a JSON-RPC error (`invalid`) or a result. Tagged, so\n\t * that a result's own keys never decide which (a tool may return any).\n\t */\n\ttype RunOutcome =\n\t\t| { kind: \"invalid\"; message: string }\n\t\t| { kind: \"result\"; result: CallToolResult };\n\n\tconst invalidParams = (message: string): RunOutcome => ({\n\t\tkind: \"invalid\",\n\t\tmessage,\n\t});\n\n\tasync function runTool(\n\t\tparams: Json,\n\t\tsignal: AbortSignal,\n\t\tgrant: GrantRef,\n\t): Promise<RunOutcome> {\n\t\tconst name = params[\"name\"];\n\t\tif (typeof name !== \"string\")\n\t\t\treturn invalidParams(\"Invalid params: name must be a string\");\n\t\tconst tool = tools.get(name);\n\t\tif (tool === undefined) return invalidParams(`Tool ${name} not found`);\n\t\tconst raw = params[\"arguments\"] ?? {};\n\t\tif (!isObject(raw))\n\t\t\treturn invalidParams(\"Invalid params: arguments must be an object\");\n\t\tconst run = await runCall(\n\t\t\toptions,\n\t\t\ttool,\n\t\t\traw,\n\t\t\tsignal,\n\t\t\toptions.client(grant),\n\t\t);\n\t\treturn { kind: \"result\", result: run.result };\n\t}\n\n\tfunction callTool(\n\t\tid: Id,\n\t\tparams: Json,\n\t\tsignal: AbortSignal,\n\t\tgrant: GrantRef,\n\t): Response {\n\t\tconst stream = new ReadableStream<Uint8Array>({\n\t\t\tstart: (controller) => {\n\t\t\t\t/** Send the one answer and end the stream, whatever happens. */\n\t\t\t\tconst finish = (message: unknown) => {\n\t\t\t\t\tif (signal.aborted) return; // nobody listens any more\n\t\t\t\t\tlet event: Uint8Array;\n\t\t\t\t\ttry {\n\t\t\t\t\t\tevent = sseEvent(message);\n\t\t\t\t\t} catch {\n\t\t\t\t\t\t// e.g. a BigInt or a cycle inside a passed-through result\n\t\t\t\t\t\tevent = sseEvent(\n\t\t\t\t\t\t\tresult(\n\t\t\t\t\t\t\t\tid,\n\t\t\t\t\t\t\t\terrorResult(\"The tool returned a result that is not JSON.\"),\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t\ttry {\n\t\t\t\t\t\tcontroller.enqueue(event);\n\t\t\t\t\t\tcontroller.close();\n\t\t\t\t\t} catch {\n\t\t\t\t\t\t// the stream was cancelled meanwhile\n\t\t\t\t\t}\n\t\t\t\t};\n\t\t\t\trunTool(params, signal, grant).then(\n\t\t\t\t\t(outcome) =>\n\t\t\t\t\t\tfinish(\n\t\t\t\t\t\t\toutcome.kind === \"invalid\"\n\t\t\t\t\t\t\t\t? {\n\t\t\t\t\t\t\t\t\t\tjsonrpc: \"2.0\",\n\t\t\t\t\t\t\t\t\t\tid,\n\t\t\t\t\t\t\t\t\t\terror: { code: -32602, message: outcome.message },\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t: result(id, outcome.result),\n\t\t\t\t\t\t),\n\t\t\t\t\t() =>\n\t\t\t\t\t\tfinish({\n\t\t\t\t\t\t\tjsonrpc: \"2.0\",\n\t\t\t\t\t\t\tid,\n\t\t\t\t\t\t\terror: { code: -32603, message: \"Internal error\" },\n\t\t\t\t\t\t}),\n\t\t\t\t);\n\t\t\t},\n\t\t});\n\t\treturn new Response(stream, { status: 200, headers: SSE_HEADERS });\n\t}\n\n\tfunction listen(id: Id, params: Json, signal: AbortSignal): Response {\n\t\tconst notifications = honoured(params);\n\t\tconst finalResult = {\n\t\t\tjsonrpc: \"2.0\",\n\t\t\tid,\n\t\t\tresult: {\n\t\t\t\tresultType: \"complete\",\n\t\t\t\t_meta: resultMeta({ [META_SUBSCRIPTION]: id }),\n\t\t\t},\n\t\t};\n\t\t// This stream's own listener: two AI apps may both use the same id.\n\t\tlet own: { id: Id; send(m: unknown): void; end(): void } | undefined;\n\t\tconst stream = new ReadableStream<Uint8Array>({\n\t\t\tstart: (controller) => {\n\t\t\t\tcontroller.enqueue(\n\t\t\t\t\tsseEvent({\n\t\t\t\t\t\tjsonrpc: \"2.0\",\n\t\t\t\t\t\tmethod: \"notifications/subscriptions/acknowledged\",\n\t\t\t\t\t\tparams: { notifications, _meta: { [META_SUBSCRIPTION]: id } },\n\t\t\t\t\t}),\n\t\t\t\t);\n\t\t\t\tif (Object.keys(notifications).length === 0) {\n\t\t\t\t\tcontroller.enqueue(sseEvent(finalResult));\n\t\t\t\t\tcontroller.close();\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tconst listener = {\n\t\t\t\t\tid,\n\t\t\t\t\tsend: (message: unknown) => {\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tcontroller.enqueue(sseEvent(message));\n\t\t\t\t\t\t} catch {\n\t\t\t\t\t\t\tlisteners.delete(listener);\n\t\t\t\t\t\t}\n\t\t\t\t\t},\n\t\t\t\t\tend: () => {\n\t\t\t\t\t\tlisteners.delete(listener);\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tcontroller.enqueue(sseEvent(finalResult));\n\t\t\t\t\t\t\tcontroller.close();\n\t\t\t\t\t\t} catch {\n\t\t\t\t\t\t\t// already cancelled\n\t\t\t\t\t\t}\n\t\t\t\t\t},\n\t\t\t\t};\n\t\t\t\town = listener;\n\t\t\t\tlisteners.add(listener);\n\t\t\t\tsignal.addEventListener(\"abort\", () => {\n\t\t\t\t\tlisteners.delete(listener);\n\t\t\t\t\ttry {\n\t\t\t\t\t\tcontroller.close();\n\t\t\t\t\t} catch {\n\t\t\t\t\t\t// already closed\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t},\n\t\t\tcancel: () => {\n\t\t\t\tif (own !== undefined) listeners.delete(own);\n\t\t\t},\n\t\t});\n\t\treturn new Response(stream, { status: 200, headers: SSE_HEADERS });\n\t}\n\n\t/** The request checks; a `Response` when the request is refused. */\n\tfunction check(\n\t\trequest: Request,\n\t\tbody: unknown,\n\t): Response | { id: Id; method: string; params: Json } | \"notification\" {\n\t\tif (Array.isArray(body)) {\n\t\t\treturn rpcError(\n\t\t\t\t400,\n\t\t\t\tnull,\n\t\t\t\t-32600,\n\t\t\t\t\"Bad Request: JSON-RPC batches are not supported by this endpoint\",\n\t\t\t);\n\t\t}\n\t\tif (!isObject(body) || body[\"jsonrpc\"] !== \"2.0\") {\n\t\t\treturn rpcError(\n\t\t\t\t400,\n\t\t\t\tnull,\n\t\t\t\t-32600,\n\t\t\t\t\"Bad Request: the request body is not a valid JSON-RPC message\",\n\t\t\t);\n\t\t}\n\t\tconst method = body[\"method\"];\n\t\tconst rawId = body[\"id\"];\n\t\tif (typeof method !== \"string\") {\n\t\t\treturn \"result\" in body || \"error\" in body\n\t\t\t\t? rpcError(\n\t\t\t\t\t\t400,\n\t\t\t\t\t\tnull,\n\t\t\t\t\t\t-32600,\n\t\t\t\t\t\t\"Bad Request: JSON-RPC responses cannot be posted to this endpoint\",\n\t\t\t\t\t)\n\t\t\t\t: rpcError(\n\t\t\t\t\t\t400,\n\t\t\t\t\t\tnull,\n\t\t\t\t\t\t-32600,\n\t\t\t\t\t\t\"Bad Request: the request body is not a valid JSON-RPC message\",\n\t\t\t\t\t);\n\t\t}\n\t\tconst headerVersion = request.headers.get(\"mcp-protocol-version\");\n\t\tconst headerMethod = request.headers.get(\"mcp-method\");\n\t\tconst params = isObject(body[\"params\"]) ? body[\"params\"] : {};\n\t\tconst meta = isObject(params[\"_meta\"]) ? params[\"_meta\"] : undefined;\n\t\tconst claim = meta !== undefined && META_VERSION in meta;\n\t\tconst claimed =\n\t\t\ttypeof meta?.[META_VERSION] === \"string\"\n\t\t\t\t? (meta[META_VERSION] as string)\n\t\t\t\t: undefined;\n\t\tconst headerModern =\n\t\t\theaderVersion !== null && headerVersion >= MCP_PROTOCOL_VERSION;\n\n\t\tif (rawId === undefined) {\n\t\t\t// A notification: nothing to answer, but the headers must agree.\n\t\t\tif (\n\t\t\t\tclaimed !== undefined &&\n\t\t\t\theaderVersion !== null &&\n\t\t\t\theaderVersion !== claimed\n\t\t\t) {\n\t\t\t\treturn mismatch(\n\t\t\t\t\tnull,\n\t\t\t\t\theaderVersion,\n\t\t\t\t\t`the notification envelope names protocol version ${claimed} but the MCP-Protocol-Version header names ${headerVersion}`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (\n\t\t\t\t(claim || headerModern) &&\n\t\t\t\theaderMethod !== null &&\n\t\t\t\theaderMethod !== method\n\t\t\t) {\n\t\t\t\treturn mismatch(\n\t\t\t\t\tnull,\n\t\t\t\t\theaderMethod,\n\t\t\t\t\t`the notification body names method ${method} but the Mcp-Method header names ${headerMethod}`,\n\t\t\t\t);\n\t\t\t}\n\t\t\treturn \"notification\";\n\t\t}\n\t\tif (typeof rawId !== \"string\" && typeof rawId !== \"number\") {\n\t\t\treturn rpcError(\n\t\t\t\t400,\n\t\t\t\tnull,\n\t\t\t\t-32600,\n\t\t\t\t\"Bad Request: the request body is not a valid JSON-RPC message\",\n\t\t\t);\n\t\t}\n\t\tconst id = rawId;\n\t\tif (\n\t\t\t!claim ||\n\t\t\t(method === \"initialize\" &&\n\t\t\t\t(claimed === undefined || claimed < MCP_PROTOCOL_VERSION))\n\t\t) {\n\t\t\tif (method === \"initialize\") {\n\t\t\t\tif (headerModern) {\n\t\t\t\t\treturn mismatch(\n\t\t\t\t\t\tid,\n\t\t\t\t\t\theaderVersion,\n\t\t\t\t\t\t\"an initialize request (legacy handshake) was sent with a modern MCP-Protocol-Version header\",\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tconst requested =\n\t\t\t\t\ttypeof params[\"protocolVersion\"] === \"string\"\n\t\t\t\t\t\t? params[\"protocolVersion\"]\n\t\t\t\t\t\t: undefined;\n\t\t\t\treturn unsupported(id, requested);\n\t\t\t}\n\t\t\tif (headerModern) {\n\t\t\t\tconst missing = meta === undefined ? [\"_meta\"] : [META_VERSION];\n\t\t\t\treturn rpcError(\n\t\t\t\t\t400,\n\t\t\t\t\tid,\n\t\t\t\t\t-32602,\n\t\t\t\t\t`Invalid params: the MCP-Protocol-Version header names protocol revision ${headerVersion}, but the request is missing the required per-request envelope key(s): ${missing.join(\", \")}`,\n\t\t\t\t\t{ envelope: { missing } },\n\t\t\t\t);\n\t\t\t}\n\t\t\treturn unsupported(id, headerVersion ?? undefined);\n\t\t}\n\t\tconst issue = envelopeIssue(meta);\n\t\tif (issue !== undefined) {\n\t\t\treturn rpcError(\n\t\t\t\t400,\n\t\t\t\tid,\n\t\t\t\t-32602,\n\t\t\t\t`Invalid _meta envelope for protocol revision ${MCP_PROTOCOL_VERSION}: ${issue.key}: ${issue.problem}`,\n\t\t\t\t{ envelope: issue },\n\t\t\t);\n\t\t}\n\t\tif (\n\t\t\theaderVersion !== null &&\n\t\t\tclaimed !== undefined &&\n\t\t\theaderVersion !== claimed\n\t\t) {\n\t\t\treturn mismatch(\n\t\t\t\tid,\n\t\t\t\theaderVersion,\n\t\t\t\t`the body envelope names protocol version ${claimed} but the MCP-Protocol-Version header names ${headerVersion}`,\n\t\t\t);\n\t\t}\n\t\tif (headerMethod !== null && headerMethod !== method) {\n\t\t\treturn mismatch(\n\t\t\t\tid,\n\t\t\t\theaderMethod,\n\t\t\t\t`the body names method ${method} but the Mcp-Method header names ${headerMethod}`,\n\t\t\t);\n\t\t}\n\t\tif (claimed !== MCP_PROTOCOL_VERSION) return unsupported(id, claimed);\n\t\tif (headerVersion === null) {\n\t\t\treturn mismatch(\n\t\t\t\tid,\n\t\t\t\t\"(missing)\",\n\t\t\t\t`the body envelope names protocol version ${claimed} but the required MCP-Protocol-Version header is absent`,\n\t\t\t);\n\t\t}\n\t\tif (headerMethod === null) {\n\t\t\treturn mismatch(\n\t\t\t\tid,\n\t\t\t\t\"(missing)\",\n\t\t\t\t`the body names method ${method} but the required Mcp-Method header is absent`,\n\t\t\t);\n\t\t}\n\t\tif (method === \"tools/call\" && typeof params[\"name\"] === \"string\") {\n\t\t\tconst name = params[\"name\"];\n\t\t\tconst header = request.headers.get(\"mcp-name\");\n\t\t\tif (header === null) {\n\t\t\t\treturn mismatch(\n\t\t\t\t\tid,\n\t\t\t\t\t\"(missing)\",\n\t\t\t\t\t`the body carries params.name=\"${name}\" but the required Mcp-Name header is absent`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst decoded = decodeHeaderValue(header);\n\t\t\tif (decoded === undefined) {\n\t\t\t\treturn mismatch(\n\t\t\t\t\tid,\n\t\t\t\t\theader,\n\t\t\t\t\t\"the Mcp-Name header carries an invalid Base64 sentinel value\",\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (decoded !== name) {\n\t\t\t\treturn mismatch(\n\t\t\t\t\tid,\n\t\t\t\t\theader,\n\t\t\t\t\t`the body carries params.name=\"${name}\" but the Mcp-Name header names \"${decoded}\"`,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t\treturn { id, method, params };\n\t}\n\n\tfunction unsupported(id: Id, requested: string | undefined): Response {\n\t\treturn requested === undefined\n\t\t\t? rpcError(\n\t\t\t\t\t400,\n\t\t\t\t\tid,\n\t\t\t\t\tUNSUPPORTED_VERSION,\n\t\t\t\t\t\"Unsupported protocol version: the request did not name a protocol version\",\n\t\t\t\t\t{ supported: [MCP_PROTOCOL_VERSION] },\n\t\t\t\t)\n\t\t\t: rpcError(\n\t\t\t\t\t400,\n\t\t\t\t\tid,\n\t\t\t\t\tUNSUPPORTED_VERSION,\n\t\t\t\t\t`Unsupported protocol version: ${requested}`,\n\t\t\t\t\t{ supported: [MCP_PROTOCOL_VERSION], requested },\n\t\t\t\t);\n\t}\n\n\tasync function handle(\n\t\trequest: Request,\n\t\tcontext: McpRequestContext,\n\t): Promise<Response> {\n\t\tif (request.method.toUpperCase() !== \"POST\")\n\t\t\treturn rpcError(405, null, -32000, \"Method not allowed.\");\n\t\tif (!isJsonContentType(request.headers.get(\"content-type\"))) {\n\t\t\treturn rpcError(\n\t\t\t\t415,\n\t\t\t\tnull,\n\t\t\t\t-32000,\n\t\t\t\t\"Unsupported Media Type: Content-Type must be application/json\",\n\t\t\t);\n\t\t}\n\t\tlet body: unknown;\n\t\ttry {\n\t\t\tbody = JSON.parse(context.body ?? (await request.text()));\n\t\t} catch {\n\t\t\treturn rpcError(\n\t\t\t\t400,\n\t\t\t\tnull,\n\t\t\t\t-32700,\n\t\t\t\t\"Parse error: the request body is not valid JSON\",\n\t\t\t);\n\t\t}\n\t\tconst checked = check(request, body);\n\t\tif (checked instanceof Response) return checked;\n\t\tif (checked === \"notification\") return new Response(null, { status: 202 });\n\t\tconst { id, method, params } = checked;\n\t\tswitch (method) {\n\t\t\tcase \"server/discover\": {\n\t\t\t\tconst discover: Json = {\n\t\t\t\t\tsupportedVersions: [MCP_PROTOCOL_VERSION],\n\t\t\t\t\tcapabilities: { tools: { listChanged: true } },\n\t\t\t\t};\n\t\t\t\tif (server.instructions !== undefined)\n\t\t\t\t\tdiscover[\"instructions\"] = server.instructions;\n\t\t\t\tdiscover[\"ttlMs\"] = 0;\n\t\t\t\tdiscover[\"cacheScope\"] = \"private\";\n\t\t\t\treturn json(\n\t\t\t\t\t200,\n\t\t\t\t\tresult(id, discover, { [META_SERVER_INFO]: discoverInfo }),\n\t\t\t\t);\n\t\t\t}\n\t\t\tcase \"tools/list\":\n\t\t\t\treturn json(\n\t\t\t\t\t200,\n\t\t\t\t\tresult(id, { tools: listTools(), ttlMs: 0, cacheScope: \"private\" }),\n\t\t\t\t);\n\t\t\tcase \"tools/call\":\n\t\t\t\treturn callTool(id, params, request.signal, context.grant);\n\t\t\tcase \"subscriptions/listen\":\n\t\t\t\treturn listen(id, params, request.signal);\n\t\t\tdefault:\n\t\t\t\treturn rpcError(404, id, -32601, \"Method not found\");\n\t\t}\n\t}\n\n\treturn {\n\t\thandle: (request, context) =>\n\t\t\thandle(request, context).catch(() =>\n\t\t\t\trpcError(500, null, -32603, \"Internal server error\"),\n\t\t\t),\n\t\ttoolsChanged() {\n\t\t\tif (changeQueued) return;\n\t\t\tchangeQueued = true;\n\t\t\t// Several registrations in one task produce one notification.\n\t\t\tqueueMicrotask(() => {\n\t\t\t\tchangeQueued = false;\n\t\t\t\tfor (const listener of [...listeners]) {\n\t\t\t\t\tlistener.send({\n\t\t\t\t\t\tjsonrpc: \"2.0\",\n\t\t\t\t\t\tmethod: \"notifications/tools/list_changed\",\n\t\t\t\t\t\tparams: { _meta: { [META_SUBSCRIPTION]: listener.id } },\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t});\n\t\t},\n\t\tclose() {\n\t\t\tfor (const listener of [...listeners]) listener.end();\n\t\t},\n\t};\n}\n",
|
|
7
|
+
"/**\n * WebMCP → MCP mapping of annotations (DEC-022) and results (DEC-023).\n */\n\nimport type { ToolAnnotations } from \"./types.ts\";\n\n/** `_meta` key that keeps the original WebMCP hints. */\nexport const ANNOTATIONS_META_KEY = \"ch.ractive.tab-mcp/annotations\";\n\nconst WEBMCP_HINTS = [\n\t\"readOnlyHint\",\n\t\"untrustedContentHint\",\n\t\"consequentialHint\",\n\t\"debugging\",\n] as const;\nconst MCP_ONLY_HINTS = [\n\t\"destructiveHint\",\n\t\"idempotentHint\",\n\t\"openWorldHint\",\n] as const;\n\nexport interface McpToolAnnotations {\n\tannotations?: Record<string, boolean>;\n\tmeta?: Record<string, boolean>;\n}\n\n/** MCP annotations plus the WebMCP originals for `_meta`. */\nexport function mapAnnotations(hints: ToolAnnotations): McpToolAnnotations {\n\tconst annotations: Record<string, boolean> = {};\n\tif (hints.readOnlyHint === true) {\n\t\tannotations[\"readOnlyHint\"] = true;\n\t\tannotations[\"destructiveHint\"] = false;\n\t} else if (hints.readOnlyHint === false) {\n\t\tannotations[\"readOnlyHint\"] = false;\n\t}\n\tif (hints.consequentialHint === true) annotations[\"destructiveHint\"] = true;\n\tif (hints.untrustedContentHint === true) annotations[\"openWorldHint\"] = true;\n\tfor (const key of MCP_ONLY_HINTS) {\n\t\tconst value = hints[key];\n\t\tif (value !== undefined) annotations[key] = value; // MCP hints win\n\t}\n\tconst meta: Record<string, boolean> = {};\n\tfor (const key of WEBMCP_HINTS) {\n\t\tconst value = hints[key];\n\t\tif (value !== undefined) meta[key] = value;\n\t}\n\tconst out: McpToolAnnotations = {};\n\tif (Object.keys(annotations).length > 0) out.annotations = annotations;\n\tif (Object.keys(meta).length > 0) out.meta = meta;\n\treturn out;\n}\n\nexport interface CallToolResult {\n\tcontent: unknown[];\n\tstructuredContent?: Record<string, unknown>;\n\tisError?: boolean;\n\t[key: string]: unknown;\n}\n\nexport function errorResult(message: string): CallToolResult {\n\treturn { content: [{ type: \"text\", text: message }], isError: true };\n}\n\nfunction isPlainObject(v: unknown): v is Record<string, unknown> {\n\treturn typeof v === \"object\" && v !== null && !Array.isArray(v);\n}\n\n/**\n * What `execute` returned → a `CallToolResult`: a string is one text block; an\n * object with a `content` array passes through; `undefined` is an empty\n * result; any other JSON value is a text block with its JSON, plus\n * `structuredContent` when it is an object.\n */\nexport function toCallToolResult(value: unknown): CallToolResult {\n\tif (typeof value === \"string\")\n\t\treturn { content: [{ type: \"text\", text: value }] };\n\tif (value === undefined) return { content: [] };\n\tif (isPlainObject(value) && Array.isArray(value[\"content\"])) {\n\t\treturn value as CallToolResult;\n\t}\n\tlet text: string | undefined;\n\ttry {\n\t\ttext = JSON.stringify(value);\n\t} catch {\n\t\t// cyclic or BigInt\n\t}\n\tif (text === undefined)\n\t\treturn errorResult(\"The tool returned a value that is not JSON.\");\n\tconst result: CallToolResult = { content: [{ type: \"text\", text }] };\n\tif (isPlainObject(value)) result.structuredContent = value;\n\treturn result;\n}\n\n/** A thrown value → an `isError` result with its message. */\nexport function thrownResult(error: unknown): CallToolResult {\n\tconst message = error instanceof Error ? error.message : String(error);\n\treturn errorResult(message || \"The tool failed.\");\n}\n",
|
|
8
|
+
"/**\n * The tab↔relay protocol, version 1, as the tab speaks it\n * (`docs/protocol.md`, normative). Internal: not part of the public API.\n */\n\nimport type { Grant, Limits } from \"./types.ts\";\n\nexport const SUBPROTOCOL = \"tab-mcp.v1\";\n\n/** Who is calling a tunnelled request (the relay's view of the grant). */\nexport interface GrantRef {\n\tgrantId: string;\n\tclientId: string;\n\tscopes: string[];\n}\n\n// Relay → tab\n\nexport interface SessionMessage {\n\ttype: \"session\";\n\tsessionId: string;\n\taddress: string;\n\torigin: string;\n\tappName?: string;\n\t/** How AI apps pair: `code` or `oidc` (identity binding). Older relays omit it. */\n\tpairing?: \"code\" | \"oidc\";\n\texpiresAt: string;\n\tlimits: Limits;\n\tgrants: Grant[];\n}\nexport interface PingMessage {\n\ttype: \"ping\";\n\tt: number;\n}\nexport interface ByeMessage {\n\ttype: \"bye\";\n\treason: string;\n}\nexport interface HttpRequestMessage {\n\ttype: \"http.request\";\n\tid: string;\n\tmethod: string;\n\tpath: string;\n\theaders: Record<string, string>;\n\tbody: string;\n\tgrant: GrantRef;\n}\nexport interface HttpCancelMessage {\n\ttype: \"http.cancel\";\n\tid: string;\n\treason: string;\n}\nexport interface PairingCodeMessage {\n\ttype: \"pairing.code\";\n\tcode: string;\n\texpiresAt: string;\n\t/** Why it came; left out by older relays, and when it is not one of these. */\n\treason?: \"start\" | \"used\" | \"locked\" | \"expired\";\n}\n\nconst CODE_REASONS = new Set([\"start\", \"used\", \"locked\", \"expired\"]);\nexport interface GrantAddedMessage {\n\ttype: \"grant.added\";\n\tgrant: Grant;\n}\nexport interface GrantRemovedMessage {\n\ttype: \"grant.removed\";\n\tgrantId: string;\n\treason: string;\n}\nexport interface IdentityBoundMessage {\n\ttype: \"identity.bound\";\n\t/** The `round` of the `identity` this answers. */\n\tround?: number;\n}\nexport interface ErrorMessage {\n\ttype: \"error\";\n\tcode: string;\n\tmessage: string;\n\tid?: string;\n\t/** On `identity_refused`: the `round` of the `identity` it answers. */\n\tround?: number;\n}\nexport type RelayMessage =\n\t| SessionMessage\n\t| PingMessage\n\t| ByeMessage\n\t| HttpRequestMessage\n\t| HttpCancelMessage\n\t| PairingCodeMessage\n\t| GrantAddedMessage\n\t| GrantRemovedMessage\n\t| IdentityBoundMessage\n\t| ErrorMessage;\n\n// Tab → relay\n\nexport type TabMessage =\n\t| {\n\t\t\ttype: \"hello\";\n\t\t\tlibrary: { name: string; version: string };\n\t\t\tpage: { title: string };\n\t\t\tapp?: { name: string };\n\t\t\tsecret: string;\n\t\t\t/** Take the address back: the relay revokes its grants as it claims it (DEC-095). */\n\t\t\trevokeAll?: true;\n\t }\n\t| { type: \"pong\"; t: number }\n\t| { type: \"bye\"; reason: string }\n\t| {\n\t\t\ttype: \"http.response\";\n\t\t\tid: string;\n\t\t\tstatus: number;\n\t\t\theaders: Record<string, string>;\n\t\t\tbody: string;\n\t }\n\t| {\n\t\t\ttype: \"http.response.start\";\n\t\t\tid: string;\n\t\t\tstatus: number;\n\t\t\theaders: Record<string, string>;\n\t }\n\t| { type: \"http.response.chunk\"; id: string; data: string }\n\t| { type: \"http.response.end\"; id: string }\n\t| { type: \"pairing.start\" }\n\t| { type: \"pairing.stop\" }\n\t| { type: \"grant.revoke\"; grantId: string }\n\t| { type: \"grants.revokeAll\" }\n\t| { type: \"identity\"; assertion: string; round: number }\n\t| { type: \"identity.logout\" }\n\t| { type: \"error\"; code: string; message: string; id?: string };\n\ntype Json = Record<string, unknown>;\n\nfunction isObject(v: unknown): v is Json {\n\treturn typeof v === \"object\" && v !== null && !Array.isArray(v);\n}\n\nconst str = (v: unknown): v is string => typeof v === \"string\";\n\nfunction isGrant(v: unknown): v is Grant {\n\tif (!isObject(v) || !str(v[\"grantId\"]) || !str(v[\"createdAt\"])) return false;\n\tconst c = v[\"client\"];\n\treturn isObject(c) && str(c[\"id\"]) && str(c[\"name\"]) && str(c[\"host\"]);\n}\n\nfunction isLimits(v: unknown): v is Limits {\n\tif (!isObject(v)) return false;\n\treturn [\n\t\t\"maxMessageBytes\",\n\t\t\"maxBodyBytes\",\n\t\t\"requestTimeoutMs\",\n\t\t\"idleTimeoutMs\",\n\t\t\"heartbeatMs\",\n\t\t\"keepAliveMs\",\n\t\t\"maxConcurrentRequests\",\n\t].every((k) => typeof v[k] === \"number\");\n}\n\nfunction isStringRecord(v: unknown): v is Record<string, string> {\n\treturn isObject(v) && Object.values(v).every(str);\n}\n\n/**\n * Parse one frame from the relay. Returns `undefined` for anything malformed\n * or unknown; the caller ignores it (forward compatibility).\n */\nexport function parseRelayMessage(text: string): RelayMessage | undefined {\n\tlet v: unknown;\n\ttry {\n\t\tv = JSON.parse(text);\n\t} catch {\n\t\treturn undefined;\n\t}\n\tif (!isObject(v)) return undefined;\n\tswitch (v[\"type\"]) {\n\t\tcase \"session\":\n\t\t\treturn str(v[\"sessionId\"]) &&\n\t\t\t\tstr(v[\"address\"]) &&\n\t\t\t\tstr(v[\"origin\"]) &&\n\t\t\t\tstr(v[\"expiresAt\"]) &&\n\t\t\t\tisLimits(v[\"limits\"]) &&\n\t\t\t\tArray.isArray(v[\"grants\"]) &&\n\t\t\t\tv[\"grants\"].every(isGrant) &&\n\t\t\t\t(v[\"appName\"] === undefined || str(v[\"appName\"])) &&\n\t\t\t\t(v[\"pairing\"] === undefined || str(v[\"pairing\"]))\n\t\t\t\t? (v as unknown as SessionMessage)\n\t\t\t\t: undefined;\n\t\tcase \"ping\":\n\t\t\treturn typeof v[\"t\"] === \"number\"\n\t\t\t\t? (v as unknown as PingMessage)\n\t\t\t\t: undefined;\n\t\tcase \"bye\":\n\t\t\treturn { type: \"bye\", reason: str(v[\"reason\"]) ? v[\"reason\"] : \"\" };\n\t\tcase \"http.request\":\n\t\t\treturn str(v[\"id\"]) &&\n\t\t\t\tstr(v[\"method\"]) &&\n\t\t\t\tstr(v[\"path\"]) &&\n\t\t\t\tisStringRecord(v[\"headers\"]) &&\n\t\t\t\tstr(v[\"body\"]) &&\n\t\t\t\tisObject(v[\"grant\"]) &&\n\t\t\t\tstr(v[\"grant\"][\"grantId\"]) &&\n\t\t\t\tstr(v[\"grant\"][\"clientId\"])\n\t\t\t\t? (v as unknown as HttpRequestMessage)\n\t\t\t\t: undefined;\n\t\tcase \"http.cancel\":\n\t\t\treturn str(v[\"id\"]) ? (v as unknown as HttpCancelMessage) : undefined;\n\t\tcase \"pairing.code\": {\n\t\t\tif (!str(v[\"code\"]) || !str(v[\"expiresAt\"])) return undefined;\n\t\t\tconst message: PairingCodeMessage = {\n\t\t\t\ttype: \"pairing.code\",\n\t\t\t\tcode: v[\"code\"],\n\t\t\t\texpiresAt: v[\"expiresAt\"],\n\t\t\t};\n\t\t\t// An unknown reason (a newer relay) counts as none.\n\t\t\tconst reason = v[\"reason\"];\n\t\t\tif (typeof reason === \"string\" && CODE_REASONS.has(reason))\n\t\t\t\tmessage.reason = reason as NonNullable<PairingCodeMessage[\"reason\"]>;\n\t\t\treturn message;\n\t\t}\n\t\tcase \"grant.added\":\n\t\t\treturn isGrant(v[\"grant\"])\n\t\t\t\t? (v as unknown as GrantAddedMessage)\n\t\t\t\t: undefined;\n\t\tcase \"grant.removed\":\n\t\t\treturn str(v[\"grantId\"])\n\t\t\t\t? {\n\t\t\t\t\t\ttype: \"grant.removed\",\n\t\t\t\t\t\tgrantId: v[\"grantId\"],\n\t\t\t\t\t\treason: str(v[\"reason\"]) ? v[\"reason\"] : \"\",\n\t\t\t\t\t}\n\t\t\t\t: undefined;\n\t\tcase \"identity.bound\":\n\t\t\treturn typeof v[\"round\"] === \"number\"\n\t\t\t\t? { type: \"identity.bound\", round: v[\"round\"] }\n\t\t\t\t: { type: \"identity.bound\" };\n\t\tcase \"error\":\n\t\t\treturn str(v[\"code\"]) ? (v as unknown as ErrorMessage) : undefined;\n\t\tdefault:\n\t\t\treturn undefined;\n\t}\n}\n",
|
|
9
|
+
"/**\n * The address id in the `/tab` URL (DEC-098): a load balancer in front of\n * several relays routes every request of one address to one instance by it.\n * Part of the lazily loaded chunk (DEC-035), not the core.\n */\n\nconst BASE32 = \"abcdefghijklmnopqrstuvwxyz234567\";\n\n/** RFC 4648 base32, lower case, without padding (the relay's address ids). */\nfunction base32(bytes: Uint8Array): string {\n\tlet out = \"\";\n\tlet buffer = 0;\n\tlet bits = 0;\n\tfor (const byte of bytes) {\n\t\tbuffer = (buffer << 8) | byte;\n\t\tbits += 8;\n\t\twhile (bits >= 5) {\n\t\t\tbits -= 5;\n\t\t\tout += BASE32[(buffer >>> bits) & 31];\n\t\t}\n\t\tbuffer &= (1 << bits) - 1;\n\t}\n\tif (bits > 0) out += BASE32[(buffer << (5 - bits)) & 31];\n\treturn out;\n}\n\n/**\n * The address id of a secret, as the relay derives it (DEC-027):\n * base32(sha256(secret)). `undefined` where Web Crypto is missing (`null`: a\n * page on plain http other than localhost) or fails; the URL then has no id,\n * which one relay accepts and only a load balancer cannot route.\n */\nexport async function addressIdOf(\n\tsecret: string,\n\tsubtle: SubtleCrypto | null = globalThis.crypto?.subtle ?? null,\n): Promise<string | undefined> {\n\tif (subtle === null) return undefined;\n\ttry {\n\t\tconst digest = await subtle.digest(\n\t\t\t\"SHA-256\",\n\t\t\tnew TextEncoder().encode(secret),\n\t\t);\n\t\treturn base32(new Uint8Array(digest));\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\n/** The `/tab` URL with `?a=<id>`. Never the secret: URLs end up in logs. */\nexport function withAddress(url: string, address: string | undefined): string {\n\tif (address === undefined) return url;\n\tconst u = new URL(url);\n\tu.searchParams.set(\"a\", address);\n\treturn u.href;\n}\n",
|
|
10
|
+
"/**\n * The lazily loaded part (DEC-035): the WebSocket session with the relay, the\n * HTTP tunnel and the MCP handler. Loaded by `TabMcp.connect()`.\n */\n\nimport { pageIcons } from \"./icons.ts\";\nimport type { CallHost, ConnectionHandle, ConnectionHost } from \"./internal.ts\";\nimport { type CallContext, createMcpHandler, webMcpCall } from \"./mcp.ts\";\nimport {\n\ttype HttpRequestMessage,\n\tparseRelayMessage,\n\ttype RelayMessage,\n\tSUBPROTOCOL,\n\ttype TabMessage,\n} from \"./protocol.ts\";\nimport type { RegisteredTool } from \"./registry.ts\";\nimport type { DisconnectReason, SessionInfo } from \"./types.ts\";\n\n/** For the core: the address id in the `/tab` URL (DEC-098). */\nexport { addressIdOf, withAddress } from \"./address.ts\";\n/** For the core: compiles the schemas once this chunk (and the validator) is loaded. */\nexport { compileRegistry } from \"./mcp.ts\";\n\n/** What a call through the relay or WebMCP needs (`mcp.ts`), from the core's host. */\nfunction callContext(host: CallHost): CallContext {\n\treturn {\n\t\ttools: host.registry,\n\t\tconfirm: (request) => host.confirm(request),\n\t\tobserve: {\n\t\t\tstart: (call) => host.toolCallStarted(call),\n\t\t\tend: (call) => host.toolCallEnded(call),\n\t\t},\n\t};\n}\n\n/**\n * For the core: a WebMCP call of a mirrored tool (iteration 25), on the\n * same path as an AI app's (`webMcpCall` in `mcp.ts`).\n */\nexport function callFromWebMcp(\n\thost: CallHost,\n\ttool: RegisteredTool,\n\tinput: unknown,\n\tsignal: unknown,\n): Promise<unknown> {\n\treturn webMcpCall(callContext(host), tool, input, signal);\n}\n\n/** How long `connect()` waits for the relay's `session`. */\nconst CONNECT_TIMEOUT_MS = 15_000;\n\nconst CLOSE_REASONS: Record<number, DisconnectReason> = {\n\t1000: \"closed\",\n\t1008: \"policy\",\n\t1009: \"too_large\",\n\t4001: \"expired\",\n\t4002: \"idle\",\n\t4003: \"heartbeat\",\n\t4004: \"shutdown\",\n\t4005: \"replaced\",\n\t4008: \"rate_limited\",\n\t/** The URL's address id is not the secret's (DEC-098): retrying cannot help. */\n\t4009: \"policy\",\n};\n\nconst BYE_REASONS: Record<string, DisconnectReason> = {\n\treplaced: \"replaced\",\n\texpired: \"expired\",\n\tidle: \"idle\",\n\tshutdown: \"shutdown\",\n};\n\n/**\n * An error of `ready` that says why the connection did not open, so that\n * reconnecting retries only what may get better (DEC-082).\n */\nfunction refused(message: string, reason: DisconnectReason): Error {\n\treturn Object.assign(new Error(message), { reason });\n}\n\n/** Response headers the relay passes on (it drops the rest). */\nconst RESPONSE_HEADERS = [\"content-type\", \"cache-control\"];\n\nfunction pageTitle(): string {\n\tconst title = (globalThis as { document?: { title?: unknown } }).document\n\t\t?.title;\n\treturn typeof title === \"string\" ? title.slice(0, 300) : \"\";\n}\n\nfunction frameInfo(text: string): { type: string; id?: string } | undefined {\n\ttry {\n\t\tconst v = JSON.parse(text) as Record<string, unknown>;\n\t\tif (typeof v !== \"object\" || v === null || typeof v[\"type\"] !== \"string\")\n\t\t\treturn undefined;\n\t\treturn typeof v[\"id\"] === \"string\"\n\t\t\t? { type: v[\"type\"], id: v[\"id\"] }\n\t\t\t: { type: v[\"type\"] };\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\nconst KNOWN_TYPES = new Set([\n\t\"session\",\n\t\"ping\",\n\t\"bye\",\n\t\"http.request\",\n\t\"http.cancel\",\n\t\"pairing.code\",\n\t\"grant.added\",\n\t\"grant.removed\",\n\t\"identity.bound\",\n\t\"error\",\n]);\n\n/**\n * Room for a message's envelope (`http.response` with its headers, or a\n * chunk) with an id of up to 128 characters (protocol limit).\n */\nconst ENVELOPE_BYTES = 512;\n/** Worst case per UTF-16 unit once JSON-encoded as UTF-8: `\\u0001` is 6 bytes. */\nconst WORST_BYTES_PER_UNIT = 6;\nconst MIN_CHUNK_UNITS = 64;\nexport const MIN_MESSAGE_BYTES: number =\n\tENVELOPE_BYTES + WORST_BYTES_PER_UNIT * MIN_CHUNK_UNITS;\n\n/**\n * The largest piece of body text (UTF-16 units) whose message cannot exceed\n * the relay's `maxMessageBytes`; `undefined` if the limit is too small to\n * frame anything useful.\n */\nexport function chunkSize(maxMessageBytes: number): number | undefined {\n\tconst units = Math.floor(\n\t\t(maxMessageBytes - ENVELOPE_BYTES) / WORST_BYTES_PER_UNIT,\n\t);\n\treturn units >= MIN_CHUNK_UNITS ? units : undefined;\n}\n\n/**\n * Split text into pieces of at most `max` UTF-16 units, never between the two\n * halves of a surrogate pair (a lone half would not survive JSON and UTF-8).\n */\nexport function* pieces(text: string, max: number): Generator<string> {\n\tlet i = 0;\n\twhile (i < text.length) {\n\t\tlet end = Math.min(i + max, text.length);\n\t\tconst last = text.charCodeAt(end - 1);\n\t\tif (end < text.length && last >= 0xd800 && last <= 0xdbff) {\n\t\t\tend += end - 1 > i ? -1 : 1; // keep the pair together\n\t\t}\n\t\tyield text.slice(i, end);\n\t\ti = end;\n\t}\n}\n\n/**\n * How long after a sibling tab's `claimed` a `replaced` counts as caused by\n * it (DEC-095). That tab posts it when the relay accepted its session, which\n * is when the relay ended this one.\n */\nexport const SIBLING_WINDOW_MS = 10_000;\n\n/**\n * How long a replaced tab that heard no `claimed` yet waits for one before it\n * reports `replaced`: the sibling's session and this tab's `bye` leave the\n * relay at about the same time, so the message usually comes after the `bye`.\n */\nexport const SIBLING_GRACE_MS = 1_000;\n\n/**\n * The tabs of one page (same relay, same secret) tell each other on a\n * `BroadcastChannel` when the relay accepted their claim of the address\n * (`claimed`, once their `session` arrived), so that a replaced tab can tell\n * a sibling from an impostor. A sibling whose `hello` failed says nothing.\n * Nothing else goes on the channel: no secret, no address. Without\n * `BroadcastChannel` nothing is heard, and every `replaced` counts as unknown.\n */\nfunction siblingTabs(name: string | undefined): {\n\tclaimed(): void;\n\t/** `true` once `claimed` was heard in the window, `false` after the grace. */\n\theard(): Promise<boolean>;\n\tclose(): void;\n} {\n\tlet channel: BroadcastChannel | undefined;\n\tlet at = Number.NEGATIVE_INFINITY;\n\tlet onClaim: (() => void) | undefined;\n\ttry {\n\t\tif (name !== undefined && typeof BroadcastChannel === \"function\") {\n\t\t\tchannel = new BroadcastChannel(name);\n\t\t\tchannel.onmessage = (event: MessageEvent) => {\n\t\t\t\tif ((event.data as { type?: unknown } | null)?.type !== \"claimed\")\n\t\t\t\t\treturn;\n\t\t\t\tat = Date.now();\n\t\t\t\tonClaim?.();\n\t\t\t};\n\t\t}\n\t} catch {\n\t\tchannel = undefined; // e.g. an opaque origin\n\t}\n\treturn {\n\t\tclaimed() {\n\t\t\ttry {\n\t\t\t\tchannel?.postMessage({ type: \"claimed\" });\n\t\t\t} catch {\n\t\t\t\t// closed or not allowed: the other tab counts it as unknown\n\t\t\t}\n\t\t},\n\t\theard() {\n\t\t\tif (Date.now() - at <= SIBLING_WINDOW_MS) return Promise.resolve(true);\n\t\t\tif (channel === undefined) return Promise.resolve(false);\n\t\t\treturn new Promise((resolve) => {\n\t\t\t\tconst timer = setTimeout(() => resolve(false), SIBLING_GRACE_MS);\n\t\t\t\tonClaim = () => {\n\t\t\t\t\tclearTimeout(timer);\n\t\t\t\t\tresolve(true);\n\t\t\t\t};\n\t\t\t});\n\t\t},\n\t\tclose() {\n\t\t\tchannel?.close();\n\t\t},\n\t};\n}\n\n/**\n * Open the WebSocket and run the session. `revokeAll`: take the address back\n * (DEC-095); `ready` resolves only once the relay has no grant of the address\n * left, and rejects if the session ends first.\n */\nexport function openConnection(\n\thost: ConnectionHost,\n\turl: string,\n\tsecret: string,\n\trevokeAll = false,\n): ConnectionHandle {\n\tconst ws = new WebSocket(url, SUBPROTOCOL);\n\tconst inflight = new Map<string, AbortController>();\n\tlet state: \"opening\" | \"ready\" | \"closed\" = \"opening\";\n\tlet byeReason: DisconnectReason | undefined;\n\tlet maxChunk = 64 * 1024;\n\tlet heartbeat: ReturnType<typeof setTimeout> | undefined;\n\tlet heartbeatMs = 0;\n\tconst siblings = siblingTabs(host.tabs);\n\t/**\n\t * Taking the address back from a relay that ignored `hello.revokeAll` (0.4\n\t * and older): the grants still to go after `grants.revokeAll`, and the\n\t * session to resolve with then.\n\t */\n\tlet revoking: { left: Set<string>; session: SessionInfo } | undefined;\n\n\tlet resolveReady!: (session: SessionInfo) => void;\n\tlet rejectReady!: (error: Error) => void;\n\tconst ready = new Promise<SessionInfo>((resolve, reject) => {\n\t\tresolveReady = resolve;\n\t\trejectReady = reject;\n\t});\n\tready.catch(() => {}); // the caller handles it; never an unhandled rejection here\n\tconst connectTimer = setTimeout(() => {\n\t\tfail(refused(\"The relay did not answer in time.\", \"network\"));\n\t}, CONNECT_TIMEOUT_MS);\n\n\tconst handler = createMcpHandler({\n\t\t...callContext(host),\n\t\t// Without `icons`, the page's own <link rel=\"icon\">, read now.\n\t\tserver: { ...host.server, icons: host.server.icons ?? pageIcons() },\n\t\tclient: (grant) => host.clientFor(grant),\n\t});\n\tconst stopWatching = host.registry.onChange(() => handler.toolsChanged());\n\n\tfunction send(message: TabMessage): boolean {\n\t\tif (ws.readyState !== WebSocket.OPEN) return false;\n\t\ttry {\n\t\t\tws.send(JSON.stringify(message));\n\t\t\treturn true;\n\t\t} catch {\n\t\t\treturn false;\n\t\t}\n\t}\n\n\t/** Two missed pings mean the connection is dead (protocol: heartbeat). */\n\tfunction armHeartbeat(): void {\n\t\tif (heartbeatMs <= 0) return;\n\t\tclearTimeout(heartbeat);\n\t\theartbeat = setTimeout(() => {\n\t\t\tbyeReason ??= \"heartbeat\";\n\t\t\tfinish(4003);\n\t\t\ttry {\n\t\t\t\tws.close();\n\t\t\t} catch {\n\t\t\t\t// already closing\n\t\t\t}\n\t\t}, heartbeatMs * 2.5);\n\t}\n\n\tfunction fail(error: Error): void {\n\t\tif (state !== \"opening\") return;\n\t\tfinish(0);\n\t\trejectReady(error);\n\t\ttry {\n\t\t\tws.close();\n\t\t} catch {\n\t\t\t// already closed\n\t\t}\n\t}\n\n\t/** The session is over: clean up once and tell the host. */\n\tfunction finish(code: number): void {\n\t\tif (state === \"closed\") return;\n\t\tconst wasReady = state === \"ready\";\n\t\tstate = \"closed\";\n\t\tclearTimeout(connectTimer);\n\t\tclearTimeout(heartbeat);\n\t\tstopWatching();\n\t\tfor (const controller of inflight.values()) controller.abort();\n\t\tinflight.clear();\n\t\thandler.close();\n\t\tif (wasReady) {\n\t\t\tconst reason =\n\t\t\t\tbyeReason ??\n\t\t\t\tCLOSE_REASONS[code] ??\n\t\t\t\t(code === 1006 ? \"network\" : \"closed\");\n\t\t\t// The grants of a taken-back address did not all go (DEC-095).\n\t\t\trejectReady(\n\t\t\t\trefused(\n\t\t\t\t\t\"The address was taken over again before its AI apps were disconnected.\",\n\t\t\t\t\treason,\n\t\t\t\t),\n\t\t\t);\n\t\t\t// Over at once; only the detail of `replaced` waits for a sibling's\n\t\t\t// `claimed`, which comes a moment after the `bye` (DEC-095).\n\t\t\thost.closed(reason, code);\n\t\t\tif (reason === \"replaced\") {\n\t\t\t\tvoid siblings.heard().then((sibling) => {\n\t\t\t\t\tsiblings.close();\n\t\t\t\t\thost.replaced({ sibling });\n\t\t\t\t});\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t\tsiblings.close();\n\t}\n\n\tasync function tunnel(msg: HttpRequestMessage): Promise<void> {\n\t\tconst controller = new AbortController();\n\t\tinflight.set(msg.id, controller);\n\t\tconst live = () =>\n\t\t\tstate === \"ready\" &&\n\t\t\tinflight.get(msg.id) === controller &&\n\t\t\t!controller.signal.aborted;\n\t\ttry {\n\t\t\tconst request = new Request(`https://tab.invalid${msg.path}`, {\n\t\t\t\tmethod: msg.method,\n\t\t\t\theaders: msg.headers,\n\t\t\t\tsignal: controller.signal,\n\t\t\t});\n\t\t\tconst response = await handler.handle(request, {\n\t\t\t\tgrant: msg.grant,\n\t\t\t\tbody: msg.body,\n\t\t\t});\n\t\t\tif (!live()) {\n\t\t\t\tawait response.body?.cancel().catch(() => {});\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst headers: Record<string, string> = {};\n\t\t\tfor (const name of RESPONSE_HEADERS) {\n\t\t\t\tconst value = response.headers.get(name);\n\t\t\t\tif (value !== null) headers[name] = value;\n\t\t\t}\n\t\t\tconst streamed = (headers[\"content-type\"] ?? \"\").startsWith(\n\t\t\t\t\"text/event-stream\",\n\t\t\t);\n\t\t\tif (!streamed || response.body === null) {\n\t\t\t\tconst body = await response.text();\n\t\t\t\tif (!live()) return;\n\t\t\t\tif (body.length <= maxChunk) {\n\t\t\t\t\tsend({\n\t\t\t\t\t\ttype: \"http.response\",\n\t\t\t\t\t\tid: msg.id,\n\t\t\t\t\t\tstatus: response.status,\n\t\t\t\t\t\theaders,\n\t\t\t\t\t\tbody,\n\t\t\t\t\t});\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\t// Too big for one message: stream it (the relay passes it on whole).\n\t\t\t\tsend({\n\t\t\t\t\ttype: \"http.response.start\",\n\t\t\t\t\tid: msg.id,\n\t\t\t\t\tstatus: response.status,\n\t\t\t\t\theaders,\n\t\t\t\t});\n\t\t\t\tfor (const data of pieces(body, maxChunk)) {\n\t\t\t\t\tif (!live()) break;\n\t\t\t\t\tsend({ type: \"http.response.chunk\", id: msg.id, data });\n\t\t\t\t}\n\t\t\t\tif (live()) send({ type: \"http.response.end\", id: msg.id });\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tsend({\n\t\t\t\ttype: \"http.response.start\",\n\t\t\t\tid: msg.id,\n\t\t\t\tstatus: response.status,\n\t\t\t\theaders,\n\t\t\t});\n\t\t\tconst reader = response.body.getReader();\n\t\t\tconst decoder = new TextDecoder();\n\t\t\tcontroller.signal.addEventListener(\"abort\", () => {\n\t\t\t\treader.cancel().catch(() => {});\n\t\t\t});\n\t\t\tfor (;;) {\n\t\t\t\tconst { done, value } = await reader.read();\n\t\t\t\tif (done || !live()) break;\n\t\t\t\tconst text = decoder.decode(value, { stream: true });\n\t\t\t\tfor (const data of pieces(text, maxChunk)) {\n\t\t\t\t\tsend({ type: \"http.response.chunk\", id: msg.id, data });\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (live()) send({ type: \"http.response.end\", id: msg.id });\n\t\t} catch (error) {\n\t\t\tif (live()) {\n\t\t\t\thost.error(error instanceof Error ? error : new Error(String(error)));\n\t\t\t\tsend({\n\t\t\t\t\ttype: \"http.response\",\n\t\t\t\t\tid: msg.id,\n\t\t\t\t\tstatus: 500,\n\t\t\t\t\theaders: { \"content-type\": \"application/json\" },\n\t\t\t\t\tbody: JSON.stringify({\n\t\t\t\t\t\tjsonrpc: \"2.0\",\n\t\t\t\t\t\tid: null,\n\t\t\t\t\t\terror: { code: -32603, message: \"Internal server error\" },\n\t\t\t\t\t}),\n\t\t\t\t});\n\t\t\t}\n\t\t} finally {\n\t\t\tif (inflight.get(msg.id) === controller) inflight.delete(msg.id);\n\t\t}\n\t}\n\n\tfunction onMessage(message: RelayMessage): void {\n\t\tif (state === \"opening\") {\n\t\t\tif (message.type === \"session\") {\n\t\t\t\tconst chunk = chunkSize(message.limits.maxMessageBytes);\n\t\t\t\tif (chunk === undefined) {\n\t\t\t\t\tfail(\n\t\t\t\t\t\trefused(\n\t\t\t\t\t\t\t`The relay's message limit (${message.limits.maxMessageBytes} bytes) is too small; tab-mcp needs at least ${MIN_MESSAGE_BYTES}.`,\n\t\t\t\t\t\t\t\"policy\",\n\t\t\t\t\t\t),\n\t\t\t\t\t);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tmaxChunk = chunk;\n\t\t\t\tstate = \"ready\";\n\t\t\t\tclearTimeout(connectTimer);\n\t\t\t\theartbeatMs = message.limits.heartbeatMs;\n\t\t\t\tarmHeartbeat();\n\t\t\t\tsiblings.claimed();\n\t\t\t\tconst session = host.sessionStarted(message);\n\t\t\t\tif (revokeAll && message.grants.length > 0) {\n\t\t\t\t\t// A relay that ignored hello.revokeAll: revoke now, and wait until\n\t\t\t\t\t// it has removed every grant.\n\t\t\t\t\trevoking = {\n\t\t\t\t\t\tleft: new Set(message.grants.map((g) => g.grantId)),\n\t\t\t\t\t\tsession,\n\t\t\t\t\t};\n\t\t\t\t\tsend({ type: \"grants.revokeAll\" });\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tresolveReady(session);\n\t\t\t} else if (message.type === \"error\") {\n\t\t\t\tfail(\n\t\t\t\t\trefused(\n\t\t\t\t\t\t`The relay refused the connection: ${message.message || message.code}`,\n\t\t\t\t\t\tmessage.code === \"rate_limited\" ? \"rate_limited\" : \"policy\",\n\t\t\t\t\t),\n\t\t\t\t);\n\t\t\t} else if (message.type === \"bye\") {\n\t\t\t\tfail(\n\t\t\t\t\trefused(\n\t\t\t\t\t\t`The relay ended the connection: ${message.reason}`,\n\t\t\t\t\t\tBYE_REASONS[message.reason] ?? \"closed\",\n\t\t\t\t\t),\n\t\t\t\t);\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\t\tif (state !== \"ready\") return;\n\t\tswitch (message.type) {\n\t\t\tcase \"ping\":\n\t\t\t\tarmHeartbeat();\n\t\t\t\tsend({ type: \"pong\", t: message.t });\n\t\t\t\treturn;\n\t\t\tcase \"http.request\":\n\t\t\t\tvoid tunnel(message);\n\t\t\t\treturn;\n\t\t\tcase \"http.cancel\":\n\t\t\t\tinflight.get(message.id)?.abort();\n\t\t\t\tinflight.delete(message.id);\n\t\t\t\treturn;\n\t\t\tcase \"pairing.code\":\n\t\t\t\thost.pairingCode(\n\t\t\t\t\tmessage.reason === undefined\n\t\t\t\t\t\t? { code: message.code, expiresAt: message.expiresAt }\n\t\t\t\t\t\t: {\n\t\t\t\t\t\t\t\tcode: message.code,\n\t\t\t\t\t\t\t\texpiresAt: message.expiresAt,\n\t\t\t\t\t\t\t\treason: message.reason,\n\t\t\t\t\t\t\t},\n\t\t\t\t);\n\t\t\t\treturn;\n\t\t\tcase \"grant.added\":\n\t\t\t\thost.grantAdded(message.grant);\n\t\t\t\treturn;\n\t\t\tcase \"grant.removed\":\n\t\t\t\thost.grantRemoved(message.grantId);\n\t\t\t\trevoking?.left.delete(message.grantId);\n\t\t\t\tif (revoking?.left.size === 0) resolveReady(revoking.session);\n\t\t\t\treturn;\n\t\t\tcase \"identity.bound\":\n\t\t\t\thost.identityResult(true, message.round);\n\t\t\t\treturn;\n\t\t\tcase \"bye\":\n\t\t\t\tbyeReason = BYE_REASONS[message.reason] ?? \"closed\";\n\t\t\t\t// Taken over: over at once, not when the socket closes (review of PR 39).\n\t\t\t\tif (byeReason === \"replaced\") finish(4005);\n\t\t\t\treturn;\n\t\t\tcase \"error\":\n\t\t\t\tif (message.code === \"identity_refused\") {\n\t\t\t\t\thost.identityResult(\n\t\t\t\t\t\tfalse,\n\t\t\t\t\t\ttypeof message.round === \"number\" ? message.round : undefined,\n\t\t\t\t\t\tmessage.message,\n\t\t\t\t\t);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\thost.error(\n\t\t\t\t\tnew Error(`Relay error ${message.code}: ${message.message}`),\n\t\t\t\t);\n\t\t\t\treturn;\n\t\t\tcase \"session\":\n\t\t\t\treturn; // only once\n\t\t}\n\t}\n\n\tws.addEventListener(\"open\", () => {\n\t\tif (ws.protocol !== \"\" && ws.protocol !== SUBPROTOCOL) {\n\t\t\tfail(\n\t\t\t\trefused(\n\t\t\t\t\t`The relay speaks ${ws.protocol}, not ${SUBPROTOCOL}.`,\n\t\t\t\t\t\"policy\",\n\t\t\t\t),\n\t\t\t);\n\t\t\treturn;\n\t\t}\n\t\tconst hello: TabMessage = {\n\t\t\ttype: \"hello\",\n\t\t\tlibrary: host.library,\n\t\t\tpage: { title: pageTitle() },\n\t\t\tsecret,\n\t\t};\n\t\tif (host.appName !== undefined) hello.app = { name: host.appName };\n\t\tif (revokeAll) hello.revokeAll = true;\n\t\tsend(hello);\n\t});\n\tws.addEventListener(\"message\", (event: MessageEvent) => {\n\t\tif (typeof event.data !== \"string\") return;\n\t\tconst message = parseRelayMessage(event.data);\n\t\tif (message !== undefined) {\n\t\t\tif (state === \"ready\") armHeartbeat(); // any traffic shows the link is alive\n\t\t\tonMessage(message);\n\t\t\treturn;\n\t\t}\n\t\tconst info = frameInfo(event.data);\n\t\tif (info?.id !== undefined) {\n\t\t\tsend(\n\t\t\t\tKNOWN_TYPES.has(info.type)\n\t\t\t\t\t? {\n\t\t\t\t\t\t\ttype: \"error\",\n\t\t\t\t\t\t\tcode: \"bad_message\",\n\t\t\t\t\t\t\tmessage: `malformed ${info.type}`,\n\t\t\t\t\t\t\tid: info.id,\n\t\t\t\t\t\t}\n\t\t\t\t\t: {\n\t\t\t\t\t\t\ttype: \"error\",\n\t\t\t\t\t\t\tcode: \"unknown_type\",\n\t\t\t\t\t\t\tmessage: `unknown type ${info.type}`,\n\t\t\t\t\t\t\tid: info.id,\n\t\t\t\t\t\t},\n\t\t\t);\n\t\t}\n\t});\n\tws.addEventListener(\"close\", (event: CloseEvent) => {\n\t\tif (state === \"opening\") {\n\t\t\tfinish(event.code);\n\t\t\t// No WebSocket at all: browsers say 1006, Bun 1002. The page cannot\n\t\t\t// tell a refused origin from an unreachable relay (DEC-082).\n\t\t\tconst unreachable = event.code === 1006 || event.code === 1002;\n\t\t\trejectReady(\n\t\t\t\trefused(\n\t\t\t\t\tunreachable\n\t\t\t\t\t\t? \"Could not connect to the relay (refused, unreachable, or this page's origin is not allowed).\"\n\t\t\t\t\t\t: `The relay closed the connection (${event.code}${event.reason ? `: ${event.reason}` : \"\"}).`,\n\t\t\t\t\tCLOSE_REASONS[event.code] ?? (unreachable ? \"network\" : \"closed\"),\n\t\t\t\t),\n\t\t\t);\n\t\t\treturn;\n\t\t}\n\t\tfinish(event.code);\n\t});\n\n\treturn {\n\t\tready,\n\t\tsend,\n\t\tclose(reason: DisconnectReason) {\n\t\t\tif (state === \"closed\") return;\n\t\t\tif (state === \"opening\") {\n\t\t\t\tfail(\n\t\t\t\t\tnew DOMException(\n\t\t\t\t\t\t\"The connection was cancelled\",\n\t\t\t\t\t\t\"AbortError\",\n\t\t\t\t\t) as Error,\n\t\t\t\t);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tbyeReason = reason;\n\t\t\tsend({ type: \"bye\", reason: \"user\" });\n\t\t\tfinish(1000);\n\t\t\ttry {\n\t\t\t\tws.close(1000, \"bye\");\n\t\t\t} catch {\n\t\t\t\t// already closed\n\t\t\t}\n\t\t},\n\t};\n}\n"
|
|
11
|
+
],
|
|
12
|
+
"mappings": ";AAQA,IAAM,YAAY;AAClB,IAAM,UAAU;AAChB,IAAM,WAAW;AACjB,IAAM,OAAO;AAOb,SAAS,KAAK,CAAC,MAA8B;AAAA,EAC5C,QAAQ,KAAK,UAAU,OAAO,UAAU;AAAA,EACxC,IAAI,OAAO,QAAQ;AAAA,IAAU;AAAA,EAC7B,MAAM,MAAM,YAAY,KAAK,GAAG,KAAK,IAAI,UAAU;AAAA,EACnD,MAAM,OACL,sEAAsE,KACrE,GACD,KAAK,IAAI,UAAU;AAAA,EACpB,IAAI,CAAC,OAAO,CAAC;AAAA,IAAM;AAAA,EACnB,MAAM,MAAY,EAAE,IAAI;AAAA,EACxB,IAAI,OAAO,aAAa,YAAY,qBAAqB,KAAK,QAAQ,GAAG;AAAA,IACxE,IAAI,WAAW,SAAS,YAAY;AAAA,EACrC;AAAA,EACA,MAAM,QAAQ,MAAM,QAAQ,KAAK,IAC9B,MAAM,IAAI,CAAC,MAAM,OAAO,CAAC,EAAE,YAAY,CAAC,EAAE,OAAO,CAAC,MAAM,KAAK,KAAK,CAAC,CAAC,IACpE,CAAC;AAAA,EACJ,IAAI,MAAM,SAAS;AAAA,IAAG,IAAI,QAAQ;AAAA,EAClC,IAAI,UAAU,WAAW,UAAU;AAAA,IAAQ,IAAI,QAAQ;AAAA,EACvD,OAAO;AAAA;AAID,SAAS,UAAU,CAAC,OAAgC;AAAA,EAC1D,M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
|
+
"debugId": "27B1D162301EBE6E64756E2164756E21",
|
|
14
|
+
"names": []
|
|
15
|
+
}
|
package/index.d.ts
CHANGED
|
@@ -3,5 +3,5 @@
|
|
|
3
3
|
* tab-mcp relay. This entry is the small core; `connect()` loads the rest.
|
|
4
4
|
*/
|
|
5
5
|
export { TabMcp } from "./tab-mcp.js";
|
|
6
|
-
export type { ConfirmHandler, ConfirmRequest, ConnectionState, ConnectOptions, DisconnectDetail, DisconnectReason, Grant, Icon, IdentityAssertionHandler, IdentityAssertionRequest, IdentityState, JsonSchema, Limits, PairingCode, PairingCodeReason, ReconnectingInfo, ReconnectOptions, RegisterToolOptions, RelayClient, ReplacedDetail, SecretStorage, ServerInfo, SessionInfo, TabMcpEventMap, TabMcpOptions, Tool, ToolAnnotations, ToolCallClient, ToolCallEnd, ToolCallOutcome, ToolCallResult, ToolCallStart, ToolExecuteOptions, WebMcpClient, } from "./types.js";
|
|
6
|
+
export type { ConfirmAnswer, ConfirmHandler, ConfirmRequest, ConnectionState, ConnectOptions, DisconnectDetail, DisconnectReason, Grant, Icon, IdentityAssertionHandler, IdentityAssertionRequest, IdentityState, JsonSchema, Limits, PairingCode, PairingCodeReason, ReconnectingInfo, ReconnectOptions, RegisterToolOptions, RelayClient, ReplacedDetail, SecretStorage, ServerInfo, SessionInfo, TabMcpEventMap, TabMcpOptions, Tool, ToolAnnotations, ToolCallClient, ToolCallEnd, ToolCallOutcome, ToolCallResult, ToolCallStart, ToolExecuteOptions, WebMcpClient, } from "./types.js";
|
|
7
7
|
export { VERSION } from "./version.js";
|
package/index.js
CHANGED
|
@@ -220,7 +220,7 @@ class SecretStore {
|
|
|
220
220
|
}
|
|
221
221
|
}
|
|
222
222
|
// package.json
|
|
223
|
-
var version = "0.
|
|
223
|
+
var version = "0.14.0";
|
|
224
224
|
|
|
225
225
|
// src/version.ts
|
|
226
226
|
var LIBRARY_NAME = "@ractive-ch/tab-mcp-client";
|
|
@@ -581,7 +581,7 @@ class TabMcp extends EventTarget {
|
|
|
581
581
|
return connecting;
|
|
582
582
|
}
|
|
583
583
|
async#load() {
|
|
584
|
-
const lazy = await import("./connection-
|
|
584
|
+
const lazy = await import("./connection-eqsag07j.js");
|
|
585
585
|
for (const error of lazy.compileRegistry(this.#registry))
|
|
586
586
|
this.#emit("error", { error });
|
|
587
587
|
return lazy;
|
|
@@ -780,7 +780,7 @@ class TabMcp extends EventTarget {
|
|
|
780
780
|
#confirm(request) {
|
|
781
781
|
if (this.#onConfirm !== undefined) {
|
|
782
782
|
const ask = this.#onConfirm;
|
|
783
|
-
return Promise.resolve().then(() => ask(request)).then((
|
|
783
|
+
return Promise.resolve().then(() => ask(request)).then((answer) => answer === "unanswered" ? answer : answer === true);
|
|
784
784
|
}
|
|
785
785
|
return this.confirmInPage(request);
|
|
786
786
|
}
|
|
@@ -889,5 +889,5 @@ export {
|
|
|
889
889
|
VERSION
|
|
890
890
|
};
|
|
891
891
|
|
|
892
|
-
//# debugId=
|
|
892
|
+
//# debugId=44223BB9C5F01CE164756E2164756E21
|
|
893
893
|
//# sourceMappingURL=index.js.map
|