@mcp-b/react-webmcp 0.1.4 → 0.1.6-beta.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,8 +1,8 @@
1
1
  import { ReactElement, ReactNode } from "react";
2
2
  import { z } from "zod";
3
3
  import { CallToolResult, Resource, Resource as Resource$1, ServerCapabilities, ServerCapabilities as ServerCapabilities$1, Tool, Tool as Tool$1 } from "@modelcontextprotocol/sdk/types.js";
4
+ import { ElicitationFormParams, ElicitationParams, ElicitationParams as ElicitationParams$1, ElicitationResult, ElicitationResult as ElicitationResult$1, ElicitationUrlParams, ModelContext as ModelContextProtocol, SamplingRequestParams, SamplingRequestParams as SamplingRequestParams$1, SamplingResult, SamplingResult as SamplingResult$1, ToolDescriptor } from "@mcp-b/global";
4
5
  import { ToolAnnotations } from "@mcp-b/webmcp-ts-sdk";
5
- import { ModelContext as ModelContextProtocol, ToolDescriptor } from "@mcp-b/global";
6
6
  import { Client } from "@modelcontextprotocol/sdk/client/index.js";
7
7
  import { RequestOptions } from "@modelcontextprotocol/sdk/shared/protocol.js";
8
8
  import { Transport } from "@modelcontextprotocol/sdk/shared/transport.js";
@@ -293,6 +293,191 @@ declare function useWebMCP<TInputSchema extends Record<string, z.ZodTypeAny> = R
293
293
  */
294
294
  declare function useWebMCPContext<T>(name: string, description: string, getValue: () => T): WebMCPReturn<T>;
295
295
  //#endregion
296
+ //#region src/useElicitationHandler.d.ts
297
+ /**
298
+ * State for elicitation requests, tracking the current request and results.
299
+ */
300
+ interface ElicitationState {
301
+ /** Whether an elicitation request is currently in progress */
302
+ isLoading: boolean;
303
+ /** The last elicitation result received */
304
+ result: ElicitationResult$1 | null;
305
+ /** Any error that occurred during the last request */
306
+ error: Error | null;
307
+ /** Total number of requests made */
308
+ requestCount: number;
309
+ }
310
+ /**
311
+ * Configuration options for the useElicitation hook.
312
+ */
313
+ interface UseElicitationConfig {
314
+ /**
315
+ * Optional callback invoked when an elicitation request completes successfully.
316
+ */
317
+ onSuccess?: (result: ElicitationResult$1) => void;
318
+ /**
319
+ * Optional callback invoked when an elicitation request fails.
320
+ */
321
+ onError?: (error: Error) => void;
322
+ }
323
+ /**
324
+ * Return value from the useElicitation hook.
325
+ */
326
+ interface UseElicitationReturn {
327
+ /** Current state of elicitation */
328
+ state: ElicitationState;
329
+ /** Function to request user input from the connected client */
330
+ elicitInput: (params: ElicitationParams$1) => Promise<ElicitationResult$1>;
331
+ /** Reset the state */
332
+ reset: () => void;
333
+ }
334
+ /**
335
+ * React hook for requesting user input from the connected MCP client.
336
+ *
337
+ * Elicitation allows the server (webpage) to request user input from the
338
+ * connected client. This is useful when the page needs additional information
339
+ * from the user, such as API keys, configuration options, or confirmations.
340
+ *
341
+ * There are two modes:
342
+ * 1. **Form mode**: For non-sensitive data collection using a schema-driven form.
343
+ * 2. **URL mode**: For sensitive data collection via a web URL (API keys, OAuth, etc.).
344
+ *
345
+ * @param config - Optional configuration including callbacks
346
+ * @returns Object containing state and the elicitInput function
347
+ *
348
+ * @example Form elicitation:
349
+ * ```tsx
350
+ * function ConfigForm() {
351
+ * const { state, elicitInput } = useElicitation({
352
+ * onSuccess: (result) => console.log('Got input:', result),
353
+ * onError: (error) => console.error('Elicitation failed:', error),
354
+ * });
355
+ *
356
+ * const handleConfigure = async () => {
357
+ * const result = await elicitInput({
358
+ * message: 'Please provide your configuration',
359
+ * requestedSchema: {
360
+ * type: 'object',
361
+ * properties: {
362
+ * apiKey: { type: 'string', title: 'API Key', description: 'Your API key' },
363
+ * model: { type: 'string', enum: ['gpt-4', 'gpt-3.5'], title: 'Model' }
364
+ * },
365
+ * required: ['apiKey']
366
+ * }
367
+ * });
368
+ *
369
+ * if (result.action === 'accept') {
370
+ * console.log('Config:', result.content);
371
+ * }
372
+ * };
373
+ *
374
+ * return (
375
+ * <button onClick={handleConfigure} disabled={state.isLoading}>
376
+ * Configure
377
+ * </button>
378
+ * );
379
+ * }
380
+ * ```
381
+ *
382
+ * @example URL elicitation (for sensitive data):
383
+ * ```tsx
384
+ * const { elicitInput } = useElicitation();
385
+ *
386
+ * const handleOAuth = async () => {
387
+ * const result = await elicitInput({
388
+ * mode: 'url',
389
+ * message: 'Please authenticate with GitHub',
390
+ * elicitationId: 'github-oauth-123',
391
+ * url: 'https://github.com/login/oauth/authorize?client_id=...'
392
+ * });
393
+ *
394
+ * if (result.action === 'accept') {
395
+ * console.log('OAuth completed');
396
+ * }
397
+ * };
398
+ * ```
399
+ */
400
+ declare function useElicitation(config?: UseElicitationConfig): UseElicitationReturn;
401
+ //#endregion
402
+ //#region src/useSamplingHandler.d.ts
403
+ /**
404
+ * State for sampling requests, tracking the current request and results.
405
+ */
406
+ interface SamplingState {
407
+ /** Whether a sampling request is currently in progress */
408
+ isLoading: boolean;
409
+ /** The last sampling result received */
410
+ result: SamplingResult$1 | null;
411
+ /** Any error that occurred during the last request */
412
+ error: Error | null;
413
+ /** Total number of requests made */
414
+ requestCount: number;
415
+ }
416
+ /**
417
+ * Configuration options for the useSampling hook.
418
+ */
419
+ interface UseSamplingConfig {
420
+ /**
421
+ * Optional callback invoked when a sampling request completes successfully.
422
+ */
423
+ onSuccess?: (result: SamplingResult$1) => void;
424
+ /**
425
+ * Optional callback invoked when a sampling request fails.
426
+ */
427
+ onError?: (error: Error) => void;
428
+ }
429
+ /**
430
+ * Return value from the useSampling hook.
431
+ */
432
+ interface UseSamplingReturn {
433
+ /** Current state of sampling */
434
+ state: SamplingState;
435
+ /** Function to request LLM completion from the connected client */
436
+ createMessage: (params: SamplingRequestParams$1) => Promise<SamplingResult$1>;
437
+ /** Reset the state */
438
+ reset: () => void;
439
+ }
440
+ /**
441
+ * React hook for requesting LLM completions from the connected MCP client.
442
+ *
443
+ * Sampling allows the server (webpage) to request LLM completions from the
444
+ * connected client. This is useful when the page needs AI capabilities like
445
+ * summarization, generation, or analysis.
446
+ *
447
+ * @param config - Optional configuration including callbacks
448
+ * @returns Object containing state and the createMessage function
449
+ *
450
+ * @example Basic usage:
451
+ * ```tsx
452
+ * function AIAssistant() {
453
+ * const { state, createMessage } = useSampling({
454
+ * onSuccess: (result) => console.log('Got response:', result),
455
+ * onError: (error) => console.error('Sampling failed:', error),
456
+ * });
457
+ *
458
+ * const handleAsk = async () => {
459
+ * const result = await createMessage({
460
+ * messages: [
461
+ * { role: 'user', content: { type: 'text', text: 'What is 2+2?' } }
462
+ * ],
463
+ * maxTokens: 100,
464
+ * });
465
+ * console.log(result.content);
466
+ * };
467
+ *
468
+ * return (
469
+ * <div>
470
+ * <button onClick={handleAsk} disabled={state.isLoading}>
471
+ * Ask AI
472
+ * </button>
473
+ * {state.result && <p>{JSON.stringify(state.result.content)}</p>}
474
+ * </div>
475
+ * );
476
+ * }
477
+ * ```
478
+ */
479
+ declare function useSampling(config?: UseSamplingConfig): UseSamplingReturn;
480
+ //#endregion
296
481
  //#region src/client/McpClientProvider.d.ts
297
482
  /**
298
483
  * Context value provided by McpClientProvider.
@@ -445,5 +630,5 @@ declare function McpClientProvider({
445
630
  */
446
631
  declare function useMcpClient(): McpClientContextValue;
447
632
  //#endregion
448
- export { type CallToolResult, McpClientProvider, type McpClientProviderProps, type ModelContextProtocol, type Resource, type ServerCapabilities, type Tool, type ToolAnnotations, type ToolDescriptor, type ToolExecutionState, type WebMCPConfig, type WebMCPReturn, useMcpClient, useWebMCP, useWebMCPContext };
633
+ export { type CallToolResult, type ElicitationFormParams, type ElicitationState as ElicitationHandlerState, type ElicitationState, type ElicitationParams, type ElicitationResult, type ElicitationUrlParams, McpClientProvider, type McpClientProviderProps, type ModelContextProtocol, type Resource, type SamplingState as SamplingHandlerState, type SamplingState, type SamplingRequestParams, type SamplingResult, type ServerCapabilities, type Tool, type ToolAnnotations, type ToolDescriptor, type ToolExecutionState, 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 WebMCPReturn, useElicitation, useElicitation as useElicitationHandler, useMcpClient, useSampling, useSampling as useSamplingHandler, useWebMCP, useWebMCPContext };
449
634
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","names":[],"sources":["../src/types.ts","../src/useWebMCP.ts","../src/useWebMCPContext.ts","../src/client/McpClientProvider.tsx"],"sourcesContent":[],"mappings":";;;;;;;;;;;;;;;;;AAcA;AAiDiB,UAjDA,kBAiDY,CAAA,UAAA,OAAA,CAAA,CAAA;EACW;;;;EAiCN,WAAA,EAAA,OAAA;EAAjB;;;;EAeI,UAAA,EAvFP,OAuFO,GAAA,IAAA;EAA6C;;;;EAkB3C,KAAA,EAnGd,KAmGc,GAAA,IAAA;EASH;;AAUpB;;EAKS,cAAA,EAAA,MAAA;;;;;;;AClBT;;;;;;;;;;;;;ACvEA;;;;;UFFiB,kCACM,eAAe,CAAA,CAAE,cAAc;;;AG3CvC;;EASN,IAAA,EAAA,MAAA;EACI;;;;EAKa,WAAA,EAAA,MAAA;EAUT;;;;;;AA0FjB;;;;;;EAK4B,WAAA,CAAA,EHlDZ,YGkDY;EAAY;AAgMxC;;;iBH5OiB,eAAe,CAAA,CAAE;;;;;gBAMlB;;;;;;;;mBASG,CAAA,CAAE,MAAM,CAAA,CAAE,UAAU,mBAAmB,QAAQ,WAAW;;;;;;;;0BASnD;;;;;;;;uBASH;;;;;;;;oBASH;;;;;;;;;UAUH;;;;;SAKR,mBAAmB;;;;;;;;;+BAUG,QAAQ;;;;;;;;;;;;;;;;;AAtJvC;AAiDA;;;;;;;;;;;;;;;;;;AAsFA;;;;;;;;;ACbA;;;;;;;;;;;;;ACvEA;;;;;;;;AC5Ce;;;;;;;;AAyBf;;;;AAmBS,iBFuEO,SEvEP,CAAA,qBFwEc,MExEd,CAAA,MAAA,EFwE6B,CAAA,CAAE,UExE/B,CA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eA;;;;;;AA2EA;;;;ACxGA;AAcA;AAeA;;;;;;AAgDA;;;;AC9De;;;;;;;;AAyBf;;;;;;AA0FA;;;;;;;;AAqMA;;;;;;iBArMgB,iBAAA;;;;;GAKb,yBAAyB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAgMZ,YAAA,CAAA,GAAY"}
package/dist/index.js CHANGED
@@ -1,2 +1,2 @@
1
- import{createContext as e,useCallback as t,useContext as n,useEffect as r,useRef as i,useState as a}from"react";import{z as o}from"zod";import{ResourceListChangedNotificationSchema as s,ToolListChangedNotificationSchema as c}from"@modelcontextprotocol/sdk/types.js";import{jsx as l}from"react/jsx-runtime";function u(e){let t={},n=[];for(let[r,i]of Object.entries(e)){let e=i.description||void 0,a=`string`;i instanceof o.ZodNumber?a=`number`:i instanceof o.ZodBoolean?a=`boolean`:i instanceof o.ZodArray?a=`array`:i instanceof o.ZodObject&&(a=`object`),t[r]={type:a,...e&&{description:e}},i.isOptional()||n.push(r)}return{type:`object`,properties:t,...n.length>0&&{required:n}}}function d(e){return typeof e==`string`?e:JSON.stringify(e,null,2)}function f(e){let{name:n,description:s,inputSchema:c,outputSchema:l,annotations:f,handler:p,formatOutput:m=d,onSuccess:h,onError:g}=e,[_,v]=a({isExecuting:!1,lastResult:null,error:null,executionCount:0}),y=i(p),b=i(h),x=i(g),S=i(m);r(()=>{y.current=p},[p]),r(()=>{b.current=h},[h]),r(()=>{x.current=g},[g]),r(()=>{S.current=m},[m]);let C=c?o.object(c):null,w=t(async e=>{v(e=>({...e,isExecuting:!0,error:null}));try{let t=C?C.parse(e):e,n=await y.current(t);return v(e=>({isExecuting:!1,lastResult:n,error:null,executionCount:e.executionCount+1})),b.current&&b.current(n,e),n}catch(t){let n=t instanceof Error?t:Error(String(t));throw v(e=>({...e,isExecuting:!1,error:n})),x.current&&x.current(n,e),n}},[C]),T=t(()=>{v({isExecuting:!1,lastResult:null,error:null,executionCount:0})},[]);return r(()=>{if(typeof window>`u`||!window.navigator?.modelContext){console.warn(`[useWebMCP] window.navigator.modelContext is not available. Tool "${n}" will not be registered.`);return}let e=c?u(c):void 0,t=l?u(l):void 0,r=async(e,t)=>{try{let t=await w(e);return{content:[{type:`text`,text:S.current(t)}]}}catch(e){return{content:[{type:`text`,text:`Error: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}},i=window.navigator.modelContext.registerTool({name:n,description:s,inputSchema:e||{type:`object`,properties:{}},...t&&{outputSchema:t},...f&&{annotations:f},execute:async e=>await r(e,{})});if(console.log(`[useWebMCP] Registered tool: ${n}`),typeof window<`u`){let e=window.navigator.modelContext.listTools(),t=window;t.mcpTools=e.map(e=>e.name)}return()=>{if(i&&(i.unregister(),console.log(`[useWebMCP] Unregistered tool: ${n}`),typeof window<`u`&&window.navigator?.modelContext)){let e=window.navigator.modelContext.listTools(),t=window;t.mcpTools=e.map(e=>e.name)}}},[n,s,c,l,f,w]),{state:_,execute:w,reset:T}}function p(e,t,n){let r=i(n);return r.current=n,f({name:e,description:t,annotations:{title:`Context: ${e}`,readOnlyHint:!0,idempotentHint:!0,destructiveHint:!1,openWorldHint:!1},handler:async()=>r.current(),formatOutput:e=>typeof e==`string`?e:JSON.stringify(e,null,2)})}const m=e(null);function h({children:e,client:n,transport:o,opts:u={}}){let[d,f]=a([]),[p,h]=a([]),[g,_]=a(!1),[v,y]=a(null),[b,x]=a(!1),[S,C]=a(null),w=i(`disconnected`),T=t(async()=>{if(n){if(!n.getServerCapabilities()?.resources){f([]);return}try{f((await n.listResources()).resources)}catch(e){throw console.error(`Error fetching resources:`,e),e}}},[n]),E=t(async()=>{if(n){if(!n.getServerCapabilities()?.tools){h([]);return}try{h((await n.listTools()).tools)}catch(e){throw console.error(`Error fetching tools:`,e),e}}},[n]),D=t(async()=>{if(!n||!o)throw Error(`Client or transport not available`);if(w.current===`disconnected`){w.current=`connecting`,_(!0),y(null);try{await n.connect(o,u);let e=n.getServerCapabilities();x(!0),C(e||null),w.current=`connected`,await Promise.all([T(),E()])}catch(e){let t=e instanceof Error?e:Error(String(e));throw w.current=`disconnected`,y(t),t}finally{_(!1)}}},[n,o,u,T,E]);return r(()=>{if(!b||!n)return;let e=n.getServerCapabilities();return e?.resources?.listChanged&&n.setNotificationHandler(s,()=>{T().catch(console.error)}),e?.tools?.listChanged&&n.setNotificationHandler(c,()=>{E().catch(console.error)}),()=>{e?.resources?.listChanged&&n.removeNotificationHandler(`notifications/resources/list_changed`),e?.tools?.listChanged&&n.removeNotificationHandler(`notifications/tools/list_changed`)}},[n,b,T,E]),r(()=>(D().catch(e=>{console.error(`Failed to connect MCP client:`,e)}),()=>{w.current=`disconnected`,x(!1)}),[n,o]),l(m.Provider,{value:{client:n,tools:p,resources:d,isConnected:b,isLoading:g,error:v,capabilities:S,reconnect:D},children:e})}function g(){let e=n(m);if(!e)throw Error(`useMcpClient must be used within an McpClientProvider`);return e}export{h as McpClientProvider,g as useMcpClient,f as useWebMCP,p as useWebMCPContext};
1
+ import{createContext as e,useCallback as t,useContext as n,useEffect as r,useRef as i,useState as a}from"react";import{z as o}from"zod";import{ResourceListChangedNotificationSchema as s,ToolListChangedNotificationSchema as c}from"@modelcontextprotocol/sdk/types.js";import{jsx as l}from"react/jsx-runtime";function u(e){let t={},n=[];for(let[r,i]of Object.entries(e)){let e=i.description||void 0,a=`string`;i instanceof o.ZodNumber?a=`number`:i instanceof o.ZodBoolean?a=`boolean`:i instanceof o.ZodArray?a=`array`:i instanceof o.ZodObject&&(a=`object`),t[r]={type:a,...e&&{description:e}},i.isOptional()||n.push(r)}return{type:`object`,properties:t,...n.length>0&&{required:n}}}function d(e){return typeof e==`string`?e:JSON.stringify(e,null,2)}function f(e){let{name:n,description:s,inputSchema:c,outputSchema:l,annotations:f,handler:p,formatOutput:m=d,onSuccess:h,onError:g}=e,[_,v]=a({isExecuting:!1,lastResult:null,error:null,executionCount:0}),y=i(p),b=i(h),x=i(g),S=i(m);r(()=>{y.current=p},[p]),r(()=>{b.current=h},[h]),r(()=>{x.current=g},[g]),r(()=>{S.current=m},[m]);let C=c?o.object(c):null,w=t(async e=>{v(e=>({...e,isExecuting:!0,error:null}));try{let t=C?C.parse(e):e,n=await y.current(t);return v(e=>({isExecuting:!1,lastResult:n,error:null,executionCount:e.executionCount+1})),b.current&&b.current(n,e),n}catch(t){let n=t instanceof Error?t:Error(String(t));throw v(e=>({...e,isExecuting:!1,error:n})),x.current&&x.current(n,e),n}},[C]),T=t(()=>{v({isExecuting:!1,lastResult:null,error:null,executionCount:0})},[]);return r(()=>{if(typeof window>`u`||!window.navigator?.modelContext){console.warn(`[useWebMCP] window.navigator.modelContext is not available. Tool "${n}" will not be registered.`);return}let e=c?u(c):void 0,t=l?u(l):void 0,r=async(e,t)=>{try{let t=await w(e);return{content:[{type:`text`,text:S.current(t)}]}}catch(e){return{content:[{type:`text`,text:`Error: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}},i=window.navigator.modelContext.registerTool({name:n,description:s,inputSchema:e||{type:`object`,properties:{}},...t&&{outputSchema:t},...f&&{annotations:f},execute:async e=>await r(e,{})});if(console.log(`[useWebMCP] Registered tool: ${n}`),typeof window<`u`){let e=window.navigator.modelContext.listTools(),t=window;t.mcpTools=e.map(e=>e.name)}return()=>{if(i&&(i.unregister(),console.log(`[useWebMCP] Unregistered tool: ${n}`),typeof window<`u`&&window.navigator?.modelContext)){let e=window.navigator.modelContext.listTools(),t=window;t.mcpTools=e.map(e=>e.name)}}},[n,s,c,l,f,w]),{state:_,execute:w,reset:T}}function p(e,t,n){let r=i(n);return r.current=n,f({name:e,description:t,annotations:{title:`Context: ${e}`,readOnlyHint:!0,idempotentHint:!0,destructiveHint:!1,openWorldHint:!1},handler:async()=>r.current(),formatOutput:e=>typeof e==`string`?e:JSON.stringify(e,null,2)})}function m(e={}){let{onSuccess:n,onError:r}=e,[i,o]=a({isLoading:!1,result:null,error:null,requestCount:0}),s=t(()=>{o({isLoading:!1,result:null,error:null,requestCount:0})},[]);return{state:i,elicitInput:t(async e=>{if(typeof window>`u`||!window.navigator?.modelContext)throw Error(`navigator.modelContext is not available`);o(e=>({...e,isLoading:!0,error:null}));try{let t=await window.navigator.modelContext.elicitInput(e);return o(e=>({isLoading:!1,result:t,error:null,requestCount:e.requestCount+1})),n?.(t),t}catch(e){let t=e instanceof Error?e:Error(String(e));throw o(e=>({...e,isLoading:!1,error:t})),r?.(t),t}},[n,r]),reset:s}}function h(e={}){let{onSuccess:n,onError:r}=e,[i,o]=a({isLoading:!1,result:null,error:null,requestCount:0}),s=t(()=>{o({isLoading:!1,result:null,error:null,requestCount:0})},[]);return{state:i,createMessage:t(async e=>{if(typeof window>`u`||!window.navigator?.modelContext)throw Error(`navigator.modelContext is not available`);o(e=>({...e,isLoading:!0,error:null}));try{let t=await window.navigator.modelContext.createMessage(e);return o(e=>({isLoading:!1,result:t,error:null,requestCount:e.requestCount+1})),n?.(t),t}catch(e){let t=e instanceof Error?e:Error(String(e));throw o(e=>({...e,isLoading:!1,error:t})),r?.(t),t}},[n,r]),reset:s}}const g=e(null);function _({children:e,client:n,transport:o,opts:u={}}){let[d,f]=a([]),[p,m]=a([]),[h,_]=a(!1),[v,y]=a(null),[b,x]=a(!1),[S,C]=a(null),w=i(`disconnected`),T=t(async()=>{if(n){if(!n.getServerCapabilities()?.resources){f([]);return}try{f((await n.listResources()).resources)}catch(e){throw console.error(`Error fetching resources:`,e),e}}},[n]),E=t(async()=>{if(n){if(!n.getServerCapabilities()?.tools){m([]);return}try{m((await n.listTools()).tools)}catch(e){throw console.error(`Error fetching tools:`,e),e}}},[n]),D=t(async()=>{if(!n||!o)throw Error(`Client or transport not available`);if(w.current===`disconnected`){w.current=`connecting`,_(!0),y(null);try{await n.connect(o,u);let e=n.getServerCapabilities();x(!0),C(e||null),w.current=`connected`,await Promise.all([T(),E()])}catch(e){let t=e instanceof Error?e:Error(String(e));throw w.current=`disconnected`,y(t),t}finally{_(!1)}}},[n,o,u,T,E]);return r(()=>{if(!b||!n)return;let e=n.getServerCapabilities();return e?.resources?.listChanged&&n.setNotificationHandler(s,()=>{T().catch(console.error)}),e?.tools?.listChanged&&n.setNotificationHandler(c,()=>{E().catch(console.error)}),()=>{e?.resources?.listChanged&&n.removeNotificationHandler(`notifications/resources/list_changed`),e?.tools?.listChanged&&n.removeNotificationHandler(`notifications/tools/list_changed`)}},[n,b,T,E]),r(()=>(D().catch(e=>{console.error(`Failed to connect MCP client:`,e)}),()=>{w.current=`disconnected`,x(!1)}),[n,o]),l(g.Provider,{value:{client:n,tools:p,resources:d,isConnected:b,isLoading:h,error:v,capabilities:S,reconnect:D},children:e})}function v(){let e=n(g);if(!e)throw Error(`useMcpClient must be used within an McpClientProvider`);return e}export{_ as McpClientProvider,m as useElicitation,m as useElicitationHandler,v as useMcpClient,h as useSampling,h as useSamplingHandler,f as useWebMCP,p as useWebMCPContext};
2
2
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["properties: Record<string, unknown>","required: string[]"],"sources":["../src/useWebMCP.ts","../src/useWebMCPContext.ts","../src/client/McpClientProvider.tsx"],"sourcesContent":["import type { InputSchema } from '@mcp-b/global';\nimport type { CallToolResult } from '@modelcontextprotocol/sdk/types.js';\nimport { useCallback, useEffect, useRef, useState } from 'react';\nimport { z } from 'zod';\nimport type { ToolExecutionState, WebMCPConfig, WebMCPReturn } from './types.js';\n\n/**\n * Converts a Zod schema object to JSON Schema format for MCP.\n * Handles basic type inference for common Zod types.\n *\n * @internal\n * @param schema - Record of Zod type definitions\n * @returns JSON Schema object with type, properties, and required fields\n */\nfunction zodToJsonSchema(schema: Record<string, z.ZodTypeAny>): {\n type: string;\n properties?: Record<string, unknown>;\n required?: string[];\n} {\n const properties: Record<string, unknown> = {};\n const required: string[] = [];\n\n for (const [key, zodType] of Object.entries(schema)) {\n const description = (zodType as { description?: string }).description || undefined;\n\n let type = 'string';\n if (zodType instanceof z.ZodNumber) {\n type = 'number';\n } else if (zodType instanceof z.ZodBoolean) {\n type = 'boolean';\n } else if (zodType instanceof z.ZodArray) {\n type = 'array';\n } else if (zodType instanceof z.ZodObject) {\n type = 'object';\n }\n\n properties[key] = {\n type,\n ...(description && { description }),\n };\n\n if (!zodType.isOptional()) {\n required.push(key);\n }\n }\n\n return {\n type: 'object',\n properties,\n ...(required.length > 0 && { required }),\n };\n}\n\n/**\n * Default output formatter that converts values to formatted JSON strings.\n *\n * @internal\n * @param output - The value to format\n * @returns Formatted string representation\n */\nfunction defaultFormatOutput(output: unknown): string {\n if (typeof output === 'string') {\n return output;\n }\n return JSON.stringify(output, null, 2);\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 * - Validates input using Zod schemas\n * - Handles tool execution and lifecycle callbacks\n * - Automatically unregisters on component unmount\n *\n * @template TInputSchema - Zod schema object defining input parameter types\n * @template TOutput - Type of data returned by the handler function\n *\n * @param config - Configuration object for the tool\n * @returns Object containing execution state and control methods\n *\n * @public\n *\n * @example\n * Basic tool registration:\n * ```tsx\n * function PostActions() {\n * const likeTool = useWebMCP({\n * name: 'posts_like',\n * description: 'Like a post by ID',\n * inputSchema: {\n * postId: z.string().uuid().describe('The ID of the post to like'),\n * },\n * handler: async ({ postId }) => {\n * await api.posts.like(postId);\n * return { success: true, postId };\n * },\n * });\n *\n * if (likeTool.state.isExecuting) {\n * return <Spinner />;\n * }\n *\n * return <div>Post actions ready</div>;\n * }\n * ```\n *\n * @example\n * Tool with annotations and callbacks:\n * ```tsx\n * const deleteTool = useWebMCP({\n * name: 'posts_delete',\n * description: 'Delete a post permanently',\n * inputSchema: {\n * postId: z.string().uuid(),\n * },\n * annotations: {\n * destructiveHint: true,\n * idempotentHint: false,\n * },\n * handler: async ({ postId }) => {\n * await api.posts.delete(postId);\n * return { deleted: true };\n * },\n * onSuccess: () => {\n * navigate('/posts');\n * toast.success('Post deleted');\n * },\n * onError: (error) => {\n * toast.error(`Failed to delete: ${error.message}`);\n * },\n * });\n * ```\n */\nexport function useWebMCP<\n TInputSchema extends Record<string, z.ZodTypeAny> = Record<string, never>,\n TOutput = string,\n>(config: WebMCPConfig<TInputSchema, TOutput>): WebMCPReturn<TOutput> {\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\n useEffect(() => {\n handlerRef.current = handler;\n }, [handler]);\n\n useEffect(() => {\n onSuccessRef.current = onSuccess;\n }, [onSuccess]);\n\n useEffect(() => {\n onErrorRef.current = onError;\n }, [onError]);\n\n useEffect(() => {\n formatOutputRef.current = formatOutput;\n }, [formatOutput]);\n\n const validator = inputSchema ? z.object(inputSchema) : null;\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(\n async (input: unknown): Promise<TOutput> => {\n setState((prev) => ({\n ...prev,\n isExecuting: true,\n error: null,\n }));\n\n try {\n const validatedInput = validator ? validator.parse(input) : input;\n const result = await handlerRef.current(validatedInput as never);\n\n setState((prev) => ({\n isExecuting: false,\n lastResult: result,\n error: null,\n executionCount: prev.executionCount + 1,\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 setState((prev) => ({\n ...prev,\n isExecuting: false,\n error: err,\n }));\n\n if (onErrorRef.current) {\n onErrorRef.current(err, input);\n }\n\n throw err;\n }\n },\n [validator]\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 const inputJsonSchema = inputSchema ? zodToJsonSchema(inputSchema) : undefined;\n const outputJsonSchema = outputSchema ? zodToJsonSchema(outputSchema) : undefined;\n\n const mcpHandler = async (input: unknown, _extra: unknown): Promise<CallToolResult> => {\n try {\n const result = await execute(input);\n const formattedOutput = formatOutputRef.current(result);\n\n return {\n content: [\n {\n type: 'text',\n text: formattedOutput,\n },\n ],\n };\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 fallbackInputSchema: InputSchema = {\n type: 'object',\n properties: {},\n };\n\n const registration = window.navigator.modelContext.registerTool({\n name,\n description,\n inputSchema: (inputJsonSchema || fallbackInputSchema) as InputSchema,\n ...(outputJsonSchema && { outputSchema: outputJsonSchema as InputSchema }),\n ...(annotations && { annotations }),\n execute: async (args: Record<string, unknown>) => {\n const result = await mcpHandler(args, {});\n return result;\n },\n });\n\n console.log(`[useWebMCP] Registered tool: ${name}`);\n\n // Expose registered tools on window for testing\n if (typeof window !== 'undefined') {\n const tools = window.navigator.modelContext.listTools();\n const w = window as unknown as Window & { mcpTools: string[] };\n w.mcpTools = tools.map((t) => t.name);\n }\n\n return () => {\n if (registration) {\n registration.unregister();\n console.log(`[useWebMCP] Unregistered tool: ${name}`);\n\n // Update window.mcpTools after unregistration\n if (typeof window !== 'undefined' && window.navigator?.modelContext) {\n const tools = window.navigator.modelContext.listTools();\n const w = window as unknown as Window & { mcpTools: string[] };\n w.mcpTools = tools.map((t) => t.name);\n }\n }\n };\n }, [name, description, inputSchema, outputSchema, annotations, execute]);\n\n return {\n state,\n execute,\n reset,\n };\n}\n","import { useRef } from 'react';\nimport type { WebMCPReturn } from './types.js';\nimport { useWebMCP } from './useWebMCP.js';\n\n/**\n * Convenience hook for exposing read-only context data to AI assistants.\n *\n * This is a simplified wrapper around {@link useWebMCP} specifically designed for\n * context tools that expose data without performing actions. The hook automatically\n * configures appropriate annotations (read-only, idempotent) and handles value\n * serialization.\n *\n * @template T - The type of context data to expose\n *\n * @param name - Unique identifier for the context tool (e.g., 'context_current_post')\n * @param description - Human-readable description of the context for AI assistants\n * @param getValue - Function that returns the current context value\n * @returns Tool execution state and control methods\n *\n * @public\n *\n * @example\n * Expose current post context:\n * ```tsx\n * function PostDetailPage() {\n * const { postId } = useParams();\n * const { data: post } = useQuery(['post', postId], () => fetchPost(postId));\n *\n * useWebMCPContext(\n * 'context_current_post',\n * 'Get the currently viewed post ID and metadata',\n * () => ({\n * postId,\n * title: post?.title,\n * author: post?.author,\n * tags: post?.tags,\n * createdAt: post?.createdAt,\n * })\n * );\n *\n * return <PostContent post={post} />;\n * }\n * ```\n *\n * @example\n * Expose user session context:\n * ```tsx\n * function AppRoot() {\n * const { user, isAuthenticated } = useAuth();\n *\n * useWebMCPContext(\n * 'context_user_session',\n * 'Get the current user session information',\n * () => ({\n * isAuthenticated,\n * userId: user?.id,\n * email: user?.email,\n * permissions: user?.permissions,\n * })\n * );\n *\n * return <App />;\n * }\n * ```\n */\nexport function useWebMCPContext<T>(\n name: string,\n description: string,\n getValue: () => T\n): WebMCPReturn<T> {\n const getValueRef = useRef(getValue);\n getValueRef.current = getValue;\n\n return useWebMCP<Record<string, never>, T>({\n name,\n description,\n annotations: {\n title: `Context: ${name}`,\n readOnlyHint: true,\n idempotentHint: true,\n destructiveHint: false,\n openWorldHint: false,\n },\n handler: async () => {\n return getValueRef.current();\n },\n formatOutput: (output) => {\n if (typeof output === 'string') {\n return output;\n }\n return JSON.stringify(output, null, 2);\n },\n });\n}\n","import type { Client } from '@modelcontextprotocol/sdk/client/index.js';\nimport type { RequestOptions } from '@modelcontextprotocol/sdk/shared/protocol.js';\nimport type { Transport } from '@modelcontextprotocol/sdk/shared/transport.js';\nimport type {\n Tool as McpTool,\n Resource,\n ServerCapabilities,\n} from '@modelcontextprotocol/sdk/types.js';\nimport {\n ResourceListChangedNotificationSchema,\n ToolListChangedNotificationSchema,\n} from '@modelcontextprotocol/sdk/types.js';\nimport {\n createContext,\n type ReactElement,\n type ReactNode,\n useCallback,\n useContext,\n useEffect,\n useRef,\n useState,\n} from 'react';\n\n/**\n * Context value provided by McpClientProvider.\n *\n * @internal\n */\ninterface McpClientContextValue {\n client: Client;\n tools: McpTool[];\n resources: Resource[];\n isConnected: boolean;\n isLoading: boolean;\n error: Error | null;\n capabilities: ServerCapabilities | null;\n reconnect: () => Promise<void>;\n}\n\nconst McpClientContext = createContext<McpClientContextValue | null>(null);\n\n/**\n * Props for the McpClientProvider component.\n *\n * @public\n */\nexport interface McpClientProviderProps {\n /**\n * React children to render within the provider.\n */\n children: ReactNode;\n\n /**\n * MCP Client instance to use for communication.\n */\n client: Client;\n\n /**\n * Transport instance for the client to connect through.\n */\n transport: Transport;\n\n /**\n * Optional request options for the connection.\n */\n opts?: RequestOptions;\n}\n\n/**\n * Provider component that manages an MCP client connection and exposes\n * tools, resources, and connection state to child components.\n *\n * This provider handles:\n * - Establishing and maintaining the MCP client connection\n * - Fetching available tools and resources from the server\n * - Listening for server notifications about tool/resource changes\n * - Managing connection state and errors\n * - Automatic cleanup on unmount\n *\n * @param props - Component props\n * @returns Provider component wrapping children\n *\n * @public\n *\n * @example\n * Connect to an MCP server via tab transport:\n * ```tsx\n * import { Client } from '@modelcontextprotocol/sdk/client/index.js';\n * import { TabClientTransport } from '@mcp-b/transports';\n * import { McpClientProvider } from '@mcp-b/react-webmcp';\n *\n * const client = new Client(\n * { name: 'my-app', version: '1.0.0' },\n * { capabilities: {} }\n * );\n *\n * const transport = new TabClientTransport('mcp', {\n * clientInstanceId: 'my-app-instance',\n * });\n *\n * function App() {\n * return (\n * <McpClientProvider client={client} transport={transport}>\n * <MyAppContent />\n * </McpClientProvider>\n * );\n * }\n * ```\n *\n * @example\n * Access tools from child components:\n * ```tsx\n * function MyAppContent() {\n * const { tools, isConnected, isLoading } = useMcpClient();\n *\n * if (isLoading) {\n * return <div>Connecting to MCP server...</div>;\n * }\n *\n * if (!isConnected) {\n * return <div>Failed to connect to MCP server</div>;\n * }\n *\n * return (\n * <div>\n * <h2>Available Tools:</h2>\n * <ul>\n * {tools.map(tool => (\n * <li key={tool.name}>{tool.description}</li>\n * ))}\n * </ul>\n * </div>\n * );\n * }\n * ```\n */\nexport function McpClientProvider({\n children,\n client,\n transport,\n opts = {},\n}: McpClientProviderProps): ReactElement {\n const [resources, setResources] = useState<Resource[]>([]);\n const [tools, setTools] = useState<McpTool[]>([]);\n const [isLoading, setIsLoading] = useState<boolean>(false);\n const [error, setError] = useState<Error | null>(null);\n const [isConnected, setIsConnected] = useState<boolean>(false);\n const [capabilities, setCapabilities] = useState<ServerCapabilities | null>(null);\n\n const connectionStateRef = useRef<'disconnected' | 'connecting' | 'connected'>('disconnected');\n\n /**\n * Fetches available resources from the MCP server.\n * Only fetches if the server supports the resources capability.\n */\n const fetchResourcesInternal = useCallback(async () => {\n if (!client) return;\n\n const serverCapabilities = client.getServerCapabilities();\n if (!serverCapabilities?.resources) {\n setResources([]);\n return;\n }\n\n try {\n const response = await client.listResources();\n setResources(response.resources);\n } catch (e) {\n console.error('Error fetching resources:', e);\n throw e;\n }\n }, [client]);\n\n /**\n * Fetches available tools from the MCP server.\n * Only fetches if the server supports the tools capability.\n */\n const fetchToolsInternal = useCallback(async () => {\n if (!client) return;\n\n const serverCapabilities = client.getServerCapabilities();\n if (!serverCapabilities?.tools) {\n setTools([]);\n return;\n }\n\n try {\n const response = await client.listTools();\n setTools(response.tools);\n } catch (e) {\n console.error('Error fetching tools:', e);\n throw e;\n }\n }, [client]);\n\n /**\n * Establishes connection to the MCP server.\n * Safe to call multiple times - will no-op if already connected or connecting.\n */\n const reconnect = useCallback(async () => {\n if (!client || !transport) {\n throw new Error('Client or transport not available');\n }\n\n if (connectionStateRef.current !== 'disconnected') {\n return;\n }\n\n connectionStateRef.current = 'connecting';\n setIsLoading(true);\n setError(null);\n\n try {\n await client.connect(transport, opts);\n const caps = client.getServerCapabilities();\n setIsConnected(true);\n setCapabilities(caps || null);\n connectionStateRef.current = 'connected';\n\n await Promise.all([fetchResourcesInternal(), fetchToolsInternal()]);\n } catch (e) {\n const err = e instanceof Error ? e : new Error(String(e));\n connectionStateRef.current = 'disconnected';\n setError(err);\n throw err;\n } finally {\n setIsLoading(false);\n }\n }, [client, transport, opts, fetchResourcesInternal, fetchToolsInternal]);\n\n useEffect(() => {\n if (!isConnected || !client) {\n return;\n }\n\n const serverCapabilities = client.getServerCapabilities();\n\n const handleResourcesChanged = () => {\n fetchResourcesInternal().catch(console.error);\n };\n\n const handleToolsChanged = () => {\n fetchToolsInternal().catch(console.error);\n };\n\n if (serverCapabilities?.resources?.listChanged) {\n client.setNotificationHandler(ResourceListChangedNotificationSchema, handleResourcesChanged);\n }\n\n if (serverCapabilities?.tools?.listChanged) {\n client.setNotificationHandler(ToolListChangedNotificationSchema, handleToolsChanged);\n }\n\n return () => {\n if (serverCapabilities?.resources?.listChanged) {\n client.removeNotificationHandler('notifications/resources/list_changed');\n }\n\n if (serverCapabilities?.tools?.listChanged) {\n client.removeNotificationHandler('notifications/tools/list_changed');\n }\n };\n }, [client, isConnected, fetchResourcesInternal, fetchToolsInternal]);\n\n useEffect(() => {\n // Initial connection - reconnect() has its own guard to prevent concurrent connections\n reconnect().catch((err) => {\n console.error('Failed to connect MCP client:', err);\n });\n\n // Cleanup: mark as disconnected so next mount will reconnect\n return () => {\n connectionStateRef.current = 'disconnected';\n setIsConnected(false);\n };\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [client, transport]);\n\n return (\n <McpClientContext.Provider\n value={{\n client,\n tools,\n resources,\n isConnected,\n isLoading,\n error,\n capabilities,\n reconnect,\n }}\n >\n {children}\n </McpClientContext.Provider>\n );\n}\n\n/**\n * Hook to access the MCP client context.\n * Must be used within an {@link McpClientProvider}.\n *\n * @returns The MCP client context including client instance, tools, resources, and connection state\n * @throws Error if used outside of McpClientProvider\n *\n * @public\n *\n * @example\n * ```tsx\n * function ToolsList() {\n * const { tools, isConnected, error, reconnect } = useMcpClient();\n *\n * if (error) {\n * return (\n * <div>\n * Error: {error.message}\n * <button onClick={reconnect}>Retry</button>\n * </div>\n * );\n * }\n *\n * if (!isConnected) {\n * return <div>Not connected</div>;\n * }\n *\n * return (\n * <ul>\n * {tools.map(tool => (\n * <li key={tool.name}>{tool.description}</li>\n * ))}\n * </ul>\n * );\n * }\n * ```\n */\nexport function useMcpClient() {\n const context = useContext(McpClientContext);\n if (!context) {\n throw new Error('useMcpClient must be used within an McpClientProvider');\n }\n return context;\n}\n"],"mappings":"kTAcA,SAAS,EAAgB,EAIvB,CACA,IAAMA,EAAsC,EAAE,CACxCC,EAAqB,EAAE,CAE7B,IAAK,GAAM,CAAC,EAAK,KAAY,OAAO,QAAQ,EAAO,CAAE,CACnD,IAAM,EAAe,EAAqC,aAAe,IAAA,GAErE,EAAO,SACP,aAAmB,EAAE,UACvB,EAAO,SACE,aAAmB,EAAE,WAC9B,EAAO,UACE,aAAmB,EAAE,SAC9B,EAAO,QACE,aAAmB,EAAE,YAC9B,EAAO,UAGT,EAAW,GAAO,CAChB,OACA,GAAI,GAAe,CAAE,cAAa,CACnC,CAEI,EAAQ,YAAY,EACvB,EAAS,KAAK,EAAI,CAItB,MAAO,CACL,KAAM,SACN,aACA,GAAI,EAAS,OAAS,GAAK,CAAE,WAAU,CACxC,CAUH,SAAS,EAAoB,EAAyB,CAIpD,OAHI,OAAO,GAAW,SACb,EAEF,KAAK,UAAU,EAAQ,KAAM,EAAE,CAwExC,SAAgB,EAGd,EAAoE,CACpE,GAAM,CACJ,OACA,cACA,cACA,eACA,cACA,UACA,eAAe,EACf,YACA,WACE,EAEE,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],"sources":["../src/useWebMCP.ts","../src/useWebMCPContext.ts","../src/useElicitationHandler.ts","../src/useSamplingHandler.ts","../src/client/McpClientProvider.tsx"],"sourcesContent":["import type { InputSchema } from '@mcp-b/global';\nimport type { CallToolResult } from '@modelcontextprotocol/sdk/types.js';\nimport { useCallback, useEffect, useRef, useState } from 'react';\nimport { z } from 'zod';\nimport type { ToolExecutionState, WebMCPConfig, WebMCPReturn } from './types.js';\n\n/**\n * Converts a Zod schema object to JSON Schema format for MCP.\n * Handles basic type inference for common Zod types.\n *\n * @internal\n * @param schema - Record of Zod type definitions\n * @returns JSON Schema object with type, properties, and required fields\n */\nfunction zodToJsonSchema(schema: Record<string, z.ZodTypeAny>): {\n type: string;\n properties?: Record<string, unknown>;\n required?: string[];\n} {\n const properties: Record<string, unknown> = {};\n const required: string[] = [];\n\n for (const [key, zodType] of Object.entries(schema)) {\n const description = (zodType as { description?: string }).description || undefined;\n\n let type = 'string';\n if (zodType instanceof z.ZodNumber) {\n type = 'number';\n } else if (zodType instanceof z.ZodBoolean) {\n type = 'boolean';\n } else if (zodType instanceof z.ZodArray) {\n type = 'array';\n } else if (zodType instanceof z.ZodObject) {\n type = 'object';\n }\n\n properties[key] = {\n type,\n ...(description && { description }),\n };\n\n if (!zodType.isOptional()) {\n required.push(key);\n }\n }\n\n return {\n type: 'object',\n properties,\n ...(required.length > 0 && { required }),\n };\n}\n\n/**\n * Default output formatter that converts values to formatted JSON strings.\n *\n * @internal\n * @param output - The value to format\n * @returns Formatted string representation\n */\nfunction defaultFormatOutput(output: unknown): string {\n if (typeof output === 'string') {\n return output;\n }\n return JSON.stringify(output, null, 2);\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 * - Validates input using Zod schemas\n * - Handles tool execution and lifecycle callbacks\n * - Automatically unregisters on component unmount\n *\n * @template TInputSchema - Zod schema object defining input parameter types\n * @template TOutput - Type of data returned by the handler function\n *\n * @param config - Configuration object for the tool\n * @returns Object containing execution state and control methods\n *\n * @public\n *\n * @example\n * Basic tool registration:\n * ```tsx\n * function PostActions() {\n * const likeTool = useWebMCP({\n * name: 'posts_like',\n * description: 'Like a post by ID',\n * inputSchema: {\n * postId: z.string().uuid().describe('The ID of the post to like'),\n * },\n * handler: async ({ postId }) => {\n * await api.posts.like(postId);\n * return { success: true, postId };\n * },\n * });\n *\n * if (likeTool.state.isExecuting) {\n * return <Spinner />;\n * }\n *\n * return <div>Post actions ready</div>;\n * }\n * ```\n *\n * @example\n * Tool with annotations and callbacks:\n * ```tsx\n * const deleteTool = useWebMCP({\n * name: 'posts_delete',\n * description: 'Delete a post permanently',\n * inputSchema: {\n * postId: z.string().uuid(),\n * },\n * annotations: {\n * destructiveHint: true,\n * idempotentHint: false,\n * },\n * handler: async ({ postId }) => {\n * await api.posts.delete(postId);\n * return { deleted: true };\n * },\n * onSuccess: () => {\n * navigate('/posts');\n * toast.success('Post deleted');\n * },\n * onError: (error) => {\n * toast.error(`Failed to delete: ${error.message}`);\n * },\n * });\n * ```\n */\nexport function useWebMCP<\n TInputSchema extends Record<string, z.ZodTypeAny> = Record<string, never>,\n TOutput = string,\n>(config: WebMCPConfig<TInputSchema, TOutput>): WebMCPReturn<TOutput> {\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\n useEffect(() => {\n handlerRef.current = handler;\n }, [handler]);\n\n useEffect(() => {\n onSuccessRef.current = onSuccess;\n }, [onSuccess]);\n\n useEffect(() => {\n onErrorRef.current = onError;\n }, [onError]);\n\n useEffect(() => {\n formatOutputRef.current = formatOutput;\n }, [formatOutput]);\n\n const validator = inputSchema ? z.object(inputSchema) : null;\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(\n async (input: unknown): Promise<TOutput> => {\n setState((prev) => ({\n ...prev,\n isExecuting: true,\n error: null,\n }));\n\n try {\n const validatedInput = validator ? validator.parse(input) : input;\n const result = await handlerRef.current(validatedInput as never);\n\n setState((prev) => ({\n isExecuting: false,\n lastResult: result,\n error: null,\n executionCount: prev.executionCount + 1,\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 setState((prev) => ({\n ...prev,\n isExecuting: false,\n error: err,\n }));\n\n if (onErrorRef.current) {\n onErrorRef.current(err, input);\n }\n\n throw err;\n }\n },\n [validator]\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 const inputJsonSchema = inputSchema ? zodToJsonSchema(inputSchema) : undefined;\n const outputJsonSchema = outputSchema ? zodToJsonSchema(outputSchema) : undefined;\n\n const mcpHandler = async (input: unknown, _extra: unknown): Promise<CallToolResult> => {\n try {\n const result = await execute(input);\n const formattedOutput = formatOutputRef.current(result);\n\n return {\n content: [\n {\n type: 'text',\n text: formattedOutput,\n },\n ],\n };\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 fallbackInputSchema: InputSchema = {\n type: 'object',\n properties: {},\n };\n\n const registration = window.navigator.modelContext.registerTool({\n name,\n description,\n inputSchema: (inputJsonSchema || fallbackInputSchema) as InputSchema,\n ...(outputJsonSchema && { outputSchema: outputJsonSchema as InputSchema }),\n ...(annotations && { annotations }),\n execute: async (args: Record<string, unknown>) => {\n const result = await mcpHandler(args, {});\n return result;\n },\n });\n\n console.log(`[useWebMCP] Registered tool: ${name}`);\n\n // Expose registered tools on window for testing\n if (typeof window !== 'undefined') {\n const tools = window.navigator.modelContext.listTools();\n const w = window as unknown as Window & { mcpTools: string[] };\n w.mcpTools = tools.map((t) => t.name);\n }\n\n return () => {\n if (registration) {\n registration.unregister();\n console.log(`[useWebMCP] Unregistered tool: ${name}`);\n\n // Update window.mcpTools after unregistration\n if (typeof window !== 'undefined' && window.navigator?.modelContext) {\n const tools = window.navigator.modelContext.listTools();\n const w = window as unknown as Window & { mcpTools: string[] };\n w.mcpTools = tools.map((t) => t.name);\n }\n }\n };\n }, [name, description, inputSchema, outputSchema, annotations, execute]);\n\n return {\n state,\n execute,\n reset,\n };\n}\n","import { useRef } from 'react';\nimport type { WebMCPReturn } from './types.js';\nimport { useWebMCP } from './useWebMCP.js';\n\n/**\n * Convenience hook for exposing read-only context data to AI assistants.\n *\n * This is a simplified wrapper around {@link useWebMCP} specifically designed for\n * context tools that expose data without performing actions. The hook automatically\n * configures appropriate annotations (read-only, idempotent) and handles value\n * serialization.\n *\n * @template T - The type of context data to expose\n *\n * @param name - Unique identifier for the context tool (e.g., 'context_current_post')\n * @param description - Human-readable description of the context for AI assistants\n * @param getValue - Function that returns the current context value\n * @returns Tool execution state and control methods\n *\n * @public\n *\n * @example\n * Expose current post context:\n * ```tsx\n * function PostDetailPage() {\n * const { postId } = useParams();\n * const { data: post } = useQuery(['post', postId], () => fetchPost(postId));\n *\n * useWebMCPContext(\n * 'context_current_post',\n * 'Get the currently viewed post ID and metadata',\n * () => ({\n * postId,\n * title: post?.title,\n * author: post?.author,\n * tags: post?.tags,\n * createdAt: post?.createdAt,\n * })\n * );\n *\n * return <PostContent post={post} />;\n * }\n * ```\n *\n * @example\n * Expose user session context:\n * ```tsx\n * function AppRoot() {\n * const { user, isAuthenticated } = useAuth();\n *\n * useWebMCPContext(\n * 'context_user_session',\n * 'Get the current user session information',\n * () => ({\n * isAuthenticated,\n * userId: user?.id,\n * email: user?.email,\n * permissions: user?.permissions,\n * })\n * );\n *\n * return <App />;\n * }\n * ```\n */\nexport function useWebMCPContext<T>(\n name: string,\n description: string,\n getValue: () => T\n): WebMCPReturn<T> {\n const getValueRef = useRef(getValue);\n getValueRef.current = getValue;\n\n return useWebMCP<Record<string, never>, T>({\n name,\n description,\n annotations: {\n title: `Context: ${name}`,\n readOnlyHint: true,\n idempotentHint: true,\n destructiveHint: false,\n openWorldHint: false,\n },\n handler: async () => {\n return getValueRef.current();\n },\n formatOutput: (output) => {\n if (typeof output === 'string') {\n return output;\n }\n return JSON.stringify(output, null, 2);\n },\n });\n}\n","import type { ElicitationParams, ElicitationResult } from '@mcp-b/global';\nimport { useCallback, useState } from 'react';\n\n/**\n * State for elicitation requests, tracking the current request and results.\n */\nexport interface ElicitationState {\n /** Whether an elicitation request is currently in progress */\n isLoading: boolean;\n /** The last elicitation result received */\n result: ElicitationResult | null;\n /** Any error that occurred during the last request */\n error: Error | null;\n /** Total number of requests made */\n requestCount: number;\n}\n\n/**\n * Configuration options for the useElicitation hook.\n */\nexport interface UseElicitationConfig {\n /**\n * Optional callback invoked when an elicitation request completes successfully.\n */\n onSuccess?: (result: ElicitationResult) => void;\n\n /**\n * Optional callback invoked when an elicitation request fails.\n */\n onError?: (error: Error) => void;\n}\n\n/**\n * Return value from the useElicitation hook.\n */\nexport interface UseElicitationReturn {\n /** Current state of elicitation */\n state: ElicitationState;\n /** Function to request user input from the connected client */\n elicitInput: (params: ElicitationParams) => Promise<ElicitationResult>;\n /** Reset the state */\n reset: () => void;\n}\n\n/**\n * React hook for requesting user input from the connected MCP client.\n *\n * Elicitation allows the server (webpage) to request user input from the\n * connected client. This is useful when the page needs additional information\n * from the user, such as API keys, configuration options, or confirmations.\n *\n * There are two modes:\n * 1. **Form mode**: For non-sensitive data collection using a schema-driven form.\n * 2. **URL mode**: For sensitive data collection via a web URL (API keys, OAuth, etc.).\n *\n * @param config - Optional configuration including callbacks\n * @returns Object containing state and the elicitInput function\n *\n * @example Form elicitation:\n * ```tsx\n * function ConfigForm() {\n * const { state, elicitInput } = useElicitation({\n * onSuccess: (result) => console.log('Got input:', result),\n * onError: (error) => console.error('Elicitation failed:', error),\n * });\n *\n * const handleConfigure = async () => {\n * const result = await elicitInput({\n * message: 'Please provide your configuration',\n * requestedSchema: {\n * type: 'object',\n * properties: {\n * apiKey: { type: 'string', title: 'API Key', description: 'Your API key' },\n * model: { type: 'string', enum: ['gpt-4', 'gpt-3.5'], title: 'Model' }\n * },\n * required: ['apiKey']\n * }\n * });\n *\n * if (result.action === 'accept') {\n * console.log('Config:', result.content);\n * }\n * };\n *\n * return (\n * <button onClick={handleConfigure} disabled={state.isLoading}>\n * Configure\n * </button>\n * );\n * }\n * ```\n *\n * @example URL elicitation (for sensitive data):\n * ```tsx\n * const { elicitInput } = useElicitation();\n *\n * const handleOAuth = async () => {\n * const result = await elicitInput({\n * mode: 'url',\n * message: 'Please authenticate with GitHub',\n * elicitationId: 'github-oauth-123',\n * url: 'https://github.com/login/oauth/authorize?client_id=...'\n * });\n *\n * if (result.action === 'accept') {\n * console.log('OAuth completed');\n * }\n * };\n * ```\n */\nexport function useElicitation(config: UseElicitationConfig = {}): UseElicitationReturn {\n const { onSuccess, onError } = config;\n\n const [state, setState] = useState<ElicitationState>({\n isLoading: false,\n result: null,\n error: null,\n requestCount: 0,\n });\n\n const reset = useCallback(() => {\n setState({\n isLoading: false,\n result: null,\n error: null,\n requestCount: 0,\n });\n }, []);\n\n const elicitInput = useCallback(\n async (params: ElicitationParams): Promise<ElicitationResult> => {\n if (typeof window === 'undefined' || !window.navigator?.modelContext) {\n throw new Error('navigator.modelContext is not available');\n }\n\n setState((prev) => ({\n ...prev,\n isLoading: true,\n error: null,\n }));\n\n try {\n const result = await window.navigator.modelContext.elicitInput(params);\n\n setState((prev) => ({\n isLoading: false,\n result,\n error: null,\n requestCount: prev.requestCount + 1,\n }));\n\n onSuccess?.(result);\n return result;\n } catch (err) {\n const error = err instanceof Error ? err : new Error(String(err));\n\n setState((prev) => ({\n ...prev,\n isLoading: false,\n error,\n }));\n\n onError?.(error);\n throw error;\n }\n },\n [onSuccess, onError]\n );\n\n return {\n state,\n elicitInput,\n reset,\n };\n}\n\n// Also export with the old name for backwards compatibility during migration\nexport { useElicitation as useElicitationHandler };\nexport type { ElicitationState as ElicitationHandlerState };\nexport type { UseElicitationConfig as UseElicitationHandlerConfig };\nexport type { UseElicitationReturn as UseElicitationHandlerReturn };\n","import type { SamplingRequestParams, SamplingResult } from '@mcp-b/global';\nimport { useCallback, useState } from 'react';\n\n/**\n * State for sampling requests, tracking the current request and results.\n */\nexport interface SamplingState {\n /** Whether a sampling request is currently in progress */\n isLoading: boolean;\n /** The last sampling result received */\n result: SamplingResult | null;\n /** Any error that occurred during the last request */\n error: Error | null;\n /** Total number of requests made */\n requestCount: number;\n}\n\n/**\n * Configuration options for the useSampling hook.\n */\nexport interface UseSamplingConfig {\n /**\n * Optional callback invoked when a sampling request completes successfully.\n */\n onSuccess?: (result: SamplingResult) => void;\n\n /**\n * Optional callback invoked when a sampling request fails.\n */\n onError?: (error: Error) => void;\n}\n\n/**\n * Return value from the useSampling hook.\n */\nexport interface UseSamplingReturn {\n /** Current state of sampling */\n state: SamplingState;\n /** Function to request LLM completion from the connected client */\n createMessage: (params: SamplingRequestParams) => Promise<SamplingResult>;\n /** Reset the state */\n reset: () => void;\n}\n\n/**\n * React hook for requesting LLM completions from the connected MCP client.\n *\n * Sampling allows the server (webpage) to request LLM completions from the\n * connected client. This is useful when the page needs AI capabilities like\n * summarization, generation, or analysis.\n *\n * @param config - Optional configuration including callbacks\n * @returns Object containing state and the createMessage function\n *\n * @example Basic usage:\n * ```tsx\n * function AIAssistant() {\n * const { state, createMessage } = useSampling({\n * onSuccess: (result) => console.log('Got response:', result),\n * onError: (error) => console.error('Sampling failed:', error),\n * });\n *\n * const handleAsk = async () => {\n * const result = await createMessage({\n * messages: [\n * { role: 'user', content: { type: 'text', text: 'What is 2+2?' } }\n * ],\n * maxTokens: 100,\n * });\n * console.log(result.content);\n * };\n *\n * return (\n * <div>\n * <button onClick={handleAsk} disabled={state.isLoading}>\n * Ask AI\n * </button>\n * {state.result && <p>{JSON.stringify(state.result.content)}</p>}\n * </div>\n * );\n * }\n * ```\n */\nexport function useSampling(config: UseSamplingConfig = {}): UseSamplingReturn {\n const { onSuccess, onError } = config;\n\n const [state, setState] = useState<SamplingState>({\n isLoading: false,\n result: null,\n error: null,\n requestCount: 0,\n });\n\n const reset = useCallback(() => {\n setState({\n isLoading: false,\n result: null,\n error: null,\n requestCount: 0,\n });\n }, []);\n\n const createMessage = useCallback(\n async (params: SamplingRequestParams): Promise<SamplingResult> => {\n if (typeof window === 'undefined' || !window.navigator?.modelContext) {\n throw new Error('navigator.modelContext is not available');\n }\n\n setState((prev) => ({\n ...prev,\n isLoading: true,\n error: null,\n }));\n\n try {\n const result = await window.navigator.modelContext.createMessage(params);\n\n setState((prev) => ({\n isLoading: false,\n result,\n error: null,\n requestCount: prev.requestCount + 1,\n }));\n\n onSuccess?.(result);\n return result;\n } catch (err) {\n const error = err instanceof Error ? err : new Error(String(err));\n\n setState((prev) => ({\n ...prev,\n isLoading: false,\n error,\n }));\n\n onError?.(error);\n throw error;\n }\n },\n [onSuccess, onError]\n );\n\n return {\n state,\n createMessage,\n reset,\n };\n}\n\n// Also export with the old name for backwards compatibility during migration\nexport { useSampling as useSamplingHandler };\nexport type { SamplingState as SamplingHandlerState };\nexport type { UseSamplingConfig as UseSamplingHandlerConfig };\nexport type { UseSamplingReturn as UseSamplingHandlerReturn };\n","import type { Client } from '@modelcontextprotocol/sdk/client/index.js';\nimport type { RequestOptions } from '@modelcontextprotocol/sdk/shared/protocol.js';\nimport type { Transport } from '@modelcontextprotocol/sdk/shared/transport.js';\nimport type {\n Tool as McpTool,\n Resource,\n ServerCapabilities,\n} from '@modelcontextprotocol/sdk/types.js';\nimport {\n ResourceListChangedNotificationSchema,\n ToolListChangedNotificationSchema,\n} from '@modelcontextprotocol/sdk/types.js';\nimport {\n createContext,\n type ReactElement,\n type ReactNode,\n useCallback,\n useContext,\n useEffect,\n useRef,\n useState,\n} from 'react';\n\n/**\n * Context value provided by McpClientProvider.\n *\n * @internal\n */\ninterface McpClientContextValue {\n client: Client;\n tools: McpTool[];\n resources: Resource[];\n isConnected: boolean;\n isLoading: boolean;\n error: Error | null;\n capabilities: ServerCapabilities | null;\n reconnect: () => Promise<void>;\n}\n\nconst McpClientContext = createContext<McpClientContextValue | null>(null);\n\n/**\n * Props for the McpClientProvider component.\n *\n * @public\n */\nexport interface McpClientProviderProps {\n /**\n * React children to render within the provider.\n */\n children: ReactNode;\n\n /**\n * MCP Client instance to use for communication.\n */\n client: Client;\n\n /**\n * Transport instance for the client to connect through.\n */\n transport: Transport;\n\n /**\n * Optional request options for the connection.\n */\n opts?: RequestOptions;\n}\n\n/**\n * Provider component that manages an MCP client connection and exposes\n * tools, resources, and connection state to child components.\n *\n * This provider handles:\n * - Establishing and maintaining the MCP client connection\n * - Fetching available tools and resources from the server\n * - Listening for server notifications about tool/resource changes\n * - Managing connection state and errors\n * - Automatic cleanup on unmount\n *\n * @param props - Component props\n * @returns Provider component wrapping children\n *\n * @public\n *\n * @example\n * Connect to an MCP server via tab transport:\n * ```tsx\n * import { Client } from '@modelcontextprotocol/sdk/client/index.js';\n * import { TabClientTransport } from '@mcp-b/transports';\n * import { McpClientProvider } from '@mcp-b/react-webmcp';\n *\n * const client = new Client(\n * { name: 'my-app', version: '1.0.0' },\n * { capabilities: {} }\n * );\n *\n * const transport = new TabClientTransport('mcp', {\n * clientInstanceId: 'my-app-instance',\n * });\n *\n * function App() {\n * return (\n * <McpClientProvider client={client} transport={transport}>\n * <MyAppContent />\n * </McpClientProvider>\n * );\n * }\n * ```\n *\n * @example\n * Access tools from child components:\n * ```tsx\n * function MyAppContent() {\n * const { tools, isConnected, isLoading } = useMcpClient();\n *\n * if (isLoading) {\n * return <div>Connecting to MCP server...</div>;\n * }\n *\n * if (!isConnected) {\n * return <div>Failed to connect to MCP server</div>;\n * }\n *\n * return (\n * <div>\n * <h2>Available Tools:</h2>\n * <ul>\n * {tools.map(tool => (\n * <li key={tool.name}>{tool.description}</li>\n * ))}\n * </ul>\n * </div>\n * );\n * }\n * ```\n */\nexport function McpClientProvider({\n children,\n client,\n transport,\n opts = {},\n}: McpClientProviderProps): ReactElement {\n const [resources, setResources] = useState<Resource[]>([]);\n const [tools, setTools] = useState<McpTool[]>([]);\n const [isLoading, setIsLoading] = useState<boolean>(false);\n const [error, setError] = useState<Error | null>(null);\n const [isConnected, setIsConnected] = useState<boolean>(false);\n const [capabilities, setCapabilities] = useState<ServerCapabilities | null>(null);\n\n const connectionStateRef = useRef<'disconnected' | 'connecting' | 'connected'>('disconnected');\n\n /**\n * Fetches available resources from the MCP server.\n * Only fetches if the server supports the resources capability.\n */\n const fetchResourcesInternal = useCallback(async () => {\n if (!client) return;\n\n const serverCapabilities = client.getServerCapabilities();\n if (!serverCapabilities?.resources) {\n setResources([]);\n return;\n }\n\n try {\n const response = await client.listResources();\n setResources(response.resources);\n } catch (e) {\n console.error('Error fetching resources:', e);\n throw e;\n }\n }, [client]);\n\n /**\n * Fetches available tools from the MCP server.\n * Only fetches if the server supports the tools capability.\n */\n const fetchToolsInternal = useCallback(async () => {\n if (!client) return;\n\n const serverCapabilities = client.getServerCapabilities();\n if (!serverCapabilities?.tools) {\n setTools([]);\n return;\n }\n\n try {\n const response = await client.listTools();\n setTools(response.tools);\n } catch (e) {\n console.error('Error fetching tools:', e);\n throw e;\n }\n }, [client]);\n\n /**\n * Establishes connection to the MCP server.\n * Safe to call multiple times - will no-op if already connected or connecting.\n */\n const reconnect = useCallback(async () => {\n if (!client || !transport) {\n throw new Error('Client or transport not available');\n }\n\n if (connectionStateRef.current !== 'disconnected') {\n return;\n }\n\n connectionStateRef.current = 'connecting';\n setIsLoading(true);\n setError(null);\n\n try {\n await client.connect(transport, opts);\n const caps = client.getServerCapabilities();\n setIsConnected(true);\n setCapabilities(caps || null);\n connectionStateRef.current = 'connected';\n\n await Promise.all([fetchResourcesInternal(), fetchToolsInternal()]);\n } catch (e) {\n const err = e instanceof Error ? e : new Error(String(e));\n connectionStateRef.current = 'disconnected';\n setError(err);\n throw err;\n } finally {\n setIsLoading(false);\n }\n }, [client, transport, opts, fetchResourcesInternal, fetchToolsInternal]);\n\n useEffect(() => {\n if (!isConnected || !client) {\n return;\n }\n\n const serverCapabilities = client.getServerCapabilities();\n\n const handleResourcesChanged = () => {\n fetchResourcesInternal().catch(console.error);\n };\n\n const handleToolsChanged = () => {\n fetchToolsInternal().catch(console.error);\n };\n\n if (serverCapabilities?.resources?.listChanged) {\n client.setNotificationHandler(ResourceListChangedNotificationSchema, handleResourcesChanged);\n }\n\n if (serverCapabilities?.tools?.listChanged) {\n client.setNotificationHandler(ToolListChangedNotificationSchema, handleToolsChanged);\n }\n\n return () => {\n if (serverCapabilities?.resources?.listChanged) {\n client.removeNotificationHandler('notifications/resources/list_changed');\n }\n\n if (serverCapabilities?.tools?.listChanged) {\n client.removeNotificationHandler('notifications/tools/list_changed');\n }\n };\n }, [client, isConnected, fetchResourcesInternal, fetchToolsInternal]);\n\n useEffect(() => {\n // Initial connection - reconnect() has its own guard to prevent concurrent connections\n reconnect().catch((err) => {\n console.error('Failed to connect MCP client:', err);\n });\n\n // Cleanup: mark as disconnected so next mount will reconnect\n return () => {\n connectionStateRef.current = 'disconnected';\n setIsConnected(false);\n };\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [client, transport]);\n\n return (\n <McpClientContext.Provider\n value={{\n client,\n tools,\n resources,\n isConnected,\n isLoading,\n error,\n capabilities,\n reconnect,\n }}\n >\n {children}\n </McpClientContext.Provider>\n );\n}\n\n/**\n * Hook to access the MCP client context.\n * Must be used within an {@link McpClientProvider}.\n *\n * @returns The MCP client context including client instance, tools, resources, and connection state\n * @throws Error if used outside of McpClientProvider\n *\n * @public\n *\n * @example\n * ```tsx\n * function ToolsList() {\n * const { tools, isConnected, error, reconnect } = useMcpClient();\n *\n * if (error) {\n * return (\n * <div>\n * Error: {error.message}\n * <button onClick={reconnect}>Retry</button>\n * </div>\n * );\n * }\n *\n * if (!isConnected) {\n * return <div>Not connected</div>;\n * }\n *\n * return (\n * <ul>\n * {tools.map(tool => (\n * <li key={tool.name}>{tool.description}</li>\n * ))}\n * </ul>\n * );\n * }\n * ```\n */\nexport function useMcpClient() {\n const context = useContext(McpClientContext);\n if (!context) {\n throw new Error('useMcpClient must be used within an McpClientProvider');\n }\n return context;\n}\n"],"mappings":"kTAcA,SAAS,EAAgB,EAIvB,CACA,IAAMA,EAAsC,EAAE,CACxCC,EAAqB,EAAE,CAE7B,IAAK,GAAM,CAAC,EAAK,KAAY,OAAO,QAAQ,EAAO,CAAE,CACnD,IAAM,EAAe,EAAqC,aAAe,IAAA,GAErE,EAAO,SACP,aAAmB,EAAE,UACvB,EAAO,SACE,aAAmB,EAAE,WAC9B,EAAO,UACE,aAAmB,EAAE,SAC9B,EAAO,QACE,aAAmB,EAAE,YAC9B,EAAO,UAGT,EAAW,GAAO,CAChB,OACA,GAAI,GAAe,CAAE,cAAa,CACnC,CAEI,EAAQ,YAAY,EACvB,EAAS,KAAK,EAAI,CAItB,MAAO,CACL,KAAM,SACN,aACA,GAAI,EAAS,OAAS,GAAK,CAAE,WAAU,CACxC,CAUH,SAAS,EAAoB,EAAyB,CAIpD,OAHI,OAAO,GAAW,SACb,EAEF,KAAK,UAAU,EAAQ,KAAM,EAAE,CAwExC,SAAgB,EAGd,EAAoE,CACpE,GAAM,CACJ,OACA,cACA,cACA,eACA,cACA,UACA,eAAe,EACf,YACA,WACE,EA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,EAAa,EAAwB,EAAmB,CAAC,CAErE,OAEE,GAAW,CAAC,MAAO,GAAQ,CACzB,QAAQ,MAAM,gCAAiC,EAAI,EACnD,KAGW,CACX,EAAmB,QAAU,eAC7B,EAAe,GAAM,GAGtB,CAAC,EAAQ,EAAU,CAAC,CAGrB,EAAC,EAAiB,SAAA,CAChB,MAAO,CACL,SACA,QACA,YACA,cACA,YACA,QACA,eACA,YACD,CAEA,YACyB,CAyChC,SAAgB,GAAe,CAC7B,IAAM,EAAU,EAAW,EAAiB,CAC5C,GAAI,CAAC,EACH,MAAU,MAAM,wDAAwD,CAE1E,OAAO"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mcp-b/react-webmcp",
3
- "version": "0.1.4",
3
+ "version": "0.1.6-beta.0",
4
4
  "description": "React hooks for Model Context Protocol - register tools via navigator.modelContext and consume tools from MCP servers",
5
5
  "keywords": [
6
6
  "mcp",
@@ -38,9 +38,9 @@
38
38
  ],
39
39
  "dependencies": {
40
40
  "@modelcontextprotocol/sdk": "1.15.0",
41
- "@mcp-b/global": "1.1.1",
42
- "@mcp-b/webmcp-ts-sdk": "1.0.1",
43
- "@mcp-b/transports": "1.1.1"
41
+ "@mcp-b/global": "1.1.3-beta.0",
42
+ "@mcp-b/transports": "1.1.2-beta.0",
43
+ "@mcp-b/webmcp-ts-sdk": "1.0.2-beta.0"
44
44
  },
45
45
  "devDependencies": {
46
46
  "@types/node": "22.17.2",