@johnhenry/browsermesh-mcp 0.0.0-stage → 0.0.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 John Henry
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,78 @@
1
- # Temporary Holding Version
1
+ # browsermesh-mcp
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ [![npm version](https://img.shields.io/npm/v/%40johnhenry%2Fbrowsermesh-mcp.svg)](https://www.npmjs.com/package/@johnhenry/browsermesh-mcp)
4
+ [![license](https://img.shields.io/npm/l/%40johnhenry%2Fbrowsermesh-mcp.svg)](LICENSE)
5
+
6
+ A page's WebMCP tools (or any explicit list of tools) reachable from **another
7
+ browser** over a browsermesh protocol channel, with no wsh relay in between.
8
+
9
+ The far side speaks plain MCP JSON-RPC, so an MCP client library can be pointed
10
+ at the channel through a tiny transport; a small typed client is included. The
11
+ tool bridge is wsh's (`@johnhenry/wsh/page`), peer-depended on; wsh has no
12
+ dependency on browsermesh. Design and rules:
13
+ [`docs/design/mcp-over-mesh.md`](../../docs/design/mcp-over-mesh.md); threat
14
+ model: [`docs/security.md`](../../docs/security.md#mcp-across-the-mesh).
15
+
16
+ ```js
17
+ import { attachService, createMeshProtocolService } from '@johnhenry/browsermesh-apps'
18
+ import { captureWebMcp } from '@johnhenry/wsh/page'
19
+ import { serveMcpOnMesh, connectMcpOnMesh, mcpScopes } from '@johnhenry/browsermesh-mcp'
20
+
21
+ // --- the page that owns the tools (call captureWebMcp BEFORE the application's code) ---
22
+ captureWebMcp(window)
23
+ const service = attachService(node, undefined, createMeshProtocolService()).api
24
+ const served = serveMcpOnMesh(service, {
25
+ window,
26
+ allow: ['search', 'checkout'], // what the page offers at all; nothing by default
27
+ approve: 'consequential', // default: the PERSON AT THIS PAGE is asked before a tool that is not read-only runs
28
+ })
29
+ node.registry.grantCapabilities(peerPodId, [...mcpScopes.open(), ...mcpScopes.tool('search')])
30
+
31
+ // --- another browser ---
32
+ const client = await connectMcpOnMesh(callerService, serverPodId)
33
+ await client.initialize()
34
+ const tools = await client.listTools() // only what this peer may list
35
+ const result = await client.callTool('search', { q: 'x' }, { signal }) // result.untrusted === true
36
+ // or with an MCP SDK client: await sdkClient.connect(client.transport)
37
+ ```
38
+
39
+ ## Who may do what
40
+
41
+ Default deny at every step; asked of the node's `PeerRegistry` for the channel's
42
+ verified peer on every request, so a revocation or an expiry applies to the next
43
+ call.
44
+
45
+ | scope | allows |
46
+ |---|---|
47
+ | `protocol:mcp:open` | opening the channel (`mcpScopes.open()`) |
48
+ | `mcp:<tool>:list` | seeing the tool in `tools/list` |
49
+ | `mcp:<tool>:call` | calling it (`mcpScopes.tool(name)` gives both) |
50
+ | `mcp:*:list`, `mcp:*:call` | every tool (`mcpScopes.all()`) |
51
+
52
+ A grant lets a peer *ask*. A tool that is not read-only is then asked about by the
53
+ **serving** page (`approve`, `prompt`); the caller never sees or answers that.
54
+
55
+ ## What is and is not offered
56
+
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,
60
+ 16 KiB of schema per tool, 64 KiB of input, 256 KiB of result, 4 in flight and 30
61
+ calls a minute per session, a 120 s call timeout. Cancelling a call, or closing
62
+ the channel, aborts the tool's `signal`.
63
+
64
+ ## API
65
+
66
+ - `serveMcpOnMesh(service, { window | tools, allow, approve, prompt, capture, limits, authorize, onCall, onSession })`
67
+ returns `{ sessions(), list(), closeSessions(reason, peer?), close() }`. `authorize(peer, tool, action)` replaces
68
+ the registry-backed decision.
69
+ - `openMcpOnMesh(channel)` / `connectMcpOnMesh(service, peer)`: `{ initialize, listTools, callTool, request,
70
+ onToolsChanged, onLog, onClose, close, transport }`.
71
+ - `MeshMcpTransport`: an MCP SDK `Transport` over the channel (cancel notifications abort the request).
72
+ - `mcpScopes`, `MCP_PROTOCOL`.
73
+
74
+ ## Compatibility
75
+
76
+ Nothing new on the link: the protocol name is `mcp` (version 1) on the existing protocol seam. A peer without
77
+ 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`.
package/package.json CHANGED
@@ -1,6 +1,40 @@
1
1
  {
2
2
  "name": "@johnhenry/browsermesh-mcp",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.0.0",
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
+ "type": "module",
6
+ "main": "./src/index.mjs",
7
+ "types": "./src/index.d.ts",
8
+ "exports": {
9
+ ".": {
10
+ "types": "./src/index.d.ts",
11
+ "import": "./src/index.mjs"
12
+ }
13
+ },
14
+ "files": [
15
+ "src",
16
+ "LICENSE",
17
+ "README.md"
18
+ ],
19
+ "keywords": [
20
+ "mcp",
21
+ "webmcp",
22
+ "browsermesh",
23
+ "p2p",
24
+ "tools"
25
+ ],
26
+ "license": "MIT",
27
+ "repository": {
28
+ "type": "git",
29
+ "url": "https://github.com/johnhenry/browsermesh",
30
+ "directory": "packages/browsermesh-mcp"
31
+ },
32
+ "homepage": "https://opensource.johnhenry.me/browsermesh/",
33
+ "peerDependencies": {
34
+ "@johnhenry/browsermesh-apps": ">=0.21.0 <1.0.0",
35
+ "@johnhenry/wsh": ">=0.48.0 <1.0.0"
36
+ },
37
+ "engines": {
38
+ "node": ">=26.0.0"
39
+ }
40
+ }
package/src/client.mjs ADDED
@@ -0,0 +1,173 @@
1
+ /**
2
+ * client.mjs -- the consuming side: a small typed client over an opened `mcp` protocol channel, and a
3
+ * Transport an MCP client library can be pointed at.
4
+ *
5
+ * const client = await connectMcpOnMesh(service, bobPodId) // opens the protocol
6
+ * await client.initialize()
7
+ * const tools = await client.listTools()
8
+ * const result = await client.callTool('search', { q: 'x' }, { signal }) // result.untrusted === true
9
+ *
10
+ * // or with an MCP SDK client: await sdkClient.connect(client.transport)
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.
15
+ */
16
+ import { assertProtocolChannel } from '@johnhenry/browsermesh-apps'
17
+ import { MCP_PROTOCOL } from './scopes.mjs'
18
+
19
+ const PROTOCOL_VERSION = '2025-06-18'
20
+ /** Longer than the serving side's call timeout (120 s), so the server's own timeout is the one that answers. */
21
+ const DEFAULT_CALL_TIMEOUT_MS = 125_000
22
+
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
+ }
29
+
30
+ /**
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).
34
+ */
35
+ export class MeshMcpTransport {
36
+ #client
37
+ #inflight = new Map()
38
+ #started = false
39
+ #closed = false
40
+ #off = []
41
+ sessionId
42
+ onclose
43
+ onerror
44
+ onmessage
45
+
46
+ /** @param {object} client what `openMcpOnMesh` returns */
47
+ constructor(client) { this.#client = client }
48
+
49
+ async start() {
50
+ if (this.#started) return
51
+ this.#started = true
52
+ this.#off.push(
53
+ this.#client._subscribe('notification', (message) => this.onmessage?.(message)),
54
+ this.#client.onClose(() => this.#ended()),
55
+ )
56
+ }
57
+
58
+ async send(message) {
59
+ if (this.#closed) throw new Error('the mesh MCP transport is closed')
60
+ 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))
74
+ }
75
+
76
+ async close() {
77
+ if (this.#closed) return
78
+ this.#ended()
79
+ await this.#client.close()
80
+ }
81
+
82
+ #ended() {
83
+ if (this.#closed) return
84
+ this.#closed = true
85
+ for (const controller of this.#inflight.values()) controller.abort()
86
+ this.#inflight.clear()
87
+ for (const off of this.#off.splice(0)) off()
88
+ this.onclose?.()
89
+ }
90
+ }
91
+
92
+ /**
93
+ * @param {object} channel an opened protocol channel (`service.openProtocol(peer, 'mcp')`)
94
+ * @returns the client: `{ peer, initialize, listTools, callTool, request, notify, onToolsChanged, onLog, onClose, close, transport }`
95
+ */
96
+ export function openMcpOnMesh(channel) {
97
+ assertProtocolChannel(channel)
98
+ const hubs = { notification: new Set(), changed: new Set(), log: new Set(), close: new Set() }
99
+ const fire = (set, value) => { for (const cb of [...set]) { try { cb(value) } catch { /* a listener's problem */ } } }
100
+ const subscribe = (kind, cb) => { hubs[kind].add(cb); return () => hubs[kind].delete(cb) }
101
+ let closed = false
102
+ let transport = null
103
+
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 } : {}) })
112
+ })
113
+ const pending = new Set()
114
+ const abortPending = () => { for (const c of [...pending]) c.abort() }
115
+ channel.onClose(() => { closed = true; abortPending(); fire(hubs.close) })
116
+
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) })
125
+ }
126
+
127
+ const client = {
128
+ peer: channel.peer,
129
+ get closed() { return closed },
130
+ /** Escape hatch for tests and for methods this client has no helper for. */
131
+ request,
132
+ notify: (method, params) => channel.notify(method, params),
133
+ _subscribe: subscribe,
134
+ /** `initialize`, then `notifications/initialized` (which is what starts list-changed). */
135
+ async initialize({ signal } = {}) {
136
+ const result = await request('initialize', { protocolVersion: PROTOCOL_VERSION, capabilities: {}, clientInfo: { name: '@johnhenry/browsermesh-mcp', version: '0' } }, { signal })
137
+ await channel.notify('notifications/initialized')
138
+ return result
139
+ },
140
+ /** The tools this peer may list. */
141
+ async listTools({ signal } = {}) {
142
+ const result = await request('tools/list', {}, { signal })
143
+ return Array.isArray(result?.tools) ? result.tools : []
144
+ },
145
+ /** Call a tool. `signal` cancels: the serving page's tool sees its own `signal` abort. The result is always marked `untrusted`. */
146
+ async callTool(name, args = {}, { signal, timeoutMs = DEFAULT_CALL_TIMEOUT_MS } = {}) {
147
+ const result = await request('tools/call', { name, arguments: args }, { signal, timeoutMs })
148
+ return { ...result, untrusted: true }
149
+ },
150
+ onToolsChanged: (cb) => subscribe('changed', cb),
151
+ onLog: (cb) => subscribe('log', cb),
152
+ onClose(cb) {
153
+ if (closed) { queueMicrotask(cb); return () => {} }
154
+ return subscribe('close', cb)
155
+ },
156
+ close() { abortPending(); channel.close() },
157
+ /** An MCP SDK `Transport` over this channel. */
158
+ get transport() { return (transport ??= new MeshMcpTransport(client)) },
159
+ }
160
+ return client
161
+ }
162
+
163
+ /**
164
+ * Open the `mcp` protocol on `peer` and return the client.
165
+ * @param {object} service the api of `attachService(node, undefined, createMeshProtocolService())`
166
+ * @param {string} peer pod id of the pod that serves the tools
167
+ * @param {{ protocol?: string, signal?: AbortSignal, timeoutMs?: number }} [options]
168
+ */
169
+ export async function connectMcpOnMesh(service, peer, { protocol = MCP_PROTOCOL, signal, timeoutMs } = {}) {
170
+ const api = service?.api && typeof service.api.openProtocol === 'function' ? service.api : service
171
+ if (!api || typeof api.openProtocol !== 'function') throw new TypeError('connectMcpOnMesh: first argument must be a protocol service')
172
+ return openMcpOnMesh(await api.openProtocol(peer, protocol, { signal, timeoutMs }))
173
+ }
package/src/index.d.ts ADDED
@@ -0,0 +1,110 @@
1
+ /** A protocol service: the api of `attachService(node, undefined, createMeshProtocolService())`. */
2
+ export interface McpProtocolService {
3
+ serveProtocol(name: string, handler: (channel: any, info: { peer: string; version: number }) => void, options?: { versions?: number[] }): () => void
4
+ openProtocol(peer: string, name: string, options?: { signal?: AbortSignal; timeoutMs?: number }): Promise<any>
5
+ rootAuthorizer?(protocol: string, options?: { actions?: string[] }): { can(peer: string, root: string, action: string): boolean }
6
+ }
7
+
8
+ export const MCP_PROTOCOL: 'mcp'
9
+ export const MCP_ACTIONS: readonly ['list', 'call']
10
+ export const TOOL_SCOPE_NAME: RegExp
11
+
12
+ export const mcpScopes: Readonly<{
13
+ /** `['protocol:mcp:open']` */
14
+ open(protocol?: string): string[]
15
+ /** `mcp:<tool>:list` and `mcp:<tool>:call` (or the actions given). Throws on a name that cannot sit in a scope. */
16
+ tool(name: string, actions?: readonly ('list' | 'call')[], protocol?: string): string[]
17
+ /** `mcp:*:list` and `mcp:*:call`. */
18
+ all(actions?: readonly ('list' | 'call')[], protocol?: string): string[]
19
+ }>
20
+
21
+ export interface McpToolDefinition {
22
+ name: string
23
+ title?: string
24
+ description: string
25
+ inputSchema?: Record<string, unknown>
26
+ outputSchema?: Record<string, unknown>
27
+ annotations?: { readOnlyHint?: boolean; untrustedContentHint?: boolean; consequentialHint?: boolean; debugging?: boolean }
28
+ execute(input: Record<string, any>, options: { signal: AbortSignal }): unknown | Promise<unknown>
29
+ }
30
+
31
+ export interface McpCall { name: string; title: string | null; description: string; input: Record<string, unknown>; consequential: boolean; readOnly: boolean }
32
+ export interface McpCallEvent {
33
+ outcome: 'ok' | 'error' | 'denied' | 'approved' | 'refused' | 'unknown' | 'unlisted' | 'unauthorized'
34
+ name?: string
35
+ /** `fingerprint` is the caller's verified pod id. */
36
+ who?: { username: string | null; fingerprint: string | null }
37
+ limit?: string
38
+ detail?: string
39
+ }
40
+
41
+ export interface ServeMcpOptions {
42
+ /** The realm whose WebMCP tools are served. Give this, `tools`, or both. */
43
+ window?: object
44
+ tools?: McpToolDefinition[]
45
+ /** Exact tool names the page offers. Nothing is offered by default. */
46
+ allow: string[]
47
+ approve?: 'never' | 'consequential' | 'always'
48
+ /** 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
+ capture?: { list(): McpToolDefinition[]; subscribe?(fn: () => void): () => void } | null
51
+ limits?: Partial<{ maxTools: number; maxSchemaBytes: number; maxInputBytes: number; maxResultBytes: number; maxInflight: number; maxCallsPerMinute: number; callTimeoutMs: number }>
52
+ /** Replaces the registry-backed decision. */
53
+ authorize?: (peer: string, tool: string, action: 'list' | 'call') => boolean
54
+ onCall?: (event: McpCallEvent) => void
55
+ onSession?: (event: { peer: string; state: 'open' | 'close' }) => void
56
+ guard?: () => string | null
57
+ server?: { name?: string; version?: string }
58
+ timers?: object
59
+ protocol?: string
60
+ now?: () => number
61
+ }
62
+
63
+ export interface ServedMcp {
64
+ readonly protocol: string
65
+ sessions(): Array<{ peer: string; since: number }>
66
+ list(): Promise<object[]>
67
+ closeSessions(reason: string, peer?: string): Promise<number>
68
+ close(): Promise<void>
69
+ }
70
+
71
+ export function serveMcpOnMesh(service: McpProtocolService | { api: McpProtocolService }, options: ServeMcpOptions): ServedMcp
72
+
73
+ export interface McpToolResult {
74
+ content: Array<{ type: string; text?: string; [k: string]: unknown }>
75
+ structuredContent?: unknown
76
+ isError?: boolean
77
+ _meta?: Record<string, unknown>
78
+ /** Always true: the result is data of the serving page. */
79
+ untrusted: true
80
+ }
81
+
82
+ export interface McpMeshClient {
83
+ readonly peer: string
84
+ readonly closed: boolean
85
+ request(method: string, params?: unknown, options?: { signal?: AbortSignal; timeoutMs?: number }): Promise<any>
86
+ notify(method: string, params?: unknown): Promise<void>
87
+ initialize(options?: { signal?: AbortSignal }): Promise<any>
88
+ listTools(options?: { signal?: AbortSignal }): Promise<any[]>
89
+ callTool(name: string, args?: Record<string, unknown>, options?: { signal?: AbortSignal; timeoutMs?: number }): Promise<McpToolResult>
90
+ onToolsChanged(cb: () => void): () => void
91
+ onLog(cb: (params: unknown) => void): () => void
92
+ onClose(cb: () => void): () => void
93
+ close(): void
94
+ /** An MCP SDK `Transport` over this channel. */
95
+ readonly transport: MeshMcpTransport
96
+ }
97
+
98
+ export class MeshMcpTransport {
99
+ constructor(client: McpMeshClient)
100
+ sessionId?: string
101
+ onclose?: () => void
102
+ onerror?: (error: Error) => void
103
+ onmessage?: (message: any) => void
104
+ start(): Promise<void>
105
+ send(message: any): Promise<void>
106
+ close(): Promise<void>
107
+ }
108
+
109
+ export function openMcpOnMesh(channel: any): McpMeshClient
110
+ export function connectMcpOnMesh(service: McpProtocolService | { api: McpProtocolService }, peer: string, options?: { protocol?: string; signal?: AbortSignal; timeoutMs?: number }): Promise<McpMeshClient>
package/src/index.mjs ADDED
@@ -0,0 +1,3 @@
1
+ export { serveMcpOnMesh } from './serve.mjs'
2
+ export { openMcpOnMesh, connectMcpOnMesh, MeshMcpTransport } from './client.mjs'
3
+ export { MCP_PROTOCOL, MCP_ACTIONS, TOOL_SCOPE_NAME, mcpScopes } from './scopes.mjs'
@@ -0,0 +1,63 @@
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
+ }
package/src/scopes.mjs ADDED
@@ -0,0 +1,39 @@
1
+ /**
2
+ * scopes.mjs -- the grant strings of MCP over the mesh.
3
+ *
4
+ * protocol:mcp:open open the channel (and initialize, ping)
5
+ * mcp:<tool>:list see that tool in tools/list
6
+ * mcp:<tool>:call call it
7
+ * mcp:*:list, mcp:*:call every tool (the registry's own wildcards)
8
+ *
9
+ * They are checked per request through `PeerRegistry.checkAccess(peer, 'mcp:<tool>', action)`
10
+ * (see `createRootAuthorizer` in browsermesh-apps), so a revocation or an expiry applies to the
11
+ * very next request. A tool name must be able to sit in a scope: letters, digits, `.`, `_` and
12
+ * `-`, no `:` and no `*`, so a name can never widen a grant.
13
+ */
14
+
15
+ export const MCP_PROTOCOL = 'mcp'
16
+
17
+ /** The tool names that can be granted. Wider than wsh's tool names only in that a name may not start with `_`, `.` or `-`. */
18
+ export const TOOL_SCOPE_NAME = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/
19
+
20
+ export const MCP_ACTIONS = Object.freeze(['list', 'call'])
21
+
22
+ /** @param {string} name @returns {string} */
23
+ function toolName(name) {
24
+ if (typeof name !== 'string' || !TOOL_SCOPE_NAME.test(name)) throw new TypeError('tool name must match /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/ (no ":" and no "*")')
25
+ return name
26
+ }
27
+
28
+ /** The scopes to hand to `registry.grantCapabilities(peer, ...)`. */
29
+ export const mcpScopes = Object.freeze({
30
+ /** `['protocol:mcp:open']` */
31
+ open: (protocol = MCP_PROTOCOL) => [`protocol:${protocol}:open`],
32
+ /** `mcp:<tool>:<action>` for each action (default: list and call). */
33
+ tool: (name, actions = MCP_ACTIONS, protocol = MCP_PROTOCOL) => actions.map((action) => {
34
+ if (!MCP_ACTIONS.includes(action)) throw new TypeError(`unknown action ${JSON.stringify(action)} (list, call)`)
35
+ return `${protocol}:${toolName(name)}:${action}`
36
+ }),
37
+ /** Every tool: `mcp:*:list` and `mcp:*:call`. */
38
+ all: (actions = MCP_ACTIONS, protocol = MCP_PROTOCOL) => actions.map((action) => `${protocol}:*:${action}`),
39
+ })
package/src/serve.mjs ADDED
@@ -0,0 +1,161 @@
1
+ /**
2
+ * serve.mjs -- a page's WebMCP tools (or an explicit tool list) as the protocol `mcp` on a mesh node.
3
+ *
4
+ * const service = attachService(node, undefined, createMeshProtocolService()).api
5
+ * const served = serveMcpOnMesh(service, { window, allow: ['search', 'buy'], approve: 'consequential' })
6
+ * node.registry.grantCapabilities(peerPodId, [...mcpScopes.open(), ...mcpScopes.tool('search')])
7
+ *
8
+ * What it decides, in order, on every request of every session:
9
+ * 1. the channel opened at all: `protocol:mcp:open` (the protocol host's own check, default deny);
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;
12
+ * 4. for a tool that is not read-only: the person at THIS page says yes (`approve`, `prompt`);
13
+ * 5. bounds, by name (`limits`).
14
+ * The peer is the channel's verified one, never a field of a message. The question to the person is the
15
+ * serving page's: the caller cannot see, answer or influence it.
16
+ */
17
+ import { webmcpTools, WEBMCP_DEFAULT_LIMITS } from '@johnhenry/wsh/page'
18
+ import { MCP_PROTOCOL, MCP_ACTIONS, TOOL_SCOPE_NAME } from './scopes.mjs'
19
+ import { rpcChannelOverMesh, mcpError } from './rpc-seam.mjs'
20
+
21
+ const realmTimers = () => ({
22
+ setTimeout: (fn, ms) => globalThis.setTimeout(fn, ms),
23
+ clearTimeout: (id) => globalThis.clearTimeout(id),
24
+ setInterval: (fn, ms) => globalThis.setInterval(fn, ms),
25
+ clearInterval: (id) => globalThis.clearInterval(id),
26
+ })
27
+
28
+ const INVALID_PARAMS = -32602
29
+ const STREAM_LIMIT = -32002
30
+
31
+ /** @param {any} service the api of `attachService(node, undefined, createMeshProtocolService())`, or the attached host itself */
32
+ function protocolApi(service) {
33
+ const api = service?.api && typeof service.api.serveProtocol === 'function' ? service.api : service
34
+ if (!api || typeof api.serveProtocol !== 'function') throw new TypeError('serveMcpOnMesh: first argument must be a protocol service (the api of attachService(node, undefined, createMeshProtocolService()))')
35
+ return api
36
+ }
37
+
38
+ /**
39
+ * @param {object} service see `protocolApi`
40
+ * @param {object} options
41
+ * @param {object} [options.window] the realm whose WebMCP tools are served (a page's window, an iframe's, a fake one in a test)
42
+ * @param {object[]} [options.tools] explicit tool definitions (as the page passes to `registerTool`); with no `window` these are all there is
43
+ * @param {string[]} options.allow exact tool names the page offers: nothing is offered by default
44
+ * @param {'never'|'consequential'|'always'} [options.approve='consequential'] when the person at THIS page is asked
45
+ * @param {Function} [options.prompt] `(call, who, { signal }) => boolean | Promise<boolean>`; default: a dialog in `window.document`, else deny
46
+ * @param {object} [options.capture] a capture other than the one `captureWebMcp(window)` made
47
+ * @param {object} [options.limits] bounds, by name (see WEBMCP_DEFAULT_LIMITS)
48
+ * @param {(peer: string, tool: string, action: 'list'|'call') => boolean} [options.authorize]
49
+ * Replaces the registry-backed decision (default: `service.rootAuthorizer('mcp')`, i.e. `PeerRegistry.checkAccess`).
50
+ * @param {(event: object) => void} [options.onCall] audit: every call's outcome, and `unauthorized` for a grant that is missing
51
+ * @param {(event: { peer: string, state: 'open'|'close' }) => void} [options.onSession] audit: a session opened or closed
52
+ * @param {string} [options.protocol='mcp']
53
+ * @param {() => number} [options.now]
54
+ */
55
+ export function serveMcpOnMesh(service, options = {}) {
56
+ const api = protocolApi(service)
57
+ const {
58
+ window, tools, allow, approve, prompt, capture, limits = {}, authorize, onCall, onSession, guard, server, timers,
59
+ protocol = MCP_PROTOCOL, now = () => Date.now(),
60
+ } = options
61
+ if (window === undefined && !Array.isArray(tools)) throw new TypeError('serveMcpOnMesh: give a window (its WebMCP tools) or a tools array')
62
+ if (!Array.isArray(allow)) throw new TypeError('serveMcpOnMesh: allow must be an array of tool names (nothing is offered by default)')
63
+ if (authorize !== undefined && typeof authorize !== 'function') throw new TypeError('serveMcpOnMesh: authorize must be a function')
64
+ if (onSession !== undefined && typeof onSession !== 'function') throw new TypeError('serveMcpOnMesh: onSession must be a function')
65
+
66
+ const roots = authorize ? null : (typeof api.rootAuthorizer === 'function' ? api.rootAuthorizer(protocol, { actions: [...MCP_ACTIONS] }) : null)
67
+ /** Default deny: no authorizer, a name that cannot sit in a scope, or any throw is a refusal. */
68
+ const can = (peer, tool, action) => {
69
+ if (typeof tool !== 'string' || !TOOL_SCOPE_NAME.test(tool)) return false
70
+ try {
71
+ if (authorize) return authorize(peer, tool, action) === true
72
+ return roots ? roots.can(peer, tool, action) === true : false
73
+ } catch { return false }
74
+ }
75
+
76
+ const emit = (event) => { if (onCall) { try { onCall(event) } catch { /* the embedder's callback */ } } }
77
+ const handler = webmcpTools({
78
+ window: window ?? {},
79
+ allow,
80
+ ...(tools ? { tools } : {}),
81
+ ...(approve !== undefined ? { approve } : {}),
82
+ ...(prompt !== undefined ? { prompt } : {}),
83
+ ...(capture !== undefined ? { capture } : {}),
84
+ limits,
85
+ onCall: emit,
86
+ ...(guard ? { guard } : {}),
87
+ ...(server ? { server } : {}),
88
+ // The bridge never reaches for globals; a window that cannot run timers (a fake one, a tools-only server) gets the realm's own.
89
+ ...(timers ? { timers } : (window?.setTimeout ? {} : { timers: realmTimers() })),
90
+ now,
91
+ })
92
+ const maxCallsPerMinute = limits.maxCallsPerMinute ?? WEBMCP_DEFAULT_LIMITS.maxCallsPerMinute
93
+
94
+ /** @type {Set<{ peer: string, since: number }>} */
95
+ const sessions = new Set()
96
+
97
+ const unserve = api.serveProtocol(protocol, (channel) => {
98
+ const peer = channel.peer
99
+ const who = { username: null, fingerprint: peer }
100
+ const session = { peer, since: now(), starts: [] }
101
+ sessions.add(session)
102
+ try { onSession?.({ peer, state: 'open' }) } catch { /* the embedder's callback */ }
103
+ channel.onClose(() => {
104
+ sessions.delete(session)
105
+ try { onSession?.({ peer, state: 'close' }) } catch { /* the embedder's callback */ }
106
+ })
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
+ })
146
+
147
+ return {
148
+ protocol,
149
+ /** Who is connected now. */
150
+ sessions: () => [...sessions].map(({ peer, since }) => ({ peer, since })),
151
+ /** The tools (as `tools/list` states them) that any peer could be granted now. */
152
+ async list() { return (await handler.list()).filter((t) => TOOL_SCOPE_NAME.test(t.name)) },
153
+ /** 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),
155
+ /** Stop serving: no new channel opens, and every session ends. */
156
+ async close() {
157
+ unserve()
158
+ await handler.closeSessions('the page stopped serving its tools')
159
+ },
160
+ }
161
+ }