@mcp-b/webmcp-ts-sdk 5.1.0 → 6.0.0-beta.20261001010549

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
@@ -20,10 +20,7 @@ pnpm add @mcp-b/webmcp-ts-sdk @mcp-b/transports
20
20
  import { TabServerTransport } from '@mcp-b/transports';
21
21
  import { BrowserMcpServer } from '@mcp-b/webmcp-ts-sdk';
22
22
 
23
- const server = new BrowserMcpServer({
24
- name: 'catalog-app',
25
- version: '1.0.0',
26
- });
23
+ const server = new BrowserMcpServer({ name: 'catalog-app', version: '1.0.0' });
27
24
 
28
25
  await server.connect(
29
26
  new TabServerTransport({
@@ -56,7 +53,7 @@ An `AbortSignal` owns each WebMCP tool registration. Aborting it removes the loc
56
53
 
57
54
  ## What the adapter owns
58
55
 
59
- - WebMCP `registerTool()`, `getTools()`, `ontoolchange`, and descriptor-based `executeTool()`
56
+ - WebMCP `registerTool()`, `getTools()`, `ontoolchange`, `ontoolactivated`, `ontoolcancel`, and descriptor-based `executeTool()`
60
57
  - Native `document.modelContext` registration mirroring and tool reconciliation
61
58
  - MCP-B `registerPrompt()`, `registerResource()`, and `listTools()` extensions
62
59
  - MCP transport lifecycle through `connect()` and `close()`
@@ -67,32 +64,34 @@ Prompt and resource discovery also belongs to MCP. Use a connected MCP client in
67
64
 
68
65
  ## Native integration
69
66
 
70
- Pass an existing context as `native`, then reconcile its current tools:
67
+ The constructor uses `document.modelContext`, installing the bundled `@mcp-b/webmcp-polyfill` (about 28 KB minified) when needed, and delegates browser discovery, execution, and access checks to that context. Without a WebMCP context (no `document`, or an insecure page), the server serves MCP only. The document property keeps exposing the underlying context; `@mcp-b/global` installs the extended API and connects its default transport.
68
+
69
+ To select a context explicitly, pass it as `native`, then reconcile its current tools:
71
70
 
72
71
  ```ts
73
- const server = new BrowserMcpServer(
74
- { name: 'catalog-app', version: '1.0.0' },
75
- { native: document.modelContext }
76
- );
72
+ const native = document.modelContext;
73
+ if (!native) throw new Error('Install a WebMCP runtime first');
74
+ const server = new BrowserMcpServer({ name: 'catalog-app', version: '1.0.0' }, { native });
77
75
 
78
76
  await server.syncNativeTools();
79
77
  ```
80
78
 
81
- `syncNativeTools()` resolves after reconciliation. Later native `toolchange` events trigger another reconciliation. Backfill requires Chrome's optional descriptor-based `executeTool()` extension.
79
+ `syncNativeTools()` resolves after reconciliation, and later native `toolchange` events reconcile again. The [package reference](https://docs.mcp-b.ai/packages/webmcp-ts-sdk/reference) covers frame scope, native result conversion, lifecycle events, and the MCP-only mode.
82
80
 
83
81
  ## Schema boundary
84
82
 
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.
83
+ `BrowserMcpServer` accepts JSON Schema and Standard JSON Schema input metadata. The official MCP server validates input and `outputSchema` on **MCP client calls** only; direct `executeTool()` calls and native mirrors invoke the browser callback without that validation, so validate in the callback when both paths can call a tool. The [`@mcp-b/react-webmcp`](../react-webmcp/README.md) hook already does this.
86
84
 
87
- MCP requires an object-root tool input schema. An array-root WebMCP tool remains available through WebMCP but is omitted from MCP discovery.
85
+ MCP requires an object-root tool input schema. An array-root WebMCP tool remains available through WebMCP but is omitted from MCP discovery. Direct registrations on `server.mcpServer` use the official SDK's schema APIs; Zod 4.2 or newer is supported, and Zod 3 is unsupported. See [the package reference](https://docs.mcp-b.ai/packages/webmcp-ts-sdk/reference#schema-boundary) for the contracts and [schemas and structured output](https://docs.mcp-b.ai/how-to/use-schemas-and-structured-output) for examples.
88
86
 
89
87
  ## Exports
90
88
 
91
- - `BrowserMcpServer`
92
- - `BrowserMcpServerOptions`
93
- - `isBrowserMcpServer`
94
- - `PromptDescriptor`
95
- - `ResourceDescriptor`
89
+ - `BrowserMcpServer`, `BrowserMcpServerOptions`, `isBrowserMcpServer`
90
+ - `PromptDescriptor`, `ResourceDescriptor`, `RegistrationHandle`
91
+ - `ModelContext`, `ModelContextWithExtensions`, `RegisteredTool`, `ToolDescriptor`, `ToolDescriptorFromSchema`, `ToolListItem`, `InputSchema`, and the other MCP-B descriptor and inference types
92
+ - `CallToolResult`, `ContentBlock`, `TextContent`, `JsonObject`, `JsonValue`, re-exported from `@modelcontextprotocol/server`
93
+ - `WebMCP`, the upstream namespace re-exported through `@mcp-b/webmcp-polyfill`, which also brings the polyfill's `SubmitEvent` and `ModelContext` declarations into scope
94
+ - `@mcp-b/webmcp-ts-sdk/schema`: `normalizeInputSchema()`, `normalizeToolResponse()`, `isMcpStandardSchema()`, `ToolInputSchema`, `NormalizedInputSchema`
96
95
 
97
96
  Import MCP clients, servers, schemas, transports, and validators from the official `@modelcontextprotocol/*` packages.
98
97
 
@@ -0,0 +1,22 @@
1
+ import { CallToolResult as CallToolResult$1, ContentBlock, JSONObject as JsonObject, JSONValue as JsonValue, TextContent } from "@modelcontextprotocol/server";
2
+ import { WebMCP } from "webmcp-types";
3
+ import { StandardJSONSchemaV1 } from "@standard-schema/spec";
4
+
5
+ //#region src/common.d.ts
6
+ /** JSON Schema object accepted at the WebMCP boundary. */
7
+ type StandardJsonSchemaObject = ReturnType<StandardJSONSchemaV1.Converter['input']>;
8
+ interface InputSchema extends StandardJsonSchemaObject {
9
+ type?: unknown;
10
+ properties?: Readonly<StandardJsonSchemaObject> | undefined;
11
+ required?: readonly string[] | undefined;
12
+ }
13
+ /** Object or array values accepted at the WebMCP runtime boundary. */
14
+ type WebMcpToolObjectInput = Parameters<WebMCP.ToolExecuteCallback>[0];
15
+ type WebMcpToolInput = WebMcpToolObjectInput | unknown[];
16
+ /** Handle returned by MCP-B registration helpers. */
17
+ interface RegistrationHandle {
18
+ unregister(): void;
19
+ }
20
+ //#endregion
21
+ export { JsonValue as a, WebMcpToolInput as c, JsonObject as i, WebMcpToolObjectInput as l, ContentBlock as n, RegistrationHandle as o, InputSchema as r, TextContent as s, CallToolResult$1 as t };
22
+ //# sourceMappingURL=common-CRzM40Z0.d.ts.map
package/dist/index.d.ts CHANGED
@@ -1,18 +1,122 @@
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";
1
+ import { a as JsonValue, c as WebMcpToolInput, i as JsonObject, l as WebMcpToolObjectInput, n as ContentBlock, o as RegistrationHandle, r as InputSchema, s as TextContent, t as CallToolResult } from "./common-CRzM40Z0.js";
2
+ import { WebMCP } from "@mcp-b/webmcp-polyfill";
3
+ import { GetPromptResult, Implementation, JsonSchemaType, McpServer, ReadResourceResult, ServerOptions, ToolAnnotations as ToolAnnotations$1, Transport, Variables } from "@modelcontextprotocol/server";
4
+ import { WebMCP as WebMCP$1 } from "webmcp-types";
3
5
 
6
+ //#region src/json-schema.d.ts
7
+ /** JSON Schema Draft 2020-12 accepted by the inference helpers. */
8
+ type JsonSchemaForInference = JsonSchemaType;
9
+ type JsonSchemaType$1 = 'string' | 'number' | 'integer' | 'boolean' | 'null' | 'object' | 'array';
10
+ type Simplify<T> = { [K in keyof T]: T[K] } & {};
11
+ type EmptyObject = Record<never, never>;
12
+ type ConstValue<TSchema> = TSchema extends {
13
+ const: infer TValue;
14
+ } ? TValue : never;
15
+ type EnumValue<TSchema> = TSchema extends {
16
+ enum: readonly (infer TValue)[];
17
+ } ? TValue : never;
18
+ type Properties<TSchema> = TSchema extends {
19
+ properties: infer TProperties extends NonNullable<InputSchema['properties']>;
20
+ } ? TProperties : EmptyObject;
21
+ type RequiredKeys<TSchema> = TSchema extends {
22
+ required: readonly (infer TKey extends string)[];
23
+ } ? string extends TKey ? never : Extract<TKey, keyof Properties<TSchema>> : never;
24
+ type AdditionalProperties<TSchema> = TSchema extends {
25
+ additionalProperties: false;
26
+ } ? keyof Properties<TSchema> extends never ? Record<string, never> : EmptyObject : keyof Properties<TSchema> extends never ? TSchema extends {
27
+ additionalProperties: infer TAdditional extends object;
28
+ } ? Record<string, InferJsonSchema<TAdditional>> : WebMcpToolObjectInput : WebMcpToolObjectInput;
29
+ type InferObject<TSchema> = Simplify<{ -readonly [K in keyof Properties<TSchema> as K extends RequiredKeys<TSchema> ? K : never]-?: InferJsonSchema<Properties<TSchema>[K]> } & { -readonly [K in keyof Properties<TSchema> as K extends RequiredKeys<TSchema> ? never : K]?: InferJsonSchema<Properties<TSchema>[K]> } & AdditionalProperties<TSchema>>;
30
+ type TypeKeyword<TSchema> = TSchema extends {
31
+ type: infer TType;
32
+ } ? TType : TSchema extends {
33
+ properties: unknown;
34
+ } | {
35
+ required: unknown;
36
+ } | {
37
+ additionalProperties: unknown;
38
+ } ? 'object' : never;
39
+ type TypeOptions<TSchema> = TypeKeyword<TSchema> extends readonly unknown[] ? Extract<TypeKeyword<TSchema>[number], JsonSchemaType$1> : Extract<TypeKeyword<TSchema>, JsonSchemaType$1>;
40
+ type InferType<TSchema, TType extends JsonSchemaType$1> = TType extends 'object' ? InferObject<TSchema> : TType extends 'array' ? TSchema extends {
41
+ items: infer TItems;
42
+ } ? InferJsonSchema<TItems>[] : unknown[] : TType extends 'string' ? string : TType extends 'number' | 'integer' ? number : TType extends 'boolean' ? boolean : TType extends 'null' ? null : unknown;
43
+ /** Infers a TypeScript value from the supported JSON Schema keywords. */
44
+ type InferJsonSchema<TSchema> = TSchema extends false ? never : TSchema extends true ? unknown : [InputSchema] extends [TSchema] ? unknown : [ConstValue<TSchema>] extends [never] ? [EnumValue<TSchema>] extends [never] ? TypeOptions<TSchema> extends never ? unknown : InferType<TSchema, TypeOptions<TSchema>> : EnumValue<TSchema> : ConstValue<TSchema>;
45
+ /** Uses WebMCP's schema inference for the callback input. */
46
+ type InferArgsFromInputSchema<TSchema extends object> = Parameters<WebMCP$1.ModelContextToolFromSchema<TSchema>['execute']>[0];
47
+ //#endregion
48
+ //#region src/tool.d.ts
49
+ /** MCP annotations plus the WebMCP tool annotations. */
50
+ type ToolAnnotations = ToolAnnotations$1 & WebMCP$1.ToolAnnotations;
51
+ type MaybePromise<T> = WebMCP$1.MaybePromise<T>;
52
+ /**
53
+ * Tool dictionary accepted by the standard browser API.
54
+ * @see https://webmachinelearning.github.io/webmcp/#dictdef-modelcontexttool
55
+ */
56
+ interface ModelContextTool<TArgs extends object = WebMcpToolObjectInput, TResult = unknown, TName extends string = string> extends Omit<WebMCP$1.ModelContextTool, 'name' | 'inputSchema' | 'execute'> {
57
+ name: TName;
58
+ inputSchema?: InputSchema | undefined;
59
+ execute: (input: TArgs, options: WebMCP$1.ToolExecuteCallbackOptions) => MaybePromise<TResult>;
60
+ }
61
+ /** MCP-B tool dictionary with output metadata. */
62
+ type ToolDescriptor<TArgs extends object = WebMcpToolObjectInput, TResult = unknown, TName extends string = string> = Omit<ModelContextTool<TArgs, TResult, TName>, 'annotations'> & {
63
+ outputSchema?: JsonSchemaForInference;
64
+ annotations?: ToolAnnotations;
65
+ };
66
+ /** MCP response with `structuredContent` inferred from an output schema. */
67
+ type ToolResultFromOutputSchema<TOutputSchema extends JsonSchemaForInference | undefined = undefined> = [TOutputSchema] extends [undefined] ? CallToolResult : TOutputSchema extends JsonSchemaForInference ? Omit<CallToolResult, 'structuredContent'> & {
68
+ structuredContent: InferJsonSchema<TOutputSchema>;
69
+ } : never;
70
+ type ExecuteResult<TOutputSchema extends JsonSchemaForInference | undefined> = [TOutputSchema] extends [undefined] ? unknown : TOutputSchema extends JsonSchemaForInference ? InferJsonSchema<TOutputSchema> | ToolResultFromOutputSchema<TOutputSchema> : never;
71
+ /** Tool dictionary with input and output inferred from JSON Schema literals. */
72
+ type ToolDescriptorFromSchema<TInputSchema extends InputSchema, TOutputSchema extends JsonSchemaForInference | undefined = undefined, TName extends string = string> = Omit<ToolDescriptor<InferArgsFromInputSchema<TInputSchema>, ExecuteResult<TOutputSchema>, TName>, 'inputSchema' | 'outputSchema'> & {
73
+ inputSchema: TInputSchema;
74
+ } & ([TOutputSchema] extends [undefined] ? {
75
+ outputSchema?: undefined;
76
+ } : {
77
+ outputSchema: TOutputSchema;
78
+ });
79
+ /** Tool metadata returned by the MCP-B `listTools()` extension. */
80
+ type ToolListItem<TName extends string = string> = Omit<ToolDescriptor<WebMcpToolObjectInput, unknown, TName>, 'execute' | 'inputSchema'> & {
81
+ inputSchema: InputSchema;
82
+ };
83
+ //#endregion
84
+ //#region src/model-context.d.ts
85
+ /** Options for tools exposed by descendant documents. */
86
+ type ModelContextGetToolOptions = WebMCP$1.ModelContextGetToolOptions;
87
+ /** Tool metadata returned by `document.modelContext.getTools()`. */
88
+ type RegisteredTool = WebMCP$1.RegisteredTool;
89
+ /** Options accepted by `ModelContext.registerTool()`. */
90
+ type ModelContextRegisterToolOptions = WebMCP$1.ModelContextRegisterToolOptions;
91
+ type WidenedSchema<TSchema extends InputSchema> = string extends TSchema['type'] ? unknown : never;
92
+ /** The upstream WebMCP browser contract. */
93
+ type ModelContext = WebMCP$1.ModelContext;
94
+ /** Non-standard methods exposed by MCP-B runtimes. */
95
+ interface ModelContextExtensions {
96
+ registerTool<const TInputSchema extends JsonSchemaForInference, const TOutputSchema extends JsonSchemaForInference | undefined = undefined, TName extends string = string>(tool: ToolDescriptorFromSchema<TInputSchema, TOutputSchema, TName>, options?: ModelContextRegisterToolOptions): Promise<void>;
97
+ registerTool<TInputSchema extends InputSchema, TArgs extends WebMcpToolInput = WebMcpToolInput, TName extends string = string>(tool: ToolDescriptor<TArgs, unknown, TName> & {
98
+ inputSchema: TInputSchema;
99
+ } & WidenedSchema<TInputSchema>, options?: ModelContextRegisterToolOptions): Promise<void>;
100
+ registerTool<TArgs extends WebMcpToolInput = WebMcpToolObjectInput, TName extends string = string>(tool: Omit<ToolDescriptor<TArgs, unknown, TName>, 'inputSchema'> & {
101
+ inputSchema?: undefined;
102
+ }, options?: ModelContextRegisterToolOptions): Promise<void>;
103
+ listTools(): ToolListItem[];
104
+ }
105
+ type ModelContextWithExtensions = Omit<ModelContext, 'registerTool'> & ModelContextExtensions;
106
+ //#endregion
4
107
  //#region src/browser-server.d.ts
5
108
  declare const SERVER_MARKER_PROPERTY: "__isBrowserMcpServer";
6
109
  declare function isBrowserMcpServer(context: unknown): context is BrowserMcpServer;
110
+ type ModelContextEventHandler = ModelContext['ontoolchange'];
7
111
  interface BrowserMcpServerOptions extends ServerOptions {
112
+ /** Underlying context. Defaults to document.modelContext, installing upstream if needed. */
8
113
  native?: ModelContext;
9
114
  }
10
115
  /**
11
116
  * Thin WebMCP-to-MCP v2 adapter.
12
117
  *
13
118
  * 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.
119
+ * behavior. This class extends the upstream WebMCP context with MCP capabilities.
16
120
  */
17
121
  declare class BrowserMcpServer extends EventTarget implements ModelContextWithExtensions {
18
122
  readonly [SERVER_MARKER_PROPERTY]: true;
@@ -29,19 +133,24 @@ declare class BrowserMcpServer extends EventTarget implements ModelContextWithEx
29
133
  private readonly removingNativeTools;
30
134
  private nativeSyncQueue;
31
135
  private nativeToolChangeQueue;
32
- private nativeToolChangeListener;
136
+ private readonly nativeToolChangeListener;
33
137
  private closed;
34
138
  private closePromise;
35
- private ontoolchangeHandler;
36
- private readonly ontoolchangeListener;
139
+ private readonly eventHandlers;
140
+ private readonly eventHandlerListener;
141
+ private readonly nativeLifecycleListener;
37
142
  constructor(serverInfo: Implementation, options?: BrowserMcpServerOptions);
38
- get ontoolchange(): ((this: ModelContext, event: Event) => unknown) | null;
39
- set ontoolchange(handler: ((this: ModelContext, event: Event) => unknown) | null);
143
+ private getEventHandler;
144
+ private setEventHandler;
145
+ get ontoolchange(): ModelContextEventHandler;
146
+ set ontoolchange(handler: ModelContextEventHandler);
147
+ get ontoolactivated(): ModelContextEventHandler;
148
+ set ontoolactivated(handler: ModelContextEventHandler);
149
+ get ontoolcancel(): ModelContextEventHandler;
150
+ set ontoolcancel(handler: ModelContextEventHandler);
40
151
  private notifyProducerToolsChanged;
41
- private getNativeStandardToolsApi;
42
152
  private registerNativeToolMirror;
43
153
  private abortNativeToolMirror;
44
- private validateToolDescriptor;
45
154
  private registerToolInMcp;
46
155
  readonly registerTool: ModelContextWithExtensions['registerTool'];
47
156
  private removeTool;
@@ -51,15 +160,15 @@ declare class BrowserMcpServer extends EventTarget implements ModelContextWithEx
51
160
  registerPrompt(descriptor: PromptDescriptor): RegistrationHandle;
52
161
  listTools(): ToolListItem[];
53
162
  getTools(options?: ModelContextGetToolOptions): Promise<RegisteredTool[]>;
54
- executeTool(tool: RegisteredTool, inputArgsJson: string, options?: ChromeModelContextExecuteToolOptions): Promise<string | null>;
163
+ executeTool(...args: Parameters<ModelContext['executeTool']>): Promise<string>;
55
164
  /**
56
165
  * Re-evaluate which registered tools may appear on the wire.
57
166
  *
58
- * `exposedTo` narrows a tool to named embedder origins. The peer origin is only known
59
- * once a transport that reports one has heard from its peer, so a restricted tool stays
60
- * disabled until then — and stays disabled forever on transports that cannot name a peer
61
- * at all. Failing closed keeps a tool that asked for a narrow audience from reaching a
62
- * wider one; unrestricted tools are untouched and behave exactly as before.
167
+ * A published tool without `exposedTo` is enabled. `exposedTo` narrows a tool to named
168
+ * embedder origins. The peer origin is only known once a transport that reports one has
169
+ * heard from its peer, so a restricted tool stays disabled until then — and stays
170
+ * disabled forever on transports that cannot name a peer at all. Failing closed keeps a
171
+ * tool that asked for a narrow audience from reaching a wider one.
63
172
  */
64
173
  private applyToolExposure;
65
174
  /**
@@ -86,5 +195,5 @@ interface PromptDescriptor {
86
195
  get: (args: Record<string, string>) => Promise<GetPromptResult>;
87
196
  }
88
197
  //#endregion
89
- export { BrowserMcpServer, type BrowserMcpServerOptions, type PromptDescriptor, type ResourceDescriptor, isBrowserMcpServer };
198
+ export { BrowserMcpServer, type BrowserMcpServerOptions, type CallToolResult, type ContentBlock, type InferArgsFromInputSchema, type InferJsonSchema, type InputSchema, type JsonObject, type JsonSchemaForInference, type JsonValue, type MaybePromise, type ModelContext, type ModelContextExtensions, type ModelContextGetToolOptions, type ModelContextRegisterToolOptions, type ModelContextTool, type ModelContextWithExtensions, type PromptDescriptor, type RegisteredTool, type RegistrationHandle, type ResourceDescriptor, type TextContent, type ToolAnnotations, type ToolDescriptor, type ToolDescriptorFromSchema, type ToolListItem, type ToolResultFromOutputSchema, type WebMCP, type WebMcpToolInput, type WebMcpToolObjectInput, isBrowserMcpServer };
90
199
  //# sourceMappingURL=index.d.ts.map