usewebmcp 0.2.3-beta.0 → 0.3.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 +252 -0
- package/dist/index.d.ts +354 -1
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +2 -1
- package/dist/index.js.map +1 -0
- package/package.json +22 -12
package/README.md
ADDED
|
@@ -0,0 +1,252 @@
|
|
|
1
|
+
# usewebmcp
|
|
2
|
+
|
|
3
|
+
Standalone React hooks for strict core WebMCP tool registration via `navigator.modelContext`.
|
|
4
|
+
|
|
5
|
+
`usewebmcp` is intentionally separate from `@mcp-b/react-webmcp`:
|
|
6
|
+
|
|
7
|
+
- Use `usewebmcp` for strict core WebMCP workflows.
|
|
8
|
+
- Use `@mcp-b/react-webmcp` for full MCP-B runtime features (resources, prompts, client/provider flows, etc.).
|
|
9
|
+
|
|
10
|
+
## Package Selection
|
|
11
|
+
|
|
12
|
+
| Package | Use When |
|
|
13
|
+
| --- | --- |
|
|
14
|
+
| `usewebmcp` | React hooks for strict core `navigator.modelContext` tools |
|
|
15
|
+
| `@mcp-b/react-webmcp` | React hooks for full MCP-B runtime surface |
|
|
16
|
+
| `@mcp-b/webmcp-polyfill` | You need a strict core runtime polyfill |
|
|
17
|
+
| `@mcp-b/global` | You need full MCP-B runtime (core + extensions) |
|
|
18
|
+
|
|
19
|
+
## Install
|
|
20
|
+
|
|
21
|
+
```bash
|
|
22
|
+
pnpm add usewebmcp react
|
|
23
|
+
# or
|
|
24
|
+
npm install usewebmcp react
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
Optional (only if you want Standard Schema authoring like Zod v4 input schemas):
|
|
28
|
+
|
|
29
|
+
```bash
|
|
30
|
+
pnpm add zod
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
## Runtime Prerequisite
|
|
34
|
+
|
|
35
|
+
`usewebmcp` expects `window.navigator.modelContext` to exist.
|
|
36
|
+
|
|
37
|
+
You can provide it via:
|
|
38
|
+
|
|
39
|
+
- Browser-native WebMCP implementation, or
|
|
40
|
+
- `@mcp-b/webmcp-polyfill`, or
|
|
41
|
+
- `@mcp-b/global`
|
|
42
|
+
|
|
43
|
+
If `navigator.modelContext` is missing, the hook logs a warning and skips registration.
|
|
44
|
+
|
|
45
|
+
## Quick Start
|
|
46
|
+
|
|
47
|
+
```tsx
|
|
48
|
+
import { initializeWebMCPPolyfill } from '@mcp-b/webmcp-polyfill';
|
|
49
|
+
import { useWebMCP } from 'usewebmcp';
|
|
50
|
+
|
|
51
|
+
initializeWebMCPPolyfill();
|
|
52
|
+
|
|
53
|
+
const COUNTER_INPUT_SCHEMA = {
|
|
54
|
+
type: 'object',
|
|
55
|
+
properties: {},
|
|
56
|
+
} as const;
|
|
57
|
+
|
|
58
|
+
const COUNTER_OUTPUT_SCHEMA = {
|
|
59
|
+
type: 'object',
|
|
60
|
+
properties: {
|
|
61
|
+
count: { type: 'integer' },
|
|
62
|
+
},
|
|
63
|
+
required: ['count'],
|
|
64
|
+
additionalProperties: false,
|
|
65
|
+
} as const;
|
|
66
|
+
|
|
67
|
+
export function CounterTool() {
|
|
68
|
+
const counterTool = useWebMCP({
|
|
69
|
+
name: 'counter_get',
|
|
70
|
+
description: 'Get current count',
|
|
71
|
+
inputSchema: COUNTER_INPUT_SCHEMA,
|
|
72
|
+
outputSchema: COUNTER_OUTPUT_SCHEMA,
|
|
73
|
+
handler: async () => ({ count: 42 }),
|
|
74
|
+
});
|
|
75
|
+
|
|
76
|
+
return (
|
|
77
|
+
<div>
|
|
78
|
+
<p>Executions: {counterTool.state.executionCount}</p>
|
|
79
|
+
<p>Last count: {counterTool.state.lastResult?.count ?? 'none'}</p>
|
|
80
|
+
{counterTool.state.error && <p>Error: {counterTool.state.error.message}</p>}
|
|
81
|
+
</div>
|
|
82
|
+
);
|
|
83
|
+
}
|
|
84
|
+
```
|
|
85
|
+
|
|
86
|
+
## How `useWebMCP` Works
|
|
87
|
+
|
|
88
|
+
- Registers a tool on mount with `navigator.modelContext.registerTool(...)`.
|
|
89
|
+
- Unregisters on unmount with `navigator.modelContext.unregisterTool(name)`.
|
|
90
|
+
- Exposes local execution state:
|
|
91
|
+
- `state.isExecuting`
|
|
92
|
+
- `state.lastResult`
|
|
93
|
+
- `state.error`
|
|
94
|
+
- `state.executionCount`
|
|
95
|
+
- Returns `execute(input)` for manual in-app invocation and `reset()` for state reset.
|
|
96
|
+
|
|
97
|
+
`handler` can be synchronous or asynchronous.
|
|
98
|
+
|
|
99
|
+
## Type Inference
|
|
100
|
+
|
|
101
|
+
### Input inference
|
|
102
|
+
|
|
103
|
+
`inputSchema` supports:
|
|
104
|
+
|
|
105
|
+
- JSON Schema literals (`as const`) via `InferArgsFromInputSchema`
|
|
106
|
+
- Standard Schema v1 input typing (for example Zod v4 / Valibot / ArkType) via `~standard.types.input`
|
|
107
|
+
|
|
108
|
+
```tsx
|
|
109
|
+
const INPUT_SCHEMA = {
|
|
110
|
+
type: 'object',
|
|
111
|
+
properties: {
|
|
112
|
+
query: { type: 'string' },
|
|
113
|
+
limit: { type: 'integer' },
|
|
114
|
+
},
|
|
115
|
+
required: ['query'],
|
|
116
|
+
additionalProperties: false,
|
|
117
|
+
} as const;
|
|
118
|
+
|
|
119
|
+
useWebMCP({
|
|
120
|
+
name: 'search',
|
|
121
|
+
description: 'Search docs',
|
|
122
|
+
inputSchema: INPUT_SCHEMA,
|
|
123
|
+
handler(input) {
|
|
124
|
+
// input is inferred as { query: string; limit?: number }
|
|
125
|
+
return { total: 1 };
|
|
126
|
+
},
|
|
127
|
+
});
|
|
128
|
+
```
|
|
129
|
+
|
|
130
|
+
### Output inference
|
|
131
|
+
|
|
132
|
+
When `outputSchema` is provided as a literal JSON object schema:
|
|
133
|
+
|
|
134
|
+
- `handler` return type is inferred from `outputSchema`
|
|
135
|
+
- `state.lastResult` is inferred to the same type
|
|
136
|
+
- MCP response includes `structuredContent`
|
|
137
|
+
|
|
138
|
+
```tsx
|
|
139
|
+
const OUTPUT_SCHEMA = {
|
|
140
|
+
type: 'object',
|
|
141
|
+
properties: {
|
|
142
|
+
total: { type: 'integer' },
|
|
143
|
+
},
|
|
144
|
+
required: ['total'],
|
|
145
|
+
additionalProperties: false,
|
|
146
|
+
} as const;
|
|
147
|
+
|
|
148
|
+
const tool = useWebMCP({
|
|
149
|
+
name: 'count_items',
|
|
150
|
+
description: 'Count items',
|
|
151
|
+
outputSchema: OUTPUT_SCHEMA,
|
|
152
|
+
handler: () => ({ total: 3 }),
|
|
153
|
+
});
|
|
154
|
+
|
|
155
|
+
// tool.state.lastResult is inferred as { total: number } | null
|
|
156
|
+
```
|
|
157
|
+
|
|
158
|
+
## Manual `execute(...)` Calls
|
|
159
|
+
|
|
160
|
+
You can call the returned `execute(...)` function directly from your component.
|
|
161
|
+
|
|
162
|
+
```tsx
|
|
163
|
+
function SearchToolPanel() {
|
|
164
|
+
const searchTool = useWebMCP({
|
|
165
|
+
name: 'search_local',
|
|
166
|
+
description: 'Run local search',
|
|
167
|
+
inputSchema: {
|
|
168
|
+
type: 'object',
|
|
169
|
+
properties: { query: { type: 'string' } },
|
|
170
|
+
required: ['query'],
|
|
171
|
+
additionalProperties: false,
|
|
172
|
+
} as const,
|
|
173
|
+
handler: async ({ query }) => ({ query, total: query.length }),
|
|
174
|
+
});
|
|
175
|
+
|
|
176
|
+
return (
|
|
177
|
+
<button
|
|
178
|
+
onClick={async () => {
|
|
179
|
+
await searchTool.execute({ query: 'webmcp' });
|
|
180
|
+
}}
|
|
181
|
+
>
|
|
182
|
+
Run Search
|
|
183
|
+
</button>
|
|
184
|
+
);
|
|
185
|
+
}
|
|
186
|
+
```
|
|
187
|
+
|
|
188
|
+
## Output Schema Contract
|
|
189
|
+
|
|
190
|
+
If `outputSchema` is defined, the handler must return a JSON-serializable object result.
|
|
191
|
+
|
|
192
|
+
Returning a non-object value (`string`, `null`, array, etc.) causes an error response from the registered MCP tool.
|
|
193
|
+
|
|
194
|
+
## Re-Registration and Performance
|
|
195
|
+
|
|
196
|
+
The tool re-registers when any of these change:
|
|
197
|
+
|
|
198
|
+
- `name`
|
|
199
|
+
- `description`
|
|
200
|
+
- `inputSchema` reference
|
|
201
|
+
- `outputSchema` reference
|
|
202
|
+
- `annotations` reference
|
|
203
|
+
- values in `deps`
|
|
204
|
+
|
|
205
|
+
The hook avoids re-registration when only callback references change:
|
|
206
|
+
|
|
207
|
+
- `handler`
|
|
208
|
+
- `onSuccess`
|
|
209
|
+
- `onError`
|
|
210
|
+
- `formatOutput`
|
|
211
|
+
|
|
212
|
+
Latest callback versions are still used at execution time.
|
|
213
|
+
|
|
214
|
+
Recommendation:
|
|
215
|
+
|
|
216
|
+
- Define schemas/annotations outside render or memoize them.
|
|
217
|
+
- Keep `deps` primitive when possible.
|
|
218
|
+
|
|
219
|
+
## API
|
|
220
|
+
|
|
221
|
+
### `useWebMCP(config, deps?)`
|
|
222
|
+
|
|
223
|
+
`config` fields:
|
|
224
|
+
|
|
225
|
+
- `name: string`
|
|
226
|
+
- `description: string`
|
|
227
|
+
- `inputSchema?`
|
|
228
|
+
- `outputSchema?`
|
|
229
|
+
- `annotations?`
|
|
230
|
+
- `handler(input)`
|
|
231
|
+
- `formatOutput?(output)` (deprecated)
|
|
232
|
+
- `onSuccess?(result, input)`
|
|
233
|
+
- `onError?(error, input)`
|
|
234
|
+
|
|
235
|
+
Return value:
|
|
236
|
+
|
|
237
|
+
- `state`
|
|
238
|
+
- `execute(input)`
|
|
239
|
+
- `reset()`
|
|
240
|
+
|
|
241
|
+
`execute(input)` is a local direct call to your handler for in-app control/testing.
|
|
242
|
+
Tool calls coming from MCP clients still go through `navigator.modelContext`.
|
|
243
|
+
|
|
244
|
+
## Important Notes
|
|
245
|
+
|
|
246
|
+
- This is a client-side hook package (`'use client'`).
|
|
247
|
+
- `formatOutput` is deprecated; prefer `outputSchema` + structured output.
|
|
248
|
+
- When handler output is not a string, default text content is pretty-printed JSON.
|
|
249
|
+
|
|
250
|
+
## License
|
|
251
|
+
|
|
252
|
+
MIT
|
package/dist/index.d.ts
CHANGED
|
@@ -1 +1,354 @@
|
|
|
1
|
-
|
|
1
|
+
import { DependencyList } from "react";
|
|
2
|
+
import { ToolInputSchema } from "@mcp-b/webmcp-polyfill";
|
|
3
|
+
import { InferArgsFromInputSchema, InferJsonSchema, InputSchema, JsonSchemaObject, ToolAnnotations } from "@mcp-b/webmcp-types";
|
|
4
|
+
|
|
5
|
+
//#region src/types.d.ts
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Infers handler input type from either a Standard Schema or JSON Schema.
|
|
9
|
+
*
|
|
10
|
+
* - **Standard Schema** (Zod v4, Valibot, ArkType): extracts `~standard.types.input`
|
|
11
|
+
* - **JSON Schema** (`as const`): uses `InferArgsFromInputSchema` for structural inference
|
|
12
|
+
* - **Fallback**: `Record<string, unknown>`
|
|
13
|
+
*
|
|
14
|
+
* @template T - The input schema type
|
|
15
|
+
* @internal
|
|
16
|
+
*/
|
|
17
|
+
type InferToolInput<T> = T extends {
|
|
18
|
+
readonly '~standard': {
|
|
19
|
+
readonly types?: infer Types;
|
|
20
|
+
};
|
|
21
|
+
} ? Types extends {
|
|
22
|
+
readonly input: infer I;
|
|
23
|
+
} ? I : Record<string, unknown> : T extends InputSchema ? InferArgsFromInputSchema<T> : Record<string, unknown>;
|
|
24
|
+
/**
|
|
25
|
+
* Utility type to infer the output type from a JSON Schema object.
|
|
26
|
+
*
|
|
27
|
+
* When `TOutputSchema` is a literal `JsonSchemaObject`, this resolves to
|
|
28
|
+
* `InferJsonSchema<TOutputSchema>`. When it's `undefined`,
|
|
29
|
+
* it falls back to the provided `TFallback` type.
|
|
30
|
+
*
|
|
31
|
+
* @template TOutputSchema - JSON Schema object for output inference
|
|
32
|
+
* @template TFallback - Fallback type when no schema is provided
|
|
33
|
+
* @internal
|
|
34
|
+
*/
|
|
35
|
+
type InferOutput<TOutputSchema extends JsonSchemaObject | undefined = undefined, TFallback = unknown> = TOutputSchema extends JsonSchemaObject ? InferJsonSchema<TOutputSchema> : TFallback;
|
|
36
|
+
/**
|
|
37
|
+
* Represents the current execution state of a tool, including loading status,
|
|
38
|
+
* results, errors, and execution history.
|
|
39
|
+
*
|
|
40
|
+
* @template TOutput - The type of data returned by the tool handler
|
|
41
|
+
* @public
|
|
42
|
+
*/
|
|
43
|
+
interface ToolExecutionState<TOutput = unknown> {
|
|
44
|
+
/**
|
|
45
|
+
* Indicates whether the tool is currently executing.
|
|
46
|
+
* Use this to show loading states in your UI.
|
|
47
|
+
*/
|
|
48
|
+
isExecuting: boolean;
|
|
49
|
+
/**
|
|
50
|
+
* The result from the most recent successful execution.
|
|
51
|
+
* Will be `null` if the tool hasn't been executed or last execution failed.
|
|
52
|
+
*/
|
|
53
|
+
lastResult: TOutput | null;
|
|
54
|
+
/**
|
|
55
|
+
* The error from the most recent failed execution.
|
|
56
|
+
* Will be `null` if the tool hasn't been executed or last execution succeeded.
|
|
57
|
+
*/
|
|
58
|
+
error: Error | null;
|
|
59
|
+
/**
|
|
60
|
+
* Total number of times this tool has been executed.
|
|
61
|
+
* Increments on successful executions only.
|
|
62
|
+
*/
|
|
63
|
+
executionCount: number;
|
|
64
|
+
}
|
|
65
|
+
/**
|
|
66
|
+
* Configuration options for the `useWebMCP` hook.
|
|
67
|
+
*
|
|
68
|
+
* Defines a tool's metadata, schema, handler, and lifecycle callbacks.
|
|
69
|
+
* Uses JSON Schema for type inference via `as const`.
|
|
70
|
+
*
|
|
71
|
+
* @template TInputSchema - JSON Schema defining input parameters
|
|
72
|
+
* @template TOutputSchema - JSON Schema object defining output structure (enables structuredContent)
|
|
73
|
+
*
|
|
74
|
+
* @public
|
|
75
|
+
*
|
|
76
|
+
* @example Basic tool without output schema:
|
|
77
|
+
* ```typescript
|
|
78
|
+
* const config: WebMCPConfig = {
|
|
79
|
+
* name: 'posts_like',
|
|
80
|
+
* description: 'Like a post by its ID',
|
|
81
|
+
* inputSchema: {
|
|
82
|
+
* type: 'object',
|
|
83
|
+
* properties: { postId: { type: 'string' } },
|
|
84
|
+
* required: ['postId'],
|
|
85
|
+
* } as const,
|
|
86
|
+
* handler: async ({ postId }) => {
|
|
87
|
+
* await api.likePost(postId);
|
|
88
|
+
* return { success: true };
|
|
89
|
+
* },
|
|
90
|
+
* };
|
|
91
|
+
* ```
|
|
92
|
+
*
|
|
93
|
+
* @example Tool with output schema (enables MCP structuredContent):
|
|
94
|
+
* ```typescript
|
|
95
|
+
* useWebMCP({
|
|
96
|
+
* name: 'posts_like',
|
|
97
|
+
* description: 'Like a post and return updated like count',
|
|
98
|
+
* inputSchema: {
|
|
99
|
+
* type: 'object',
|
|
100
|
+
* properties: { postId: { type: 'string' } },
|
|
101
|
+
* required: ['postId'],
|
|
102
|
+
* } as const,
|
|
103
|
+
* outputSchema: {
|
|
104
|
+
* type: 'object',
|
|
105
|
+
* properties: {
|
|
106
|
+
* likes: { type: 'number', description: 'Updated like count' },
|
|
107
|
+
* likedAt: { type: 'string', description: 'ISO timestamp of the like' },
|
|
108
|
+
* },
|
|
109
|
+
* } as const,
|
|
110
|
+
* handler: async ({ postId }) => {
|
|
111
|
+
* const result = await api.likePost(postId);
|
|
112
|
+
* return { likes: result.likes, likedAt: new Date().toISOString() };
|
|
113
|
+
* },
|
|
114
|
+
* });
|
|
115
|
+
* ```
|
|
116
|
+
*/
|
|
117
|
+
interface WebMCPConfig<TInputSchema extends ToolInputSchema = InputSchema, TOutputSchema extends JsonSchemaObject | undefined = undefined> {
|
|
118
|
+
/**
|
|
119
|
+
* Unique identifier for the tool (e.g., 'posts_like', 'graph_navigate').
|
|
120
|
+
* Must follow naming conventions: lowercase with underscores.
|
|
121
|
+
*/
|
|
122
|
+
name: string;
|
|
123
|
+
/**
|
|
124
|
+
* Human-readable description explaining what the tool does.
|
|
125
|
+
* This description is used by AI assistants to understand when to use the tool.
|
|
126
|
+
*/
|
|
127
|
+
description: string;
|
|
128
|
+
/**
|
|
129
|
+
* Schema defining the input parameters for the tool.
|
|
130
|
+
* Accepts JSON Schema (with `as const`) or any Standard Schema v1
|
|
131
|
+
* library (Zod v4, Valibot, ArkType, etc.).
|
|
132
|
+
*
|
|
133
|
+
* @example JSON Schema
|
|
134
|
+
* ```typescript
|
|
135
|
+
* inputSchema: {
|
|
136
|
+
* type: 'object',
|
|
137
|
+
* properties: {
|
|
138
|
+
* postId: { type: 'string', description: 'The ID of the post to like' },
|
|
139
|
+
* },
|
|
140
|
+
* required: ['postId'],
|
|
141
|
+
* } as const
|
|
142
|
+
* ```
|
|
143
|
+
*
|
|
144
|
+
* @example Standard Schema (Zod v4)
|
|
145
|
+
* ```typescript
|
|
146
|
+
* inputSchema: z.object({ postId: z.string() })
|
|
147
|
+
* ```
|
|
148
|
+
*/
|
|
149
|
+
inputSchema?: TInputSchema;
|
|
150
|
+
/**
|
|
151
|
+
* **Recommended:** JSON Schema object defining the expected output structure.
|
|
152
|
+
*
|
|
153
|
+
* When provided, this enables three key features:
|
|
154
|
+
* 1. **Type Safety**: The handler's return type is inferred from this schema
|
|
155
|
+
* 2. **MCP structuredContent**: The MCP response includes `structuredContent`
|
|
156
|
+
* containing the typed output per the MCP specification
|
|
157
|
+
* 3. **AI Understanding**: AI models can better understand and use the tool's output
|
|
158
|
+
*
|
|
159
|
+
* @see {@link https://spec.modelcontextprotocol.io/specification/server/tools/#output-schemas}
|
|
160
|
+
*
|
|
161
|
+
* @example
|
|
162
|
+
* ```typescript
|
|
163
|
+
* outputSchema: {
|
|
164
|
+
* type: 'object',
|
|
165
|
+
* properties: {
|
|
166
|
+
* counter: { type: 'number', description: 'The current counter value' },
|
|
167
|
+
* timestamp: { type: 'string', description: 'ISO timestamp' },
|
|
168
|
+
* },
|
|
169
|
+
* } as const
|
|
170
|
+
* ```
|
|
171
|
+
*/
|
|
172
|
+
outputSchema?: TOutputSchema;
|
|
173
|
+
/**
|
|
174
|
+
* Optional metadata annotations providing hints about tool behavior.
|
|
175
|
+
* See {@link ToolAnnotations} for available options.
|
|
176
|
+
*/
|
|
177
|
+
annotations?: ToolAnnotations;
|
|
178
|
+
/**
|
|
179
|
+
* The function that executes when the tool is called.
|
|
180
|
+
* Can be synchronous or asynchronous.
|
|
181
|
+
*
|
|
182
|
+
* When `outputSchema` is provided, the return type is inferred from the schema.
|
|
183
|
+
* Otherwise, any return type is allowed.
|
|
184
|
+
*
|
|
185
|
+
* @param input - Validated input parameters matching the inputSchema
|
|
186
|
+
* @returns The result data or a Promise resolving to the result
|
|
187
|
+
*/
|
|
188
|
+
handler: (input: InferToolInput<TInputSchema>) => Promise<InferOutput<TOutputSchema>> | InferOutput<TOutputSchema>;
|
|
189
|
+
/**
|
|
190
|
+
* Custom formatter for the MCP text response.
|
|
191
|
+
*
|
|
192
|
+
* @deprecated Use `outputSchema` instead. The `outputSchema` provides type-safe
|
|
193
|
+
* structured output via MCP's `structuredContent`, which is the recommended
|
|
194
|
+
* approach for tool outputs. This property will be removed in a future version.
|
|
195
|
+
*
|
|
196
|
+
* @param output - The raw output from the handler
|
|
197
|
+
* @returns Formatted string for the MCP response content
|
|
198
|
+
*/
|
|
199
|
+
formatOutput?: (output: InferOutput<TOutputSchema>) => string;
|
|
200
|
+
/**
|
|
201
|
+
* Optional callback invoked when the tool execution succeeds.
|
|
202
|
+
* Useful for triggering side effects like navigation or analytics.
|
|
203
|
+
*
|
|
204
|
+
* @param result - The successful result from the handler
|
|
205
|
+
* @param input - The input that was passed to the handler
|
|
206
|
+
*/
|
|
207
|
+
onSuccess?: (result: InferOutput<TOutputSchema>, input: unknown) => void;
|
|
208
|
+
/**
|
|
209
|
+
* Optional callback invoked when the tool execution fails.
|
|
210
|
+
* Useful for error handling, logging, or showing user notifications.
|
|
211
|
+
*
|
|
212
|
+
* @param error - The error that occurred during execution
|
|
213
|
+
* @param input - The input that was passed to the handler
|
|
214
|
+
*/
|
|
215
|
+
onError?: (error: Error, input: unknown) => void;
|
|
216
|
+
}
|
|
217
|
+
/**
|
|
218
|
+
* Return value from the `useWebMCP` hook.
|
|
219
|
+
* Provides access to execution state and methods for manual tool control.
|
|
220
|
+
*
|
|
221
|
+
* @template TOutputSchema - JSON Schema object defining output structure
|
|
222
|
+
* @public
|
|
223
|
+
*/
|
|
224
|
+
interface WebMCPReturn<TOutputSchema extends JsonSchemaObject | undefined = undefined> {
|
|
225
|
+
/**
|
|
226
|
+
* Current execution state including loading status, results, and errors.
|
|
227
|
+
* See {@link ToolExecutionState} for details.
|
|
228
|
+
*/
|
|
229
|
+
state: ToolExecutionState<InferOutput<TOutputSchema>>;
|
|
230
|
+
/**
|
|
231
|
+
* Manually execute the tool with the provided input.
|
|
232
|
+
* Useful for testing, debugging, or triggering execution from your UI.
|
|
233
|
+
*
|
|
234
|
+
* @param input - The input parameters to pass to the tool
|
|
235
|
+
* @returns Promise resolving to the tool's output
|
|
236
|
+
* @throws Error if validation fails or handler throws
|
|
237
|
+
*/
|
|
238
|
+
execute: (input: unknown) => Promise<InferOutput<TOutputSchema>>;
|
|
239
|
+
/**
|
|
240
|
+
* Reset the execution state to its initial values.
|
|
241
|
+
* Clears results, errors, and resets the execution count.
|
|
242
|
+
*/
|
|
243
|
+
reset: () => void;
|
|
244
|
+
}
|
|
245
|
+
//#endregion
|
|
246
|
+
//#region src/useWebMCP.d.ts
|
|
247
|
+
/**
|
|
248
|
+
* React hook for registering and managing Model Context Protocol (MCP) tools.
|
|
249
|
+
*
|
|
250
|
+
* This hook handles the complete lifecycle of an MCP tool:
|
|
251
|
+
* - Registers the tool with `window.navigator.modelContext`
|
|
252
|
+
* - Manages execution state (loading, results, errors)
|
|
253
|
+
* - Handles tool execution and lifecycle callbacks
|
|
254
|
+
* - Automatically unregisters on component unmount
|
|
255
|
+
* - Returns `structuredContent` when `outputSchema` is defined
|
|
256
|
+
*
|
|
257
|
+
* ## Output Schema (Recommended)
|
|
258
|
+
*
|
|
259
|
+
* Always define an `outputSchema` for your tools. This provides:
|
|
260
|
+
* - **Type Safety**: Handler return type is inferred from the schema
|
|
261
|
+
* - **MCP structuredContent**: AI models receive structured, typed data
|
|
262
|
+
* - **Better AI Understanding**: Models can reason about your tool's output format
|
|
263
|
+
*
|
|
264
|
+
* ```tsx
|
|
265
|
+
* useWebMCP({
|
|
266
|
+
* name: 'get_user',
|
|
267
|
+
* description: 'Get user by ID',
|
|
268
|
+
* inputSchema: {
|
|
269
|
+
* type: 'object',
|
|
270
|
+
* properties: { userId: { type: 'string' } },
|
|
271
|
+
* required: ['userId'],
|
|
272
|
+
* } as const,
|
|
273
|
+
* outputSchema: {
|
|
274
|
+
* type: 'object',
|
|
275
|
+
* properties: {
|
|
276
|
+
* id: { type: 'string' },
|
|
277
|
+
* name: { type: 'string' },
|
|
278
|
+
* email: { type: 'string' },
|
|
279
|
+
* },
|
|
280
|
+
* } as const,
|
|
281
|
+
* handler: async ({ userId }) => {
|
|
282
|
+
* const user = await fetchUser(userId);
|
|
283
|
+
* return { id: user.id, name: user.name, email: user.email };
|
|
284
|
+
* },
|
|
285
|
+
* });
|
|
286
|
+
* ```
|
|
287
|
+
*
|
|
288
|
+
* ## Re-render Optimization
|
|
289
|
+
*
|
|
290
|
+
* This hook is optimized to minimize unnecessary tool re-registrations:
|
|
291
|
+
*
|
|
292
|
+
* - **Ref-based callbacks**: `handler`, `onSuccess`, `onError`, and `formatOutput`
|
|
293
|
+
* are stored in refs, so changing these functions won't trigger re-registration.
|
|
294
|
+
*
|
|
295
|
+
* **IMPORTANT**: If `inputSchema`, `outputSchema`, or `annotations` are defined inline
|
|
296
|
+
* or change on every render, the tool will re-register unnecessarily. To avoid this,
|
|
297
|
+
* define them outside your component with `as const`:
|
|
298
|
+
*
|
|
299
|
+
* ```tsx
|
|
300
|
+
* // Good: Static schema defined outside component
|
|
301
|
+
* const OUTPUT_SCHEMA = {
|
|
302
|
+
* type: 'object',
|
|
303
|
+
* properties: { count: { type: 'number' } },
|
|
304
|
+
* } as const;
|
|
305
|
+
*
|
|
306
|
+
* // Bad: Inline schema (creates new object every render)
|
|
307
|
+
* useWebMCP({
|
|
308
|
+
* outputSchema: { type: 'object', properties: { count: { type: 'number' } } } as const,
|
|
309
|
+
* });
|
|
310
|
+
* ```
|
|
311
|
+
*
|
|
312
|
+
* @template TInputSchema - JSON Schema defining input parameter types (use `as const` for inference)
|
|
313
|
+
* @template TOutputSchema - JSON Schema object defining output structure (enables structuredContent)
|
|
314
|
+
*
|
|
315
|
+
* @param config - Configuration object for the tool
|
|
316
|
+
* @param deps - Optional dependency array that triggers tool re-registration when values change.
|
|
317
|
+
*
|
|
318
|
+
* @returns Object containing execution state and control methods
|
|
319
|
+
*
|
|
320
|
+
* @public
|
|
321
|
+
*
|
|
322
|
+
* @example
|
|
323
|
+
* Basic tool with outputSchema (recommended):
|
|
324
|
+
* ```tsx
|
|
325
|
+
* function PostActions() {
|
|
326
|
+
* const likeTool = useWebMCP({
|
|
327
|
+
* name: 'posts_like',
|
|
328
|
+
* description: 'Like a post by ID',
|
|
329
|
+
* inputSchema: {
|
|
330
|
+
* type: 'object',
|
|
331
|
+
* properties: { postId: { type: 'string', description: 'The post ID' } },
|
|
332
|
+
* required: ['postId'],
|
|
333
|
+
* } as const,
|
|
334
|
+
* outputSchema: {
|
|
335
|
+
* type: 'object',
|
|
336
|
+
* properties: {
|
|
337
|
+
* success: { type: 'boolean' },
|
|
338
|
+
* likeCount: { type: 'number' },
|
|
339
|
+
* },
|
|
340
|
+
* } as const,
|
|
341
|
+
* handler: async ({ postId }) => {
|
|
342
|
+
* const result = await api.posts.like(postId);
|
|
343
|
+
* return { success: true, likeCount: result.likes };
|
|
344
|
+
* },
|
|
345
|
+
* });
|
|
346
|
+
*
|
|
347
|
+
* return <div>Likes: {likeTool.state.lastResult?.likeCount ?? 0}</div>;
|
|
348
|
+
* }
|
|
349
|
+
* ```
|
|
350
|
+
*/
|
|
351
|
+
declare function useWebMCP<TInputSchema extends ToolInputSchema = InputSchema, TOutputSchema extends JsonSchemaObject | undefined = undefined>(config: WebMCPConfig<TInputSchema, TOutputSchema>, deps?: DependencyList): WebMCPReturn<TOutputSchema>;
|
|
352
|
+
//#endregion
|
|
353
|
+
export { type InferOutput, type InferToolInput, type ToolExecutionState, type WebMCPConfig, type WebMCPReturn, useWebMCP };
|
|
354
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","names":[],"sources":["../src/types.ts","../src/useWebMCP.ts"],"sourcesContent":[],"mappings":";;;;;;;;;AAmBA;;;;;;;AAK+B,KALnB,cAKmB,CAAA,CAAA,CAAA,GALC,CAKD,SAAA;EAAzB,SAAA,WAAA,EAAA;IACA,SAAA,KAAA,CAAA,EAAA,KAAA,MAAA;EAAM,CAAA;AAaZ,CAAA,GAlBI,KAkBQ,SAAW;EACC,SAAA,KAAA,EAAA,KAAA,EAAA;CAEpB,GApBE,CAoBF,GAnBE,MAmBF,CAAA,MAAA,EAAA,OAAA,CAAA,GAlBA,CAkBA,SAlBU,WAkBV,GAjBE,wBAiBF,CAjB2B,CAiB3B,CAAA,GAhBE,MAgBF,CAAA,MAAA,EAAA,OAAA,CAAA;;;;;;AASJ;AA8EA;;;;;AA6DiB,KAvJL,WAuJK,CAAA,sBAtJO,gBAsJP,GAAA,SAAA,GAAA,SAAA,EAAA,YAAA,OAAA,CAAA,GApJb,aAoJa,SApJS,gBAoJT,GApJ4B,eAoJ5B,CApJ4C,aAoJ5C,CAAA,GApJ6D,SAoJ7D;;;;;;;;AAoB4B,UA/J5B,kBA+J4B,CAAA,UAAA,OAAA,CAAA,CAAA;EAYP;;;;EAkBlB,WAAA,EAAA,OAAA;EAAK;AAUzB;;;EAK4B,UAAA,EAjMd,OAiMc,GAAA,IAAA;EAAnB;;;;EAU6B,KAAA,EArM7B,KAqM6B,GAAA,IAAA;;;;ACtGtC;EACuB,cAAA,EAAA,MAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;UDnCN,kCACM,kBAAkB,mCACjB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;gBAmCR;;;;;;;;;;;;;;;;;;;;;;;iBAwBC;;;;;gBAMD;;;;;;;;;;;mBAaL,eAAe,kBACnB,QAAQ,YAAY,kBAAkB,YAAY;;;;;;;;;;;0BAY/B,YAAY;;;;;;;;uBASf,YAAY;;;;;;;;oBASf;;;;;;;;;UAUH,mCAAmC;;;;;SAK3C,mBAAmB,YAAY;;;;;;;;;+BAUT,QAAQ,YAAY;;;;;;;;;;AArPnD;;;;;;;;;;;AAmBA;;;;;;;;AAYA;AA8EA;;;;;;;;;;;;;;;;;;;;AAyHA;;;;;;;;;;;;ACvFA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAAgB,+BACO,kBAAkB,mCACjB,kDAEd,aAAa,cAAc,uBAC5B,iBACN,aAAa"}
|
package/dist/index.js
CHANGED
|
@@ -1 +1,2 @@
|
|
|
1
|
-
|
|
1
|
+
"use client";import{useCallback as e,useEffect as t,useLayoutEffect as n,useRef as r,useState as i}from"react";function a(e){return typeof e==`string`?e:JSON.stringify(e,null,2)}const o=new Map;function s(e){if(!e||typeof e!=`object`||Array.isArray(e))return null;try{let t=JSON.parse(JSON.stringify(e));return!t||typeof t!=`object`||Array.isArray(t)?null:t}catch{return null}}const c=typeof window<`u`?n:t;function l(){let e=globalThis.process?.env?.NODE_ENV;return e===void 0?!1:e!==`production`}function u(n,u){let{name:d,description:f,inputSchema:p,outputSchema:m,annotations:h,handler:g,formatOutput:_=a,onSuccess:v,onError:y}=n,[b,x]=i({isExecuting:!1,lastResult:null,error:null,executionCount:0}),S=r(g),C=r(v),w=r(y),T=r(_),E=r(!0),D=r(new Set),O=r({inputSchema:p,outputSchema:m,annotations:h,description:f,deps:u});c(()=>{S.current=g,C.current=v,w.current=y,T.current=_},[g,v,y,_]),t(()=>(E.current=!0,()=>{E.current=!1}),[]),t(()=>{if(!l()){O.current={inputSchema:p,outputSchema:m,annotations:h,description:f,deps:u};return}let e=(e,t)=>{D.current.has(e)||(console.warn(`[useWebMCP] ${t}`),D.current.add(e))},t=O.current;p&&t.inputSchema&&t.inputSchema!==p&&e(`inputSchema`,`Tool "${d}" inputSchema reference changed; memoize or define it outside the component to avoid re-registration.`),m&&t.outputSchema&&t.outputSchema!==m&&e(`outputSchema`,`Tool "${d}" outputSchema reference changed; memoize or define it outside the component to avoid re-registration.`),h&&t.annotations&&t.annotations!==h&&e(`annotations`,`Tool "${d}" annotations reference changed; memoize or define it outside the component to avoid re-registration.`),f!==t.description&&e(`description`,`Tool "${d}" description changed; this re-registers the tool. Memoize the description if it does not need to update.`),u?.some(e=>typeof e==`object`&&!!e||typeof e==`function`)&&e(`deps`,`Tool "${d}" deps contains non-primitive values; prefer primitives or memoize objects/functions to reduce re-registration.`),O.current={inputSchema:p,outputSchema:m,annotations:h,description:f,deps:u}},[h,u,f,p,d,m]);let k=e(async e=>{x(e=>({...e,isExecuting:!0,error:null}));try{let t=await S.current(e);return E.current&&x(e=>({isExecuting:!1,lastResult:t,error:null,executionCount:e.executionCount+1})),C.current&&C.current(t,e),t}catch(t){let n=t instanceof Error?t:Error(String(t));throw E.current&&x(e=>({...e,isExecuting:!1,error:n})),w.current&&w.current(n,e),n}},[]),A=r(k);t(()=>{A.current=k},[k]);let j=e(e=>A.current(e),[]),M=e(()=>{x({isExecuting:!1,lastResult:null,error:null,executionCount:0})},[]);return t(()=>{if(typeof window>`u`||!window.navigator?.modelContext){console.warn(`[useWebMCP] window.navigator.modelContext is not available. Tool "${d}" will not be registered.`);return}let e=async e=>{try{let t=await A.current(e),n={content:[{type:`text`,text:T.current(t)}]};if(m){let e=s(t);if(!e)throw Error(`Tool "${d}" outputSchema requires the handler to return a JSON object result`);n.structuredContent=e}return n}catch(e){return{content:[{type:`text`,text:`Error: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}},t=Symbol(d),n=window.navigator.modelContext;return n.registerTool({name:d,description:f,...p&&{inputSchema:p},...m&&{outputSchema:m},...h&&{annotations:h},execute:e}),o.set(d,t),()=>{if(o.get(d)===t){o.delete(d);try{n.unregisterTool(d)}catch(e){l()&&console.warn(`[useWebMCP] Failed to unregister tool "${d}" during cleanup:`,e)}}}},[d,f,p,m,h,...u??[]]),{state:b,execute:j,reset:M}}export{u as useWebMCP};
|
|
2
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","names":["response: CallToolResult"],"sources":["../src/useWebMCP.ts"],"sourcesContent":["import type { ToolInputSchema } from '@mcp-b/webmcp-polyfill';\nimport type {\n CallToolResult,\n InputSchema,\n JsonSchemaObject,\n ToolDescriptor,\n} from '@mcp-b/webmcp-types';\nimport type { DependencyList } from 'react';\nimport { useCallback, useEffect, useLayoutEffect, useRef, useState } from 'react';\nimport type {\n InferOutput,\n InferToolInput,\n ToolExecutionState,\n WebMCPConfig,\n WebMCPReturn,\n} from './types.js';\n\n/**\n * Default output formatter that converts values to formatted JSON strings.\n *\n * String values are returned as-is; all other types are serialized to\n * indented JSON for readability.\n *\n * @internal\n */\nfunction defaultFormatOutput(output: unknown): string {\n if (typeof output === 'string') {\n return output;\n }\n return JSON.stringify(output, null, 2);\n}\n\nconst TOOL_OWNER_BY_NAME = new Map<string, symbol>();\ntype StructuredContent = Exclude<CallToolResult['structuredContent'], undefined>;\n\nfunction toStructuredContent(value: unknown): StructuredContent | null {\n if (!value || typeof value !== 'object' || Array.isArray(value)) {\n return null;\n }\n\n try {\n const normalized = JSON.parse(JSON.stringify(value)) as unknown;\n if (!normalized || typeof normalized !== 'object' || Array.isArray(normalized)) {\n return null;\n }\n return normalized as StructuredContent;\n } catch {\n return null;\n }\n}\n\nconst useIsomorphicLayoutEffect = typeof window !== 'undefined' ? useLayoutEffect : useEffect;\n\nfunction isDev(): boolean {\n const env = (globalThis as { process?: { env?: { NODE_ENV?: string } } }).process?.env?.NODE_ENV;\n return env !== undefined ? env !== 'production' : false;\n}\n\n/**\n * React hook for registering and managing Model Context Protocol (MCP) tools.\n *\n * This hook handles the complete lifecycle of an MCP tool:\n * - Registers the tool with `window.navigator.modelContext`\n * - Manages execution state (loading, results, errors)\n * - Handles tool execution and lifecycle callbacks\n * - Automatically unregisters on component unmount\n * - Returns `structuredContent` when `outputSchema` is defined\n *\n * ## Output Schema (Recommended)\n *\n * Always define an `outputSchema` for your tools. This provides:\n * - **Type Safety**: Handler return type is inferred from the schema\n * - **MCP structuredContent**: AI models receive structured, typed data\n * - **Better AI Understanding**: Models can reason about your tool's output format\n *\n * ```tsx\n * useWebMCP({\n * name: 'get_user',\n * description: 'Get user by ID',\n * inputSchema: {\n * type: 'object',\n * properties: { userId: { type: 'string' } },\n * required: ['userId'],\n * } as const,\n * outputSchema: {\n * type: 'object',\n * properties: {\n * id: { type: 'string' },\n * name: { type: 'string' },\n * email: { type: 'string' },\n * },\n * } as const,\n * handler: async ({ userId }) => {\n * const user = await fetchUser(userId);\n * return { id: user.id, name: user.name, email: user.email };\n * },\n * });\n * ```\n *\n * ## Re-render Optimization\n *\n * This hook is optimized to minimize unnecessary tool re-registrations:\n *\n * - **Ref-based callbacks**: `handler`, `onSuccess`, `onError`, and `formatOutput`\n * are stored in refs, so changing these functions won't trigger re-registration.\n *\n * **IMPORTANT**: If `inputSchema`, `outputSchema`, or `annotations` are defined inline\n * or change on every render, the tool will re-register unnecessarily. To avoid this,\n * define them outside your component with `as const`:\n *\n * ```tsx\n * // Good: Static schema defined outside component\n * const OUTPUT_SCHEMA = {\n * type: 'object',\n * properties: { count: { type: 'number' } },\n * } as const;\n *\n * // Bad: Inline schema (creates new object every render)\n * useWebMCP({\n * outputSchema: { type: 'object', properties: { count: { type: 'number' } } } as const,\n * });\n * ```\n *\n * @template TInputSchema - JSON Schema defining input parameter types (use `as const` for inference)\n * @template TOutputSchema - JSON Schema object defining output structure (enables structuredContent)\n *\n * @param config - Configuration object for the tool\n * @param deps - Optional dependency array that triggers tool re-registration when values change.\n *\n * @returns Object containing execution state and control methods\n *\n * @public\n *\n * @example\n * Basic tool with outputSchema (recommended):\n * ```tsx\n * function PostActions() {\n * const likeTool = useWebMCP({\n * name: 'posts_like',\n * description: 'Like a post by ID',\n * inputSchema: {\n * type: 'object',\n * properties: { postId: { type: 'string', description: 'The post ID' } },\n * required: ['postId'],\n * } as const,\n * outputSchema: {\n * type: 'object',\n * properties: {\n * success: { type: 'boolean' },\n * likeCount: { type: 'number' },\n * },\n * } as const,\n * handler: async ({ postId }) => {\n * const result = await api.posts.like(postId);\n * return { success: true, likeCount: result.likes };\n * },\n * });\n *\n * return <div>Likes: {likeTool.state.lastResult?.likeCount ?? 0}</div>;\n * }\n * ```\n */\nexport function useWebMCP<\n TInputSchema extends ToolInputSchema = InputSchema,\n TOutputSchema extends JsonSchemaObject | undefined = undefined,\n>(\n config: WebMCPConfig<TInputSchema, TOutputSchema>,\n deps?: DependencyList\n): WebMCPReturn<TOutputSchema> {\n type TOutput = InferOutput<TOutputSchema>;\n type TInput = InferToolInput<TInputSchema>;\n const {\n name,\n description,\n inputSchema,\n outputSchema,\n annotations,\n handler,\n formatOutput = defaultFormatOutput,\n onSuccess,\n onError,\n } = config;\n\n const [state, setState] = useState<ToolExecutionState<TOutput>>({\n isExecuting: false,\n lastResult: null,\n error: null,\n executionCount: 0,\n });\n\n const handlerRef = useRef(handler);\n const onSuccessRef = useRef(onSuccess);\n const onErrorRef = useRef(onError);\n const formatOutputRef = useRef(formatOutput);\n const isMountedRef = useRef(true);\n const warnedRef = useRef(new Set<string>());\n const prevConfigRef = useRef({\n inputSchema,\n outputSchema,\n annotations,\n description,\n deps,\n });\n // Update refs when callbacks change (doesn't trigger re-registration)\n useIsomorphicLayoutEffect(() => {\n handlerRef.current = handler;\n onSuccessRef.current = onSuccess;\n onErrorRef.current = onError;\n formatOutputRef.current = formatOutput;\n }, [handler, onSuccess, onError, formatOutput]);\n\n // Cleanup: mark component as unmounted\n useEffect(() => {\n isMountedRef.current = true;\n return () => {\n isMountedRef.current = false;\n };\n }, []);\n\n useEffect(() => {\n if (!isDev()) {\n prevConfigRef.current = { inputSchema, outputSchema, annotations, description, deps };\n return;\n }\n\n const warnOnce = (key: string, message: string) => {\n if (warnedRef.current.has(key)) {\n return;\n }\n console.warn(`[useWebMCP] ${message}`);\n warnedRef.current.add(key);\n };\n\n const prev = prevConfigRef.current;\n\n if (inputSchema && prev.inputSchema && prev.inputSchema !== inputSchema) {\n warnOnce(\n 'inputSchema',\n `Tool \"${name}\" inputSchema reference changed; memoize or define it outside the component to avoid re-registration.`\n );\n }\n\n if (outputSchema && prev.outputSchema && prev.outputSchema !== outputSchema) {\n warnOnce(\n 'outputSchema',\n `Tool \"${name}\" outputSchema reference changed; memoize or define it outside the component to avoid re-registration.`\n );\n }\n\n if (annotations && prev.annotations && prev.annotations !== annotations) {\n warnOnce(\n 'annotations',\n `Tool \"${name}\" annotations reference changed; memoize or define it outside the component to avoid re-registration.`\n );\n }\n\n if (description !== prev.description) {\n warnOnce(\n 'description',\n `Tool \"${name}\" description changed; this re-registers the tool. Memoize the description if it does not need to update.`\n );\n }\n\n if (\n deps?.some(\n (value) => (typeof value === 'object' && value !== null) || typeof value === 'function'\n )\n ) {\n warnOnce(\n 'deps',\n `Tool \"${name}\" deps contains non-primitive values; prefer primitives or memoize objects/functions to reduce re-registration.`\n );\n }\n\n prevConfigRef.current = { inputSchema, outputSchema, annotations, description, deps };\n }, [annotations, deps, description, inputSchema, name, outputSchema]);\n\n /**\n * Executes the tool handler with input validation and state management.\n *\n * @param input - The input parameters to validate and pass to the handler\n * @returns Promise resolving to the handler's output\n * @throws Error if validation fails or the handler throws\n */\n const execute = useCallback(async (input: unknown): Promise<TOutput> => {\n setState((prev) => ({\n ...prev,\n isExecuting: true,\n error: null,\n }));\n\n try {\n const result = await handlerRef.current(input as TInput);\n\n // Only update state if component is still mounted\n if (isMountedRef.current) {\n setState((prev) => ({\n isExecuting: false,\n lastResult: result,\n error: null,\n executionCount: prev.executionCount + 1,\n }));\n }\n\n if (onSuccessRef.current) {\n onSuccessRef.current(result, input);\n }\n\n return result;\n } catch (error) {\n const err = error instanceof Error ? error : new Error(String(error));\n\n // Only update state if component is still mounted\n if (isMountedRef.current) {\n setState((prev) => ({\n ...prev,\n isExecuting: false,\n error: err,\n }));\n }\n\n if (onErrorRef.current) {\n onErrorRef.current(err, input);\n }\n\n throw err;\n }\n }, []);\n const executeRef = useRef(execute);\n\n useEffect(() => {\n executeRef.current = execute;\n }, [execute]);\n\n const stableExecute = useCallback(\n (input: unknown): Promise<TOutput> => executeRef.current(input),\n []\n );\n\n /**\n * Resets the execution state to initial values.\n */\n const reset = useCallback(() => {\n setState({\n isExecuting: false,\n lastResult: null,\n error: null,\n executionCount: 0,\n });\n }, []);\n\n useEffect(() => {\n if (typeof window === 'undefined' || !window.navigator?.modelContext) {\n console.warn(\n `[useWebMCP] window.navigator.modelContext is not available. Tool \"${name}\" will not be registered.`\n );\n return;\n }\n\n /**\n * Handles MCP tool execution by running the handler and formatting the response.\n *\n * @param input - The input parameters from the MCP client\n * @returns CallToolResult with text content and optional structuredContent\n */\n const mcpHandler = async (input: unknown): Promise<CallToolResult> => {\n try {\n const result = await executeRef.current(input);\n const formattedOutput = formatOutputRef.current(result);\n\n const response: CallToolResult = {\n content: [\n {\n type: 'text',\n text: formattedOutput,\n },\n ],\n };\n\n if (outputSchema) {\n const structuredContent = toStructuredContent(result);\n if (!structuredContent) {\n throw new Error(\n `Tool \"${name}\" outputSchema requires the handler to return a JSON object result`\n );\n }\n response.structuredContent = structuredContent;\n }\n\n return response;\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : String(error);\n\n return {\n content: [\n {\n type: 'text',\n text: `Error: ${errorMessage}`,\n },\n ],\n isError: true,\n };\n }\n };\n\n const ownerToken = Symbol(name);\n const modelContext = window.navigator.modelContext;\n\n (modelContext.registerTool as (tool: ToolDescriptor) => void)({\n name,\n description,\n ...(inputSchema && { inputSchema: inputSchema as InputSchema }),\n ...(outputSchema && { outputSchema: outputSchema as InputSchema }),\n ...(annotations && { annotations }),\n execute: mcpHandler,\n });\n TOOL_OWNER_BY_NAME.set(name, ownerToken);\n\n return () => {\n const currentOwner = TOOL_OWNER_BY_NAME.get(name);\n if (currentOwner !== ownerToken) {\n return;\n }\n\n TOOL_OWNER_BY_NAME.delete(name);\n try {\n modelContext.unregisterTool(name);\n } catch (error) {\n if (isDev()) {\n console.warn(`[useWebMCP] Failed to unregister tool \"${name}\" during cleanup:`, error);\n }\n }\n };\n // Spread operator in dependencies: Allows users to provide additional dependencies\n // via the `deps` parameter. While unconventional, this pattern is intentional to support\n // dynamic dependency injection. The spread is safe because deps is validated and warned\n // about non-primitive values earlier in this hook.\n }, [name, description, inputSchema, outputSchema, annotations, ...(deps ?? [])]);\n\n return {\n state,\n execute: stableExecute,\n reset,\n };\n}\n"],"mappings":"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"}
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "usewebmcp",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"description": "React hooks for
|
|
3
|
+
"version": "0.3.0",
|
|
4
|
+
"description": "Standalone React hooks for strict core WebMCP tool registration with navigator.modelContext",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"mcp",
|
|
7
7
|
"model-context-protocol",
|
|
@@ -12,16 +12,15 @@
|
|
|
12
12
|
"ai",
|
|
13
13
|
"assistant",
|
|
14
14
|
"tools",
|
|
15
|
-
"zod",
|
|
16
15
|
"usewebmcp"
|
|
17
16
|
],
|
|
18
|
-
"homepage": "https://github.com/WebMCP-org/
|
|
17
|
+
"homepage": "https://github.com/WebMCP-org/npm-packages#readme",
|
|
19
18
|
"bugs": {
|
|
20
|
-
"url": "https://github.com/WebMCP-org/
|
|
19
|
+
"url": "https://github.com/WebMCP-org/npm-packages/issues"
|
|
21
20
|
},
|
|
22
21
|
"repository": {
|
|
23
22
|
"type": "git",
|
|
24
|
-
"url": "git+https://github.com/WebMCP-org/
|
|
23
|
+
"url": "git+https://github.com/WebMCP-org/npm-packages.git",
|
|
25
24
|
"directory": "packages/usewebmcp"
|
|
26
25
|
},
|
|
27
26
|
"license": "MIT",
|
|
@@ -38,17 +37,26 @@
|
|
|
38
37
|
"dist"
|
|
39
38
|
],
|
|
40
39
|
"dependencies": {
|
|
41
|
-
"@mcp-b/
|
|
40
|
+
"@mcp-b/webmcp-polyfill": "0.2.0",
|
|
41
|
+
"@mcp-b/webmcp-types": "0.2.0"
|
|
42
42
|
},
|
|
43
43
|
"devDependencies": {
|
|
44
44
|
"@types/node": "22.17.2",
|
|
45
|
-
"@types/react": "^19.
|
|
45
|
+
"@types/react": "^19.2.9",
|
|
46
|
+
"@vitest/browser": "^4.0.18",
|
|
47
|
+
"@vitest/browser-playwright": "^4.0.18",
|
|
48
|
+
"@vitest/coverage-v8": "^4.0.18",
|
|
49
|
+
"playwright": "^1.58.0",
|
|
50
|
+
"react": "^19.1.0",
|
|
51
|
+
"react-dom": "^19.1.0",
|
|
46
52
|
"tsdown": "^0.15.10",
|
|
47
|
-
"typescript": "^5.8.3"
|
|
53
|
+
"typescript": "^5.8.3",
|
|
54
|
+
"vitest": "^4.0.18",
|
|
55
|
+
"vitest-browser-react": "^2.0.4",
|
|
56
|
+
"@mcp-b/global": "0.0.0-beta-20260217171247"
|
|
48
57
|
},
|
|
49
58
|
"peerDependencies": {
|
|
50
|
-
"react": "^17.0.0 || ^18.0.0 || ^19.0.0"
|
|
51
|
-
"zod": "^3.25.0"
|
|
59
|
+
"react": "^17.0.0 || ^18.0.0 || ^19.0.0"
|
|
52
60
|
},
|
|
53
61
|
"publishConfig": {
|
|
54
62
|
"access": "public",
|
|
@@ -63,6 +71,8 @@
|
|
|
63
71
|
"lint": "biome lint --write .",
|
|
64
72
|
"publish:dry": "pnpm publish --access public --dry-run",
|
|
65
73
|
"publish:npm": "pnpm publish --access public",
|
|
66
|
-
"
|
|
74
|
+
"test": "vitest run",
|
|
75
|
+
"test:watch": "vitest",
|
|
76
|
+
"typecheck": "tsc --noEmit && vitest run --typecheck --silent"
|
|
67
77
|
}
|
|
68
78
|
}
|