@johnhenry/browsermesh-mcp 0.1.0 → 0.2.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 CHANGED
@@ -55,8 +55,9 @@ A grant lets a peer *ask*. A tool that is not read-only is then asked about by t
55
55
  ## What is and is not offered
56
56
 
57
57
  Tools only. No resources, prompts, sampling, roots or elicitation. Results are
58
- labelled untrusted (`_meta['browsermesh/untrusted']`, `untrusted: true` on the
59
- typed client). Bounds (`limits`) are wsh's `WEBMCP_DEFAULT_LIMITS`: 64 tools,
58
+ labelled untrusted (`_meta['wsh/untrusted']` from wsh and `_meta['browsermesh/untrusted']` from this layer,
59
+ `untrusted: true` on the typed client). The caller is wsh's identity object in the prompt and in `onCall`:
60
+ `{ username: null, fingerprint, podId }`, `podId` the channel's verified peer and `fingerprint` the hex name of the same key. Bounds (`limits`) are wsh's `WEBMCP_DEFAULT_LIMITS`: 64 tools,
60
61
  16 KiB of schema per tool, 64 KiB of input, 256 KiB of result, 4 in flight and 30
61
62
  calls a minute per session, a 120 s call timeout. Cancelling a call, or closing
62
63
  the channel, aborts the tool's `signal`.
@@ -73,6 +74,8 @@ the channel, aborts the tool's `signal`.
73
74
 
74
75
  ## Compatibility
75
76
 
76
- Nothing new on the link: the protocol name is `mcp` (version 1) on the existing protocol seam. A peer without
77
+ Nothing new on the link: the protocol name is `mcp` (version 1) on the existing protocol seam, and its messages are
78
+ plain MCP JSON-RPC 2.0 objects in the channel's own messages (wsh's `serveMcpOverDuplex`). A peer without
77
79
  protocol support answers `mesh.protocol.open` with -32601; one that does not serve `mcp` answers -32003. Peer
78
- dependencies: `@johnhenry/wsh` >=0.48.0 and `@johnhenry/browsermesh-apps`.
80
+ dependencies: `@johnhenry/wsh` >=0.49.0 (tested at 0.49.0) and `@johnhenry/browsermesh-apps`. This package has
81
+ not been published before this change; nothing older speaks to it.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@johnhenry/browsermesh-mcp",
3
- "version": "0.1.0",
3
+ "version": "0.2.0",
4
4
  "description": "A page's WebMCP tools (or any tool list) served over a browsermesh protocol channel, and a client for them, with per-tool grants and the approval kept with the page",
5
5
  "type": "module",
6
6
  "main": "./src/index.mjs",
@@ -36,14 +36,14 @@
36
36
  "homepage": "https://opensource.johnhenry.me/browsermesh/",
37
37
  "peerDependencies": {
38
38
  "@johnhenry/browsermesh-apps": ">=0.21.0 <1.0.0",
39
- "@johnhenry/wsh": ">=0.48.0 <1.0.0"
39
+ "@johnhenry/wsh": ">=0.49.0 <1.0.0"
40
40
  },
41
41
  "devDependencies": {
42
42
  "@johnhenry/browsermesh-apps": "^0.21.1",
43
43
  "@johnhenry/browsermesh-core": "^0.13.0",
44
44
  "@johnhenry/browsermesh-discovery": "^0.4.0",
45
- "@johnhenry/browsermesh-primitives": "^0.6.0",
46
- "@johnhenry/wsh": "^0.48.0",
45
+ "@johnhenry/browsermesh-primitives": "^0.6.1",
46
+ "@johnhenry/wsh": "^0.50.0",
47
47
  "node-datachannel": "^0.33.4"
48
48
  },
49
49
  "engines": {
package/src/client.mjs CHANGED
@@ -9,32 +9,33 @@
9
9
  *
10
10
  * // or with an MCP SDK client: await sdkClient.connect(client.transport)
11
11
  *
12
- * The client sends no request the server did not ask for and answers none: it registers no request handler,
13
- * so sampling, roots and elicitation requests from the far side are refused (-32601). The result of a call is
14
- * data of the serving page: `untrusted` is always true, and nothing here interprets the text.
12
+ * The wire is plain MCP JSON-RPC 2.0 in the channel's own messages (what wsh's `serveMcpOverDuplex` speaks), so
13
+ * the transport is a pass-through and the typed client only matches answers to requests by id. The client sends
14
+ * no request the server did not ask for and answers none (a request from the far side gets -32601), so sampling,
15
+ * roots and elicitation are refused. The result of a call is data of the serving page: `untrusted` is always
16
+ * true, and nothing here interprets the text.
15
17
  */
16
- import { assertProtocolChannel } from '@johnhenry/browsermesh-apps'
18
+ import { assertProtocolChannel, MeshChannelError, ChannelErrorCode } from '@johnhenry/browsermesh-apps'
17
19
  import { MCP_PROTOCOL } from './scopes.mjs'
18
20
 
19
21
  const PROTOCOL_VERSION = '2025-06-18'
22
+ export const MCP_ERROR_REASON = 'mcp-error'
23
+ /** Same as the channel's own default for a request. */
24
+ const DEFAULT_REQUEST_TIMEOUT_MS = 30_000
20
25
  /** Longer than the serving side's call timeout (120 s), so the server's own timeout is the one that answers. */
21
26
  const DEFAULT_CALL_TIMEOUT_MS = 125_000
22
27
 
23
- const isCancel = (e) => e?.code === -32001
24
-
25
- /** An MCP JSON-RPC error object from a thrown channel error. */
26
- function rpcErrorOf(e) {
27
- return { code: Number.isInteger(e?.code) ? e.code : -32603, message: String(e?.message ?? e), ...(e?.data !== undefined ? { data: e.data } : {}) }
28
- }
28
+ const cancelled = (reason, message) => new MeshChannelError(ChannelErrorCode.CANCELLED, reason, message)
29
+ /** An MCP/JSON-RPC error object as a channel error: the code, message and data cross unchanged. */
30
+ const mcpError = (e) => new MeshChannelError(Number.isInteger(e?.code) ? e.code : ChannelErrorCode.INTERNAL, MCP_ERROR_REASON, String(e?.message ?? 'error'), e?.data)
29
31
 
30
32
  /**
31
- * A Transport in the shape the MCP SDK's `Client` takes (structural: the SDK is not imported).
32
- * JSON-RPC requests become channel requests, notifications become channel notifications, and
33
- * `notifications/cancelled` aborts the request it names (the channel then cancels it on the far side).
33
+ * A Transport in the shape the MCP SDK's `Client` takes (structural: the SDK is not imported). The SDK speaks
34
+ * JSON-RPC and so does the channel: messages pass through as they are (a `notifications/cancelled` too, which the
35
+ * serving side turns into an abort of the tool's `signal`).
34
36
  */
35
37
  export class MeshMcpTransport {
36
38
  #client
37
- #inflight = new Map()
38
39
  #started = false
39
40
  #closed = false
40
41
  #off = []
@@ -50,7 +51,7 @@ export class MeshMcpTransport {
50
51
  if (this.#started) return
51
52
  this.#started = true
52
53
  this.#off.push(
53
- this.#client._subscribe('notification', (message) => this.onmessage?.(message)),
54
+ this.#client._subscribe('message', (message) => this.onmessage?.(message)),
54
55
  this.#client.onClose(() => this.#ended()),
55
56
  )
56
57
  }
@@ -58,19 +59,7 @@ export class MeshMcpTransport {
58
59
  async send(message) {
59
60
  if (this.#closed) throw new Error('the mesh MCP transport is closed')
60
61
  if (!message || typeof message !== 'object') throw new TypeError('a JSON-RPC message is an object')
61
- const { method, id, params } = message
62
- if (typeof method !== 'string') return // a response to a server request: there are none to answer
63
- if (id === undefined) {
64
- if (method === 'notifications/cancelled') { this.#inflight.get(params?.requestId)?.abort(); return }
65
- await this.#client.notify(method, params)
66
- return
67
- }
68
- const controller = new AbortController()
69
- this.#inflight.set(id, controller)
70
- this.#client.request(method, params, { signal: controller.signal, timeoutMs: method === 'tools/call' ? DEFAULT_CALL_TIMEOUT_MS : undefined }).then(
71
- (result) => { if (!controller.signal.aborted) this.onmessage?.({ jsonrpc: '2.0', id, result }) },
72
- (e) => { if (!(controller.signal.aborted && isCancel(e))) this.onmessage?.({ jsonrpc: '2.0', id, error: rpcErrorOf(e) }) },
73
- ).finally(() => this.#inflight.delete(id))
62
+ await this.#client._send(message)
74
63
  }
75
64
 
76
65
  async close() {
@@ -82,8 +71,6 @@ export class MeshMcpTransport {
82
71
  #ended() {
83
72
  if (this.#closed) return
84
73
  this.#closed = true
85
- for (const controller of this.#inflight.values()) controller.abort()
86
- this.#inflight.clear()
87
74
  for (const off of this.#off.splice(0)) off()
88
75
  this.onclose?.()
89
76
  }
@@ -95,33 +82,60 @@ export class MeshMcpTransport {
95
82
  */
96
83
  export function openMcpOnMesh(channel) {
97
84
  assertProtocolChannel(channel)
98
- const hubs = { notification: new Set(), changed: new Set(), log: new Set(), close: new Set() }
85
+ const hubs = { message: new Set(), changed: new Set(), log: new Set(), close: new Set() }
99
86
  const fire = (set, value) => { for (const cb of [...set]) { try { cb(value) } catch { /* a listener's problem */ } } }
100
87
  const subscribe = (kind, cb) => { hubs[kind].add(cb); return () => hubs[kind].delete(cb) }
88
+ /** id -> { resolve, reject } of the requests this client made. */
89
+ const pending = new Map()
90
+ let nextId = 1
101
91
  let closed = false
102
92
  let transport = null
103
93
 
104
- // The only notifications an MCP tool server sends. Nothing else is listened for.
105
- channel.onNotification('notifications/tools/list_changed', (params) => {
106
- fire(hubs.changed)
107
- fire(hubs.notification, { jsonrpc: '2.0', method: 'notifications/tools/list_changed', ...(params !== undefined ? { params } : {}) })
108
- })
109
- channel.onNotification('notifications/message', (params) => {
110
- fire(hubs.log, params)
111
- fire(hubs.notification, { jsonrpc: '2.0', method: 'notifications/message', ...(params !== undefined ? { params } : {}) })
94
+ const send = (message) => channel.send(message)
95
+ const endPending = (reason, message) => { for (const entry of [...pending.values()]) entry.reject(cancelled(reason, message)) }
96
+
97
+ channel.onMessage((message) => {
98
+ if (!message || typeof message !== 'object' || message.jsonrpc !== '2.0') return
99
+ if (typeof message.method === 'string') {
100
+ // A request of the far side: this client answers none.
101
+ if (Object.hasOwn(message, 'id')) { void send({ jsonrpc: '2.0', id: message.id, error: { code: ChannelErrorCode.METHOD_NOT_FOUND, message: `method not found: ${message.method}` } }).catch(() => {}); return }
102
+ // The only notifications an MCP tool server sends. Nothing else is listened for.
103
+ if (message.method === 'notifications/tools/list_changed') fire(hubs.changed)
104
+ else if (message.method === 'notifications/message') fire(hubs.log, message.params)
105
+ else return
106
+ fire(hubs.message, message)
107
+ return
108
+ }
109
+ const entry = pending.get(message.id)
110
+ if (entry) {
111
+ if (Object.hasOwn(message, 'error')) entry.reject(mcpError(message.error))
112
+ else entry.resolve(message.result)
113
+ } else fire(hubs.message, message) // an answer to something the transport sent
112
114
  })
113
- const pending = new Set()
114
- const abortPending = () => { for (const c of [...pending]) c.abort() }
115
- channel.onClose(() => { closed = true; abortPending(); fire(hubs.close) })
115
+ channel.onClose(() => { closed = true; endPending('channel-closed', 'the channel closed'); fire(hubs.close) })
116
116
 
117
117
  // Every request is ended when the channel closes (by either side); the caller's signal cancels just that request.
118
- const request = (method, params, { signal, timeoutMs } = {}) => {
119
- const own = new AbortController()
120
- const onAbort = () => own.abort()
121
- if (signal?.aborted) own.abort(); else signal?.addEventListener('abort', onAbort, { once: true })
122
- pending.add(own)
123
- return channel.request(method, params ?? {}, { signal: own.signal, ...(timeoutMs ? { timeoutMs } : {}) })
124
- .finally(() => { pending.delete(own); signal?.removeEventListener('abort', onAbort) })
118
+ const request = (method, params, { signal, timeoutMs = method === 'tools/call' ? DEFAULT_CALL_TIMEOUT_MS : DEFAULT_REQUEST_TIMEOUT_MS } = {}) => {
119
+ if (closed) return Promise.reject(cancelled('channel-closed', 'the channel closed'))
120
+ if (signal?.aborted) return Promise.reject(cancelled('cancelled', 'request aborted'))
121
+ const id = `c${nextId++}`
122
+ return new Promise((resolve, reject) => {
123
+ let timer
124
+ const done = () => { pending.delete(id); clearTimeout(timer); signal?.removeEventListener('abort', onAbort) }
125
+ const fail = (e, tellFar = false) => {
126
+ if (!pending.has(id)) return
127
+ done()
128
+ reject(e)
129
+ // The far side is told, so the tool's own signal fires.
130
+ if (tellFar && !closed) void send({ jsonrpc: '2.0', method: 'notifications/cancelled', params: { requestId: id } }).catch(() => {})
131
+ }
132
+ const onAbort = () => fail(cancelled('cancelled', 'request aborted'), true)
133
+ pending.set(id, { resolve: (value) => { done(); resolve(value) }, reject: fail })
134
+ signal?.addEventListener('abort', onAbort, { once: true })
135
+ timer = setTimeout(() => fail(cancelled('timeout', `request ${method} timed out after ${timeoutMs}ms`), true), timeoutMs)
136
+ timer.unref?.()
137
+ send({ jsonrpc: '2.0', id, method, params: params ?? {} }).catch((e) => fail(e))
138
+ })
125
139
  }
126
140
 
127
141
  const client = {
@@ -129,12 +143,13 @@ export function openMcpOnMesh(channel) {
129
143
  get closed() { return closed },
130
144
  /** Escape hatch for tests and for methods this client has no helper for. */
131
145
  request,
132
- notify: (method, params) => channel.notify(method, params),
146
+ notify: (method, params) => send({ jsonrpc: '2.0', method, ...(params !== undefined ? { params } : {}) }),
133
147
  _subscribe: subscribe,
148
+ _send: send,
134
149
  /** `initialize`, then `notifications/initialized` (which is what starts list-changed). */
135
150
  async initialize({ signal } = {}) {
136
151
  const result = await request('initialize', { protocolVersion: PROTOCOL_VERSION, capabilities: {}, clientInfo: { name: '@johnhenry/browsermesh-mcp', version: '0' } }, { signal })
137
- await channel.notify('notifications/initialized')
152
+ await client.notify('notifications/initialized')
138
153
  return result
139
154
  },
140
155
  /** The tools this peer may list. */
@@ -153,7 +168,7 @@ export function openMcpOnMesh(channel) {
153
168
  if (closed) { queueMicrotask(cb); return () => {} }
154
169
  return subscribe('close', cb)
155
170
  },
156
- close() { abortPending(); channel.close() },
171
+ close() { endPending('channel-closed', 'the channel closed'); channel.close() },
157
172
  /** An MCP SDK `Transport` over this channel. */
158
173
  get transport() { return (transport ??= new MeshMcpTransport(client)) },
159
174
  }
package/src/index.d.ts CHANGED
@@ -30,10 +30,11 @@ export interface McpToolDefinition {
30
30
 
31
31
  export interface McpCall { name: string; title: string | null; description: string; input: Record<string, unknown>; consequential: boolean; readOnly: boolean }
32
32
  export interface McpCallEvent {
33
- outcome: 'ok' | 'error' | 'denied' | 'approved' | 'refused' | 'unknown' | 'unlisted' | 'unauthorized'
33
+ /** `unknown` is also what a tool the caller has no `call` grant for is reported as: it is answered like a tool that does not exist. */
34
+ outcome: 'ok' | 'error' | 'denied' | 'approved' | 'refused' | 'unknown' | 'unlisted'
34
35
  name?: string
35
- /** `fingerprint` is the caller's verified pod id. */
36
- who?: { username: string | null; fingerprint: string | null }
36
+ /** wsh's caller identity: `podId` is the caller's verified pod id and `fingerprint` the hex name of the same key, derived from it. */
37
+ who?: { username: string | null; fingerprint: string | null; podId?: string | null }
37
38
  limit?: string
38
39
  detail?: string
39
40
  }
@@ -46,7 +47,7 @@ export interface ServeMcpOptions {
46
47
  allow: string[]
47
48
  approve?: 'never' | 'consequential' | 'always'
48
49
  /** The person at THIS page. Answers `true` to allow. Default: a dialog in `window.document`, else deny. */
49
- prompt?: (call: McpCall, who: { username: string | null; fingerprint: string | null }, extra: { signal: AbortSignal }) => boolean | Promise<boolean>
50
+ prompt?: (call: McpCall, who: { username: string | null; fingerprint: string | null; podId?: string | null }, extra: { signal: AbortSignal }) => boolean | Promise<boolean>
50
51
  capture?: { list(): McpToolDefinition[]; subscribe?(fn: () => void): () => void } | null
51
52
  limits?: Partial<{ maxTools: number; maxSchemaBytes: number; maxInputBytes: number; maxResultBytes: number; maxInflight: number; maxCallsPerMinute: number; callTimeoutMs: number }>
52
53
  /** Replaces the registry-backed decision. */
package/src/serve.mjs CHANGED
@@ -8,15 +8,21 @@
8
8
  * What it decides, in order, on every request of every session:
9
9
  * 1. the channel opened at all: `protocol:mcp:open` (the protocol host's own check, default deny);
10
10
  * 2. the page offers the tool at all: `allow` (exact names, nothing by default);
11
- * 3. this peer may see it (`mcp:<tool>:list`) or call it (`mcp:<tool>:call`), through the registry;
11
+ * 3. this peer may see it (`mcp:<tool>:list`) or call it (`mcp:<tool>:call`), through the registry,
12
+ * asked through wsh's own hook (`permits`): listing is `{ kind: 'mcp-tool', op: 'list' }`, a call
13
+ * `{ kind: 'mcp-call', op: 'call' }`, so the two are scoped apart without wrapping the handler;
12
14
  * 4. for a tool that is not read-only: the person at THIS page says yes (`approve`, `prompt`);
13
15
  * 5. bounds, by name (`limits`).
14
16
  * The peer is the channel's verified one, never a field of a message. The question to the person is the
15
17
  * serving page's: the caller cannot see, answer or influence it.
18
+ *
19
+ * The wire is plain MCP JSON-RPC 2.0 in the protocol channel's own messages (`serveMcpOverDuplex` of
20
+ * `@johnhenry/wsh/page`): the channel's credit and ordering carry it, and an MCP client library can be
21
+ * pointed straight at it.
16
22
  */
17
- import { webmcpTools, WEBMCP_DEFAULT_LIMITS } from '@johnhenry/wsh/page'
23
+ import { webmcpTools, serveMcpOverDuplex } from '@johnhenry/wsh/page'
24
+ import { podIdToFingerprint } from '@johnhenry/wsh/identity'
18
25
  import { MCP_PROTOCOL, MCP_ACTIONS, TOOL_SCOPE_NAME } from './scopes.mjs'
19
- import { rpcChannelOverMesh, mcpError } from './rpc-seam.mjs'
20
26
 
21
27
  const realmTimers = () => ({
22
28
  setTimeout: (fn, ms) => globalThis.setTimeout(fn, ms),
@@ -25,8 +31,19 @@ const realmTimers = () => ({
25
31
  clearInterval: (id) => globalThis.clearInterval(id),
26
32
  })
27
33
 
28
- const INVALID_PARAMS = -32602
29
- const STREAM_LIMIT = -32002
34
+ /** The largest message the seam accepts or sends: wsh's default, and never more than the channel carries. */
35
+ const MAX_MESSAGE_BYTES = 1024 * 1024
36
+
37
+ /**
38
+ * Every result of a tool call is page content that may carry text written by third parties. wsh labels it
39
+ * (`_meta['wsh/untrusted']`, which no tool can unset); this layer adds its own label beside it.
40
+ */
41
+ function labelled(message) {
42
+ const meta = message?.result?._meta
43
+ return meta && meta['wsh/untrusted'] === true
44
+ ? { ...message, result: { ...message.result, _meta: { ...meta, 'browsermesh/untrusted': true } } }
45
+ : message
46
+ }
30
47
 
31
48
  /** @param {any} service the api of `attachService(node, undefined, createMeshProtocolService())`, or the attached host itself */
32
49
  function protocolApi(service) {
@@ -89,59 +106,37 @@ export function serveMcpOnMesh(service, options = {}) {
89
106
  ...(timers ? { timers } : (window?.setTimeout ? {} : { timers: realmTimers() })),
90
107
  now,
91
108
  })
92
- const maxCallsPerMinute = limits.maxCallsPerMinute ?? WEBMCP_DEFAULT_LIMITS.maxCallsPerMinute
93
109
 
94
- /** @type {Set<{ peer: string, since: number }>} */
110
+ /** wsh's hook, for one peer: listing a tool and running one are asked apart, each for its own action. Anything else is refused. */
111
+ const permitsFor = (peer) => (request) => {
112
+ if (request?.kind === 'mcp-tool') return can(peer, request.tool, 'list')
113
+ if (request?.kind === 'mcp-call') return can(peer, request.tool, 'call')
114
+ return false
115
+ }
116
+
117
+ /** @type {Set<{ peer: string, since: number, session: object, channel: object }>} */
95
118
  const sessions = new Set()
119
+ /** wsh ends a session by itself (`closeSessions`, a failed send); the mesh channel under it is closed here when it does. */
120
+ const reap = () => { for (const s of sessions) if (s.session.closed && !s.channel.closed) { try { s.channel.close('session ended') } catch { /* already closed */ } } }
96
121
 
97
122
  const unserve = api.serveProtocol(protocol, (channel) => {
98
123
  const peer = channel.peer
99
- const who = { username: null, fingerprint: peer }
100
- const session = { peer, since: now(), starts: [] }
101
- sessions.add(session)
124
+ const entry = { peer, since: now(), session: null, channel }
125
+ entry.session = serveMcpOverDuplex(handler, {
126
+ // The channel's own message queue is the duplex: reliable, in order, with the channel's credit as backpressure.
127
+ send: (message) => channel.send(labelled(message)).catch((e) => { try { channel.close('send failed') } catch { /* already closed */ } throw e }),
128
+ who: { podId: peer },
129
+ permits: permitsFor(peer),
130
+ maxMessageBytes: Math.min(channel.maxMessageBytes, MAX_MESSAGE_BYTES),
131
+ })
132
+ sessions.add(entry)
102
133
  try { onSession?.({ peer, state: 'open' }) } catch { /* the embedder's callback */ }
134
+ channel.onMessage((message) => { entry.session.receive(message) })
103
135
  channel.onClose(() => {
104
- sessions.delete(session)
136
+ entry.session.close('channel closed')
137
+ sessions.delete(entry)
105
138
  try { onSession?.({ peer, state: 'close' }) } catch { /* the embedder's callback */ }
106
139
  })
107
-
108
- const rpc = rpcChannelOverMesh(channel, {
109
- intercept: {
110
- // Only the tools this peer may list; a tool it may only call is callable but not listed.
111
- 'tools/list': async (_params, _ctx, inner) => {
112
- const result = await inner()
113
- return { ...result, tools: (result?.tools ?? []).filter((t) => can(peer, t.name, 'list')) }
114
- },
115
- 'tools/call': async (params, _ctx, inner) => {
116
- // Counted whether or not the call is allowed, so a caller cannot probe names without bound.
117
- const t = now()
118
- session.starts = session.starts.filter((s) => t - s < 60_000)
119
- if (session.starts.length >= maxCallsPerMinute) {
120
- emit({ outcome: 'refused', name: params?.name, who, limit: 'maxCallsPerMinute', detail: `more than ${maxCallsPerMinute} calls in a minute` })
121
- throw mcpError(STREAM_LIMIT, `refused: maxCallsPerMinute: more than ${maxCallsPerMinute} calls in a minute`, { limit: 'maxCallsPerMinute' })
122
- }
123
- session.starts.push(t)
124
- const name = params?.name
125
- if (!can(peer, name, 'call')) {
126
- emit({ outcome: 'unauthorized', name: typeof name === 'string' ? name.slice(0, 128) : undefined, who, detail: 'no grant' })
127
- // The same answer as a tool that does not exist.
128
- throw mcpError(INVALID_PARAMS, `unknown tool: ${name}`)
129
- }
130
- const result = await inner()
131
- return {
132
- ...result,
133
- // The result is data of this page and may carry text written by third parties; no tool can unset this.
134
- _meta: { ...(result?._meta ?? {}), 'wsh/untrusted': true, 'browsermesh/untrusted': true },
135
- }
136
- },
137
- },
138
- })
139
- handler(rpc, {
140
- user: null,
141
- fingerprint: peer,
142
- // The bridge asks this to decide what a session sees: a tool is visible to a peer with any scope on it.
143
- permits: (request) => request?.kind === 'mcp-tool' && (can(peer, request.tool, 'list') || can(peer, request.tool, 'call')),
144
- })
145
140
  })
146
141
 
147
142
  return {
@@ -151,11 +146,20 @@ export function serveMcpOnMesh(service, options = {}) {
151
146
  /** The tools (as `tools/list` states them) that any peer could be granted now. */
152
147
  async list() { return (await handler.list()).filter((t) => TOOL_SCOPE_NAME.test(t.name)) },
153
148
  /** Tell every session (or those of one peer) why, then end it. Resolves with how many were ended. */
154
- closeSessions: (reason, peer) => handler.closeSessions(reason, peer),
149
+ async closeSessions(reason, peer) {
150
+ let fingerprint
151
+ if (peer !== undefined) {
152
+ try { fingerprint = podIdToFingerprint(peer) } catch { return 0 }
153
+ }
154
+ const ended = await handler.closeSessions(reason, fingerprint)
155
+ reap()
156
+ return ended
157
+ },
155
158
  /** Stop serving: no new channel opens, and every session ends. */
156
159
  async close() {
157
160
  unserve()
158
161
  await handler.closeSessions('the page stopped serving its tools')
162
+ reap()
159
163
  },
160
164
  }
161
165
  }
package/src/rpc-seam.mjs DELETED
@@ -1,63 +0,0 @@
1
- /**
2
- * rpc-seam.mjs -- the one file that knows the shape of wsh's WebMCP bridge.
3
- *
4
- * In wsh 0.48 the bridge core is `webmcpTools(options)`: a handler `(channel, ctx)` that wants the part of
5
- * wsh's own `RpcChannel` it uses (`onRequest`, `onNotification`, `notify`, `close`, an assignable `onClose`)
6
- * and a caller identity in `ctx`. A browsermesh protocol channel is a different object with the same
7
- * jobs, so this gives the bridge a small stand-in backed by the protocol channel:
8
- *
9
- * - handlers run on the protocol channel, with the channel's own `ctx` (`id`, `signal`, `peer`);
10
- * - a hook per method may wrap a handler (the per-tool grants are applied there, by the caller);
11
- * - errors keep their JSON-RPC code, message and data (`RpcError` -> `MeshChannelError`),
12
- * so the caller sees what an MCP client would see.
13
- *
14
- * When wsh exports the handler core for any duplex with a transport-neutral caller identity, this is the
15
- * file that is replaced.
16
- */
17
- import { MeshChannelError } from '@johnhenry/browsermesh-apps'
18
-
19
- export const MCP_ERROR_REASON = 'mcp-error'
20
-
21
- /** An MCP/JSON-RPC error as a channel error: the code, message and data cross unchanged. */
22
- export function mcpError(code, message, data) {
23
- return new MeshChannelError(code, MCP_ERROR_REASON, message, data)
24
- }
25
-
26
- /** @param {unknown} e */
27
- export function asChannelError(e) {
28
- if (e instanceof MeshChannelError) return e
29
- if (Number.isInteger(e?.code)) return mcpError(e.code, e.message, e.data)
30
- return e
31
- }
32
-
33
- /**
34
- * @param {object} channel a protocol channel (see `assertProtocolChannel`)
35
- * @param {{ intercept?: Record<string, (params: any, ctx: any, inner: () => Promise<any>) => Promise<any>> }} [options]
36
- * `intercept[method]` runs instead of the handler the bridge registers for `method`, and calls `inner()` to reach it.
37
- */
38
- export function rpcChannelOverMesh(channel, { intercept = {} } = {}) {
39
- let onClose = null
40
- channel.onClose((error) => {
41
- try { onClose?.(error?.message ?? 'closed') } catch { /* the bridge's cleanup must not break the close */ }
42
- })
43
- return {
44
- get closed() { return channel.closed === true },
45
- onRequest(method, handler) {
46
- const hook = intercept[method]
47
- return channel.onRequest(method, async (params, ctx) => {
48
- try {
49
- return hook ? await hook(params, ctx, () => handler(params, ctx)) : await handler(params, ctx)
50
- } catch (e) {
51
- throw asChannelError(e)
52
- }
53
- })
54
- },
55
- onNotification(method, handler) {
56
- return channel.onNotification(method, (params) => handler(params))
57
- },
58
- notify(method, params) { return channel.notify(method, params) },
59
- async close(reason) { channel.close(reason) },
60
- get onClose() { return onClose },
61
- set onClose(fn) { onClose = typeof fn === 'function' ? fn : null },
62
- }
63
- }