@mcp-b/react-webmcp 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/dist/index.d.ts CHANGED
@@ -1,459 +1,177 @@
1
+ import { InferOutput, InferToolInput, ToolExecutionState, WebMCPConfig, WebMCPReturn, WebMCPReturn as WebMCPReturn$1, useWebMCP } from "usewebmcp";
2
+ import { ReactElement, ReactNode } from "react";
1
3
  import { ToolInputSchema, ToolInputSchema as ToolInputSchema$1 } from "@mcp-b/webmcp-polyfill/schema";
2
- import { DependencyList, ReactElement, ReactNode } from "react";
3
- import { BrowserMcpServer as ModelContextProtocol, Client, PromptDescriptor, PromptMessage, RequestOptions, Resource, ResourceContents, ResourceDescriptor, SamplingRequestParams, SamplingResult, ServerCapabilities, Tool, Transport } from "@mcp-b/webmcp-ts-sdk";
4
- import { CallToolResult, ElicitationParams, ElicitationResult, InferArgsFromInputSchema, InferJsonSchema, InputSchema, JsonSchemaForInference, ToolAnnotations, ToolDescriptor } from "@mcp-b/webmcp-types";
5
- import { z } from "zod";
4
+ import { BrowserMcpServer as ModelContextProtocol, PromptDescriptor, PromptDescriptor as PromptDescriptor$1, ResourceDescriptor, ResourceDescriptor as ResourceDescriptor$1 } from "@mcp-b/webmcp-ts-sdk";
5
+ import { Client, ConnectOptions, Resource, ServerCapabilities, Tool, Transport } from "@modelcontextprotocol/client";
6
+ import { CallToolResult, MaybePromise, ToolAnnotations, ToolDescriptor } from "@mcp-b/webmcp-types";
6
7
 
7
- //#region src/zod-utils.d.ts
8
- type ZodSchemaObject = Record<string, z.ZodTypeAny>;
9
- type ZodSchema = ZodSchemaObject | z.ZodTypeAny;
10
- //#endregion
11
- //#region src/types.d.ts
12
- /**
13
- * Union of all input schema types supported by react-webmcp:
14
- * - `ToolInputSchema` (JSON Schema + Standard Schema v1)
15
- * - `ZodSchemaObject` (Zod v3 `Record<string, z.ZodTypeAny>`)
16
- */
17
- type ReactWebMCPInputSchema = ToolInputSchema$1 | ZodSchemaObject;
18
- /**
19
- * Union of all output schema types supported by react-webmcp:
20
- * - `JsonSchemaForInference` (MCP output schema)
21
- * - `ZodSchema` (converted to the inferable JSON Schema subset at runtime)
22
- */
23
- type ReactWebMCPOutputSchema = JsonSchemaForInference | ZodSchema;
24
- /**
25
- * Infers handler input type from a Standard Schema, Zod v3 schema, or JSON Schema.
26
- *
27
- * - **Standard Schema** (Zod v4, Valibot, ArkType): extracts `~standard.types.input`
28
- * - **Zod v3** (`Record<string, z.ZodTypeAny>`): uses `z.infer<z.ZodObject<T>>`
29
- * - **JSON Schema** (`as const`): uses `InferArgsFromInputSchema` for structural inference
30
- * - **Fallback**: `Record<string, unknown>`
31
- *
32
- * @template T - The input schema type
33
- * @internal
34
- */
35
- type InferToolInput<T> = T extends Record<string, z.ZodTypeAny> ? z.infer<z.ZodObject<T>> : T extends {
36
- readonly '~standard': {
37
- readonly types?: infer Types;
38
- };
39
- } ? NonNullable<Types> extends {
40
- readonly input: infer I;
41
- } ? I : Record<string, unknown> : T extends InputSchema ? InferArgsFromInputSchema<T> : Record<string, unknown>;
8
+ //#region src/client/McpClientProvider.d.ts
42
9
  /**
43
- * Utility type to infer the output type from an output schema.
44
- *
45
- * - inferable JSON Schema resolves via `InferJsonSchema`
46
- * - `ZodSchemaObject` resolves via `z.infer<z.ZodObject<...>>`
47
- * - `undefined` falls back to `TFallback`
10
+ * Context value provided by McpClientProvider.
48
11
  *
49
- * @template TOutputSchema - Output schema for result inference
50
- * @template TFallback - Fallback type when no schema is provided
51
12
  * @internal
52
13
  */
53
- type InferOutput<TOutputSchema extends ReactWebMCPOutputSchema | undefined = undefined, TFallback = unknown> = TOutputSchema extends undefined ? TFallback : TOutputSchema extends z.ZodTypeAny ? z.infer<TOutputSchema> : TOutputSchema extends Record<string, z.ZodTypeAny> ? z.infer<z.ZodObject<TOutputSchema>> : TOutputSchema extends JsonSchemaForInference ? InferJsonSchema<TOutputSchema> : TFallback;
14
+ interface McpClientContextValue {
15
+ client: Client;
16
+ tools: Tool[];
17
+ resources: Resource[];
18
+ isConnected: boolean;
19
+ isLoading: boolean;
20
+ error: Error | null;
21
+ capabilities: ServerCapabilities | null;
22
+ reconnect: (freshTransport?: Transport) => Promise<void>;
23
+ }
54
24
  /**
55
- * Represents the current execution state of a tool, including loading status,
56
- * results, errors, and execution history.
25
+ * Props for the McpClientProvider component.
57
26
  *
58
- * @template TOutput - The type of data returned by the tool handler
59
27
  * @public
60
28
  */
61
- interface ToolExecutionState<TOutput = unknown> {
29
+ interface McpClientProviderProps {
62
30
  /**
63
- * Indicates whether the tool is currently executing.
64
- * Use this to show loading states in your UI.
31
+ * React children to render within the provider.
65
32
  */
66
- isExecuting: boolean;
33
+ children: ReactNode;
67
34
  /**
68
- * The result from the most recent successful execution.
69
- * Will be `null` if the tool hasn't been executed or last execution failed.
35
+ * MCP Client instance to use for communication.
70
36
  */
71
- lastResult: TOutput | null;
37
+ client: Client;
72
38
  /**
73
- * The error from the most recent failed execution.
74
- * Will be `null` if the tool hasn't been executed or last execution succeeded.
39
+ * Transport instance for the client to connect through.
75
40
  */
76
- error: Error | null;
41
+ transport: Transport;
77
42
  /**
78
- * Total number of times this tool has been executed.
79
- * Increments on successful executions only.
43
+ * Optional connection options.
80
44
  */
81
- executionCount: number;
45
+ opts?: ConnectOptions;
82
46
  }
83
47
  /**
84
- * Configuration options for the `useWebMCP` hook.
48
+ * Provider component that manages an MCP client connection and exposes
49
+ * tools, resources, and connection state to child components.
85
50
  *
86
- * Defines a tool's metadata, schema, handler, and lifecycle callbacks.
51
+ * This provider handles:
52
+ * - Establishing and maintaining the MCP client connection
53
+ * - Fetching available tools and resources from the server
54
+ * - Listening for server notifications about tool/resource changes
55
+ * - Managing connection state and errors
56
+ * - Automatic cleanup on unmount
87
57
  *
88
- * @template TInputSchema - Schema defining input parameters
89
- * @template TOutputSchema - Output schema defining output structure
58
+ * @param props - Component props
59
+ * @returns Provider component wrapping children
90
60
  *
91
61
  * @public
92
62
  *
93
- * @example Basic tool without output schema:
94
- * ```typescript
95
- * const config: WebMCPConfig = {
96
- * name: 'posts_like',
97
- * description: 'Like a post by its ID',
98
- * inputSchema: {
99
- * type: 'object',
100
- * properties: { postId: { type: 'string' } },
101
- * required: ['postId'],
102
- * } as const,
103
- * handler: async ({ postId }) => {
104
- * await api.likePost(postId);
105
- * return { success: true };
106
- * },
107
- * };
108
- * ```
109
- *
110
- * @example Tool with output schema (enables MCP structuredContent):
111
- * ```typescript
112
- * useWebMCP({
113
- * name: 'posts_like',
114
- * description: 'Like a post and return updated like count',
115
- * inputSchema: {
116
- * type: 'object',
117
- * properties: { postId: { type: 'string' } },
118
- * required: ['postId'],
119
- * } as const,
120
- * outputSchema: {
121
- * type: 'object',
122
- * properties: {
123
- * likes: { type: 'number', description: 'Updated like count' },
124
- * likedAt: { type: 'string', description: 'ISO timestamp of the like' },
125
- * },
126
- * } as const,
127
- * handler: async ({ postId }) => {
128
- * const result = await api.likePost(postId);
129
- * return { likes: result.likes, likedAt: new Date().toISOString() };
130
- * },
131
- * });
132
- * ```
133
- */
134
- interface WebMCPConfig<TInputSchema extends ReactWebMCPInputSchema = InputSchema, TOutputSchema extends ReactWebMCPOutputSchema | undefined = undefined> {
135
- /**
136
- * Unique identifier for the tool (e.g., 'posts_like', 'graph_navigate').
137
- * Must follow naming conventions: lowercase with underscores.
138
- */
139
- name: string;
140
- /**
141
- * Human-readable description explaining what the tool does.
142
- * This description is used by AI assistants to understand when to use the tool.
143
- */
144
- description: string;
145
- /**
146
- * Schema defining the input parameters for the tool.
147
- * Use `as const` to enable type inference for the handler's input.
148
- *
149
- * @example
150
- * ```typescript
151
- * inputSchema: {
152
- * type: 'object',
153
- * properties: {
154
- * postId: { type: 'string', description: 'The ID of the post to like' },
155
- * userId: { type: 'string' },
156
- * },
157
- * required: ['postId'],
158
- * } as const
159
- * ```
160
- */
161
- inputSchema?: TInputSchema;
162
- /**
163
- * **Recommended:** Output schema defining the expected output structure.
164
- * Accepts an inferable JSON Schema or a Zod schema that converts to one.
165
- *
166
- * When provided, this enables three key features:
167
- * 1. **Type Safety**: The handler's return type is inferred from this schema
168
- * 2. **MCP structuredContent**: The MCP response includes `structuredContent`
169
- * containing the typed output per the MCP specification
170
- * 3. **AI Understanding**: AI models can better understand and use the tool's output
171
- *
172
- * @see {@link https://spec.modelcontextprotocol.io/specification/server/tools/#output-schemas}
173
- *
174
- * @example
175
- * ```typescript
176
- * outputSchema: {
177
- * type: 'object',
178
- * properties: {
179
- * counter: { type: 'number', description: 'The current counter value' },
180
- * timestamp: { type: 'string', description: 'ISO timestamp' },
181
- * },
182
- * } as const
183
- * ```
184
- */
185
- outputSchema?: TOutputSchema;
186
- /**
187
- * Optional metadata annotations providing hints about tool behavior.
188
- * See {@link ToolAnnotations} for available options.
189
- */
190
- annotations?: ToolAnnotations;
191
- /**
192
- * The function that executes when the tool is called.
193
- * Can be synchronous or asynchronous.
194
- *
195
- * When `outputSchema` is provided, the return type is inferred from the schema.
196
- * Otherwise, any return type is allowed.
197
- *
198
- * @param input - Validated input parameters matching the inputSchema
199
- * @returns The result data or a Promise resolving to the result
200
- */
201
- handler: (input: InferToolInput<TInputSchema>) => Promise<InferOutput<TOutputSchema>> | InferOutput<TOutputSchema>;
202
- /**
203
- * Custom formatter for the MCP text response.
204
- *
205
- * @deprecated Use `outputSchema` instead. The `outputSchema` provides type-safe
206
- * structured output via MCP's `structuredContent`, which is the recommended
207
- * approach for tool outputs. This property will be removed in a future version.
208
- *
209
- * @param output - The raw output from the handler
210
- * @returns Formatted string for the MCP response content
211
- */
212
- formatOutput?: (output: InferOutput<TOutputSchema>) => string;
213
- /**
214
- * Optional callback invoked when the tool execution succeeds.
215
- * Useful for triggering side effects like navigation or analytics.
216
- *
217
- * @param result - The successful result from the handler
218
- * @param input - The input that was passed to the handler
219
- */
220
- onSuccess?: (result: InferOutput<TOutputSchema>, input: unknown) => void;
221
- /**
222
- * Optional callback invoked when the tool execution fails.
223
- * Useful for error handling, logging, or showing user notifications.
224
- *
225
- * @param error - The error that occurred during execution
226
- * @param input - The input that was passed to the handler
227
- */
228
- onError?: (error: Error, input: unknown) => void;
229
- }
230
- /**
231
- * Return value from the `useWebMCP` hook.
232
- * Provides access to execution state and methods for manual tool control.
63
+ * @example
64
+ * Connect to an MCP server via tab transport:
65
+ * ```tsx
66
+ * import { TabClientTransport } from '@mcp-b/transports';
67
+ * import { McpClientProvider } from '@mcp-b/react-webmcp';
68
+ * import { Client } from '@modelcontextprotocol/client';
233
69
  *
234
- * @template TOutputSchema - Output schema defining output structure
235
- * @public
236
- */
237
- interface WebMCPReturn<TOutputSchema extends ReactWebMCPOutputSchema | undefined = undefined, TInputSchema extends ReactWebMCPInputSchema = InputSchema> {
238
- /**
239
- * Current execution state including loading status, results, and errors.
240
- * See {@link ToolExecutionState} for details.
241
- */
242
- state: ToolExecutionState<InferOutput<TOutputSchema>>;
243
- /**
244
- * Manually execute the tool with the provided input.
245
- * Useful for testing, debugging, or triggering execution from your UI.
246
- *
247
- * @param input - The input parameters to pass to the tool
248
- * @returns Promise resolving to the tool's output
249
- * @throws Error if validation fails or handler throws
250
- */
251
- execute: (input: InferToolInput<TInputSchema>) => Promise<InferOutput<TOutputSchema>>;
252
- /**
253
- * Reset the execution state to its initial values.
254
- * Clears results, errors, and resets the execution count.
255
- */
256
- reset: () => void;
257
- }
258
- /**
259
- * Configuration options for the `useWebMCPPrompt` hook.
260
- * Defines a prompt's metadata, argument schema, and message generator.
70
+ * const client = new Client(
71
+ * { name: 'my-app', version: '1.0.0' },
72
+ * { versionNegotiation: { mode: 'auto' } }
73
+ * );
261
74
  *
262
- * @template TArgsSchema - JSON Schema defining prompt arguments
263
- * @public
75
+ * const transport = new TabClientTransport({
76
+ * channelId: 'mcp',
77
+ * targetOrigin: window.location.origin,
78
+ * });
264
79
  *
265
- * @example
266
- * ```typescript
267
- * const config: WebMCPPromptConfig = {
268
- * name: 'review_code',
269
- * description: 'Review code for best practices',
270
- * argsSchema: {
271
- * type: 'object',
272
- * properties: {
273
- * code: { type: 'string', description: 'The code to review' },
274
- * language: { type: 'string', description: 'Programming language' },
275
- * },
276
- * required: ['code'],
277
- * } as const,
278
- * get: async ({ code, language }) => ({
279
- * messages: [{
280
- * role: 'user',
281
- * content: { type: 'text', text: `Review this ${language ?? ''} code:\n${code}` }
282
- * }]
283
- * }),
284
- * };
80
+ * function App() {
81
+ * return (
82
+ * <McpClientProvider client={client} transport={transport}>
83
+ * <MyAppContent />
84
+ * </McpClientProvider>
85
+ * );
86
+ * }
285
87
  * ```
286
- */
287
- interface WebMCPPromptConfig<TArgsSchema extends ReactWebMCPInputSchema = InputSchema> {
288
- /**
289
- * Unique identifier for the prompt (e.g., 'review_code', 'summarize_text').
290
- */
291
- name: string;
292
- /**
293
- * Optional description explaining what the prompt does.
294
- * This helps AI assistants understand when to use the prompt.
295
- */
296
- description?: string;
297
- /**
298
- * Optional JSON Schema defining the arguments for the prompt.
299
- * Use `as const` to enable type inference for the `get` function's arguments.
300
- */
301
- argsSchema?: TArgsSchema;
302
- /**
303
- * Function that generates the prompt messages.
304
- * Can be synchronous or asynchronous.
305
- *
306
- * @param args - Validated arguments matching the argsSchema
307
- * @returns Object containing the prompt messages
308
- */
309
- get: (args: InferToolInput<TArgsSchema>) => Promise<{
310
- messages: PromptMessage[];
311
- }> | {
312
- messages: PromptMessage[];
313
- };
314
- }
315
- /**
316
- * Return value from the `useWebMCPPrompt` hook.
317
- * Indicates whether the prompt is registered.
318
88
  *
319
- * @public
320
- */
321
- interface WebMCPPromptReturn {
322
- /**
323
- * Whether the prompt is currently registered with the Model Context API.
324
- */
325
- isRegistered: boolean;
326
- }
327
- /**
328
- * Configuration options for the `useWebMCPResource` hook.
329
- * Defines a resource's metadata and read handler.
89
+ * @example
90
+ * Access tools from child components:
91
+ * ```tsx
92
+ * function MyAppContent() {
93
+ * const { tools, isConnected, isLoading } = useMcpClient();
330
94
  *
331
- * @public
95
+ * if (isLoading) {
96
+ * return <div>Connecting to MCP server...</div>;
97
+ * }
332
98
  *
333
- * @example Static resource
334
- * ```typescript
335
- * const config: WebMCPResourceConfig = {
336
- * uri: 'config://app-settings',
337
- * name: 'App Settings',
338
- * description: 'Application configuration',
339
- * mimeType: 'application/json',
340
- * read: async (uri) => ({
341
- * contents: [{ uri: uri.href, text: JSON.stringify(settings) }]
342
- * }),
343
- * };
344
- * ```
99
+ * if (!isConnected) {
100
+ * return <div>Failed to connect to MCP server</div>;
101
+ * }
345
102
  *
346
- * @example Dynamic resource with URI template
347
- * ```typescript
348
- * const config: WebMCPResourceConfig = {
349
- * uri: 'user://{userId}/profile',
350
- * name: 'User Profile',
351
- * description: 'User profile data',
352
- * read: async (uri, params) => ({
353
- * contents: [{
354
- * uri: uri.href,
355
- * text: JSON.stringify(await fetchUser(params?.userId ?? ''))
356
- * }]
357
- * }),
358
- * };
103
+ * return (
104
+ * <div>
105
+ * <h2>Available Tools:</h2>
106
+ * <ul>
107
+ * {tools.map(tool => (
108
+ * <li key={tool.name}>{tool.description}</li>
109
+ * ))}
110
+ * </ul>
111
+ * </div>
112
+ * );
113
+ * }
359
114
  * ```
360
115
  */
361
- interface WebMCPResourceConfig {
362
- /**
363
- * The resource URI or URI template.
364
- * - Static: "config://app-settings"
365
- * - Template: "user://{userId}/profile" where {userId} becomes a parameter
366
- */
367
- uri: string;
368
- /**
369
- * Human-readable name for the resource.
370
- */
371
- name: string;
372
- /**
373
- * Optional description of what the resource provides.
374
- */
375
- description?: string;
376
- /**
377
- * Optional MIME type of the resource content.
378
- */
379
- mimeType?: string;
380
- /**
381
- * Function that reads and returns the resource content.
382
- *
383
- * @param uri - The resolved URI being requested
384
- * @param params - Parameters extracted from URI template (if applicable)
385
- * @returns Resource contents with the data
386
- */
387
- read: (uri: URL, params?: Record<string, string>) => Promise<{
388
- contents: ResourceContents[];
389
- }>;
390
- }
391
- /**
392
- * Return value from the `useWebMCPResource` hook.
393
- * Indicates whether the resource is registered.
394
- *
395
- * @public
396
- */
397
- interface WebMCPResourceReturn {
398
- /**
399
- * Whether the resource is currently registered with the Model Context API.
400
- */
401
- isRegistered: boolean;
402
- }
403
- //#endregion
404
- //#region src/useWebMCP.d.ts
116
+ declare function McpClientProvider({
117
+ children,
118
+ client,
119
+ transport,
120
+ opts
121
+ }: McpClientProviderProps): ReactElement;
405
122
  /**
406
- * React hook for registering and managing Model Context Protocol (MCP) tools.
407
- *
408
- * This hook handles the complete lifecycle of an MCP tool:
409
- * - Registers the tool with `window.document.modelContext`
410
- * - Manages execution state (loading, results, errors)
411
- * - Handles tool execution and lifecycle callbacks
412
- * - Automatically unregisters on component unmount
413
- * - Returns `structuredContent` when `outputSchema` is defined
123
+ * Hook to access the MCP client context.
124
+ * Must be used within an {@link McpClientProvider}.
414
125
  *
415
- * ## Output Schema (Recommended)
126
+ * @returns The MCP client context including client instance, tools, resources, and connection state
127
+ * @throws Error if used outside of McpClientProvider
416
128
  *
417
- * Always define an `outputSchema` for your tools. This provides:
418
- * - **Type Safety**: Handler return type is inferred from the schema
419
- * - **MCP structuredContent**: AI models receive structured, typed data
420
- * - **Better AI Understanding**: Models can reason about your tool's output format
129
+ * @public
421
130
  *
131
+ * @example
422
132
  * ```tsx
423
- * useWebMCP({
424
- * name: 'get_user',
425
- * description: 'Get user by ID',
426
- * inputSchema: {
427
- * type: 'object',
428
- * properties: { userId: { type: 'string' } },
429
- * required: ['userId'],
430
- * } as const,
431
- * outputSchema: {
432
- * type: 'object',
433
- * properties: {
434
- * id: { type: 'string' },
435
- * name: { type: 'string' },
436
- * email: { type: 'string' },
437
- * },
438
- * } as const,
439
- * handler: async ({ userId }) => {
440
- * const user = await fetchUser(userId);
441
- * return { id: user.id, name: user.name, email: user.email };
442
- * },
443
- * });
444
- * ```
445
- *
446
- * @template TInputSchema - JSON Schema defining input parameter types (use `as const` for inference)
447
- * @template TOutputSchema - JSON Schema defining output structure
133
+ * function ToolsList() {
134
+ * const { tools, isConnected, error, reconnect } = useMcpClient();
448
135
  *
449
- * @param config - Configuration object for the tool
450
- * @param deps - Optional dependency array that triggers tool re-registration when values change.
136
+ * if (error) {
137
+ * return (
138
+ * <div>
139
+ * Error: {error.message}
140
+ * <button onClick={() => void reconnect()}>Retry</button>
141
+ * </div>
142
+ * );
143
+ * }
451
144
  *
452
- * @returns Object containing execution state and control methods
145
+ * if (!isConnected) {
146
+ * return <div>Not connected</div>;
147
+ * }
453
148
  *
454
- * @public
149
+ * return (
150
+ * <ul>
151
+ * {tools.map(tool => (
152
+ * <li key={tool.name}>{tool.description}</li>
153
+ * ))}
154
+ * </ul>
155
+ * );
156
+ * }
157
+ * ```
455
158
  */
456
- declare function useWebMCP<TInputSchema extends ReactWebMCPInputSchema = InputSchema, TOutputSchema extends ReactWebMCPOutputSchema | undefined = undefined>(config: WebMCPConfig<TInputSchema, TOutputSchema>, deps?: DependencyList): WebMCPReturn<TOutputSchema, TInputSchema>;
159
+ declare function useMcpClient(): McpClientContextValue;
160
+ //#endregion
161
+ //#region src/types.d.ts
162
+ /** A single message returned by {@link WebMCPPromptConfig.get}. */
163
+ type PromptMessage = Awaited<ReturnType<PromptDescriptor$1['get']>>['messages'][number];
164
+ /** A single entry returned by {@link WebMCPResourceConfig.read}. */
165
+ type ResourceContents = Awaited<ReturnType<ResourceDescriptor$1['read']>>['contents'][number];
166
+ type WebMCPPromptConfig = Pick<PromptDescriptor$1, 'name' | 'description'> & {
167
+ argsSchema?: ToolInputSchema$1;
168
+ get: (args: Parameters<PromptDescriptor$1['get']>[0]) => MaybePromise<Awaited<ReturnType<PromptDescriptor$1['get']>>>;
169
+ };
170
+ interface WebMCPPromptReturn {
171
+ isRegistered: boolean;
172
+ }
173
+ type WebMCPResourceConfig = ResourceDescriptor$1;
174
+ type WebMCPResourceReturn = WebMCPPromptReturn;
457
175
  //#endregion
458
176
  //#region src/useWebMCPContext.d.ts
459
177
  /**
@@ -464,9 +182,7 @@ declare function useWebMCP<TInputSchema extends ReactWebMCPInputSchema = InputSc
464
182
  * configures appropriate annotations (read-only, idempotent) and handles value
465
183
  * serialization.
466
184
  *
467
- * Note: This hook does not use an output schema, so the result will not include
468
- * `structuredContent` in the MCP response. Use {@link useWebMCP} directly with
469
- * `outputSchema` if you need structured output for MCP compliance.
185
+ * JSON-compatible values are normalized to text plus `structuredContent`.
470
186
  *
471
187
  * @template T - The type of context data to expose
472
188
  *
@@ -521,19 +237,16 @@ declare function useWebMCP<TInputSchema extends ReactWebMCPInputSchema = InputSc
521
237
  * }
522
238
  * ```
523
239
  */
524
- declare function useWebMCPContext<T>(name: string, description: string, getValue: () => T): WebMCPReturn;
240
+ declare function useWebMCPContext<T>(name: string, description: string, getValue: () => T): WebMCPReturn$1;
525
241
  //#endregion
526
242
  //#region src/useWebMCPPrompt.d.ts
527
243
  /**
528
244
  * React hook for registering Model Context Protocol (MCP) prompts.
529
245
  *
530
246
  * This hook handles the complete lifecycle of an MCP prompt:
531
- * - Registers the prompt with `window.document.modelContext`
532
- * - Converts Zod schemas to JSON Schema for argument validation
247
+ * - Registers the prompt with the installed MCP-B `BrowserMcpServer`
533
248
  * - Automatically unregisters on component unmount
534
249
  *
535
- * @template TArgsSchema - Zod schema object defining argument types
536
- *
537
250
  * @param config - Configuration object for the prompt
538
251
  * @returns Object indicating registration status
539
252
  *
@@ -588,14 +301,14 @@ declare function useWebMCPContext<T>(name: string, description: string, getValue
588
301
  * }
589
302
  * ```
590
303
  */
591
- declare function useWebMCPPrompt<TArgsSchema extends ReactWebMCPInputSchema = InputSchema>(config: WebMCPPromptConfig<TArgsSchema>): WebMCPPromptReturn;
304
+ declare function useWebMCPPrompt(config: WebMCPPromptConfig): WebMCPPromptReturn;
592
305
  //#endregion
593
306
  //#region src/useWebMCPResource.d.ts
594
307
  /**
595
308
  * React hook for registering Model Context Protocol (MCP) resources.
596
309
  *
597
310
  * This hook handles the complete lifecycle of an MCP resource:
598
- * - Registers the resource with `window.document.modelContext`
311
+ * - Registers the resource with the installed MCP-B `BrowserMcpServer`
599
312
  * - Supports both static URIs and URI templates with parameters
600
313
  * - Automatically unregisters on component unmount
601
314
  *
@@ -635,7 +348,7 @@ declare function useWebMCPPrompt<TArgsSchema extends ReactWebMCPInputSchema = In
635
348
  * description: 'User profile data by ID',
636
349
  * mimeType: 'application/json',
637
350
  * read: async (uri, params) => {
638
- * const userId = params?.userId ?? '';
351
+ * const userId = typeof params?.userId === 'string' ? params.userId : '';
639
352
  * const profile = await fetchUserProfile(userId);
640
353
  * return {
641
354
  * contents: [{
@@ -652,342 +365,27 @@ declare function useWebMCPPrompt<TArgsSchema extends ReactWebMCPInputSchema = In
652
365
  */
653
366
  declare function useWebMCPResource(config: WebMCPResourceConfig): WebMCPResourceReturn;
654
367
  //#endregion
655
- //#region src/useElicitationHandler.d.ts
656
- /**
657
- * State for elicitation requests, tracking the current request and results.
658
- */
659
- interface ElicitationState {
660
- /** Whether an elicitation request is currently in progress */
661
- isLoading: boolean;
662
- /** The last elicitation result received */
663
- result: ElicitationResult | null;
664
- /** Any error that occurred during the last request */
665
- error: Error | null;
666
- /** Total number of requests made */
667
- requestCount: number;
668
- }
669
- /**
670
- * Configuration options for the useElicitation hook.
671
- */
672
- interface UseElicitationConfig {
673
- /**
674
- * Optional callback invoked when an elicitation request completes successfully.
675
- */
676
- onSuccess?: (result: ElicitationResult) => void;
677
- /**
678
- * Optional callback invoked when an elicitation request fails.
679
- */
680
- onError?: (error: Error) => void;
681
- }
682
- /**
683
- * Return value from the useElicitation hook.
684
- */
685
- interface UseElicitationReturn {
686
- /** Current state of elicitation */
687
- state: ElicitationState;
688
- /** Function to request user input from the connected client */
689
- elicitInput: (params: ElicitationParams) => Promise<ElicitationResult>;
690
- /** Reset the state */
691
- reset: () => void;
692
- }
693
- /**
694
- * React hook for requesting user input from the connected MCP client.
695
- *
696
- * Elicitation allows the server (webpage) to request user input from the
697
- * connected client. This is useful when the page needs additional information
698
- * from the user, such as API keys, configuration options, or confirmations.
699
- *
700
- * There are two modes:
701
- * 1. **Form mode**: For non-sensitive data collection using a schema-driven form.
702
- * 2. **URL mode**: For sensitive data collection via a web URL (API keys, OAuth, etc.).
703
- *
704
- * @param config - Optional configuration including callbacks
705
- * @returns Object containing state and the elicitInput function
706
- *
707
- * @example Form elicitation:
708
- * ```tsx
709
- * function ConfigForm() {
710
- * const { state, elicitInput } = useElicitation({
711
- * onSuccess: (result) => console.log('Got input:', result),
712
- * onError: (error) => console.error('Elicitation failed:', error),
713
- * });
714
- *
715
- * const handleConfigure = async () => {
716
- * const result = await elicitInput({
717
- * message: 'Please provide your configuration',
718
- * requestedSchema: {
719
- * type: 'object',
720
- * properties: {
721
- * apiKey: { type: 'string', title: 'API Key', description: 'Your API key' },
722
- * model: { type: 'string', enum: ['gpt-4', 'gpt-3.5'], title: 'Model' }
723
- * },
724
- * required: ['apiKey']
725
- * }
726
- * });
727
- *
728
- * if (result.action === 'accept') {
729
- * console.log('Config:', result.content);
730
- * }
731
- * };
732
- *
733
- * return (
734
- * <button onClick={handleConfigure} disabled={state.isLoading}>
735
- * Configure
736
- * </button>
737
- * );
738
- * }
739
- * ```
740
- *
741
- * @example URL elicitation (for sensitive data):
742
- * ```tsx
743
- * const { elicitInput } = useElicitation();
744
- *
745
- * const handleOAuth = async () => {
746
- * const result = await elicitInput({
747
- * mode: 'url',
748
- * message: 'Please authenticate with GitHub',
749
- * elicitationId: 'github-oauth-123',
750
- * url: 'https://github.com/login/oauth/authorize?client_id=...'
751
- * });
752
- *
753
- * if (result.action === 'accept') {
754
- * console.log('OAuth completed');
755
- * }
756
- * };
757
- * ```
758
- */
759
- declare function useElicitation(config?: UseElicitationConfig): UseElicitationReturn;
760
- //#endregion
761
- //#region src/useSamplingHandler.d.ts
762
- /**
763
- * State for sampling requests, tracking the current request and results.
764
- */
765
- interface SamplingState {
766
- /** Whether a sampling request is currently in progress */
767
- isLoading: boolean;
768
- /** The last sampling result received */
769
- result: SamplingResult | null;
770
- /** Any error that occurred during the last request */
771
- error: Error | null;
772
- /** Total number of requests made */
773
- requestCount: number;
774
- }
775
- /**
776
- * Configuration options for the useSampling hook.
777
- */
778
- interface UseSamplingConfig {
779
- /**
780
- * Optional callback invoked when a sampling request completes successfully.
781
- */
782
- onSuccess?: (result: SamplingResult) => void;
783
- /**
784
- * Optional callback invoked when a sampling request fails.
785
- */
786
- onError?: (error: Error) => void;
787
- }
788
- /**
789
- * Return value from the useSampling hook.
790
- */
791
- interface UseSamplingReturn {
792
- /** Current state of sampling */
793
- state: SamplingState;
794
- /** Function to request LLM completion from the connected client */
795
- createMessage: (params: SamplingRequestParams) => Promise<SamplingResult>;
796
- /** Reset the state */
797
- reset: () => void;
798
- }
799
- /**
800
- * React hook for requesting LLM completions from the connected MCP client.
801
- *
802
- * Sampling allows the server (webpage) to request LLM completions from the
803
- * connected client. This is useful when the page needs AI capabilities like
804
- * summarization, generation, or analysis.
805
- *
806
- * @param config - Optional configuration including callbacks
807
- * @returns Object containing state and the createMessage function
808
- *
809
- * @example Basic usage:
810
- * ```tsx
811
- * function AIAssistant() {
812
- * const { state, createMessage } = useSampling({
813
- * onSuccess: (result) => console.log('Got response:', result),
814
- * onError: (error) => console.error('Sampling failed:', error),
815
- * });
816
- *
817
- * const handleAsk = async () => {
818
- * const result = await createMessage({
819
- * messages: [
820
- * { role: 'user', content: { type: 'text', text: 'What is 2+2?' } }
821
- * ],
822
- * maxTokens: 100,
823
- * });
824
- * console.log(result.content);
825
- * };
826
- *
827
- * return (
828
- * <div>
829
- * <button onClick={handleAsk} disabled={state.isLoading}>
830
- * Ask AI
831
- * </button>
832
- * {state.result && <p>{JSON.stringify(state.result.content)}</p>}
833
- * </div>
834
- * );
835
- * }
836
- * ```
837
- */
838
- declare function useSampling(config?: UseSamplingConfig): UseSamplingReturn;
839
- //#endregion
840
- //#region src/client/McpClientProvider.d.ts
841
- /**
842
- * Context value provided by McpClientProvider.
843
- *
844
- * @internal
845
- */
846
- interface McpClientContextValue {
847
- client: Client;
848
- tools: Tool[];
849
- resources: Resource[];
850
- isConnected: boolean;
851
- isLoading: boolean;
852
- error: Error | null;
853
- capabilities: ServerCapabilities | null;
854
- reconnect: () => Promise<void>;
855
- }
856
- /**
857
- * Props for the McpClientProvider component.
858
- *
859
- * @public
860
- */
861
- interface McpClientProviderProps {
862
- /**
863
- * React children to render within the provider.
864
- */
865
- children: ReactNode;
866
- /**
867
- * MCP Client instance to use for communication.
868
- */
869
- client: Client;
870
- /**
871
- * Transport instance for the client to connect through.
872
- */
873
- transport: Transport;
874
- /**
875
- * Optional request options for the connection.
876
- */
877
- opts?: RequestOptions;
368
+ //#region src/index.d.ts
369
+ declare module 'react' {
370
+ interface FormHTMLAttributes<T> {
371
+ toolname?: string;
372
+ tooltitle?: string;
373
+ tooldescription?: string;
374
+ toolautosubmit?: '' | 'toolautosubmit';
375
+ }
376
+ interface FieldsetHTMLAttributes<T> {
377
+ toolparamdescription?: string;
378
+ }
379
+ interface InputHTMLAttributes<T> {
380
+ toolparamdescription?: string;
381
+ }
382
+ interface SelectHTMLAttributes<T> {
383
+ toolparamdescription?: string;
384
+ }
385
+ interface TextareaHTMLAttributes<T> {
386
+ toolparamdescription?: string;
387
+ }
878
388
  }
879
- /**
880
- * Provider component that manages an MCP client connection and exposes
881
- * tools, resources, and connection state to child components.
882
- *
883
- * This provider handles:
884
- * - Establishing and maintaining the MCP client connection
885
- * - Fetching available tools and resources from the server
886
- * - Listening for server notifications about tool/resource changes
887
- * - Managing connection state and errors
888
- * - Automatic cleanup on unmount
889
- *
890
- * @param props - Component props
891
- * @returns Provider component wrapping children
892
- *
893
- * @public
894
- *
895
- * @example
896
- * Connect to an MCP server via tab transport:
897
- * ```tsx
898
- * import { Client } from '@modelcontextprotocol/sdk/client/index.js';
899
- * import { TabClientTransport } from '@mcp-b/transports';
900
- * import { McpClientProvider } from '@mcp-b/react-webmcp';
901
- *
902
- * const client = new Client(
903
- * { name: 'my-app', version: '1.0.0' },
904
- * { capabilities: {} }
905
- * );
906
- *
907
- * const transport = new TabClientTransport('mcp', {
908
- * clientInstanceId: 'my-app-instance',
909
- * });
910
- *
911
- * function App() {
912
- * return (
913
- * <McpClientProvider client={client} transport={transport}>
914
- * <MyAppContent />
915
- * </McpClientProvider>
916
- * );
917
- * }
918
- * ```
919
- *
920
- * @example
921
- * Access tools from child components:
922
- * ```tsx
923
- * function MyAppContent() {
924
- * const { tools, isConnected, isLoading } = useMcpClient();
925
- *
926
- * if (isLoading) {
927
- * return <div>Connecting to MCP server...</div>;
928
- * }
929
- *
930
- * if (!isConnected) {
931
- * return <div>Failed to connect to MCP server</div>;
932
- * }
933
- *
934
- * return (
935
- * <div>
936
- * <h2>Available Tools:</h2>
937
- * <ul>
938
- * {tools.map(tool => (
939
- * <li key={tool.name}>{tool.description}</li>
940
- * ))}
941
- * </ul>
942
- * </div>
943
- * );
944
- * }
945
- * ```
946
- */
947
- declare function McpClientProvider({
948
- children,
949
- client,
950
- transport,
951
- opts
952
- }: McpClientProviderProps): ReactElement;
953
- /**
954
- * Hook to access the MCP client context.
955
- * Must be used within an {@link McpClientProvider}.
956
- *
957
- * @returns The MCP client context including client instance, tools, resources, and connection state
958
- * @throws Error if used outside of McpClientProvider
959
- *
960
- * @public
961
- *
962
- * @example
963
- * ```tsx
964
- * function ToolsList() {
965
- * const { tools, isConnected, error, reconnect } = useMcpClient();
966
- *
967
- * if (error) {
968
- * return (
969
- * <div>
970
- * Error: {error.message}
971
- * <button onClick={reconnect}>Retry</button>
972
- * </div>
973
- * );
974
- * }
975
- *
976
- * if (!isConnected) {
977
- * return <div>Not connected</div>;
978
- * }
979
- *
980
- * return (
981
- * <ul>
982
- * {tools.map(tool => (
983
- * <li key={tool.name}>{tool.description}</li>
984
- * ))}
985
- * </ul>
986
- * );
987
- * }
988
- * ```
989
- */
990
- declare function useMcpClient(): McpClientContextValue;
991
389
  //#endregion
992
- export { type CallToolResult, type ElicitationState as ElicitationHandlerState, type ElicitationState, type InferOutput, type InferToolInput, McpClientProvider, type McpClientProviderProps, type ModelContextProtocol, type PromptDescriptor, type PromptMessage, type ReactWebMCPInputSchema, type ResourceContents, type ResourceDescriptor, type SamplingState as SamplingHandlerState, type SamplingState, type ToolAnnotations, type ToolDescriptor, type ToolExecutionState, type ToolInputSchema, type UseElicitationConfig, type UseElicitationConfig as UseElicitationHandlerConfig, type UseElicitationReturn as UseElicitationHandlerReturn, type UseElicitationReturn, type UseSamplingConfig, type UseSamplingConfig as UseSamplingHandlerConfig, type UseSamplingReturn as UseSamplingHandlerReturn, type UseSamplingReturn, type WebMCPConfig, type WebMCPPromptConfig, type WebMCPPromptReturn, type WebMCPResourceConfig, type WebMCPResourceReturn, type WebMCPReturn, type ZodSchema, type ZodSchemaObject, useElicitation, useElicitation as useElicitationHandler, useMcpClient, useSampling, useSampling as useSamplingHandler, useWebMCP, useWebMCPContext, useWebMCPPrompt, useWebMCPResource };
390
+ export { type CallToolResult, type InferOutput, type InferToolInput, McpClientProvider, type McpClientProviderProps, type ModelContextProtocol, type PromptDescriptor, type PromptMessage, type ResourceContents, type ResourceDescriptor, type ToolAnnotations, type ToolDescriptor, type ToolExecutionState, type ToolInputSchema, type WebMCPConfig, type WebMCPPromptConfig, type WebMCPPromptReturn, type WebMCPResourceConfig, type WebMCPResourceReturn, type WebMCPReturn, useMcpClient, useWebMCP, useWebMCPContext, useWebMCPPrompt, useWebMCPResource };
993
391
  //# sourceMappingURL=index.d.ts.map