@mcp-b/webmcp-ts-sdk 4.1.0-beta.20260702224704 → 5.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/README.md CHANGED
@@ -1,261 +1,108 @@
1
1
  # @mcp-b/webmcp-ts-sdk
2
2
 
3
- > Browser-adapted MCP TypeScript SDK - Dynamic tool registration for AI agents like Claude, ChatGPT, and Gemini
3
+ A thin WebMCP adapter over the official MCP TypeScript SDK v2.
4
4
 
5
5
  [![npm version](https://img.shields.io/npm/v/@mcp-b/webmcp-ts-sdk?style=flat-square)](https://www.npmjs.com/package/@mcp-b/webmcp-ts-sdk)
6
6
  [![npm downloads](https://img.shields.io/npm/dm/@mcp-b/webmcp-ts-sdk?style=flat-square)](https://www.npmjs.com/package/@mcp-b/webmcp-ts-sdk)
7
7
  [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg?style=flat-square)](https://opensource.org/licenses/MIT)
8
- [![TypeScript](https://img.shields.io/badge/TypeScript-5.0+-blue?style=flat-square)](https://www.typescriptlang.org/)
9
- **[Reference](https://docs.mcp-b.ai/packages/webmcp-ts-sdk/reference)** | **[First Tool Tutorial](https://docs.mcp-b.ai/tutorials/first-tool)**
10
8
 
11
- **@mcp-b/webmcp-ts-sdk** adapts the official MCP TypeScript SDK for browser environments, enabling dynamic tool registration required by the WebMCP API. This allows AI agents like Claude, ChatGPT, Gemini, Cursor, and Copilot to interact with browser-based applications.
12
-
13
- ## Why Use @mcp-b/webmcp-ts-sdk?
14
-
15
- | Feature | Benefit |
16
- | ----------------------------- | --------------------------------------------------------------------- |
17
- | **Dynamic Tool Registration** | Register tools after transport connection - required for browser apps |
18
- | **Full SDK Compatibility** | Re-exports all types, classes, and utilities from official SDK |
19
- | **Type-Safe** | No prototype hacks - clean TypeScript extension |
20
- | **Auto-Updates** | Types and protocol follow official SDK automatically |
21
-
22
- ## Overview
23
-
24
- This package adapts the official [@modelcontextprotocol/sdk](https://www.npmjs.com/package/@modelcontextprotocol/sdk) for browser environments with modifications to support dynamic tool registration required by the [WebMCP API](https://webmachinelearning.github.io/webmcp/) (`document.modelContext`).
25
-
26
- ## Why This Package Exists
27
-
28
- The official MCP TypeScript SDK has a restriction that prevents registering server capabilities (like tools) after a transport connection is established. This is enforced by this check in the `Server` class:
29
-
30
- ```typescript
31
- public registerCapabilities(capabilities: ServerCapabilities): void {
32
- if (this.transport) {
33
- throw new Error('Cannot register capabilities after connecting to transport');
34
- }
35
- ...
36
- }
37
- ```
38
-
39
- For WebMCP, this restriction is incompatible because:
40
-
41
- 1. **Tools arrive dynamically** - Web pages call `document.modelContext.registerTool(...)` at any time
42
- 2. **Transport must be ready immediately** - The MCP server/transport needs to be connected when the page loads
43
- 3. **Asynchronous registration** - Tools are registered as the page's JavaScript executes, potentially long after initialization
44
-
45
- This package solves the problem by **pre-registering tool capabilities** before the transport connects, allowing dynamic tool registration to work seamlessly.
46
-
47
- Compatibility note:
48
-
49
- - `BrowserMcpServer.registerTool(tool, options?)` accepts the WebMCP April 23, 2026 draft signature, including `options.signal` (`AbortSignal`) for unregistration. When the signal aborts, both the server-side registration and the mirrored native registration are removed.
50
- - The same call resolves `undefined`, matching current Chromium and the WebMCP spec.
51
- - `unregisterTool(name)` was removed from the WebMCP draft on April 23, 2026 in favor of the `AbortSignal` flow. It is kept on `BrowserMcpServer` with a one-time deprecation warning for older MCP-B integrations. It will be removed in the next major version.
52
- - `provideContext()` and `clearContext()` were removed from the WebMCP draft on March 5, 2026 and are not exposed by `BrowserMcpServer`.
53
-
54
- ## Modifications from Official SDK
55
-
56
- ### BrowserMcpServer Class
57
-
58
- The `BrowserMcpServer` extends `McpServer` with these changes:
59
-
60
- ```typescript
61
- export class BrowserMcpServer extends BaseMcpServer {
62
- constructor(serverInfo, options?) {
63
- // Pre-register tool capabilities in constructor
64
- const enhancedOptions = {
65
- ...options,
66
- capabilities: mergeCapabilities(options?.capabilities || {}, {
67
- tools: { listChanged: true },
68
- }),
69
- };
70
- super(serverInfo, enhancedOptions);
71
- }
72
-
73
- async connect(transport: Transport) {
74
- // Ensure capabilities are set before connecting
75
- // This bypasses the "cannot register after connect" restriction
76
- return super.connect(transport);
77
- }
78
- }
79
- ```
80
-
81
- **Key Difference**: Capabilities are registered **before** connecting, allowing tools to be added dynamically afterward.
82
-
83
- ## What's Re-Exported
84
-
85
- This package re-exports almost everything from the official SDK:
86
-
87
- ### Types
88
-
89
- - All MCP protocol types (`Tool`, `Resource`, `Prompt`, etc.)
90
- - Request/response schemas
91
- - Client and server capabilities
92
- - Error codes and constants
93
-
94
- ### Classes
95
-
96
- - `Server` - Base server class (unchanged)
97
- - `McpServer` - Aliased to `BrowserMcpServer` with our modifications
98
-
99
- ### Utilities
100
-
101
- - `Transport` interface
102
- - `mergeCapabilities` helper
103
- - Protocol version constants
9
+ [`BrowserMcpServer`](https://docs.mcp-b.ai/packages/webmcp-ts-sdk/reference) composes and exposes the official v2 `McpServer`. Use this package when you need direct control over the browser adapter. Most applications should use [`@mcp-b/global`](https://docs.mcp-b.ai/packages/global/overview).
104
10
 
105
11
  ## Installation
106
12
 
107
13
  ```bash
108
- npm install @mcp-b/webmcp-ts-sdk
109
- # or
110
- pnpm add @mcp-b/webmcp-ts-sdk
14
+ pnpm add @mcp-b/webmcp-ts-sdk @mcp-b/transports
111
15
  ```
112
16
 
113
- ## Usage
114
-
115
- Use it exactly like the official SDK:
17
+ ## Example
116
18
 
117
- ```typescript
118
- import { McpServer } from '@mcp-b/webmcp-ts-sdk';
19
+ ```ts
119
20
  import { TabServerTransport } from '@mcp-b/transports';
21
+ import { BrowserMcpServer } from '@mcp-b/webmcp-ts-sdk';
120
22
 
121
- const server = new McpServer({
122
- name: 'my-web-app',
23
+ const server = new BrowserMcpServer({
24
+ name: 'catalog-app',
123
25
  version: '1.0.0',
124
26
  });
125
27
 
126
- // Connect transport first
127
- const transport = new TabServerTransport({ allowedOrigins: ['*'] });
128
- await server.connect(transport);
129
-
130
- // Now you can register tools dynamically (this would fail with official SDK)
131
- server.registerTool(
132
- 'my-tool',
133
- {
134
- description: 'A dynamically registered tool',
135
- inputSchema: { message: z.string() },
136
- // outputSchema is MCP-B metadata for structured, type-safe responses
137
- outputSchema: { result: z.string() },
138
- },
139
- async ({ message }) => {
140
- return {
141
- content: [{ type: 'text', text: `Echo: ${message}` }],
142
- // structuredContent should match the outputSchema for MCP-B adapters
143
- structuredContent: { result: `Echo: ${message}` },
144
- };
145
- }
28
+ await server.connect(
29
+ new TabServerTransport({
30
+ allowedOrigins: ['https://shop.example'],
31
+ })
146
32
  );
147
33
 
148
- // Example with complex output schema
149
- server.registerTool(
150
- 'analyze-data',
34
+ const controller = new AbortController();
35
+
36
+ await server.registerTool(
151
37
  {
152
- description: 'Analyze data and return structured results',
38
+ name: 'echo',
39
+ description: 'Echo a message',
153
40
  inputSchema: {
154
- data: z.array(z.number()),
155
- operation: z.enum(['sum', 'average', 'stats']),
41
+ type: 'object',
42
+ properties: { message: { type: 'string' } },
43
+ required: ['message'],
156
44
  },
157
- outputSchema: {
158
- result: z.number(),
159
- operation: z.string(),
160
- metadata: z.object({
161
- count: z.number(),
162
- min: z.number().optional(),
163
- max: z.number().optional(),
164
- }),
45
+ async execute({ message }) {
46
+ return { content: [{ type: 'text', text: `Echo: ${String(message)}` }] };
165
47
  },
166
48
  },
167
- async ({ data, operation }) => {
168
- const stats = calculateStats(data, operation);
169
- return {
170
- content: [{ type: 'text', text: `Result: ${stats.result}` }],
171
- structuredContent: stats,
172
- };
173
- }
49
+ { signal: controller.signal }
174
50
  );
175
- ```
176
-
177
- ## Architecture
178
51
 
52
+ controller.abort();
179
53
  ```
180
- ┌─────────────────────────────────┐
181
- │ @mcp-b/webmcp-ts-sdk │
182
- │ │
183
- │ ┌───────────────────────────┐ │
184
- │ │ BrowserMcpServer │ │
185
- │ │ (Modified behavior) │ │
186
- │ └───────────┬───────────────┘ │
187
- │ │ extends │
188
- │ ▼ │
189
- │ ┌───────────────────────────┐ │
190
- │ │ @modelcontextprotocol/sdk │ │
191
- │ │ (Official SDK) │ │
192
- │ │ - Types │ │
193
- │ │ - Protocol │ │
194
- │ │ - Validation │ │
195
- │ └───────────────────────────┘ │
196
- └─────────────────────────────────┘
197
- ```
198
-
199
- ## Maintenance Strategy
200
54
 
201
- This package is designed for **minimal maintenance**:
55
+ An `AbortSignal` owns each WebMCP tool registration. Aborting it removes the local MCP registration and its native mirror.
202
56
 
203
- - **Automatic updates** for types, protocol, validation via official SDK dependency
204
- - **Small modification surface** - capability registration and browser runtime adaptation
205
- - **Type-safe** - no prototype hacks or unsafe casts
57
+ ## What the adapter owns
206
58
 
207
- ### Syncing with Upstream
59
+ - WebMCP `registerTool()`, `getTools()`, `ontoolchange`, and descriptor-based `executeTool()`
60
+ - Native `document.modelContext` registration mirroring and tool reconciliation
61
+ - MCP-B `registerPrompt()`, `registerResource()`, and `listTools()` extensions
62
+ - MCP transport lifecycle through `connect()` and `close()`
208
63
 
209
- When the official SDK updates:
64
+ The official `McpServer` owns MCP registration, validation, and protocol behavior. Access it through `server.mcpServer` for official SDK APIs. Register multi-round tools directly on `server.mcpServer`; WebMCP descriptor callbacks are single-round when exposed over MCP.
210
65
 
211
- 1. Update the catalog version in `pnpm-workspace.yaml`
212
- 2. Run `pnpm install` to get latest SDK
213
- 3. Test that capability registration still works
214
- 4. Update this README if SDK behavior changes
66
+ Prompt and resource discovery also belongs to MCP. Use a connected MCP client instead of adapter-side list, read, or get methods.
215
67
 
216
- The modification surface is intentionally small and should be checked whenever
217
- the upstream SDK changes capability registration behavior.
68
+ ## Native integration
218
69
 
219
- ## Frequently Asked Questions
70
+ Pass an existing context as `native`, then reconcile its current tools:
220
71
 
221
- ### Why can't I use the official SDK directly?
222
-
223
- The official SDK throws an error if you try to register tools after connecting a transport. Browsers need dynamic registration because tools arrive asynchronously as the page loads.
72
+ ```ts
73
+ const server = new BrowserMcpServer(
74
+ { name: 'catalog-app', version: '1.0.0' },
75
+ { native: document.modelContext }
76
+ );
224
77
 
225
- ### Is this a fork of the official SDK?
78
+ await server.syncNativeTools();
79
+ ```
226
80
 
227
- No. It is an adapter that extends the official SDK. Core protocol handling and most SDK types come from the upstream package.
81
+ `syncNativeTools()` resolves after reconciliation. Later native `toolchange` events trigger another reconciliation. Backfill requires Chrome's optional descriptor-based `executeTool()` extension.
228
82
 
229
- ### Will this break when the official SDK updates?
83
+ ## Schema boundary
230
84
 
231
- Unlikely. The modification surface is isolated. When upstream updates, update the dependency and run the conformance tests.
85
+ The browser-facing API accepts JSON Schema and Standard Schema inputs. The adapter converts them to the MCP SDK v2 contract. Direct upstream registrations can use Zod 4.2 or newer or the official `fromJsonSchema` helper; Zod 3 is unsupported.
232
86
 
233
- ### When should I use this vs `@mcp-b/global`?
87
+ MCP requires an object-root tool input schema. An array-root WebMCP tool remains available through WebMCP but is omitted from MCP discovery.
234
88
 
235
- Use `@mcp-b/global` for the standard `document.modelContext` API. Use this package directly only if you need low-level control over the MCP server.
89
+ ## Exports
236
90
 
237
- ## Related Packages
91
+ - `BrowserMcpServer`
92
+ - `BrowserMcpServerOptions`
93
+ - `isBrowserMcpServer`
94
+ - `PromptDescriptor`
95
+ - `ResourceDescriptor`
238
96
 
239
- - [`@mcp-b/global`](https://docs.mcp-b.ai/packages/global/reference) - Full MCP-B browser runtime (uses this package internally)
240
- - [`@mcp-b/transports`](https://docs.mcp-b.ai/packages/transports/reference) - Browser-specific MCP transports
241
- - [`@mcp-b/react-webmcp`](https://docs.mcp-b.ai/packages/react-webmcp/reference) - React hooks for MCP
242
- - [`chrome-devtools-mcp`](https://github.com/ChromeDevTools/chrome-devtools-mcp) - Upstream Chrome DevTools MCP server
243
- - [`@modelcontextprotocol/sdk`](https://www.npmjs.com/package/@modelcontextprotocol/sdk) - Official MCP SDK
97
+ Import MCP clients, servers, schemas, transports, and validators from the official `@modelcontextprotocol/*` packages.
244
98
 
245
- ## Resources
99
+ ## Related documentation
246
100
 
247
- - [WebMCP Documentation](https://docs.mcp-b.ai)
101
+ - [Package reference](https://docs.mcp-b.ai/packages/webmcp-ts-sdk/reference)
102
+ - [MCP TypeScript SDK v2](https://ts.sdk.modelcontextprotocol.io/v2/)
248
103
  - [WebMCP specification](https://webmachinelearning.github.io/webmcp/)
249
- - [Model Context Protocol Spec](https://modelcontextprotocol.io/)
250
- - [Official MCP TypeScript SDK](https://github.com/modelcontextprotocol/typescript-sdk)
251
- - [MCP GitHub Repository](https://github.com/modelcontextprotocol)
104
+ - [Chrome Model Context Tool Inspector](https://chromewebstore.google.com/detail/model-context-tool-inspec/gbpdfapgefenggkahomfgkhfehlcenpd)
252
105
 
253
106
  ## License
254
107
 
255
- MIT - see [LICENSE](../../LICENSE) for details
256
-
257
- ## Support
258
-
259
- - [GitHub Issues](https://github.com/WebMCP-org/npm-packages/issues)
260
- - [Documentation](https://docs.mcp-b.ai)
261
- - [Discord Community](https://discord.gg/a9fBR6Bw)
108
+ MIT. See [LICENSE](../../LICENSE).
package/dist/index.d.ts CHANGED
@@ -1,249 +1,89 @@
1
- import { Client } from "@modelcontextprotocol/sdk/client/index.js";
2
- import { RequestOptions, RequestOptions as RequestOptions$1, mergeCapabilities } from "@modelcontextprotocol/sdk/shared/protocol.js";
3
- import { ReadBuffer, serializeMessage } from "@modelcontextprotocol/sdk/shared/stdio.js";
4
- import { CallToolRequest, CallToolRequestSchema, CallToolResult, CallToolResultSchema, ClientCapabilities, ClientNotification, ClientRequest, ClientResult, CreateMessageRequest, CreateMessageRequest as CreateMessageRequest$1, CreateMessageRequestSchema, CreateMessageResult, CreateMessageResult as CreateMessageResult$1, CreateMessageResultSchema, ElicitRequest, ElicitRequest as ElicitRequest$1, ElicitRequestSchema, ElicitResult, ElicitResult as ElicitResult$1, ElicitResultSchema, ErrorCode, GetPromptRequest, GetPromptRequestSchema, GetPromptResult, GetPromptResultSchema, Implementation, Implementation as Implementation$1, InitializeRequest, InitializeRequestSchema, InitializeResult, InitializeResultSchema, JSONRPCMessage, JSONRPCMessageSchema, LATEST_PROTOCOL_VERSION, ListPromptsRequest, ListPromptsRequestSchema, ListPromptsResult, ListPromptsResultSchema, ListResourcesRequest, ListResourcesRequestSchema, ListResourcesResult, ListResourcesResultSchema, ListToolsRequest, ListToolsRequestSchema, ListToolsResult, ListToolsResultSchema, LoggingLevel, LoggingLevelSchema, LoggingMessageNotification, McpError, Notification, Prompt, PromptMessage, PromptMessage as PromptMessage$1, ReadResourceRequest, ReadResourceRequestSchema, ReadResourceResult, ReadResourceResultSchema, Request, Resource, ResourceContents, ResourceListChangedNotificationSchema, ResourceTemplate, Result, SUPPORTED_PROTOCOL_VERSIONS, ServerCapabilities, ServerNotification, ServerRequest, ServerResult, Tool, ToolAnnotations, ToolListChangedNotificationSchema } from "@modelcontextprotocol/sdk/types.js";
5
- import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
6
- import { CfWorkerJsonSchemaValidator, CfWorkerJsonSchemaValidator as PolyfillJsonSchemaValidator } from "@modelcontextprotocol/sdk/validation/cfworker";
7
- import { Transport, Transport as Transport$1, TransportSendOptions } from "@modelcontextprotocol/sdk/shared/transport.js";
8
- import { InputSchema, InputSchema as InputSchema$1, InputSchemaProperty, JsonObject, JsonValue, ModelContextClient, ModelContextCore, ModelContextRegisterToolOptions, ModelContextTestingExecuteToolOptions, ModelContextToolInfo, ModelContextToolReference, ResourceContents as ResourceContents$1, ToolDescriptor, ToolDescriptor as ToolDescriptor$1, ToolExecuteResult, ToolListItem, ToolListItem as ToolListItem$1, ToolResponse, ToolResponse as ToolResponse$1 } from "@mcp-b/webmcp-types";
9
- import { ServerOptions } from "@modelcontextprotocol/sdk/server/index.js";
10
- import { JsonSchemaValidatorResult, jsonSchemaValidator } from "@modelcontextprotocol/sdk/validation";
1
+ import { GetPromptResult, Implementation, McpServer, ReadResourceResult, ServerOptions, Transport, Variables } from "@modelcontextprotocol/server";
2
+ import { ChromeModelContextExecuteToolOptions, InputSchema, ModelContext, ModelContextGetToolOptions, ModelContextWithExtensions, RegisteredTool, RegistrationHandle, ToolListItem } from "@mcp-b/webmcp-types";
11
3
 
12
4
  //#region src/browser-server.d.ts
13
5
  declare const SERVER_MARKER_PROPERTY: "__isBrowserMcpServer";
6
+ declare function isBrowserMcpServer(context: unknown): context is BrowserMcpServer;
14
7
  interface BrowserMcpServerOptions extends ServerOptions {
15
- native?: ModelContextCore;
8
+ native?: ModelContext;
16
9
  }
17
10
  /**
18
- * Browser-optimized MCP Server that speaks WebMCP natively.
11
+ * Thin WebMCP-to-MCP v2 adapter.
19
12
  *
20
- * Implements `registerTool(tool, options?)` while retaining MCP capabilities
21
- * (resources, prompts, elicitation, sampling) via BaseMcpServer.
22
- *
23
- * Deprecated compatibility (kept for Chrome Beta 147 and existing wrappers,
24
- * removed in the next major): `unregisterTool(name)`.
25
- *
26
- * When `native` is provided, tool operations are mirrored so that
27
- * navigator.modelContextTesting stays in sync.
13
+ * The official v2 `McpServer` owns MCP registration, validation, and transport
14
+ * behavior. This class only adds the document-facing WebMCP contract and native
15
+ * Chrome mirroring.
28
16
  */
29
- declare class BrowserMcpServer extends McpServer {
17
+ declare class BrowserMcpServer extends EventTarget implements ModelContextWithExtensions {
30
18
  readonly [SERVER_MARKER_PROPERTY]: true;
31
- private native;
32
- private _promptSchemas;
33
- private _jsonValidator;
34
- private _publicMethodsBound;
35
- private _unregisterToolDeprecationWarned;
36
- private _nativeToolCleanups;
37
- private _tools;
38
- private _producerEventTarget;
39
- private _ontoolchange;
40
- private _producerToolsChangedQueued;
41
- constructor(serverInfo: Implementation$1, options?: BrowserMcpServerOptions);
42
- /**
43
- * navigator.modelContext consumers may destructure methods (e.g. const { registerTool } = ...).
44
- * Bind methods once so they remain callable outside instance-method invocation syntax.
45
- */
46
- private bindPublicApiMethods;
47
- private get _parentResources();
48
- private get _parentPrompts();
49
- private toJsonSchema;
50
- private toInputTransportSchema;
51
- private toOutputTransportSchema;
52
- private isZodSchema;
53
- private getNativeLegacyToolsApi;
19
+ readonly mcpServer: McpServer;
20
+ private readonly native;
21
+ private readonly ownerDocument;
22
+ private readonly tools;
23
+ private peerOrigin;
24
+ private readonly registrations;
25
+ private readonly nativeToolAbortControllers;
26
+ private readonly nativeBackfilledTools;
27
+ private readonly pendingTools;
28
+ private readonly removingNativeTools;
29
+ private nativeSyncQueue;
30
+ private nativeToolChangeQueue;
31
+ private nativeToolChangeListener;
32
+ private closed;
33
+ private closePromise;
34
+ private ontoolchangeHandler;
35
+ private readonly ontoolchangeListener;
36
+ constructor(serverInfo: Implementation, options?: BrowserMcpServerOptions);
37
+ get ontoolchange(): ((this: ModelContext, event: Event) => unknown) | null;
38
+ set ontoolchange(handler: ((this: ModelContext, event: Event) => unknown) | null);
39
+ private notifyProducerToolsChanged;
54
40
  private getNativeStandardToolsApi;
55
- private getNativeUnregisterTool;
56
- private createNativeToolCleanup;
57
41
  private registerNativeToolMirror;
58
- private unregisterNativeToolMirror;
59
- private installToolRequestHandlers;
60
- private registerToolInServer;
61
- get ontoolchange(): ((this: ModelContextCore, ev: Event) => unknown) | null;
62
- set ontoolchange(handler: ((this: ModelContextCore, ev: Event) => unknown) | null);
63
- addEventListener(type: string, listener: EventListenerOrEventListenerObject | null, options?: boolean | AddEventListenerOptions): void;
64
- removeEventListener(type: string, listener: EventListenerOrEventListenerObject | null, options?: boolean | EventListenerOptions): void;
65
- dispatchEvent(event: Event): boolean;
66
- private notifyProducerToolsChanged;
67
- backfillTools(tools: readonly ToolListItem$1[], execute: (name: string, args: Record<string, unknown>) => Promise<ToolResponse$1>): number;
68
- registerTool(tool: ToolDescriptor$1, options?: ModelContextRegisterToolOptions): Promise<void>;
69
- /**
70
- * Backfill tools that were already registered on the native/polyfill context
71
- * before this BrowserMcpServer wrapper was installed.
72
- */
73
- syncNativeTools(): number;
42
+ private abortNativeToolMirror;
43
+ private validateToolDescriptor;
44
+ private registerToolInMcp;
45
+ readonly registerTool: ModelContextWithExtensions['registerTool'];
46
+ private removeTool;
47
+ syncNativeTools(): Promise<void>;
74
48
  private backfillNativeStandardTools;
75
- unregisterTool(nameOrTool: string | ModelContextToolReference): void;
76
- registerResource(descriptor: {
77
- uri: string;
78
- name: string;
79
- description?: string;
80
- mimeType?: string;
81
- read: (uri: URL, params?: Record<string, string>) => Promise<{
82
- contents: ResourceContents$1[];
83
- }>;
84
- }): {
85
- unregister: () => void;
86
- };
87
- registerPrompt(descriptor: {
88
- name: string;
89
- description?: string;
90
- argsSchema?: InputSchema$1;
91
- get: (args: Record<string, unknown>) => Promise<{
92
- messages: PromptMessage$1[];
93
- }>;
94
- }): {
95
- unregister: () => void;
96
- };
97
- private resolveToolNameForUnregister;
98
- private warnUnregisterToolDeprecationOnce;
99
- listResources(): Array<{
100
- uri: string;
101
- name: string;
102
- description?: string;
103
- mimeType?: string;
104
- }>;
105
- readResource(uri: string): Promise<{
106
- contents: ResourceContents$1[];
107
- }>;
108
- listPrompts(): Array<{
109
- name: string;
110
- description?: string;
111
- arguments?: Array<{
112
- name: string;
113
- description?: string;
114
- required?: boolean;
115
- }>;
116
- }>;
117
- getPrompt(name: string, args?: Record<string, unknown>): Promise<{
118
- messages: PromptMessage$1[];
119
- }>;
120
- listTools(): ToolListItem$1[];
121
- private listToolsForMcpTransport;
122
- private toMcpCallToolResult;
123
- getTools(): Promise<ModelContextToolInfo[]>;
124
- /**
125
- * Override SDK's validateToolInput to handle both Zod schemas and plain JSON Schema.
126
- * Zod schemas use the SDK's safeParseAsync; plain JSON Schema uses the configured SDK validator.
127
- */
128
- validateToolInput(tool: {
129
- inputSchema?: unknown;
130
- }, args: Record<string, unknown> | undefined, toolName: string): Promise<Record<string, unknown> | undefined>;
49
+ registerResource(descriptor: ResourceDescriptor): RegistrationHandle;
50
+ registerPrompt(descriptor: PromptDescriptor): RegistrationHandle;
51
+ listTools(): ToolListItem[];
52
+ getTools(options?: ModelContextGetToolOptions): Promise<RegisteredTool[]>;
53
+ executeTool(tool: RegisteredTool, inputArgsJson: string, options?: ChromeModelContextExecuteToolOptions): Promise<string | null>;
131
54
  /**
132
- * Override SDK's validateToolOutput to handle both Zod schemas and plain JSON Schema.
133
- */
134
- validateToolOutput(tool: {
135
- outputSchema?: unknown;
136
- }, result: unknown, toolName: string): Promise<void>;
137
- /**
138
- * Executes a registered tool by name.
55
+ * Re-evaluate which registered tools may appear on the wire.
139
56
  *
140
- * @deprecated Prefer the WebMCP standard producer path: get a descriptor from
141
- * `getTools()` and pass it to `executeTool(tool, inputArgsJson)`. This method
142
- * remains as an MCP-B compatibility convenience and MCP transport bridge.
57
+ * `exposedTo` narrows a tool to named embedder origins. The peer origin is only known
58
+ * once a transport that reports one has heard from its peer, so a restricted tool stays
59
+ * disabled until then — and stays disabled forever on transports that cannot name a peer
60
+ * at all. Failing closed keeps a tool that asked for a narrow audience from reaching a
61
+ * wider one; unrestricted tools are untouched and behave exactly as before.
143
62
  */
144
- callTool(params: {
145
- name: string;
146
- arguments?: Record<string, unknown>;
147
- }): Promise<ToolResponse$1>;
63
+ private applyToolExposure;
148
64
  /**
149
- * Executes a tool descriptor returned from getTools().
150
- */
151
- executeTool(tool: ModelContextToolInfo, inputArgsJson: string, options?: ModelContextTestingExecuteToolOptions): Promise<string | null>;
152
- /**
153
- * Executes a registered tool by name.
154
- *
155
- * @deprecated Prefer the WebMCP standard producer path: get a descriptor from
156
- * `getTools()` and pass it to `executeTool(tool, inputArgsJson)`.
65
+ * Follow the peer origin of transports that report one, so `exposedTo` can be scoped to
66
+ * the embedder actually connected. Duck-typed rather than imported: the SDK must not take
67
+ * a build dependency on `@mcp-b/transports`, and transports that never name a peer simply
68
+ * leave every restricted tool disabled.
157
69
  */
158
- executeTool(name: string, args?: Record<string, unknown>): Promise<ToolResponse$1>;
159
- /**
160
- * Override connect to initialize request handlers BEFORE the transport connection.
161
- * This prevents "Cannot register capabilities after connecting to transport" errors
162
- * when tools are registered dynamically after connection.
163
- *
164
- * Tool handlers are installed with the public low-level Server API in the constructor.
165
- * Prompt/resource handlers still come from the parent, then prompt handlers are replaced
166
- * where the parent expects Zod shapes instead of plain JSON Schema.
167
- */
168
- connect(transport: Transport$1): Promise<void>;
169
- createMessage(params: CreateMessageRequest$1['params'], options?: RequestOptions$1): Promise<CreateMessageResult$1>;
170
- elicitInput(params: ElicitRequest$1['params'], options?: RequestOptions$1): Promise<ElicitResult$1>;
70
+ private observePeerOrigin;
71
+ connect(transport: Transport): Promise<void>;
72
+ close(): Promise<void>;
171
73
  }
172
74
  interface ResourceDescriptor {
173
75
  uri: string;
174
76
  name: string;
175
77
  description?: string;
176
78
  mimeType?: string;
177
- read: (uri: URL, params?: Record<string, string>) => Promise<{
178
- contents: ResourceContents$1[];
179
- }>;
79
+ read: (uri: URL, params?: Variables) => Promise<ReadResourceResult>;
180
80
  }
181
81
  interface PromptDescriptor {
182
82
  name: string;
183
83
  description?: string;
184
- argsSchema?: InputSchema$1;
185
- get: (args: Record<string, unknown>) => Promise<{
186
- messages: PromptMessage$1[];
187
- }>;
84
+ argsSchema?: InputSchema;
85
+ get: (args: Record<string, string>) => Promise<GetPromptResult>;
188
86
  }
189
87
  //#endregion
190
- //#region src/no-op-validator.d.ts
191
- /**
192
- * No-op JSON Schema validator for browser environments.
193
- *
194
- * This validator bypasses the MCP SDK's internal ajv-based validation which causes
195
- * "Error compiling schema" errors in browser extensions due to ajv's use of
196
- * eval/Function constructor.
197
- *
198
- * Validation is handled externally by Zod in @mcp-b/global, making the SDK's
199
- * internal validation redundant. This no-op validator allows the SDK to function
200
- * without the ajv dependency issues.
201
- */
202
- /**
203
- * A no-op JSON Schema validator that always returns valid.
204
- *
205
- * Use this in browser environments where:
206
- * - ajv causes "Error compiling schema" errors
207
- * - Validation is already handled elsewhere (e.g., by Zod)
208
- * - You need to avoid eval/Function constructor restrictions
209
- *
210
- * @example
211
- * ```typescript
212
- * import { BrowserMcpServer } from '@mcp-b/webmcp-ts-sdk';
213
- * import { NoOpJsonSchemaValidator } from '@mcp-b/webmcp-ts-sdk/no-op-validator';
214
- *
215
- * const server = new BrowserMcpServer(
216
- * { name: 'my-server', version: '1.0.0' },
217
- * { jsonSchemaValidator: new NoOpJsonSchemaValidator() }
218
- * );
219
- * ```
220
- */
221
- declare class NoOpJsonSchemaValidator implements jsonSchemaValidator {
222
- /**
223
- * Returns a validator function that always passes.
224
- * The input data is passed through unchanged.
225
- *
226
- * @param _schema - The JSON Schema (ignored)
227
- * @returns A validator function that always returns valid
228
- */
229
- getValidator<T>(_schema: unknown): (input: unknown) => JsonSchemaValidatorResult<T>;
230
- }
231
- //#endregion
232
- //#region src/schema.d.ts
233
- declare const DEFAULT_INPUT_SCHEMA: InputSchema$1;
234
- interface ToWebMcpJsonSchemaOptions {
235
- requireObjectType?: boolean;
236
- }
237
- /**
238
- * Converts Zod schemas, Zod raw shapes, or plain JSON Schema objects to the
239
- * JSON Schema shape expected by WebMCP tool descriptors.
240
- */
241
- declare function toWebMcpJsonSchema(schema: unknown, options?: ToWebMcpJsonSchemaOptions): InputSchema$1;
242
- declare function toWebMcpInputSchema(schema: unknown): InputSchema$1;
243
- //#endregion
244
- //#region src/index.d.ts
245
- type SamplingRequestParams = CreateMessageRequest$1['params'];
246
- type SamplingResult = CreateMessageResult$1;
247
- //#endregion
248
- export { BrowserMcpServer, BrowserMcpServer as McpServer, type BrowserMcpServerOptions, type CallToolRequest, CallToolRequestSchema, type CallToolResult, CallToolResultSchema, CfWorkerJsonSchemaValidator, Client, type ClientCapabilities, type ClientNotification, type ClientRequest, type ClientResult, type CreateMessageRequest, CreateMessageRequestSchema, type CreateMessageResult, CreateMessageResultSchema, DEFAULT_INPUT_SCHEMA, type ElicitRequest, ElicitRequestSchema, type ElicitResult, ElicitResultSchema, ErrorCode, type GetPromptRequest, GetPromptRequestSchema, type GetPromptResult, GetPromptResultSchema, type Implementation, type InitializeRequest, InitializeRequestSchema, type InitializeResult, InitializeResultSchema, type InputSchema, type InputSchemaProperty, type JSONRPCMessage, JSONRPCMessageSchema, type JsonObject, type JsonValue, LATEST_PROTOCOL_VERSION, type ListPromptsRequest, ListPromptsRequestSchema, type ListPromptsResult, ListPromptsResultSchema, type ListResourcesRequest, ListResourcesRequestSchema, type ListResourcesResult, ListResourcesResultSchema, type ListToolsRequest, ListToolsRequestSchema, type ListToolsResult, ListToolsResultSchema, type LoggingLevel, LoggingLevelSchema, type LoggingMessageNotification, type McpError, type ModelContextClient, NoOpJsonSchemaValidator, type Notification, PolyfillJsonSchemaValidator, type Prompt, type PromptDescriptor, type PromptMessage, ReadBuffer, type ReadResourceRequest, ReadResourceRequestSchema, type ReadResourceResult, ReadResourceResultSchema, type Request, type RequestOptions, type Resource, type ResourceContents, type ResourceDescriptor, ResourceListChangedNotificationSchema, type ResourceTemplate, type Result, SERVER_MARKER_PROPERTY, SUPPORTED_PROTOCOL_VERSIONS, SamplingRequestParams, SamplingResult, type ServerCapabilities, type ServerNotification, type ServerRequest, type ServerResult, type ToWebMcpJsonSchemaOptions, type Tool, type ToolAnnotations, type ToolDescriptor, type ToolExecuteResult, ToolListChangedNotificationSchema, type ToolListItem, type ToolResponse, type Transport, type TransportSendOptions, mergeCapabilities, serializeMessage, toWebMcpInputSchema, toWebMcpJsonSchema };
88
+ export { BrowserMcpServer, type BrowserMcpServerOptions, type PromptDescriptor, type ResourceDescriptor, isBrowserMcpServer };
249
89
  //# sourceMappingURL=index.d.ts.map