1!function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{};e._posthogReleaseId=e._posthogReleaseId||"01a0a586-0c81-0000-f937-3ebdf34f6c62";var n=(new e.Error).stack;n&&(e._posthogChunkIds=e._posthogChunkIds||{},e._posthogChunkIds[n]="db97438d-9145-57c5-be8e-30fde126fbfa")}catch(e){}}();(globalThis.TURBOPACK||(globalThis.TURBOPACK=[])).push(["object"==typeof document?document.currentScript:void 0,566038,e=>{"use strict";var t,r,i,n,o,s,a,l,c,u=e.i(433139),d=e.i(178610),h=e.i(718024),p=e.i(613952),f=e.i(363501);e.i(964812);var m=e.i(85573),g=e.i(699461),g=g,b=g;e.i(146980);var v=e.i(887224),y=e.i(330288),w=e.i(817422),C=e.i(342146),_=e.i(958176),R=e.i(518553),S=e.i(921156),k=e.i(585549),x=e.i(884104),E=e.i(101116),z=e.i(109086);class A{_eventSlots=new Map;setHandler(e,t){let r=this._ensureEventSlot(e);r.onHandler&&t&&console.warn(`[MCP Apps] on${String(e)} handler replaced. Use addEventListener("${String(e)}", â¦) to add multiple listeners without replacing.`),r.onHandler=t}getHandler(e){return this._eventSlots.get(e)?.onHandler}addEventListener(e,t){this._ensureEventSlot(e).listeners.push(t)}removeEventListener(e,t){let r=this._eventSlots.get(e);if(!r)return;let i=r.listeners.indexOf(t);-1!==i&&r.listeners.splice(i,1)}dispatch(e,t){let r=this._eventSlots.get(e);if(r)for(let e of(r.onHandler?.(t),[...r.listeners]))e(t)}_ensureEventSlot(e){let t=this._eventSlots.get(e);return t||(t={listeners:[]},this._eventSlots.set(e,t)),t}}class P{_methods=new Set;claim(e,t){if(this._methods.has(e))throw Error(`Handler for "${e}" already registered (via ${t}). Use addEventListener() to attach multiple listeners, or the on* setter for replace semantics.`);this._methods.add(e)}replace(e){this._methods.add(e)}release(e){this._methods.delete(e)}has(e){return this._methods.has(e)}}var U=new Set;function T(e,t){let[r,i]=t,n=r?.shape;if("string"!=typeof n?.method?.value)return;let o=n.method.value,s="request"===e?"setRequestHandler":"setNotificationHandler";return U.has(s)||(U.add(s),console.warn(`[ext-apps] ${s}(Schema, handler) is deprecated; use ${s}("${o}", { params: Schema.shape.params }, handler).`)),[o,{params:n.params},"request"===e?(e,t)=>{var r;return i({method:o,params:e},{signal:(r=t).mcpReq.signal,requestId:r.mcpReq.id,sessionId:r.sessionId,_meta:r.mcpReq._meta,sendRequest:r.mcpReq.send,sendNotification:r.mcpReq.notify,authInfo:r.http?.authInfo})}:e=>i({method:o,params:e})]}var M="2026-01-26",I=w.z.union([w.z.literal("light"),w.z.literal("dark")]).describe("Color theme preference for the host environment."),q=w.z.union([w.z.literal("inline"),w.z.literal("fullscreen"),w.z.literal("pip")]).describe("Display mode for UI presentation."),L=w.z.union([w.z.literal("--color-background-primary"),w.z.literal("--color-background-secondary"),w.z.literal("--color-background-tertiary"),w.z.literal("--color-background-inverse"),w.z.literal("--color-background-ghost"),w.z.literal("--color-background-info"),w.z.literal("--color-background-danger"),w.z.literal("--color-background-success"),w.z.literal("--color-background-warning"),w.z.literal("--color-background-disabled"),w.z.literal("--color-text-primary"),w.z.literal("--color-text-secondary"),w.z.literal("--color-text-tertiary"),w.z.literal("--color-text-inverse"),w.z.literal("--color-text-ghost"),w.z.literal("--color-text-info"),w.z.literal("--color-text-danger"),w.z.literal("--color-text-success"),w.z.literal("--color-text-warning"),w.z.literal("--color-text-disabled"),w.z.literal("--color-border-primary"),w.z.literal("--color-border-secondary"),w.z.literal("--color-border-tertiary"),w.z.literal("--color-border-inverse"),w.z.literal("--color-border-ghost"),w.z.literal("--color-border-info"),w.z.literal("--color-border-danger"),w.z.literal("--color-border-success"),w.z.literal("--color-border-warning"),w.z.literal("--color-border-disabled"),w.z.literal("--color-ring-primary"),w.z.literal("--color-ring-secondary"),w.z.literal("--color-ring-inverse"),w.z.literal("--color-ring-info"),w.z.literal("--color-ring-danger"),w.z.literal("--color-ring-success"),w.z.literal("--color-ring-warning"),w.z.literal("--font-sans"),w.z.literal("--font-mono"),w.z.literal("--font-weight-normal"),w.z.literal("--font-weight-medium"),w.z.literal("--font-weight-semibold"),w.z.literal("--font-weight-bold"),w.z.literal("--font-text-xs-size"),w.z.literal("--font-text-sm-size"),w.z.literal("--font-text-md-size"),w.z.literal("--font-text-lg-size"),w.z.literal("--font-heading-xs-size"),w.z.literal("--font-heading-sm-size"),w.z.literal("--font-heading-md-size"),w.z.literal("--font-heading-lg-size"),w.z.literal("--font-heading-xl-size"),w.z.literal("--font-heading-2xl-size"),w.z.literal("--font-heading-3xl-size"),w.z.literal("--font-text-xs-line-height"),w.z.literal("--font-text-sm-line-height"),w.z.literal("--font-text-md-line-height"),w.z.literal("--font-text-lg-line-height"),w.z.literal("--font-heading-xs-line-height"),w.z.literal("--font-heading-sm-line-height"),w.z.literal("--font-heading-md-line-height"),w.z.literal("--font-heading-lg-line-height"),w.z.literal("--font-heading-xl-line-height"),w.z.literal("--font-heading-2xl-line-height"),w.z.literal("--font-heading-3xl-line-height"),w.z.literal("--border-radius-xs"),w.z.literal("--border-radius-sm"),w.z.literal("--border-radius-md"),w.z.literal("--border-radius-lg"),w.z.literal("--border-radius-xl"),w.z.literal("--border-radius-full"),w.z.literal("--border-width-regular"),w.z.literal("--shadow-hairline"),w.z.literal("--shadow-sm"),w.z.literal("--shadow-md"),w.z.literal("--shadow-lg")]).describe("CSS variable keys available to MCP apps for theming."),O=w.z.record(L.describe(`Style variables for theming MCP apps. 2 3Individual style keys are optional - hosts may provide any subset of these values. 4Values are strings containing CSS values (colors, sizes, font stacks, etc.). 5 6Note: This type uses \`Record<K, string | undefined>\` rather than \`Partial<Record<K, string>>\` 7for compatibility with Zod schema generation. Both are functionally equivalent for validation.`),w.z.union([w.z.string(),w.z.undefined()]).describe(`Style variables for theming MCP apps. 8 9Individual style keys are optional - hosts may provide any subset of these values. 10Values are strings containing CSS values (colors, sizes, font stacks, etc.). 11 12Note: This type uses \`Record<K, string | undefined>\` rather than \`Partial<Record<K, string>>\` 13for compatibility with Zod schema generation. Both are functionally equivalent for validation.`)).describe(`Style variables for theming MCP apps. 14 15Individual style keys are optional - hosts may provide any subset of these values. 16Values are strings containing CSS values (colors, sizes, font stacks, etc.). 17 18Note: This type uses \`Record<K, string | undefined>\` rather than \`Partial<Record<K, string>>\` 19for compatibility with Zod schema generation. Both are functionally equivalent for validation.`),H=w.z.object({method:w.z.literal("ui/open-link"),params:w.z.object({url:w.z.string().describe("URL to open in the host's browser")})}),N=w.z.object({isError:w.z.boolean().optional().describe("True if the host failed to open the URL (e.g., due to security policy).")}).passthrough(),j=w.z.object({isError:w.z.boolean().optional().describe("True if the download failed (e.g., user cancelled or host denied).")}).passthrough(),$=w.z.object({isError:w.z.boolean().optional().describe("True if the host rejected or failed to deliver the message.")}).passthrough(),D=w.z.object({method:w.z.literal("ui/notifications/sandbox-proxy-ready"),params:w.z.object({})}),F=w.z.object({connectDomains:w.z.array(w.z.string()).optional().describe(`Origins for network requests (fetch/XHR/WebSocket). 20 21- Maps to CSP \`connect-src\` directive 22- Empty or omitted â no network connections (secure default)`),resourceDomains:w.z.array(w.z.string()).optional().describe("Origins for static resources (images, scripts, stylesheets, fonts, media).\n\n- Maps to CSP `img-src`, `script-src`, `style-src`, `font-src`, `media-src` directives\n- Wildcard subdomains supported: `https://*.example.com`\n- Empty or omitted â no network resources (secure default)"),frameDomains:w.z.array(w.z.string()).optional().describe("Origins for nested iframes.\n\n- Maps to CSP `frame-sr
22c` directive\n- Empty or omitted â no nested iframes allowed (`frame-src 'none'`)"),baseUriDomains:w.z.array(w.z.string()).optional().describe("Allowed base URIs for the document.\n\n- Maps to CSP `base-uri` directive\n- Empty or omitted â only same origin allowed (`base-uri 'self'`)")}),K=w.z.object({camera:w.z.object({}).optional().describe("Request camera access.\n\nMaps to Permission Policy `camera` feature."),microphone:w.z.object({}).optional().describe("Request microphone access.\n\nMaps to Permission Policy `microphone` feature."),geolocation:w.z.object({}).optional().describe("Request geolocation access.\n\nMaps to Permission Policy `geolocation` feature."),clipboardWrite:w.z.object({}).optional().describe("Request clipboard write access.\n\nMaps to Permission Policy `clipboard-write` feature.")}),W=w.z.object({method:w.z.literal("ui/notifications/size-changed"),params:w.z.object({width:w.z.number().optional().describe("New width in pixels."),height:w.z.number().optional().describe("New height in pixels.")})}),V=(w.z.object({method:w.z.literal("ui/notifications/tool-input"),params:w.z.object({arguments:w.z.record(w.z.string(),w.z.unknown().describe("Complete tool call arguments as key-value pairs.")).optional().describe("Complete tool call arguments as key-value pairs.")})}),w.z.object({method:w.z.literal("ui/notifications/tool-input-partial"),params:w.z.object({arguments:w.z.record(w.z.string(),w.z.unknown().describe("Partial tool call arguments (incomplete, may change).")).optional().describe("Partial tool call arguments (incomplete, may change).")})}),w.z.object({method:w.z.literal("ui/notifications/tool-cancelled"),params:w.z.object({reason:w.z.string().optional().describe('Optional reason for the cancellation (e.g., "user action", "timeout").')})}),w.z.object({fonts:w.z.string().optional()})),B=w.z.object({variables:O.optional().describe("CSS variables for theming the app."),css:V.optional().describe("CSS blocks that apps can inject.")}),J=(w.z.object({method:w.z.literal("ui/resource-teardown"),params:w.z.object({})}),w.z.record(w.z.string(),w.z.unknown())),G=w.z.object({text:w.z.object({}).optional().describe("Host supports text content blocks."),image:w.z.object({}).optional().describe("Host supports image content blocks."),audio:w.z.object({}).optional().describe("Host supports audio content blocks."),resource:w.z.object({}).optional().describe("Host supports resource content blocks."),resourceLink:w.z.object({}).optional().describe("Host supports resource link content blocks."),structuredContent:w.z.object({}).optional().describe("Host supports structured content.")}),Y=w.z.object({method:w.z.literal("ui/notifications/request-teardown"),params:w.z.object({}).optional()}),Z=w.z.object({experimental:w.z.record(w.z.string(),w.z.record(w.z.string(),w.z.any()).describe("Experimental features keyed by identifier.")).optional().describe("Experimental features keyed by identifier."),openLinks:w.z.object({}).optional().describe("Host supports opening external URLs."),downloadFile:w.z.object({}).optional().describe("Host supports file downloads via ui/download-file."),serverTools:w.z.object({listChanged:w.z.boolean().optional().describe("Host supports tools/list_changed notifications.")}).optional().describe("Host can proxy tool calls to the MCP server."),serverResources:w.z.object({listChanged:w.z.boolean().optional().describe("Host supports resources/list_changed notifications.")}).optional().describe("Host can proxy resource reads to the MCP server."),logging:w.z.object({}).optional().describe("Host accepts log messages."),sandbox:w.z.object({permissions:K.optional().describe("Permissions granted by the host (camera, microphone, geolocation)."),csp:F.optional().describe("CSP domains approved by the host.")}).optional().describe("Sandbox configuration applied by the host."),updateModelContext:G.optional().describe("Host accepts context updates (ui/update-model-context) to be included in the model's context for future turns."),message:G.optional().describe("Host supports receiving content messages (ui/message) from the view."),sampling:w.z.object({tools:w.z.object({}).optional().describe("Host supports tool use via `tools` and `toolChoice` parameters.")}).optional().describe("Host supports LLM sampling (sampling/createMessage) from the view.\nMirrors the MCP `ClientCapabilities.sampling` shape so hosts can pass it through.")}),X=w.z.object({experimental:w.z.record(w.z.string(),w.z.record(w.z.string(),w.z.any()).describe("Experimental features keyed by identifier.")).optional().describe("Experimental features keyed by identifier."),tools:w.z.object({listChanged:w.z.boolean().optional().describe("App supports tools/list_changed notifications.")}).optional().describe("App exposes MCP-style tools that the host can call."),availableDisplayModes:w.z.array(q).optional().describe("Display modes the app supports.")}),Q=w.z.object({method:w.z.literal("ui/notifications/initialized"),params:w.z.object({}).optional()}),ee=(w.z.object({csp:F.optional().describe("Content Security Policy configuration for UI resources."),permissions:K.optional().describe("Sandbox permissions requested by the UI resource."),domain:w.z.string().optional().describe(`Dedicated origin for view sandbox. 23 24Useful when views need stable, dedicated origins for OAuth callbacks, CORS policies, or API key allowlists. 25 26**Host-dependent:** The format and validation rules for this field are determined by each host. Servers MUST consult host-specific documentation for the expected domain format. Common patterns include: 27- Hash-based subdomains (e.g., \`{hash}.claudemcpcontent.com\`) 28- URL-derived subdomains (e.g., \`www-example-com.oaiusercontent.com\`) 29 30If omitted, host uses default sandbox origin (typically per-conversation).`),prefersBorder:w.z.boolean().optional().describe(`Visual boundary preference - true if view prefers a visible border. 31 32Boolean requesting whether a visible border and background is provided by the host. Specifying an explicit value for this is recommended because hosts' defaults may vary. 33 34- \`true\`: request visible border + background 35- \`false\`: request no visible border + background 36- omitted: host decides border`)}),w.z.object({method:w.z.literal("ui/request-display-mode"),params:w.z.object({mode:q.describe("The display mode being requested.")})})),et=w.z.object({mode:q.describe("The display mode that was actually set. May differ from requested if not supported.")}).passthrough(),er=w.z.union([w.z.literal("model"),w.z.literal("app")]).describe("Tool visibility scope - who can access the tool."),ei=(w.z.object({resourceUri:w.z.string().optional(),visibility:w.z.array(er).optional().describe(`Who can access this tool. Default: ["model", "app"] 37- "model": Tool visible to and callable by the agent 38- "app": Tool callable by the app from this server only`),csp:w.z.never().optional(),permissions:w.z.never().optional()}),w.z.object({mimeTypes:w.z.array(w.z.string()).optional().describe('Array of supported MIME types for UI resources.\nMust include `"text/html;profile=mcp-app"` for MCP Apps support.')}),w.z.object({method:w.z.literal("ui/download-file"),params:w.z.object({contents:w.z.array(w.z.union([R.EmbeddedRes
38ourceSchema,x.ResourceLinkSchema])).describe("Resource contents to download â embedded (inline data) or linked (host fetches). Uses standard MCP resource types.")})})),en=w.z.object({method:w.z.literal("ui/message"),params:w.z.object({role:w.z.literal("user").describe('Message role, currently only "user" is supported.'),content:w.z.array(C.ContentBlockSchema).describe("Message content blocks (text, image, etc.).")})}),eo=(w.z.object({method:w.z.literal("ui/notifications/sandbox-resource-ready"),params:w.z.object({html:w.z.string().describe("HTML content to load into the inner iframe."),sandbox:w.z.string().optional().describe("Optional override for the inner iframe's sandbox attribute."),csp:F.optional().describe("CSP configuration from resource metadata."),permissions:K.optional().describe("Sandbox permissions from resource metadata.")})}),w.z.object({method:w.z.literal("ui/notifications/tool-result"),params:_.CallToolResultSchema.describe("Standard MCP tool execution result.")}),w.z.object({toolInfo:w.z.object({id:k.RequestIdSchema.optional().describe("JSON-RPC id of the tools/call request."),tool:E.ToolSchema.describe("Tool definition including name, inputSchema, etc.")}).optional().describe("Metadata of the tool call that instantiated this App."),theme:I.optional().describe("Current color theme preference."),styles:B.optional().describe("Style configuration for theming the app."),displayMode:q.optional().describe("How the UI is currently displayed."),availableDisplayModes:w.z.array(q).optional().describe("Display modes the host supports."),containerDimensions:w.z.union([w.z.object({height:w.z.number().describe("Fixed container height in pixels.")}),w.z.object({maxHeight:w.z.union([w.z.number(),w.z.undefined()]).optional().describe("Maximum container height in pixels.")})]).and(w.z.union([w.z.object({width:w.z.number().describe("Fixed container width in pixels.")}),w.z.object({maxWidth:w.z.union([w.z.number(),w.z.undefined()]).optional().describe("Maximum container width in pixels.")})])).optional().describe(`Container dimensions. Represents the dimensions of the iframe or other 39container holding the app. Specify either width or maxWidth, and either height or maxHeight.`),locale:w.z.string().optional().describe("User's language and region preference in BCP 47 format."),timeZone:w.z.string().optional().describe("User's timezone in IANA format."),userAgent:w.z.string().optional().describe("Host application identifier."),platform:w.z.union([w.z.literal("web"),w.z.literal("desktop"),w.z.literal("mobile")]).optional().describe("Platform type for responsive design decisions."),deviceCapabilities:w.z.object({touch:w.z.boolean().optional().describe("Whether the device supports touch input."),hover:w.z.boolean().optional().describe("Whether the device supports hover interactions.")}).optional().describe("Device input capabilities."),safeAreaInsets:w.z.object({top:w.z.number().describe("Top safe area inset in pixels."),right:w.z.number().describe("Right safe area inset in pixels."),bottom:w.z.number().describe("Bottom safe area inset in pixels."),left:w.z.number().describe("Left safe area inset in pixels.")}).optional().describe("Mobile safe area boundaries in pixels.")}).passthrough()),es=(w.z.object({method:w.z.literal("ui/notifications/host-context-changed"),params:eo.describe("Partial context update containing only changed fields.")}),w.z.object({method:w.z.literal("ui/update-model-context"),params:w.z.object({content:w.z.array(C.ContentBlockSchema).optional().describe("Context content blocks (text, image, etc.)."),structuredContent:w.z.record(w.z.string(),w.z.unknown().describe("Structured content for machine-readable context data.")).optional().describe("Structured content for machine-readable context data.")})})),ea=w.z.object({method:w.z.literal("ui/initialize"),params:w.z.object({appInfo:S.ImplementationSchema.describe("App identification (name and version)."),appCapabilities:X.describe("Features and capabilities this app provides."),protocolVersion:w.z.string().describe("Protocol version this app supports.")})}),el=w.z.object({protocolVersion:w.z.string().describe('Negotiated protocol version string (e.g., "2025-11-21").'),hostInfo:S.ImplementationSchema.describe("Host application identification and version."),hostCapabilities:Z.describe("Features and capabilities provided by the host."),hostContext:eo.describe("Rich context about the host environment.")}).passthrough(),ec="text/html;profile=mcp-app";class eu{eventTarget;eventSource;messageListener;constructor(e=window.parent,t){this.eventTarget=e,this.eventSource=t,this.messageListener=e=>{if(t&&e.source!==this.eventSource)return void console.debug("Ignoring message from unknown source",e);let r=z.JSONRPCMessageSchema.safeParse(e.data);r.success?(console.debug("Parsed message",r.data),this.onmessage?.(r.data)):e.data?.jsonrpc!=="2.0"?console.debug("Ignoring non-JSON-RPC message",r.error.message,e):(console.error("Failed to parse message",r.error.message,e),this.onerror?.(Error("Invalid JSON-RPC message received: "+r.error.message)))}}async start(){window.addEventListener("message",this.messageListener)}async send(e,t){"ui/notifications/tool-input-partial"!==e.method&&console.debug("Sending message",e),this.eventTarget.postMessage(e,"*")}async close(){window.removeEventListener("message",this.messageListener),this.onclose?.()}onclose;onerror;onmessage;sessionId;setProtocolVersion}var ed=[M];class eh extends b.g{_client;_hostInfo;_hostCapabilities;_appCapabilities;_hostContext={};_appInfo;_initializedReceived=!1;_registeredEvents=new Set;_events=new A;_methods=new P;setRequestHandler=(...e)=>{let[t,...r]=T("request",e)??e;this._methods.claim(t,"setRequestHandler"),super.setRequestHandler.call(this,t,...r)};
39setNotificationHandler=(...e)=>{let[t,...r]=T("notification",e)??e;this._methods.claim(t,"setNotificationHandler"),super.setNotificationHandler.call(this,t,...r)};removeRequestHandler=e=>{this._methods.release(e),super.removeRequestHandler(e)};removeNotificationHandler=e=>{this._methods.release(e),super.removeNotificationHandler(e)};replaceRequestHandler=(e,...t)=>{this._methods.replace(e),super.setRequestHandler.call(this,e,...t)};_wrapHandler(e,t){let r=super._wrapHandler(e,t);return"ui/initialize"===e||"ping"===e?r:async(t,i)=>(this._initializedReceived||console.warn(`[ext-apps] AppBridge received '${e}' before ui/notifications/initialized. The View is calling host methods before completing the handshake; it should await app.connect() first.`),r(t,i))}eventSchemas={sizechange:W,sandboxready:D,initialized:Q,requestteardown:Y,loggingmessage:y.LoggingMessageNotificationSchema};setEventHandler(e,t){this._ensureEventSlot(e),this._events.setHandler(e,t)}getEventHandler(e){return this._events.getHandler(e)}addEventListener(e,t){this._ensureEventSlot(e),this._events.addEventListener(e,t)}removeEventListener(e,t){this._events.removeEventListener(e,t)}_ensureEventSlot(e){if(this._registeredEvents.has(e))return;let t=this.eventSchemas[e];if(!t)throw Error(`Unknown event: ${String(e)}`);let r=t=>{"initialized"===e&&(this._initializedReceived=!0),this._events.dispatch(e,t)};"loggingmessage"===e?this.setNotificationHandler("notifications/message",e=>{r(e.params)}):this.setNotificationHandler(t.shape.method.value,{params:t.shape.params},e=>r(e)),this._registeredEvents.add(e)}warnIfRequestHandlerReplaced(e,t,r){t&&r&&console.warn(`[MCP Apps] ${e} handler replaced. Previous handler will no longer be called.`)}
39constructor(e,t,r,i){super(i),this._client=e,this._hostInfo=t,this._hostCapabilities=r,this._methods.replace("notifications/cancelled"),this._methods.replace("notifications/progress"),this._ensureEventSlot("initialized"),this._hostContext=i?.hostContext||{},this.replaceRequestHandler("ui/initialize",{params:ea.shape.params,result:el},e=>this._onAppsInitialize(e)),this.replaceRequestHandler("ping",(e,t)=>(this.onping?.(e.params,t),{})),this.replaceRequestHandler("ui/request-display-mode",{params:ee.shape.params,result:et},()=>({mode:this._hostContext.displayMode??"inline"}))}buildContext(e){return e}assertCapabilityForMethod(e){}assertRequestHandlerCapability(e){}assertNotificationCapability(e){}getAppCapabilities(){return this._appCapabilities}getAppVersion(){return this._appInfo}onping;get onsizechange(){return this.getEventHandler("sizechange")}set onsizechange(e){this.setEventHandler("sizechange",e)}get onsandboxready(){return this.getEventHandler("sandboxready")}set onsandboxready(e){this.setEventHandler("sandboxready",e)}get oninitialized(){return this.getEventHandler("initialized")}set oninitialized(e){this.setEventHandler("initialized",e)}_onmessage;get onmessage(){return this._onmessage}set onmessage(e){this.warnIfRequestHandlerReplaced("onmessage",this._onmessage,e),this._onmessage=e,this.replaceRequestHandler("ui/message",{params:en.shape.params,result:$},async(e,t)=>{if(!this._onmessage)throw Error("No onmessage handler set");return this._onmessage(e,t)})}_onopenlink;get onopenlink(){return this._onopenlink}set onopenlink(e){this.warnIfRequestHandlerReplaced("onopenlink",this._onopenlink,e),this._onopenlink=e,this.replaceRequestHandler("ui/open-link",{params:H.shape.params,result:N},async(e,t)=>{if(!this._onopenlink)throw Error("No onopenlink handler set");return this._onopenlink(e,t)})}_ondownloadfile;get ondownloadfile(){return this._ondownloadfile}set ondownloadfile(e){this.warnIfRequestHandlerReplaced("ondownloadfile",this._ondownloadfile,e),this._ondownloadfile=e,this.replaceRequestHandler("ui/download-file",{params:ei.shape.params,result:j},async(e,t)=>{if(!this._ondownloadfile)throw Error("No ondownloadfile handler set");return this._ondownloadfile(e,t)})}get onrequestteardown(){return this.getEventHandler("requestteardown")}set onrequestteardown(e){this.setEventHandler("requestteardown",e)}_onrequestdisplaymode;get onrequestdisplaymode(){return this._onrequestdisplaymode}set onrequestdisplaymode(e){this.warnIfRequestHandlerReplaced("onrequestdisplaymode",this._onrequestdisplaymode,e),this._onrequestdisplaymode=e,this.replaceRequestHandler("ui/request-display-mode",{params:ee.shape.params,result:et},async(e,t)=>{if(!this._onrequestdisplaymode)throw Error("No onrequestdisplaymode handler set");return this._onrequestdisplaymode(e,t)})}get onloggingmessage(){return this.getEventHandler("loggingmessage")}set onloggingmessage(e){this.setEventHandler("loggingmessage",e)}_onupdatemodelcontext;get onupdatemodelcontext(){return this._onupdatemodelcontext}set onupdatemodelcontext(e){this.warnIfRequestHandlerReplaced("onupdatemodelcontext",this._onupdatemodelcontext,e),this._onupdatemodelcontext=e,this.replaceRequestHandler("ui/update-model-context",{params:es.shape.params,result:v.EmptyResultSchema},async(e,t)=>{if(!this._onupdatemodelcontext)throw Error("No onupdatemodelcontext handler set");return this._onupdatemodelcontext(e,t)})}_oncalltool;get oncalltool(){return this._oncalltool}set oncalltool(e){this.warnIfRequestHandlerReplaced("oncalltool",this._oncalltool,e),this._oncalltool=e,this.replaceRequestHandler("tools/call",async(e,t)=>{if(!this._oncalltool)throw Error("No oncalltool handler set");return this._oncalltool(e.params,t)})}_oncreatesamplingmessage;get oncreatesamplingmessage(){return this._oncreatesamplingmessage}set oncreatesamplingmessage(e){this.warnIfRequestHandlerReplaced("oncreatesamplingmessage",this._oncreatesamplingmessage,e),this._oncreatesamplingmessage=e,this.replaceRequestHandler("sampling/createMessage",async(e,t)=>{if(!this._oncreatesamplingmessage)throw Error("No oncreatesamplingmessage handler set");return this._oncreatesamplingmessage(e.params,t)})}sendToolListChanged(e={}){return this.notification({method:"notifications/tools/list_changed",params:e})}_onlistresources;get onlistresources(){return this._onlistresources}set onlistresources(e){this.warnIfRequestHandlerReplaced("onlistresources",this._onlistresources,e),this._onlistresources=e,this.replaceRequestHandler("resources/list",async(e,t)=>{if(!this._onlistresources)throw Error("No onlistresources handler set");return this._onlistresources(e.params,t)})}_onlistresourcetemplates;get onlistresourcetemplates(){return this._onlistresourcetemplates}set onlistresourcetemplates(e){this.warnIfRequestHandlerReplaced("onlistresourcetemplates",this._onlistresourcetemplates,e),this._onlistresourcetemplates=e,this.replaceRequestHandler("resources/templates/list",async(e,t)=>{if(!this._onlistresourcetemplates)throw Error("No onlistresourcetemplates handler set");return this._onlistresourcetemplates(e.params,t)})}_onreadresource;get onreadresource(){return this._onreadresource}set onreadresource(e){this.warnIfRequestHandlerReplaced("onreadresource",this._onreadresource,e),this._onreadresource=e,this.replaceRequestHandler("resources/read",async(e,t)=>{if(!this._onreadresource)throw Error("No onreadresource handler set");return this._onreadresource(e.params,t)})}sendResourceListChanged(e={}){return this.notification({method:"notifications/resources/list_changed",params:e})}_onlistprompts;get onlistprompts(){return this._onlistprompts}set onlistprompts(e){this.warnIfRequestHandlerReplaced("onlistprompts",this._onlistprompts,e),this._onlistprompts=e,this.replaceRequestHandler("prompts/list",async(e,t)=>{if(!this._onlistprompts)throw Error("No onlistprompts handler set");return this._onlistprompts(e.params,t)})}sendPromptListChanged(e={}){return this.notification({method:"notifications/prompts/list_changed",params:e})}getCapabilities(){return this._hostCapabilities}async _onAppsInitialize(e){let t=e.protocolVersion;return void 0!==this._appInfo&&console.warn("[ext-apps] AppBridge received a second ui/initialize. The View may be double-mounting (e.g. React StrictMode in dev) without closing the previous App instance. Responding normally; the latest appInfo/appCapabilities replace the previous values."),this._appCapabilities=e.appCapabilities,this._appInfo=e.appInfo,{protocolVersion:ed.includes(t)?t:M,hostCapabilities:this.getCapabilities(),hostInfo:this._hostInfo,hostContext:this._hostContext}}setHostContext(e){let t={},r=!1;for(let o of Object.keys(e)){var i,n;let s=this._hostContext[o],a=e[o];i=s,n=a,JSON.stringify(i)!==JSON.stringify(n)&&(t[o]=a,r=!0)}r&&(this._hostContext=e,this.sendHostContextChange(t))}sendHostContextChange(e){return this.notification({method:"ui/notifications/host-context-changed",params:e})}sendToolInput(e){return this.notification({method:"ui/notifications/tool-input",params:e})}sendToolInputPartial(e){return this.notification({method:"ui/notifications/tool-input-partial",params:e})}sendToolResult(e){return this.notification({method:"ui/notifications/tool-result",params:e})}sendToolCancelled(e){return this.notification({method:"ui/notifications/tool-cancelled",params:e})}sendSandboxResourceReady(e){return this.notification({method:"ui/notifications/sandbox-resource-ready",params:e})}
39teardownResource(e,t){return this.request({method:"ui/resource-teardown",params:e},J,t)}sendResourceTeardown=this.teardownResource;callTool(e,t){return this.request({method:"tools/call",params:e},t)}listTools(e,t){return this.request({method:"tools/list",params:e},t)}async connect(e){if(this.transport)throw Error("AppBridge is already connected. Call close() before connecting again.");if(this._initializedReceived=!1,this._client){let e=this._client.getServerCapabilities();if(!e)throw Error("Client server capabilities not available");e.tools&&(this.oncalltool=async(e,t)=>this._client.request({method:"tools/call",params:e},{signal:t.mcpReq.signal}),e.tools.listChanged)&&this._client.setNotificationHandler("notifications/tools/list_changed",e=>this.sendToolListChanged(e.params)),e.resources&&(this.onlistresources=async(e,t)=>this._client.request({method:"resources/list",params:e},{signal:t.mcpReq.signal}),this.onlistresourcetemplates=async(e,t)=>this._client.request({method:"resources/templates/list",params:e},{signal:t.mcpReq.signal}),this.onreadresource=async(e,t)=>this._client.request({method:"resources/read",params:e},{signal:t.mcpReq.signal}),e.resources.listChanged)&&this._client.setNotificationHandler("notifications/resources/list_changed",e=>this.sendResourceListChanged(e.params)),e.prompts&&(this.onlistprompts=async(e,t)=>this._client.request({method:"prompts/list",params:e},{signal:t.mcpReq.signal}),e.prompts.listChanged)&&this._client.setNotificationHandler("notifications/prompts/list_changed",e=>this.sendPromptListChanged(e.params))}return super.connect(e)}}var ep=Object.defineProperty,ef=Object.getOwnPropertyNames,em=(e,t)=>function(){return e&&(t=(0,e[ef(e)[0]])(e=0)),t};function eg(){let e;try{e=void 0!==u.default?u.default.env?.MCP_USE_LOG_LEVEL??u.default.env?.DEBUG:void 0}catch{}let r=e?.trim().toLowerCase();return"2"===r?"debug":r&&t.includes(r)?r:"info"}var eb=em({"src/utils/logging.ts"(){t=["silent","error","warn","info","http","verbose","debug","silly"],r={silent:"",error:"â",warn:"â ï¸",info:"â¹ï¸",http:"ð",verbose:"ð",debug:"ð",silly:"ð¤ª"},i=class{constructor(e="mcp-use",t="info",r="minimal"){this.name=e,this.level=t,this.format=r}write(e,i,n){if("silent"===this.level||t.indexOf(e)>t.indexOf(this.level))return;let o=n.map(e=>{if("string"==typeof e)return e;try{return JSON.stringify(e)}catch{return String(e)}}).join(" "),s=o?`${i} ${o}`:i,a=new Date().toLocaleTimeString("en-US",{hour12:!1}),l="minimal"===this.format?e:e.toUpperCase(),c="emoji"===this.format?` ${r[e]}`:"";("error"===e?console.error:"warn"===e?console.warn:"info"===e?console.info:"debug"===e?console.debug:console.log)(`${a} [${this.name}]${c} ${l}: ${s}`)}error=(e,...t)=>this.write("error",e,t);warn=(e,...t)=>this.write("warn",e,t);info=(e,...t)=>this.write("info",e,t);debug=(e,...t)=>this.write("debug",e,t);http=(e,...t)=>this.write("http",e,t);verbose=(e,...t)=>this.write("verbose",e,t);silly=(e,...t)=>this.write("silly",e,t);setFormat(e){this.format=e}},o=(n=class{static instances={};static currentFormat="minimal";static currentLevel;static get(e="mcp-use"){return this.instances[e]??=new i(e,this.currentLevel??eg(),this.currentFormat)}static configure({level:e=eg(),format:t="minimal"}={}){for(let r of(this.currentLevel=e,this.currentFormat=t,Object.values(this.instances)))r.level=e,r.format=t}static setDebug(e){let t=2===e||!0===e?"debug":"info";for(let e of(this.currentLevel=t,Object.values(this.instances)))e.level=t;try{void 0!==u.default&&u.default.env&&(u.default.env.MCP_USE_LOG_LEVEL=t)}catch{}}static setFormat(e){this.configure({format:e})}}).get()}}),ev={},ey={clearRpcLogs:()=>eS,getAllRpcLogs:()=>e_,getRpcLogs:()=>eC,subscribeToRpcLogs:()=>eR,wrapTransportForLogging:()=>ek};for(var ew in ey)ep(ev,ew,{get:ey[ew],enumerable:!0});function eC(e){return a.getLogsForServer(e)}function e_(){return a.getAllLogs()}function eR(e){return a.subscribe(e)}function eS(e){a.clear(e)}function ek(e,t){return new class{constructor(e){this.inner=e,this.inner.onmessage=(e,r)=>{a.publish({serverId:t,direction:"receive",timestamp:new Date().toISOString(),message:e}),this.onmessage?.(e,r)},this.inner.onclose=()=>{this.onclose?.()},this.inner.onerror=e=>{this.onerror?.(e)}}onclose;onerror;onmessage;async start(){"function"==typeof this.inner.start&&await this.inner.start()}async send(e,r){a.publish({serverId:t,direction:"send",timestamp:new Date().toISOString(),message:e}),await this.inner.send(e,r)}async close(){await this.inner.close()}get sessionId(){return this.inner.sessionId}setProtocolVersion(e){"function"==typeof this.inner.setProtocolVersion&&this.inner.setProtocolVersion(e)}}(e)}var ex=em({"src/react/rpc-logger.ts"(){eb(),s=n.get("RpcLogger"),a=new class{logs=[];listeners=new Set;maxLogs=1e3;publish(e){s.debug("[RPC Logger] Publishing log:",e.direction,e.serverId,e.message?.method),this.logs.push(e),this.logs.length>this.maxLogs&&(this.logs=this.logs.slice(-this.maxLogs)),s.debug("[RPC Logger] Total logs:",this.logs.length,"Listeners:",this.listeners.size),this.listeners.forEac
39h(t=>{try{t(e)}catch(e){s.error("[RPC Logger] Listener error:",e)}})}subscribe(e){return this.listeners.add(e),()=>this.listeners.delete(e)}getLogsForServer(e){return this.logs.filter(t=>t.serverId===e)}getAllLogs(){return[...this.logs]}clear(e){e?this.logs=this.logs.filter(t=>t.serverId!==e):this.logs=[]}}}}),eE="io.modelcontextprotocol/skills",ez=["url","displayName","enabled","oauthProxyUrl","connectionMode","autoProxyFallback","callbackUrl","storageKeyPrefix","logLevel","autoRetry","autoReconnect","reconnectionOptions","popupFeatures","preventAutoAuth","detectMixedAuth","useRedirectFlow","protocolNegotiation","timeout","clientInfo"];function eA(e){let t={};for(let r of ez){let i=e[r];void 0!==i&&(t[r]=i)}if(e.proxyConfig?.proxyAddress!==void 0&&(t.proxyConfig={proxyAddress:e.proxyConfig.proxyAddress}),e.oauth){let r={};void 0!==e.oauth.clientId&&(r.clientId=e.oauth.clientId),void 0!==e.oauth.clientMetadataUrl&&(r.clientMetadataUrl=e.oauth.clientMetadataUrl),void 0!==e.oauth.scope&&(r.scope=e.oauth.scope),Object.keys(r).length>0&&(t.oauth=r)}return t}function eP(e){return{...eA(e),...void 0!==e.headers?{headers:e.headers}:{},...void 0!==e.proxyConfig?{proxyConfig:e.proxyConfig}:{},...void 0!==e.clientOptions?{clientOptions:e.clientOptions}:{}}}var eU="mcp_auth_callback",eT="mcp_auth_callback";function eM(e){try{return"u">typeof localStorage&&!!localStorage.getItem(e)}catch{return!1}}function eI({popup:e,state:t,tokensKey:r,timeoutMs:i=5*6e4,closePollMs:n=1e3,closeGraceMs:o=2e4,expectedOrigin:s="u">typeof window?window.location.origin:""}){return new Promise(a=>{let l=!1,c=null,u=null,d=null,h=null,p=e=>{if(!l){if(l=!0,c&&(clearInterval(c),c=null),u&&(clearTimeout(u),u=null),d&&(clearTimeout(d),d=null),"u">typeof window&&(window.removeEventListener("message",m),window.removeEventListener("storage",b)),h){try{h.removeEventListener("message",g),h.close()}catch{}h=null}a(e)}},f=e=>{!e||e.type!==eT||e.state&&t&&e.state!==t||(e.success?p({kind:"success"}):p({kind:"error",error:e.error??"Authentication failed in callback."}))},m=e=>{s&&e.origin!==s||f(e.data)},g=e=>{f(e.data)},b=e=>{e.key===r&&e.newValue&&p({kind:"success"})};if("u">typeof window&&(window.addEventListener("message",m),window.addEventListener("storage",b)),"u">typeof BroadcastChannel)try{(h=new BroadcastChannel(eU)).addEventListener("message",g)}catch{h=null}e&&(c=setInterval(()=>{if(l)return;let t=!1;try{t=e.closed}catch{t=!1}if(t){if(c&&(clearInterval(c),c=null),eM(r))return void p({kind:"success"});d=setTimeout(()=>{p(eM(r)?{kind:"success"}:{kind:"cancelled"})},o)}},n)),u=setTimeout(()=>{p(eM(r)?{kind:"success"}:{kind:"timeout"})},i)})}var eq=5*6e4;function eL(e,t=0){if(!e||t>5)return!1;if(e instanceof d.UnauthorizedError)return!0;if(e instanceof Error){if(401===e.code||"UnauthorizedError"===e.name)return!0;let r=e.message??"";if(r.includes("401")||r.includes("Unauthorized")||e.cause&&eL(e.cause,t+1))return!0;let i=e.data;if(i?.cause&&eL(i.cause,t+1))return!0}return!1}function eO(e,t=0){if(!e||t>5)return!1;if(e instanceof d.InsufficientScopeError||e instanceof d.UnauthorizedError)return!0;if(e instanceof Error){if("InsufficientScopeError"===e.name||"UnauthorizedError"===e.name||e.cause&&eO(e.cause,t+1))return!0;let r=e.data;if(r?.cause&&eO(r.cause,t+1))return!0}return!1}async function eH(e,t,r={}){let i=r.timeoutMs??eq,n=r.fetchFn??e.getProxyFetch?.()??void 0;if(!e.hasPendingFlow){let r=await (0,d.auth)(e,{serverUrl:t,fetchFn:n});if("AUTHORIZED"===r)return;if("REDIRECT"!==r)throw Error(`Unexpected OAuth auth() result: ${r}`)}if(!0===e.preventAutoAuth&&"function"==typeof e.startAuthorization&&e.startAuthorization(),"function"==typeof e.getAuthorizationResponse||"function"==typeof e.getAuthorizationCode){let i="function"==typeof e.getAuthorizationResponse?await e.getAuthorizationResponse():{code:await e.getAuthorizationCode()};r.finishAuthorization?await r.finishAuthorization(i.code,i.iss):await (0,d.auth)(e,{serverUrl:t,authorizationCode:i.code,...void 0!==i.iss?{iss:i.iss}:{},fetchFn:n});return}await eN(e,i)}async function eN(e,t){if("u"<typeof window)throw Error("OAuth redirect requires a browser environment or a provider with getAuthorizationCode()");if(e.useRedirectFlow)return void await new Promise(()=>{});let r=e.getKey?.("tokens");if(!r)throw Error("Browser OAuth provider must expose getKey() for token storage");let i=null,n=e.getLastAttemptedAuthUrl?.();if(n)try{i=new URL(n).searchParams.get("state")}catch{}try{let e=await eI({popup:null,state:i,tokensKey:r,timeoutMs:t});switch(e.kind){case"success":return;case"cancelled":throw Error("OAuth authentication was cancelled.");case"timeout":throw Error(`OAuth callback not received within ${t}ms. Ensure /oauth/callback calls onMcpAuthorization().`);case"error":throw Error(e.error);default:throw Error("Unexpected OAuth popup result")}}finally{e.markFlowComplete?.()}}var ej=new Set(["http://json-schema.org/draft-07/schema","https://json-schema.org/draft-07/schema"]),e$=new Set(["https://json-schema.org/draft/2019-09/schema","http://json-schema.org/draft/2019-09/schema"]),eD=new Set(["https://json-schema.org/draft/2020-12/schema","http://json-schema.org/draft/2020-12/schema"]),eF=class{getValidator(e){let t=function(e){if(!("$schema"in e)||"string"!=typeof e.$schema)return"2020-12";let t=e.$schema.replace(/#$/,"");return"http://json-schema.org/draft-04/schema"===t?"4":ej.has(t)?"7":e$.has(t)?"2019
39-09":eD.has(t)?"2020-12":void 0}(e);return(void 0!==t?new m.CfWorkerJsonSchemaValidator({draft:t}):new m.CfWorkerJsonSchemaValidator).getValidator(e)}};eb(),eb();var eK={"~standard":{version:1,vendor:"mcp-use",validate:e=>({value:e})}},eW=class{client=null;connectionManager=null;toolsCache=null;capabilitiesCache=null;serverInfoCache=null;authorizationCache;connected=!1;connectPromise=null;disconnectPromise=null;disconnectGeneration=0;opts;notificationHandlers=[];rootsCache=[];activeProgressHandlers=new Set;constructor(e={}){this.opts=e,e.roots&&(this.rootsCache=[...e.roots]),e.onNotification&&this.notificationHandlers.push(e.onNotification)}trackConnectorInit(e){var t;t={connectorType:this.constructor.name,...e},l?.(t)}onNotification(e){this.notificationHandlers.push(e),this.client&&this.setupNotificationHandler()}async forwardNotification(e){for(let t of this.notificationHandlers)try{await t(e)}catch(e){o.error("Error in notification handler:",e)}}async handleListChanged(e,t,r){t?o.warn(`[Auto] ${e} refresh failed:`,t):("notifications/tools/list_changed"===e&&r&&(this.toolsCache=[...r]),await this.forwardNotification({method:e}))}setupNotificationHandler(){if(!this.client)return;this.client.fallbackNotificationHandler=async e=>{switch(e.method){case"notifications/tools/list_changed":await this.refreshToolsCache();break;case"notifications/resources/list_changed":await this.onResourcesListChanged();break;case"notifications/prompts/list_changed":await this.onPromptsListChanged()}await this.forwardNotification(e)};let e=this.client._notificationHandlers;for(let t of["notifications/progress","notifications/cancelled"]){let r=e.get(t);r&&e.set(t,async e=>{await r(e),await this.forwardNotification(e)})}}setupRoundProgressForwarding(){if(!this.client)return;let e=this.client,t=e._onnotification.bind(this.client);e._onnotification=async e=>{e&&"object"==typeof e&&"notifications/progress"===e.method&&this.forwardRoundProgress(e.params),await t?.(e)}}forwardRoundProgress(e){if(1===this.activeProgressHandlers.size){let[t]=this.activeProgressHandlers;t?.(e)}}async refreshToolsCache(){if(this.client)try{o.debug("[Auto] Refreshing tools cache due to list_changed notification");let e=await this.client.listTools();this.toolsCache=e.tools??[],o.debug(`[Auto] Refreshed tools cache: ${this.toolsCache.length} tools`)}catch(e){o.warn("[Auto] Failed to refresh tools cache:",e)}}async onResourcesListChanged(){o.debug("[Auto] Resources list changed - clients should re-fetch if needed")}async onPromptsListChanged(){o.debug("[Auto] Prompts list changed - clients should re-fetch if needed")}async setRoots(e){this.rootsCache=[...e],this.client&&(o.debug(`Sending roots/list_changed notification with ${e.length} root(s)`),await this.client.sendRootsListChanged())}getRoots(){return[...this.rootsCache]}setupRootsHandler(){this.client&&this.client.setRequestHandler("roots/list",async()=>(o.debug(`Server requested roots list, returning ${this.rootsCache.length} root(s)`),{roots:this.rootsCache}))}setupSamplingHandler(){if(!this.client)return void o.debug("setupSamplingHandler: No client available");let e=this.opts.onSampling;e?(o.debug("setupSamplingHandler: Setting up sampling request handler"),this.client.setRequestHandler("sampling/createMessage",async t=>(o.debug("Server requested sampling, forwarding to callback"),await e(t.params))),o.debug("setupSamplingHandler: Sampling handler registered successfully")):o.debug("setupSamplingHandler: No sampling callback provided")}setupElicitationHandler(){if(!this.client)return void o.debug("setupElicitationHandler: No client available");let e=this.opts.onElicitation;e?(o.debug("setupElicitationHandler: Setting up elicitation request handler"),this.client.setRequestHandler("elicitation/create",async t=>(o.debug("Server requested elicitation, forwarding to callback"),await e(t.params))),o.debug("setupElicitationHandler: Elicitation handler registered successfully")):o.debug("setupElicitationHandler: No elicitation callback provided")}async connect(){let e=this.disconnectGeneration;for(;this.disconnectPromise;)await this.disconnectPromise;if(e!==this.disconnectGeneration)throw Error("Connection cancelled by disconnect");
39if(this.connected)return void o.debug("Already connected to MCP implementation");if(this.connectPromise)return this.connectPromise;let t=(async()=>{try{if(await this.establishTransport(),e!==this.disconnectGeneration)throw Error("Connection cancelled by disconnect");this.connected=!0}catch(e){throw this.connected=!1,await this.cleanupResources(),e}finally{this.connectPromise=null}})();return this.connectPromise=t,this.connectPromise}async establishTransport(){}async executeRequest(e){return e()}get authorization(){return this.authorizationCache}async discoverAuthorization(){return this.authorization}async authenticate(){throw Error("This connector does not support interactive OAuth")}async disconnect(){if(this.disconnectGeneration++,this.disconnectPromise)return this.disconnectPromise;if(!this.connected&&!this.connectPromise)return void o.debug("Not connected to MCP implementation");let e=(async()=>{let e=!1;try{if(this.connectPromise)try{await this.connectPromise}catch{e=!0}e||(o.debug("Disconnecting from MCP implementation"),await this.cleanupResources()),this.connected=!1,o.debug("Disconnected from MCP implementation")}finally{this.disconnectPromise=null}})();return this.disconnectPromise=e,this.disconnectPromise}get isClientConnected(){return null!=this.client}async initialize(e=this.opts.defaultRequestOptions??{}){if(!this.client)throw Error("MCP client is not connected");o.debug("Caching server capabilities & tools");let t=this.client.getServerCapabilities();this.capabilitiesCache=t||null;let r=this.client.getServerVersion();this.serverInfoCache=r?{name:r.name,version:r.version,title:r.title,description:r.description,websiteUrl:r.websiteUrl,icons:r.icons}:null;try{let t=await this.executeRequest(()=>this.client.listTools(void 0,e));this.toolsCache=t.tools??[],o.debug(`Fetched ${this.toolsCache.length} tools from server`)}catch(e){if(eO(e))throw e;-32601===e.code?o.debug("Server does not implement tools/list, assuming no tools"):o.debug("Failed to list tools, assuming empty:",e.message),this.toolsCache=[]}return o.debug("Server capabilities:",t),o.debug("Server info:",r),t}get tools(){if(!this.toolsCache)throw Error("MCP client is not initialized; call initialize() first");return this.toolsCache}get serverCapabilities(){return this.capabilitiesCache||{}}get serverInfo(){return this.serverInfoCache}get instructions(){return this.client?.getInstructions?.()}get protocolEra(){return this.client?.getProtocolEra?.()}get negotiatedProtocolVersion(){return this.client?.getNegotiatedProtocolVersion?.()}async callTool(e,t,r){if(!this.client)throw Error("MCP client is not connected");let i=r?{...r}:void 0;i?.resetTimeoutOnProgress&&!i.onprogress&&(i.onprogress=()=>{},o.debug(`[BaseConnector] Added onprogress callback for tool '${e}' to enable progressToken`)),o.debug(`Calling tool '${e}' with args`,t);let n=i?.onprogress;n&&this.activeProgressHandlers.add(n);try{let r=await this.executeRequest(()=>this.client.callTool({name:e,arguments:t},i));return o.debug(`Tool '${e}' returned`,r),r}finally{n&&this.activeProgressHandlers.delete(n)}}async listTools(e){if(!this.client)throw Error("MCP client is not connected");o.debug("[listTools] Fetching fresh tools from server...");let t=await this.executeRequest(()=>this.client.listTools(void 0,e)),r=t.tools?[...t.tools]:[];return o.debug(`[listTools] Returned ${r.length} tools:`,r.map(e=>e.name)),r}async listResources(e,t){if(!this.client)throw Error("MCP client is not connected");return o.debug("Listing resources",e?`with cursor: ${e}`:""),await this.executeRequest(()=>this.client.listResources({cursor:e},t))}async listAllResources(e){let t=this.client;if(!t)throw Error("MCP client is not connected");if(!this.capabilitiesCache?.resources)return o.debug("Server does not advertise resources capability, skipping"),{resources:[]};try{return o.debug("Listing all resources (with auto-pagination)"),await this.executeRequest(async()=>{let r,i=[];do{let n=await t.listResources({cursor:r},e);i.push(...n.resources||[]),r=n.nextCursor}while(r)return{resources:i}})}catch(e){if(-32601===e.code)return o.debug("Server advertised resources but method not found"),{resources:[]};throw e}}async listResourceTemplates(e){if(!this.client)throw Error("MCP client is not connected");return o.debug("Listing resource templates"),await this.executeRequest(()=>this.client.listResourceTemplates(void 0,e))}async complete(e,t){if(!this.client)throw Error("MCP client is not connected");o.debug("[complete] Requesting completions for:",e.ref);let r=await this.executeRequest(()=>this.client.complete(e,t));return o.debug(`[complete] Received ${r.completion.values.length} suggestions`),r}async readResource(e,t){if(!this.client)throw Error("MCP client is not connected");return o.debug(`Reading resource ${e}`),await this.executeRequest(()=>this.client.readResource({uri:e},t))}async subscribeToResource(e,t){if(!this.client)throw Error("MCP client is not connected");return o.debug(`Subscribing to resource: ${e}`),await this.executeRequest(()=>this.client.subscribeResource({uri:e},t))}async unsubscribeFromResource(e,t){if(!this.client)throw Error("MCP client is not connected");return o.debug(`Unsubscribing from resource: ${e}`),await this.executeRequest(()=>this.client.unsubscribeResource({uri:e},t))}async listPrompts(){if(!this.client)throw Error("MCP client is not connected");if(!this.capabilitiesCache?.prompts)return o.debug("Server does not advertise prompts capability, skipping"),{prompts:[]};try{return o.debug("Listing prompts"),await this.executeRequest(()=>this.client.listPrompts())}catch(e){if(-32601===e.code)return o.debug("Server advertised prompts but method not found"),{prompts:[]};throw e}}async getPrompt(e,t,r){if(!this.client)throw Error("MCP client is not connected");return o.debug(`Getting prompt ${e}`),await this.executeRequest(()=>this.client.getPrompt({name:e,arguments:t},r))}
39async request(e,t=null,r){if(!this.client)throw Error("MCP client is not connected");return o.debug(`Sending raw request '${e}' with params`,t),await this.executeRequest(()=>this.client.request({method:e,params:t??{}},eK,r))}async cleanupResources(){let e=[];if(this.client)try{"function"==typeof this.client.close&&await this.client.close()}catch(r){let t=`Error closing client: ${r}`;o.warn(t),e.push(t)}finally{this.client=null}if(this.connectionManager)try{await this.connectionManager.stop()}catch(r){let t=`Error stopping connection manager: ${r}`;o.warn(t),e.push(t)}finally{this.connectionManager=null}this.toolsCache=null,this.authorizationCache=void 0,e.length&&o.warn(`Resource cleanup finished with ${e.length} issue(s)`)}},eV=class extends eW{baseUrl;headers;timeout;customFetch;clientInfo;protocolNegotiation;gatewayUrl;serverId;reconnectionOptions;detectMixedAuth;transportType=null;streamableTransport=null;hadAccessTokenAtConnect=!1;pendingOAuthCompletion=null;authorizationDiscovery=null;constructor(e,t={}){super(t);const r=e.replace(/\/$/,"");this.baseUrl=r,this.headers={...t.headers??{}},this.gatewayUrl=t.gatewayUrl,this.serverId=t.serverId,t.authToken&&(this.headers.Authorization=`Bearer ${t.authToken}`),this.timeout=t.timeout??1e4;const i=t.fetch??globalThis.fetch.bind(globalThis);this.customFetch=this.gatewayUrl?function(e,t,r,i){let n=new URL(e),o=t.replace(/\/$/,"");return async(e,t)=>{let s=new Request(e,t),a=new URL(s.url);if(a.origin!==n.origin||a.pathname!==n.pathname)return r(s);let l=new Headers(s.headers);l.set("X-Target-URL",s.url),i&&l.set("X-Server-Id",i);let c="GET"===s.method||"HEAD"===s.method?void 0:await s.clone().arrayBuffer();return r(new Request(o,{method:s.method,headers:l,body:c,signal:s.signal,redirect:"manual"}))}}(r,this.gatewayUrl,i,this.serverId):t.fetch,this.clientInfo=t.clientInfo??{name:"http-connector",version:"1.0.0"},this.protocolNegotiation=t.protocolNegotiation??"auto",this.reconnectionOptions=t.reconnectionOptions,this.detectMixedAuth=t.detectMixedAuth??!0}get oauthProvider(){var e;return(e=this.opts.authProvider)&&"redirectToAuthorization"in e&&"function"==typeof e.redirectToAuthorization&&"tokens"in e&&"function"==typeof e.tokens?this.opts.authProvider:void 0}async completeInteractiveAuthorization(){let e=this.oauthProvider;if(!e)throw Error("No OAuth client provider is configured");this.pendingOAuthCompletion||(this.pendingOAuthCompletion=eH(e,this.baseUrl,{fetchFn:this.customFetch,finishAuthorization:async(e,t)=>{let r=this.streamableTransport;if(!r)throw Error("OAuth transport is no longer connected");await r.finishAuth(e,t)}}).then(()=>{this.authorizationCache={...this.authorizationCache??{mode:"mixed"},authenticated:!0}}).finally(()=>{this.pendingOAuthCompletion=null})),await this.pendingOAuthCompletion}async executeRequest(e){try{return await e()}catch(r){let t=this.oauthProvider;if(!t||!0===t.preventAutoAuth||!eO(r))throw r;if(await this.completeInteractiveAuthorization(),!this.connected||!this.client)throw Error("MCP client is not connected");return e()}}async authenticate(){if(!this.connected||!this.streamableTransport)throw Error("MCP client is not connected");await this.completeInteractiveAuthorization()}async discoverAuthorization(){return this.detectMixedAuth&&this.oauthProvider&&!this.hadAccessTokenAtConnect?(this.authorizationDiscovery||(this.authorizationDiscovery=this.discoverMixedAuthorization().then(e=>(e||(this.authorizationDiscovery=null),e))),this.authorizationDiscovery):this.authorizationCache}async discoverMixedAuthorization(){let e,t=new AbortController,r=new Promise((r,i)=>{e=setTimeout(()=>{let e=Error("Mixed-auth metadata discovery timed out after 2000ms");t.abort(e),i(e)},2e3)}),i=this.customFetch??globalThis.fetch.bind(globalThis);try{var n;let e=await Promise.race([(0,d.discoverOAuthProtectedResourceMetadata)(this.baseUrl,{protocolVersion:this.negotiatedProtocolVersion},(n=t.signal,async(e,t)=>{let r=t?.signal;if(!r)return i(e,{...t,signal:n});let o=new AbortController,s=()=>o.abort(r.reason),a=()=>o.abort(n.reason);r.aborted?s():r.addEventListener("abort",s,{once:!0}),n.aborted?a():n.addEventListener("abort",a,{once:!0});try{return await i(e,{...t,signal:o.signal})}finally{r.removeEventListener("abort",s),n.removeEventListener("abort",a)}})),r]);this.authorizationCache={mode:"mixed",authenticated:!1,...e.resource?{resource:e.resource}:{},...e.scopes_supported?{scopesSupported:[...e.scopes_supported]}:{}},o.info("OAuth protected-resource metadata found after anonymous connection; server uses mixed auth")}catch(e){o.debug("Mixed-auth metadata was not discovered:",e)}finally{e&&clearTimeout(e)}return this.authorizationCache}buildClientOptions(){return{...this.opts.clientOptions||{},jsonSchemaValidator:this.opts.clientOptions?.jsonSchemaValidator??new eF,versionNegotiation:{mode:this.protocolNegotiation,...this.opts.clientOptions?.versionNegotiation??{}},listChanged:{tools:{autoRefresh:!0,onChanged:(e,t)=>void this.handleListChanged("notifications/tools/list_changed",e,t)},resources:{autoRefresh:!1,onChanged:e=>void this.handleListChanged("notifications/resources/list_changed",e)},prompts:{autoRefresh:!1,onChanged:e=>void this.handleListChanged("notifications/prompts/list_changed",e)},...this.opts.clientOptions?.listChanged??{}},capabilities:{...this.opts.clientOptions?.capabilities||{},roots:{listChanged:!0},...this.opts.onSampling?{sampling:{}}:{},...this.opts.onElicitation?{elicitation:{form:{},url:{}}}:{}}}}unwrapStreamableError(e){return e instanceof f.SdkHttpError?e:e instanceof Error&&e.cause instanceof f.SdkHttpError?e.cause:null}classifyStreamableHttpFailure(e){let t,r="Unknown error",i=!1,n=this.unwrapStreamableError(e);
39if(n){let e=n.status;return i=401===e,t=e,400===e&&n.message.includes("Missing session ID")?(r="Server requires session ID",o.warn(`\u26A0\uFE0F ${r}`)):(r=404===e||405===e?`Server returned ${e} - server likely doesn't support streamable HTTP`:`Server returned ${e}: ${n.message}`,o.debug(r)),{fallbackReason:r,is401Error:i,httpStatusCode:t}}if(e instanceof Error){let t=e.toString(),n=e.message||"";i=function e(t,r=0){if(!t||r>5)return!1;if(t instanceof d.UnauthorizedError||t instanceof f.SdkHttpError&&401===t.status)return!0;if(t instanceof Error){if(t.cause&&e(t.cause,r+1))return!0;let i=t instanceof p.SdkError?t.data:void 0;if(i?.cause&&e(i.cause,r+1))return!0}return!1}(e)||t.includes("401")||n.includes("Unauthorized"),t.includes("Missing session ID")||t.includes("Bad Request: Missing session ID")||n.includes("FastMCP session ID error")?(r="Server requires session ID",o.warn(`\u26A0\uFE0F ${r}`)):(r=t.includes("405 Method Not Allowed")||t.includes("404 Not Found")?"Server doesn't support streamable HTTP (405/404)":`Streamable HTTP failed: ${e.message}`,o.debug(r))}return{fallbackReason:r,is401Error:i,httpStatusCode:t}}async establishTransport(){let e=this.baseUrl;o.debug(`Connecting to MCP implementation via HTTP: ${e}`);let t=this.oauthProvider;if(t)try{this.hadAccessTokenAtConnect=!!(await t.tokens())?.access_token}catch{this.hadAccessTokenAtConnect=!1}try{await this.connectWithStreamableHttp(e),o.debug("â
Successfully connected via streamable HTTP")}catch(n){o.debug("Streamable HTTP connect failed",n);let{fallbackReason:e,is401Error:t,httpStatusCode:r}=this.classifyStreamableHttpFailure(n);if(t){o.info("Authentication required");let e=Error("Authentication required");throw e.code=401,e}let i=Error(`Could not connect via streamable HTTP: ${e}`);throw void 0!==r&&Object.defineProperty(i,"code",{value:r,writable:!1,enumerable:!0,configurable:!0}),i}}observeSseProgress(e){if(!e.body||!e.headers.get("content-type")?.includes("text/event-stream"))return e;let[t,r]=e.body.tee();return(async()=>{let e=r.getReader(),t=new TextDecoder,i="";try{for(;;){let{done:r,value:n}=await e.read();if(r)break;let o=(i+=t.decode(n,{stream:!0})).split(/\r?\n\r?\n/);for(let e of(i=o.pop()??"",o))for(let t of e.split(/\r?\n/))if(t.startsWith("data:"))try{let e=JSON.parse(t.slice(5).trim());"notifications/progress"===e.method&&this.forwardRoundProgress(e.params)}catch{}}}catch(e){e instanceof DOMException&&"AbortError"===e.name||o.debug("Progress observer stream ended:",e)}finally{e.releaseLock()}})(),new Response(t,{status:e.status,statusText:e.statusText,headers:e.headers})}async connectWithStreamableHttp(e){try{o.debug("[HttpConnector] Connecting with Streamable HTTP",{baseUrl:e,originalUrl:this.baseUrl,gatewayUrl:this.gatewayUrl||"none",authProviderUrl:this.opts.authProvider&&"serverUrl"in this.opts.authProvider&&"string"==typeof this.opts.authProvider.serverUrl?this.opts.authProvider.serverUrl:"none",headers:this.headers});let t=this.customFetch??globalThis.fetch.bind(globalThis),r=async(e,r)=>{let i=await t(e,r),n=new Headers(e instanceof Request?e.headers:void 0);return new Headers(r?.headers).forEach((e,t)=>{n.set(t,e)}),"subscriptions/listen"===n.get("mcp-method")?i:this.observeSseProgress(i)},i=new d.StreamableHTTPClientTransport(new URL(e),{authProvider:this.opts.authProvider,fetch:r,requestInit:{headers:this.headers},reconnectionOptions:{maxReconnectionDelay:3e4,initialReconnectionDelay:1e3,reconnectionDelayGrowFactor:1.5,maxRetries:2,...this.reconnectionOptions}}),n=i;if(this.opts.wrapTransport){let e=this.baseUrl;n=this.opts.wrapTransport(n,e)}let s=this.buildClientOptions();o.debug("Creating Client with capabilities:",JSON.stringify(s.capabilities,null,2)),this.client=new d.Client(this.clientInfo,s),this.setupRootsHandler(),this.setupSamplingHandler(),this.setupElicitationHandler(),this.setupNotificationHandler(),o.debug("Roots/sampling/elicitation/notification handlers registered before connect");try{let e;await Promise.race([this.client.connect(n),new Promise((t,r)=>{e=setTimeout(()=>r(Error(`MCP connection timed out after ${this.timeout}ms`)),this.timeout)})]).finally(()=>{void 0!==e&&clearTimeout(e)});let t=i.sessionId;t&&o.debug(`Session ID obtained: ${t}`)}catch(e){if(e instanceof Error){let t=e.message||e.toString();if(t.includes("Missing session ID")||t.includes("Bad Request: Missing session ID")||t.includes("Mcp-Session-Id header is required")){let r=Error(`Session ID error: ${t}. The SDK should automatically extract session ID from initialize response.`);throw r.cause=e,r}}throw e}this.streamableTransport=i,this.connectionManager={stop:async()=>
39{if(this.streamableTransport)try{await this.streamableTransport.close()}catch(e){o.warn(`Error closing Streamable HTTP transport: ${e}`)}finally{this.streamableTransport=null}}},this.transportType="streamable-http",o.debug(`Successfully connected to MCP implementation via streamable HTTP: ${e}`),this.trackConnectorInit({serverUrl:this.baseUrl,publicIdentifier:`${this.baseUrl} (streamable-http)`})}catch(e){throw await this.cleanupResources(),e}}get publicIdentifier(){return{type:"http",url:this.baseUrl,transport:this.transportType||"unknown",protocolEra:this.protocolEra??"unknown"}}getTransportType(){return this.transportType}async cleanupResources(){if(this.streamableTransport&&"modern"!==this.protocolEra){let e;try{await Promise.race([this.streamableTransport.terminateSession().then(()=>!0),new Promise(t=>e=setTimeout(()=>t(!1),Math.min(this.timeout,5e3)))])||o.debug("Timed out terminating legacy HTTP session; closing transport")}catch(e){o.debug(`Error terminating Streamable HTTP session: ${e}`)}finally{e&&clearTimeout(e)}}await super.cleanupResources(),this.authorizationDiscovery=null}};function eB(){return"2.3.1"}var eJ="keys",eG="aes-gcm-v1",eY=new TextEncoder,eZ=new TextDecoder,eX=class{fallback=new Map;keyPromise;durable=!0;async get(e){let t;if(!this.durable)return this.fallback.get(e)??null;try{t=localStorage.getItem(e)}catch{return this.durable=!1,this.fallback.get(e)??null}if(null===t)return null;let r=function(e){try{let t=JSON.parse(e);if(!t||"object"!=typeof t||!("v"in t)||1!==t.v||!("alg"in t)||"A256GCM"!==t.alg||!("iv"in t)||"string"!=typeof t.iv||!("ciphertext"in t)||"string"!=typeof t.ciphertext)return;return t}catch{return}}(t);if(!r)return await this.set(e,t),t;try{let t=await this.getCryptoKey(),i=await globalThis.crypto.subtle.decrypt({name:"AES-GCM",iv:e1(r.iv),additionalData:eY.encode(e)},t,e1(r.ciphertext));return eZ.decode(i)}catch{return await this.remove(e),null}}async set(e,t){if(!this.durable)return void this.fallback.set(e,t);try{let r=await this.getCryptoKey(),i=globalThis.crypto.getRandomValues(new Uint8Array(12)),n=await globalThis.crypto.subtle.encrypt({name:"AES-GCM",iv:i,additionalData:eY.encode(e)},r,eY.encode(t)),o={v:1,alg:"A256GCM",iv:e0(i),ciphertext:e0(new Uint8Array(n))};localStorage.setItem(e,JSON.stringify(o)),this.fallback.delete(e)}catch{this.durable=!1;try{localStorage.removeItem(e)}catch{}this.fallback.set(e,t)}}remove(e){this.fallback.delete(e);try{localStorage.removeItem(e)}catch{this.durable=!1}}keys(){let e=new Set(this.fallback.keys());if(this.durable)try{for(let t=0;t<localStorage.length;t++){let r=localStorage.key(t);r&&e.add(r)}}catch{this.durable=!1}return[...e]}getCryptoKey(){return this.keyPromise??=eQ(),this.keyPromise}};async function eQ(){if(!globalThis.crypto?.subtle||"u"<typeof indexedDB)throw Error("Durable browser cryptography is unavailable");let e=await globalThis.crypto.subtle.generateKey({name:"AES-GCM",length:256},!1,["encrypt","decrypt"]),t=await new Promise((e,t)=>{let r=indexedDB.open("mcp-use-oauth-crypto",1);r.onupgradeneeded=()=>{let e=r.result;e.objectStoreNames.contains(eJ)||e.createObjectStore(eJ)},r.onsuccess=()=>e(r.result),r.onerror=()=>t(r.error),r.onblocked=()=>t(Error("OAuth encryption database is blocked"))});try{return await new Promise((r,i)=>{let n,o=t.transaction(eJ,"readwrite"),s=o.objectStore(eJ),a=s.get(eG);a.onsuccess=()=>{(n=a.result)||(n=e,s.put(e,eG))},a.onerror=()=>i(a.error),o.oncomplete=()=>{n?r(n):i(Error("OAuth encryption key was not initialized"))},o.onerror=()=>i(o.error),o.onabort=()=>i(o.error)})}finally{t.close()}}function e0(e){let t="";for(let r of e)t+=String.fromCharCode(r);return btoa(t)}function e1(e){let t=atob(e),r=new Uint8Array(t.length);for(let e=0;e<t.length;e++)r[e]=t.charCodeAt(e);return r}function e2(e){let t,r=()=>{throw Error(`Invalid url to pass to open(): ${e}`)};try{t=new URL(e)}catch(e){r()}return"https:"!==t.protocol&&"http:"!==t.protocol&&r(),t.hostname!==encodeURIComponent(t.hostname)&&r(),t.username&&(t.username=encodeURIComponent(t.username)),t.password&&(t.password=encodeURIComponent(t.password)),t.pathname=t.pathname.slice(0,1)+encodeURIComponent(t.pathname.slice(1)).replace(/%2f/gi,"/"),t.search=t.search.slice(0,1)+Array.from(t.searchParams.entr
39ies()).map(e4).join("&"),t.hash=t.hash.slice(0,1)+encodeURIComponent(t.hash.slice(1)),t.href}function e4([e,t]){return`${encodeURIComponent(e)}${t.length>0?`=${encodeURIComponent(t)}`:""}`}var e3=class e{serverUrl;storageKeyPrefix;serverUrlHash;clientName;clientUri;logoUri;callbackUrl;clientMetadataUrl;scope;store;allowClientSecret;constructor(t,r,i){(0,d.validateClientMetadataUrl)(r.clientMetadataUrl),this.serverUrl=t,this.storageKeyPrefix=r.storageKeyPrefix||"mcp:auth",this.serverUrlHash=e.hashString(t),this.clientName=r.clientName||"mcp-use",this.clientUri=r.clientUri||("u">typeof window?window.location.origin:"https://mcp-use.com"),this.logoUri=r.logoUri||"https://mcp-use.com/logo.png",this.callbackUrl=e2(r.callbackUrl||("u">typeof window?new URL("/oauth/callback",window.location.origin).toString():"/oauth/callback")),this.clientMetadataUrl=r.clientMetadataUrl,this.scope=r.scope,this.store=i,this.allowClientSecret=r.allowClientSecret??!0}getKey(e){return`${this.storageKeyPrefix}_${this.serverUrlHash}_${e}`}static hashString(e){let t=0;for(let r=0;r<e.length;r++)t=(t<<5)-t+e.charCodeAt(r),t&=t;return Math.abs(t).toString(16)}get redirectUrl(){return this.callbackUrl}get clientMetadata(){return{redirect_uris:[this.redirectUrl],token_endpoint_auth_method:"none",grant_types:["authorization_code","refresh_token"],response_types:["code"],client_name:this.clientName,client_uri:this.clientUri,logo_uri:this.logoUri,...this.scope?{scope:this.scope}:{}}}credentialKey(e,t){return t?this.getKey(`${e}_${encodeURIComponent(t.issuer)}`):this.getKey(e)}async readCredential(e,t){let r=this.credentialKey(e,t),i=await this.store.get(r);if(!i&&t){let i=this.credentialKey(e),n=await this.store.get(i);if(n)try{let e=JSON.parse(n);if(!e.issuer||e.issuer===t.issuer){let n={...e,issuer:t.issuer},o=JSON.stringify(n);return await this.store.set(r,o),await this.store.set(i,o),{key:r,value:n}}}catch{await this.store.remove(i)}return}if(i)try{return{key:r,value:JSON.parse(i)}}catch(t){console.warn(`[${this.storageKeyPrefix}] Failed to parse ${e.replace("_"," ")}:`,t),await this.store.remove(r);return}}async tokens(e){return(await this.readCredential("tokens",e))?.value}async saveTokens(e,t){let r=JSON.stringify(e);await this.store.set(this.credentialKey("tokens",t),r),t&&await this.store.set(this.credentialKey("tokens"),r),await this.store.remove(this.getKey("code_verifier")),await this.store.remove(this.getKey("last_auth_url")),await this.store.remove(this.getKey("last_auth_callback_url"))}async clientInformation(e){if(!this.allowClientSecret&&await this.store.get(this.getKey("client_info_redirect_uri"))!==this.redirectUrl){await this.invalidateCredentials("registration"),console.info(`[${this.storageKeyPrefix}] Re-registering browser OAuth client after its Inspector callback changed or could not be verified.`);return}let t=await this.readCredential("client_info",e);if(!t)return;let{key:r,value:i}=t;try{if(!this.allowClientSecret&&i.client_secret){await this.invalidateCredentials("registration"),console.warn(`[${this.storageKeyPrefix}] Recovered stale browser OAuth credentials containing a client_secret.`);return}let e=Array.isArray(i.redirect_uris)?i.redirect_uris:[];if(!(0===e.length&&this.allowClientSecret||e.includes(this.redirectUrl))){console.info(`[${this.storageKeyPrefix}] Recovering cached OAuth credentials after a redirect URI change.`),await this.invalidateCredentials("registration");return}return i}catch{await this.store.remove(r);return}}async saveClientInformation(e,t){if(!this.allowClientSecret&&e.client_secret)throw await this.store.remove(this.credentialKey("client_info",t)),t&&await this.store.remove(this.credentialKey("client_info")),Error("Browser OAuth clients must be public clients; client_secret persistence is not allowed.");let r=JSON.stringify(this.allowClientSecret||"redirect_uris"in e&&Array.isArray(e.redirect_uris)&&0!==e.redirect_uris.length?e:{...e,redirect_uris:[this.redirectUrl]});await this.store.set(this.credentialKey("client_info",t),r),t&&await this.store.set(this.credentialKey("client_info"),r),this.allowClientSecret||await this.store.set(this.getKey("client_info_redirect_uri"),this.redirectUrl)}async saveCodeVerifier(e){await this.store.set(this.getKey("code_verifier"),e)}async codeVerifier(){let e=this.getKey("code_verifier"),t=await this.store.get(e);if(!t)throw Error(`[${this.storageKeyPrefix}] Code verifier not found in storage for key ${e}. Auth flow likely corrupted or timed out.`);return t}
39async invalidateCredentials(e){let t=async e=>{let t=`${this.getKey(e)}_`;for(let r of(await this.store.keys()))(r===this.getKey(e)||r.startsWith(t))&&await this.store.remove(r)};switch(e){case"registration":await t("tokens"),await t("client_info"),await this.store.remove(this.getKey("code_verifier")),await this.store.remove(this.getKey("last_auth_url")),await this.store.remove(this.getKey("last_auth_callback_url")),await this.store.remove(this.getKey("client_info_redirect_uri")),await this.store.remove(this.getKey("token_endpoint"));break;case"all":await t("tokens"),await t("client_info"),await this.store.remove(this.getKey("code_verifier")),await this.store.remove(this.getKey("last_auth_url")),await this.store.remove(this.getKey("last_auth_callback_url")),await this.store.remove(this.getKey("client_info_redirect_uri")),await this.store.remove(this.getKey("discovery_state")),await this.store.remove(this.getKey("token_endpoint"));break;case"client":await t("client_info");break;case"tokens":await t("tokens");break;case"verifier":await this.store.remove(this.getKey("code_verifier"));break;case"discovery":await this.store.remove(this.getKey("discovery_state"))}}async saveDiscoveryState(e){await this.store.set(this.getKey("discovery_state"),JSON.stringify(e))}async discoveryState(){let e=await this.store.get(this.getKey("discovery_state"));if(e)try{return JSON.parse(e)}catch{await this.store.remove(this.getKey("discovery_state"));return}}async storeAuthorizationState(e,t={}){let r=globalThis.crypto.randomUUID(),i=`${this.storageKeyPrefix}_${this.serverUrlHash}_state_${r}`,n={serverUrlHash:this.serverUrlHash,expiry:Date.now()+6e5,providerOptions:{serverUrl:this.serverUrl,storageKeyPrefix:this.storageKeyPrefix,clientName:this.clientName,clientUri:this.clientUri,callbackUrl:this.callbackUrl,...this.clientMetadataUrl?{clientMetadataUrl:this.clientMetadataUrl}:{},...t.extraProviderOptions??{}},flowType:t.flowType,returnUrl:t.returnUrl};e.searchParams.set("state",r);let o=e2(e.toString());return await this.store.set(i,JSON.stringify(n)),await this.store.set(this.getKey("last_auth_callback_url"),this.redirectUrl),await this.store.set(this.getKey("last_auth_url"),o),o}async getTokenEndpoint(){return(await this.discoveryState())?.authorizationServerMetadata?.token_endpoint??null}async getResource(){let e=(await this.discoveryState())?.resourceMetadata?.resource;return"string"==typeof e?e:null}};async function e6(e){return"string"==typeof e?e:e instanceof URLSearchParams||e instanceof FormData?Object.fromEntries(e.entries()):e instanceof Blob?await e.text():e}function e5(e){let t=e.length;for(;t>0&&47===e.charCodeAt(t-1);)t--;return e.slice(0,t)}var e8=class{serverUrl;staticClientInfo;session;storage;preventAutoAuth;useRedirectFlow;oauthProxyUrl;connectionUrl;proxyOAuthRequests;lastAttemptedAuthUrl=null;authorizationPending=!1;challengedResourceMetadataUrl;onPopupWindow;constructor(e,t={}){if(t.staticClientInfo?.client_secret)throw Error("Browser OAuth clients must be public clients; staticClientInfo.client_secret is not allowed.");this.serverUrl=e,this.storage=new eX,this.session=new e3(e,{...t,allowClientSecret:!1},this.storage),this.preventAutoAuth=t.preventAutoAuth,this.useRedirectFlow=t.useRedirectFlow,this.oauthProxyUrl=t.oauthProxyUrl,this.connectionUrl=t.connectionUrl,this.proxyOAuthRequests=t.proxyOAuthRequests??!0,this.staticClientInfo=t.staticClientInfo,this.onPopupWindow=t.onPopupWindow}get storageKeyPrefix(){return this.session.storageKeyPrefix}get serverUrlHash(){return this.session.serverUrlHash}get clientName(){return this.session.clientName}get clientUri(){return this.session.clientUri}get logoUri(){return this.session.logoUri}get callbackUrl(){return this.session.callbackUrl}get scope(){return this.session.scope}get clientMetadataUrl(){return this.session.clientMetadataUrl}getKey(e){return this.session.getKey(e)}get hasPendingFlow(){return this.authorizationPending}markFlowComplete(){this.authorizationPending=!1}reanchorWellKnownUrl(e){if(!this.connectionUrl)return e;try{let t=new URL(e),r=new URL(this.connectionUrl);if(t.origin!==r.origin||!t.pathname.startsWith("/.well-known/"))return e;let i=new URL(this.serverUrl),[n,...o]=t.pathname.slice(13).split("/");if(!n)return e;let s=o.length?`/${o.join("/")}`:"",a=e5(r.pathname),l=e5(i.pathname);return`${i.origin}/.well-known/${n}${s&&s===a?l:s}${t.search}`}catch{return e}}rememberResourceMetadataChallenge(e){if(401!==e.status)return!1;let{resourceMetadataUrl:t}=(0,d.extractWWWAuthenticateParams)(e);return!!t&&(this.challengedResourceMetadataUrl=t.toString(),!0)}getProxyFetch(e){let t=e??globalThis.fetch.bind(globalThis),r=this.proxyOAuthRequests&&this.oauthProxyUrl?this.oauthProxyUrl:void 0,i=new Set,n=!1;return async(e,o)=>{let s,a,l="string"==typeof e?e:e instanceof URL?e.toString():e.url,c=this.reanch
39orWellKnownUrl(l);try{s=new URL(c).pathname}catch{return await t(e,o)}let u=s.includes("/.well-known/");if(!r){let r=await t(u?c:e,u?{...o,cache:"no-store"}:o);return u||this.rememberResourceMetadataChallenge(r),r}if(!n){n=!0;let e=(await this.discoveryState())?.authorizationServerMetadata;for(let t of["registration_endpoint","token_endpoint","revocation_endpoint","introspection_endpoint"])"string"==typeof e?.[t]&&i.add(e[t])}let d=i.has(c)||/\/(?:register|registration|token|revoke|revocation|introspect|introspection)\/?$/.test(s);if(!u&&!d){let r=await t(e,o);return this.rememberResourceMetadataChallenge(r)&&i.clear(),r}try{let i=new URL(c),n=new URL(r);if(i.origin===n.origin&&(i.pathname.startsWith(n.pathname)||c.includes("/inspector/api/oauth")))return await t(e,o)}catch{}let h=u?`${r}/metadata?serverUrl=${encodeURIComponent(this.serverUrl)}&url=${encodeURIComponent(c)}`:`${r}/proxy`;if(u){let e=await t(h,{...o,method:"GET",cache:"no-store"});try{let t=await e.clone().json();for(let e of["registration_endpoint","token_endpoint","revocation_endpoint","introspection_endpoint"])"string"==typeof t[e]&&i.add(t[e])}catch{}return e}let p=e instanceof Request?e:void 0,f=o?.method??p?.method??"POST",m=o?.headers??p?.headers;o?.body!==void 0&&null!==o.body?a=await e6(o.body):p?.body&&"GET"!==f&&"HEAD"!==f&&(a=await p.clone().text());let g=await t(h,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({serverUrl:this.serverUrl,url:c,method:f,headers:m?Object.fromEntries(new Headers(m)):{},body:a})}),b=await g.json();return g.ok&&"number"==typeof b.status?new Response(JSON.stringify(b.body),{status:b.status,statusText:"string"==typeof b.statusText?b.statusText:void 0,headers:new Headers(b.headers&&"object"==typeof b.headers?b.headers:void 0)}):new Response(JSON.stringify(b),{status:g.status,statusText:g.statusText,headers:g.headers})}}get redirectUrl(){return this.session.redirectUrl}get clientMetadata(){return this.session.clientMetadata}tokens(e){return this.session.tokens(e)}saveTokens(e,t){return this.lastAttemptedAuthUrl=null,this.authorizationPending=!1,this.session.saveTokens(e,t)}async clientInformation(e){return this.staticClientInfo?this.staticClientInfo:this.session.clientInformation(e)}async saveClientInformation(e,t){if(this.staticClientInfo)return;let{client_secret:r,...i}=e;return r&&console.info(`[${this.storageKeyPrefix}] Discarded client_secret returned for a public browser OAuth client.`),this.session.saveClientInformation(i,t)}codeVerifier(){return this.session.codeVerifier()}saveCodeVerifier(e){return this.session.saveCodeVerifier(e)}invalidateCredentials(e){return this.session.invalidateCredentials(e)}saveDiscoveryState(e){return this.session.saveDiscoveryState(e)}async discoveryState(){let e=await this.session.discoveryState(),t=this.challengedResourceMetadataUrl;return(this.challengedResourceMetadataUrl=void 0,t&&e)?void await this.session.invalidateCredentials("discovery"):e}getTokenEndpoint(){return this.session.getTokenEndpoint()}getResource(){return this.session.getResource()}async getClientCredentials(){let e=await this.clientInformation();return e?.client_id?{client_id:e.client_id}:null}async prepareAuthorizationUrl(e){let t=await this.session.storeAuthorizationState(e,{extraProviderOptions:{oauthProxyUrl:this.oauthProxyUrl,...this.clientMetadataUrl?{clientMetadataUrl:this.clientMetadataUrl}:{},...this.staticClientInfo?{staticClientInfo:this.staticClientInfo}:{},...this.scope?{scope:this.scope}:{}},flowType:this.useRedirectFlow?"redirect":"popup",returnUrl:"u">typeof window?window.location.href:void 0});return this.lastAttemptedAuthUrl=t,this.authorizationPending=!0,t}async redirectToAuthorization(e){(await this.prepareAuthorizationUrl(e),this.preventAutoAuth)?console.info(`[${this.storageKeyPrefix}] Auto-auth prevented. Authorization URL stored for manual trigger.`):this.startAuthorization()}startAuthorization(){let e=this.lastAttemptedAuthUrl;if(!e)throw Error("No prepared OAuth authorization is available");if(this.useRedirectFlow){console.info(`[${this.storageKeyPrefix}] Redirecting to authorization URL (full-page redirect).`),window.location.href=e;return}let t="width=600,height=700,resizable=yes,scrollbars=yes,status=yes";try{let r=window.open(e,`mcp_auth_${this.serverUrlHash}`,t);this.onPopupWindow&&this.onPopupWindow(e,t,r),!r||r.closed||void 0===r.closed?console.warn(`[${this.storageKeyPrefix}] Popup likely blocked by browser. Manual navigation might be required using the stored URL.`):(r.focus(),console.info(`[${this.storageKeyPrefix}] Redirecting to authorization URL in popup.`))}catch(e){console.error(`[${this.storageKeyPrefix}] Error opening popup window:`,e)}}getLastAttemptedAuthUrl(){return this.lastAttemptedAuthUrl}clearStorage(){this.lastAttemptedAuthUrl=null,this.authorizationPending=!1;let e=`${this.storageKeyPrefix}_${this.serverUrlHash}_`,t=[],r=0;for(let r of this.storage.keys())r.startsWith(e)&&t.push(r);
39return[...new Set(t)].forEach(e=>{this.storage.remove(e),r++}),r}};async function e9(e,t={}){return new e8(e,t)}eb(),eb();var e7=class{},te=class extends e7{constructor(e){super(),this.data=e}get name(){return"mcp_agent_execution"}get properties(){return{execution_method:this.data.executionMethod,query_length:this.data.query.length,success:this.data.success,model_provider:this.data.modelProvider,model_name:this.data.modelName,server_count:this.data.serverCount,total_tools_available:this.data.totalToolsAvailable,max_steps_configured:this.data.maxStepsConfigured,memory_enabled:this.data.memoryEnabled,use_server_manager:this.data.useServerManager,max_steps_used:this.data.maxStepsUsed,manage_connector:this.data.manageConnector,external_history_used:this.data.externalHistoryUsed,steps_taken:this.data.stepsTaken??null,tools_used_count:this.data.toolsUsedCount??null,response_length:this.data.response?this.data.response.length:null,execution_time_ms:this.data.executionTimeMs??null,error_type:this.data.errorType??null,conversation_history_length:this.data.conversationHistoryLength??null}}},tt=class extends e7{constructor(e){super(),this.data=e}get name(){return"mcpclient_init"}get properties(){return{code_mode:this.data.codeMode,sandbox:this.data.sandbox,all_callbacks:this.data.allCallbacks,verify:this.data.verify,servers:this.data.servers,num_servers:this.data.numServers,is_browser:this.data.isBrowser}}},tr=class extends e7{constructor(e){super(),this.data=e}get name(){return"connector_init"}get properties(){return{connector_type:this.data.connectorType,server_command:this.data.serverCommand??null,server_args:this.data.serverArgs??null,server_url:this.data.serverUrl??null,public_identifier:this.data.publicIdentifier??null}}},ti=class extends e7{constructor(e){super(),this.data=e}get name(){return"client_add_server"}get properties(){let{serverName:e,serverConfig:t}=this.data,r=t.url;return{server_name:e,server_url_domain:r?this._extractHostname(r):null,transport:t.transport??null,has_auth:!!(t.authToken||t.authProvider)}}_extractHostname(e){try{return new URL(e).hostname}catch{return null}}},tn=class extends e7{constructor(e){super(),this.data=e}get name(){return"client_remove_server"}get properties(){return{server_name:this.data.serverName}}};async function to(e,t){try{await fetch(e,t)}catch{}}var ts=/(^|_)(arguments?|args|body|command|headers?|location|message|query|response|secret|subject|token|uri|url|user_agent)(_|$)/i,ta=/(^|_)(server_identifiers?|server_names?|servers|tool_names?|tools_(available|used)_names)(_|$)/i,tl=/(_count|_length|_duration(?:_ms)?|_time_ms|(^|_)num_[a-z0-9_]+)$/i;async function tc(e){try{let t=e.host??"https://eu.i.posthog.com",r=e.apiKey??"phc_lyTtbYwvkdSbrcMQNPiKiiRWrrM1seyKIMjycSvItEI",i=JSON.stringify({api_key:r,event:e.event,distinct_id:e.distinctId,properties:function e(t,r=new WeakSet){let i={};for(let[n,o]of Object.entries(t)){let t=n.replace(/([a-z0-9])([A-Z])/g,"$1_$2").replace(/[^a-z0-9_$]+/gi,"_").toLowerCase();if(tl.test(t)){(null===o||"number"==typeof o)&&(i[n]=o);continue}ta.test(t)||ts.test(t)||(i[n]=function t(r,i){if(Array.isArray(r)){if(i.has(r))throw TypeError("Cyclic telemetry properties are not supported");i.add(r);let e=r.map(e=>t(e,i));return i.delete(r),e}if(null!==r&&"object"==typeof r&&(Object.getPrototypeOf(r)===Object.prototype||null===Object.getPrototypeOf(r))){if(i.has(r))throw TypeError("Cyclic telemetry properties are not supported");i.add(r);let t=e(r,i);return i.delete(r),t}return r}(o,r))}return i}(e.properties),timestamp:new Date().toISOString()});await to(`${t}/i/v0/e/`,{method:"POST",headers:{"Content-Type":"application/json"},keepalive:!0,body:i})}catch{}}function tu(){return globalThis.crypto.randomUUID()}var td="mcp_use_user_id",th="phc_lyTtbYwvkdSbrcMQNPiKiiRWrrM1seyKIMjycSvItEI",tp="https://eu.i.posthog.com";function tf(){return"u">typeof localStorage&&"function"==typeof localStorage.getItem&&"function"==typeof localStorage.setItem&&"function"==typeof localStorage.removeItem}var tm=class e{static instance=null;UNKNOWN_USER_ID="UNKNOWN_USER_ID";_currUserId=null;_telemetryEnabled=!1;_pending=new Set;_runtimeEnvironment;_storageCapability;_storage;_source;_productVersion;constructor(){this._runtimeEnvironment=function(){try{if(void 0!==globalThis.Bu
39n)return"bun";if(void 0!==globalThis.Deno)return"deno";if("u">typeof navigator&&navigator.userAgent?.includes("Cloudflare-Workers"))return"cloudflare-workers";if(void 0!==globalThis.EdgeRuntime)return"edge";if("u">typeof window&&"u">typeof document)return"browser";if(void 0!==u.default&&void 0!==u.default.versions?.node)return"node";return"unknown"}catch{return"unknown"}}(),this._storage=function(){if(!tf())return null;try{localStorage.setItem("__mcp_use_test__","1"),localStorage.removeItem("__mcp_use_test__")}catch{return null}return{getUserId(){try{return localStorage.getItem(td)}catch{return null}},setUserId(e){try{localStorage.setItem(td,e)}catch{}}}}()??null,this._storageCapability=this._storage?"persistent":"session-only",this._source=function(){if(void 0!==u.default&&u.default.env?.MCP_USE_TELEMETRY_SOURCE)return u.default.env.MCP_USE_TELEMETRY_SOURCE;try{if(tf())return localStorage.getItem("MCP_USE_TELEMETRY_SOURCE")??void 0}catch{}}()||this._runtimeEnvironment;const e=function(){if("u">typeof window&&!1===window.__MCP_USE_ANONYMIZED_TELEMETRY__||void 0!==u.default&&u.default.env?.MCP_USE_ANONYMIZED_TELEMETRY?.toLowerCase()==="false")return!0;try{if(tf()&&"false"===localStorage.getItem("MCP_USE_ANONYMIZED_TELEMETRY"))return!0}catch{}return!1}(),t="unknown"!==this._runtimeEnvironment;e?(this._telemetryEnabled=!1,o.debug("Telemetry disabled via opt-out")):t?(o.debug("Anonymized telemetry enabled. Set MCP_USE_ANONYMIZED_TELEMETRY=false to disable."),this._telemetryEnabled=!0):(this._telemetryEnabled=!1,o.debug(`Telemetry disabled - unknown environment: ${this._runtimeEnvironment}`))}get runtimeEnvironment(){return this._runtimeEnvironment}get storageCapability(){return this._storageCapability}static getInstance(){return e.instance||(e.instance=new e),e.instance}setSource(e){this._source=e;try{tf()&&localStorage.setItem("MCP_USE_TELEMETRY_SOURCE",e)}catch{}o.debug(`Telemetry source set to: ${e}`)}getSource(){return this._source}setProductVersion(e){this._productVersion=e}get isEnabled(){return this._telemetryEnabled}get userId(){if(this._currUserId)return this._currUserId;try{if(this._storage){let e=this._storage.getUserId();if(e)return this._currUserId=e,e;let t=tu();return this._storage.setUserId(t),this._currUserId=t,t}this._currUserId=function(){try{return`session-${tu()}`}catch{let e;return`session-${Date.now()}-${e=new Uint8Array(8),globalThis.crypto.getRandomValues(e),Array.from(e,e=>e.toString(16).padStart(2,"0")).join("")}`}}()}catch{this._currUserId=this.UNKNOWN_USER_ID}return this._currUserId}async capture(e){if(!this._telemetryEnabled)return;let t=this.userId,r={...e.properties,mcp_use_version:this._productVersion??eB(),language:"typescript",source:this._source,runtime:this._runtimeEnvironment},i=tc({host:tp,apiKey:th,event:e.name,distinctId:t,properties:r});this._pending.add(i),i.finally(()=>this._pending.delete(i))}async trackAgentExecution(e){this.isEnabled&&await this.capture(new te(e))}async trackMCPClientInit(e){this.isEnabled&&await this.capture(new tt(e))}async trackConnectorInit(e){this.isEnabled&&await this.capture(new tr(e))}async trackClientAddServer(e,t){this.isEnabled&&await this.capture(new ti({serverName:e,serverConfig:t}))}async trackClientRemoveServer(e){this.isEnabled&&await this.capture(new tn({serverName:e}))}async trackUseMcpConnection(e){this.isEnabled&&await this.capture({name:"usemcp_connection",properties:{url_domain:new URL(e.url).hostname,transport_type:e.transportType,success:e.success,error_type:e.errorType??null,connection_time_ms:e.connectionTimeMs??null,has_oauth:e.hasOAuth,has_sampling:e.hasSampling,has_elicitation:e.hasElicitation}})}async trackUseMcpToolCall(e){this.isEnabled&&await this.capture({name:"usemcp_tool_call",properties:{tool_name:e.toolName,success:e.success,error_type:e.errorType??null,execution_time_ms:e.executionTimeMs??null}})}async trackUseMcpResourceRead(e){this.isEnabled&&await this.capture({name:"usemcp_resource_read",properties:{resource_uri_scheme:e.resourceUri.split(":")[0],success:e.success,error_type:e.errorType??null}})}identify(e,t){this._currUserId=e,this._storage?.setUserId(e),this._telemetryEnabled&&tc({host:tp,apiKey:th,event:"$identify",distinctId:e,properties:{$set:t??{}}})}reset(){this._currUserId=null}flush(){Promise.allSettled([...this._pending])}async shutdown(){try{await Promise.allSettled([...this._pending]),o.debug("Telemetry fetch captures flushed")}catch(e){o.debug(`Error flushing telemetry captures: ${e}`)}}};eb();var tg=class{connector;autoConnect;constructor(e,t=!0){this.connector=e,this.autoConnect=t}async connect(){await this.connector.connect()}async disconnect(){await this.connector.disconnect()}async initialize(){!this.isConnected&&this.autoConnect&&await this.connect(),await this.connector.initialize()}get isConnected(){return this.connector&&this.connector.isClientConnected}on(e,t){"notification"===e&&this.connector.onNotification(t)}async setRoots(e){return this.connector.setRoots(e)}getRoots(){return this.connector.getRoots()}get tools(){return this.connector.tools}async listTools(e){return this.connector.listTools(e)}get serverCapabilities(){return this.connector.serverCapabilities}get serverInfo(){return this.connector.serverInfo}get authorization(){return this.connector.authorization}async discoverAuthorization(){return this.connector.discoverAuthorization()}async authenticate(){await this.connector.authenticate()}get protocolEra(){return this.connector.protocolEra}get negotiatedProtocolVersion(){return this.connector.negotiatedProtocolVersion}get info(){let e=this.protocolEra,t=this.negotiatedProtocolVersion,r=this.serverInfo;if(!e||!t)throw Error("MCP connection is not initialized");let i=this.serverCapabilities,n=i.extensions&&"object"==typeof i.extensions&&!Array.isArray(i.extensions)?i.extensions:{};return{protocolEra:e,protocolVersion:t,...r?{server:r}:{},capabilities:i,instructions:this.connector.instructions,extensions:n,...this.authorization?{authorization:this.authorization}:{}}}supports(e){return e in this.serverCapabilities}async callTool(e,t={},r){return this.connector.callTool(e,t,r)}async listResources(e,t){return this.connector.listResources(e,t)}async listAllResources(e){return this.connector.listAllResources(e)}async listResourceTemplates(e){return this.connector.listResourceTemplates(e)}async complete(e,t){return this.connector.complete(e,t)}async readResource(e,t){return this.connector.readResource(e,t)}async subscribeToResource(e,t){return this.connector.subscribeToResource(e,t)}async unsubscribeFromResource(e,t){return this.connector.unsubscribeFromResource(e,t)}async listPrompts(){return this.connector.listPrompts()}async getPrompt(e,t,r){return this.connector.getPrompt(e,t,r)}
39async request(e,t=null,r){return this.connector.request(e,t,r)}async listSkills(e,t){return await this.request("skills/list",void 0===e?{}:{cursor:e},t)}async listAllSkills(e){let t,r=[],i=new Set;do{let n=await this.listSkills(t,e);if(r.push(...Array.isArray(n.skills)?n.skills:[]),void 0!==(t=n.nextCursor)){if(i.has(t))throw Error("skills/list returned a repeated pagination cursor");i.add(t)}}while(void 0!==t)return{skills:r}}async getSkill(e,t){return await this.request("skills/get",{uri:e},t)}async readResourceDirectory(e,t,r){return await this.request("resources/directory/read",void 0===t?{uri:e}:{uri:e,cursor:t},r)}},tb=class{config={};sessions={};sessionDisconnects=new WeakMap;activeSessions=[];constructor(e){e&&(this.config=e)}disconnectSession(e){let t=this.sessionDisconnects.get(e);if(t)return t;let r=Promise.resolve().then(()=>e.disconnect());return this.sessionDisconnects.set(e,r),r}static fromDict(e){throw Error("fromDict must be implemented by concrete class")}addServer(e,t){this.config.mcpServers=this.config.mcpServers||{},this.config.mcpServers[e]=t,c?.addServer(e,t)}async removeServer(e){this.config.mcpServers?.[e]&&(await this.closeSession(e),delete this.config.mcpServers[e],c?.removeServer(e))}getServerNames(){return Object.keys(this.config.mcpServers??{})}getServerConfig(e){return this.config.mcpServers?.[e]}getConfig(){return this.config??{}}async createSession(e,t=!0){let r,i,n=this.config.mcpServers??{};if(0===Object.keys(n).length&&o.warn("No MCP servers defined in config"),!n[e])throw Error(`Server '${e}' not found in config`);let s={...n[e]};if(function(e){if(!("url"in e)||"string"!=typeof e.url||e.authProvider||e.authToken||!1===e.oauth)return!1;let t=e.headers;if(t){for(let e of Object.keys(t))if("authorization"===e.toLowerCase())return!1}return!0}(s)){let e=!1===s.oauth?void 0:s.oauth??{};r=await this.createDefaultOAuthProvider(s.url,e),s={...s,authProvider:r}}else{var a;"authProvider"in s&&s.authProvider&&(a=s.authProvider)&&"object"==typeof a&&"redirectUrl"in a&&"clientMetadata"in a&&(r=s.authProvider)}let l=async()=>{let e=new tg(await Promise.resolve(this.createConnectorFromConfig(s)));return t&&await e.initialize(),e};try{i=await l()}catch(a){let n=s;if(!t||!r||!("url"in n)||!eL(a)||r.preventAutoAuth)throw a;o.info(`[MCPClient] Unauthorized connecting to '${e}'; completing OAuth\u2026`),await eH(r,n.url),i=await l()}let c=this.sessions[e];if(this.sessions[e]=i,this.activeSessions.includes(e)||this.activeSessions.push(e),c&&c!==i)try{o.debug(`Disconnecting replaced session for server ${e}`),await this.disconnectSession(c)}catch(t){o.error(`Error disconnecting replaced session for server '${e}': ${t}`)}return i}async connect(e){return this.createSession(e)}async createAllSessions(e=!0){let t=this.config.mcpServers??{};for(let r of(0===Object.keys(t).length&&o.warn("No MCP servers defined in config"),Object.keys(t)))await this.createSession(r,e);return this.sessions}async connectAll(){return this.createAllSessions()}getSession(e){let t=this.sessions[e];return t||null}requireSession(e){let t=this.sessions[e];if(!t)throw Error(`Session '${e}' not found. Available sessions: ${this.activeSessions.join(", ")||"none"}`);return t}getAllActiveSessions(){return Object.fromEntries(this.activeSessions.map(e=>[e,this.sessions[e]]))}async closeSession(e){let t=this.sessions[e];if(!t)return void o.warn(`No session exists for server ${e}, nothing to close`);try{o.debug(`Closing session for server ${e}`),await this.disconnectSession(t)}catch(t){o.error(`Error closing session for server '${e}': ${t}`)}finally{this.sessions[e]===t&&(delete this.sessions[e],this.activeSessions=this.activeSessions.filter(t=>t!==e))}}async closeAllSessions(){let e=Object.keys(this.sessions),t=[];for(let r of e)try{o.debug(`Closing session for server ${r}`),await this.closeSession(r)}catch(i){let e=`Failed to close session for server '${r}': ${i}`;o.error(e),t.push(e)}t.length?o.error(`Encountered ${t.length} errors while closing sessions`):o.debug("All sessions closed successfully")}async close(){await this.closeAllSessions()}},tv=class e extends tb{static getPackageVersion(){return eB()}constructor(e){super(e),function(e){let t=Object.keys(e.mcpServers??{});tm.getInstance().trackMCPClientInit({codeMode:!1,sandbox:!1,allCallbacks:!1,verify:!1,servers:t,numServers:t.length,isBrowser:!0}).catch(e=>o.debug(`Failed to track BrowserMCPClient init: ${e}`))}(this.config)}static fromDict(t){return new e(t)}async createDefaultOAuthProvider(e,t={}){return e9(e,t)}createConnectorFromConfig(e){var t;let r,i,{url:n,headers:s,fetch:a,authToken:l,authProvider:c,detectMixedAuth:u,wrapTransport:d,clientOptions:h,protocolNegotiation:p,timeout:f,gatewayUrl:m,serverId:g,reconnectionOptions:b}=e;if(!n)throw Error("Server URL is required");let v=this.config,y=(r=e?.onSampling??v?.onSampling,{onSampling:r,onElicitation:e?.onElicitation??v?.onElicitation,onNotification:e?.onNotification??v?.onNotification}
39),w=(t=e.clientInfo??this.config.clientInfo,i={name:"mcp-use",title:"mcp-use",version:eB(),description:"mcp-use is a complete TypeScript framework for building and using MCP",icons:[{src:"https://mcp-use.com/logo.png"}],websiteUrl:"https://mcp-use.com"},t&&"object"==typeof t&&t.name&&t.version?{...i,...t}:i),C={headers:s,fetch:a??globalThis.fetch.bind(globalThis),authToken:l,authProvider:c,detectMixedAuth:u,wrapTransport:d,clientOptions:h,onSampling:y.onSampling,onElicitation:y.onElicitation,onNotification:y.onNotification,protocolNegotiation:p,timeout:f,clientInfo:w,gatewayUrl:m,serverId:g,reconnectionOptions:b};return o.debug(`[BrowserMCPClient] Connector options prepared (clientOptions: ${h?"provided":"none"})`),new eV(n,C)}};eb();var ty=/^\d{1,3}(\.\d{1,3}){3}$/;async function tw(e){try{let t,r=function(e){try{let t=e.includes("://")?e:`https://${e}`;return new URL(t).hostname}catch{return null}}(e);if(!r||function(e){let t=e.toLowerCase();if("localhost"===t||t.endsWith(".localhost")||"host.docker.internal"===t||"0.0.0.0"===t)return!0;if(!ty.test(t))return!1;if("127.0.0.1"===t||t.startsWith("127.")||t.startsWith("10.")||t.startsWith("192.168."))return!0;let r=/^172\.(\d+)\./.exec(t);if(r){let e=Number.parseInt(r[1],10);if(e>=16&&e<=31)return!0}return!1}(r))return null;for(let e of(t=r.split("."),Array.from({length:t.length-1},(e,r)=>t.slice(r).join("."))))try{let t=await fetch(`https://favicon.tools.mcp-use.com/${e}?response=json`,{signal:AbortSignal.timeout(2e3)});if(!t.ok)continue;let r=await t.json();if("default"===r.source)continue;let i=r.url.replace(/^http:\/\//,"https://"),n=await fetch(i,{signal:AbortSignal.timeout(2e3)});if(!n.ok)continue;return await function(e){return new Promise((t,r)=>{let i=new FileReader;i.onloadend=()=>t(i.result),i.onerror=r,i.readAsDataURL(e)})}(await n.blob())}catch{continue}return null}catch(e){return console.warn("[favicon] Error detecting favicon:",e),null}}var tC="inspector-server";function t_(e,t){if(!e)throw Error(t)}async function tR(e){try{let t=e.serverInfo.icons?.[0]?.src;if(t){e.addLog("info","Server provided icon:",t);let r=await fetch(t),i=await r.blob(),n=await new Promise((e,t)=>{let r=new FileReader;r.onloadend=()=>e(r.result),r.onerror=t,r.readAsDataURL(i)});return e.isMounted()&&(e.setServerInfo(e=>e?{...e,icon:n}:void 0),e.addLog("debug","Server icon converted to base64")),n}if(e.url){let t=await tw(e.url);if(!e.isMounted())return e.addLog("debug","Connection aborted after favicon detection - component unmounted"),null;if(t)return e.setServerInfo(e=>e?{...e,icon:t}:void 0),e.addLog("debug","Favicon detected and added to serverInfo"),t}return null}catch(t){return e.addLog("debug","Icon loading failed (non-critical):",t),null}}function tS(e){let t=function(e,t){if(t)return t;if(e)try{let t=new URL(e);return t.pathname=t.pathname.replace(/\/proxy\/?$/,"/oauth"),t.toString()}catch{return}}(e.gatewayUrl,e.oauthProxyUrl);return{provider:new e8(e.effectiveOAuthUrl,{storageKeyPrefix:e.storageKeyPrefix,clientName:e.oauthClientConfig.name,clientUri:e.oauthClientConfig.uri,logoUri:e.oauthClientConfig.logo_uri||"https://mcp-use.com/logo.png",callbackUrl:e.callbackUrl,preventAutoAuth:e.preventAutoAuth,useRedirectFlow:e.useRedirectFlow,oauthProxyUrl:t,connectionUrl:e.gatewayUrl,onPopupWindow:e.onPopupWindow,proxyOAuthRequests:e.proxyOAuthRequests,staticClientInfo:e.staticClientInfo,clientMetadataUrl:e.clientMetadataUrl,scope:e.scope}),oauthProxyUrl:t}}function tk(e,t){let r=e.connectionRef.current;if("ready"!==e.stateRef.current||!e.hasClient()||!r){var i;throw Error(`MCP client is not ready (${(i=e.stateRef.current,e.hasClient()?`state=${i}`:`client disconnected (state=${i})`)}). Cannot ${t}.`)}return r}async function tx(e,t){try{return await t()}catch(t){throw eO(t)&&e.onAuthorizationRequired(t),t}}function tE(e){var t,r;let i,o,s,a,l,c,u,p,f,m,g,b,v,{url:y,enabled:w=!0,callbackUrl:C="u">typeof window?e2(new URL("/oauth/callback",window.location.origin).toString()):"/oauth/callback",storageKeyPrefix:_="mcp:auth",authProvider:R,headers:S,proxyConfig:k,oauthProxyUrl:x,connectionMode:E,autoProxyFallback:z=!1,logLevel:A="silent",autoRetry:P=!1,autoReconnect:U=!0,reconnectionOptions:T,preventAutoAuth:M=!0,detectMixedAuth:I=!0,useRedirectFlow:q=!1,onPopupWindow:L,timeout:O=3e4,wrapTransport:H,serverId:N,fetch:j,clientOptions:$,protocolNegotiation:D,onNotification:F,onSampling:K,onElicitation:W,oauth:V}=e,B=e.clientInfo,J=B?.name,G=B?.title,Y=B?.version,Z=B?.description,X=B?.websiteUrl,Q=void 0===(t=B?.icons)?"null":0===t.length?"[]":JSON.stringify(t.map(e=>[e.src,void 0===e.mimeType?null:e.mimeType,void 0===e.sizes?null:[...e.sizes].sort()])),ee=(0,h.useMemo)(()=>
39{if(B)return{...B}},[J,G,Y,Z,X,Q]),et=k?.proxyAddress,er=function(e,t){if(void 0===e&&void 0===t)return"";let r=e=>void 0===e?"null":JSON.stringify(Object.keys(e).sort().map(t=>[t,e[t]]));return`${r(e)}|${r(t)}`}(k?.headers,k?.customHeaders),ei=(0,h.useMemo)(()=>{if(k)return{...k}},[et,er]),en=S??{},eo="http",es=ei?.proxyAddress,ea=V?.clientId?.trim()||void 0,el=V?.clientMetadataUrl?.trim()||void 0,ec=V?.scope?.trim()||void 0,eu=(0,h.useMemo)(()=>ea?{client_id:ea}:void 0,[ea]),ed=(0,h.useMemo)(()=>{let e=`useMcp:${y||"no-url"}`,t=n.get(e);return A&&(t.level=A),t},[y,A]),eh=(0,h.useMemo)(()=>(function(e){let t=e?.capabilities;if(!t||!0!==t.views)return e;let{views:r,...i}=t,n=i.extensions&&"object"==typeof i.extensions&&!Array.isArray(i.extensions)?{...i.extensions}:{};return{...e,capabilities:{...i,extensions:{...n,"io.modelcontextprotocol/ui":{mimeTypes:["text/html;profile=mcp-app"]}}}}})($),[$]),ep=(0,h.useMemo)(()=>({name:"mcp-use",title:"mcp-use",version:eB(),description:"mcp-use is a complete TypeScript framework for building and using MCP",icons:[{src:"https://mcp-use.com/logo.png"}],websiteUrl:"https://mcp-use.com"}),[]),ef=(0,h.useMemo)(()=>ee?{...ep,...ee}:ep,[ee,ep]),em=(0,h.useMemo)(()=>({name:ef.name,version:ef.version,uri:ef.websiteUrl,logo_uri:ef.icons?.[0]?.src}),[ef]),eg=(0,h.useMemo)(()=>{if("direct"===E||"proxy"===E||!z)return{enabled:!1,proxyAddress:void 0};if("boolean"==typeof z){let e=ei?.proxyAddress;return{enabled:z&&!!e,proxyAddress:e}}let e=z.proxyAddress??ei?.proxyAddress;return{enabled:!1!==z.enabled&&!!e,proxyAddress:e}},[z,E,ei]),eb=(0,h.useMemo)(()=>!1===U?{enabled:!1,initialDelay:0,healthCheckInterval:!1,healthCheckTimeout:3e4}:!0===U?{enabled:!0,initialDelay:3e3,healthCheckInterval:1e4,healthCheckTimeout:3e4}:"number"==typeof U?{enabled:!0,initialDelay:U,healthCheckInterval:1e4,healthCheckTimeout:3e4}:{enabled:!1!==U.enabled,initialDelay:U.initialDelay??3e3,healthCheckInterval:U.healthCheckInterval??1e4,healthCheckTimeout:U.healthCheckTimeout??3e4},[U]),[ev,ey]=(0,h.useState)(void 0);(0,h.useEffect)(()=>{ey(void 0)},[y,es,E,eg.proxyAddress]);let ew=(0,h.useMemo)(()=>{if(eg.enabled&&ev?.proxyAddress===eg.proxyAddress&&ev){let e=ei?.headers??{};return{...ev,headers:{...e,...ev.headers??{}}}}return"auto"===E||"direct"===E||void 0===E&&eg.enabled?void 0:ei},[ev,ei,E,eg.enabled,eg.proxyAddress]),eC=ew?.proxyAddress,e_=ew?.headers??{},eR=(0,h.useMemo)(()=>y||"",[y]),eS=(0,h.useMemo)(()=>({...e_,...en}),[e_,en]),[ek,ex]=(0,h.useState)("discovering"),[ez,eA]=(0,h.useState)([]),[eP,eM]=(0,h.useState)([]),[eq,eO]=(0,h.useState)([]),[eH,eN]=(0,h.useState)([]),[ej,e$]=(0,h.useState)([]),[eD,eF]=(0,h.useState)(e._initialServerInfo?.name?e._initialServerInfo:void 0),[eK,eW]=(0,h.useState)(),[eV,eJ]=(0,h.useState)(void 0),[eG,eY]=(0,h.useState)(void 0),[eZ,eX]=(0,h.useState)(),[eQ,e0]=(0,h.useState)({}),[e1,e4]=(0,h.useState)(void 0),[e3,e6]=(0,h.useState)([]),[e5,e8]=(0,h.useState)(void 0),[e9,e7]=(0,h.useState)(void 0),[te,tt]=(0,h.useState)(void 0),tr=(0,h.useRef)(null),ti=(0,h.useRef)(null),tn=(0,h.useRef)(R??null),to=(0,h.useRef)(null),ts=(0,h.useRef)(!1),ta=(0,h.useRef)(!0),tl=(0,h.useRef)(0),tc=(0,h.useRef)(0),tu=(0,h.useRef)(null),td=(0,h.useRef)(!1),th=(0,h.useRef)(!1),tp=(0,h.useRef)(ek),tf=(0,h.useRef)(te),tg=(0,h.useRef)(y);tf.current=te;let tb=(0,h.useRef)(U),ty=(0,h.useRef)(null),tw=(0,h.useRef)(null),tE=(0,h.useRef)(null),tz=(0,h.useRef)(K),tA=(0,h.useRef)(W),tP=(0,h.useRef)(void 0!==K),t
39U=(0,h.useRef)(void 0!==W),tT=(0,h.useRef)(F);void 0!==K&&(tz.current=K),void 0!==W&&(tA.current=W),tP.current=void 0!==K,tU.current=void 0!==W,tT.current=F;let tM=(0,h.useCallback)(async e=>tz.current(e),[]),tI=(0,h.useCallback)(async e=>tA.current(e),[]),tq=(0,h.useCallback)(e=>{tT.current?.(e)},[]);(0,h.useEffect)(()=>{tp.current=ek,tb.current=U},[ek,U]),(0,h.useEffect)(()=>{tn.current=R??null},[R]);let tL=(0,h.useCallback)((e,t,...r)=>{let i=r.length>0?`${t} ${r.map(e=>JSON.stringify(e)).join(" ")}`:t,n=`[useMcp] ${i}`;switch(e){case"error":ed.error(n);break;case"warn":ed.warn(n);break;case"info":default:ed.info(n);break;case"debug":ed.debug(n)}ta.current&&e6(t=>[...t.slice(-100),{level:e,message:i,timestamp:Date.now()}])},[ed]),tO=(0,h.useCallback)(e=>{let t=tn.current?.getLastAttemptedAuthUrl?.()??void 0;tL("info","This server requires OAuth for the requested operation; waiting for authentication.",e);let r={...tf.current??{mode:"mixed"},authenticated:!1};tf.current=r,tt(r),t&&e8(t)},[tL]),tH=(r={stateRef:tp,connectionRef:ti,hasClient:()=>null!==tr.current,isMounted:()=>ta.current,setTools:eA,setResources:eM,setResourceTemplates:eO,setPrompts:eN,setSkills:e$,addLog:tL,onAuthorizationRequired:tO},i=(0,h.useCallback)(async(e,t,i)=>{let n=tk(r,`call tool "${e}"`);r.addLog("info",`Calling tool: ${e}`,t);let o=Date.now();try{let s=await tx(r,()=>n.callTool(e,t||{},i));return r.addLog("info",`Tool "${e}" call successful:`,s),tm.getInstance().trackUseMcpToolCall({toolName:e,success:!0,executionTimeMs:Date.now()-o}).catch(()=>{}),s}catch(t){throw r.addLog("error",`Tool "${e}" call failed:`,t),tm.getInstance().trackUseMcpToolCall({toolName:e,success:!1,errorType:t instanceof Error?t.name:"UnknownError",executionTimeMs:Date.now()-o}).catch(()=>{}),t}},[r.addLog,r.onAuthorizationRequired]),o=(0,h.useCallback)(async()=>{let e=tk(r,"list resources");r.addLog("info","Listing resources");let t=await tx(r,()=>e.listAllResources());r.setResources(t.resources||[])},[r.addLog,r.onAuthorizationRequired]),s=(0,h.useCallback)(async e=>{let t=tk(r,"read resource");r.addLog("info",`Reading resource: ${e}`);try{let i=await tx(r,()=>t.readResource(e));return tm.getInstance().trackUseMcpResourceRead({resourceUri:e,success:!0}).catch(()=>{}),i}catch(t){throw tm.getInstance().trackUseMcpResourceRead({resourceUri:e,success:!1,errorType:t instanceof Error?t.name:"UnknownError"}).catch(()=>{}),t}},[r.addLog,r.onAuthorizationRequired]),a=(0,h.useCallback)(async()=>{let e=tk(r,"list skills");r.addLog("info","Listing skills");let t=await tx(r,()=>e.listAllSkills());r.setSkills(t.skills)},[r.addLog,r.onAuthorizationRequired]),l=(0,h.useCallback)(async e=>{let t=tk(r,"get skill");return r.addLog("info",`Getting skill: ${e}`),tx(r,()=>t.getSkill(e))},[r.addLog,r.onAuthorizationRequired]),c=(0,h.useCallback)(async(e,t)=>{let i=tk(r,"read resource directory");return r.addLog("info",`Reading resource directory: ${e}`),tx(r,()=>i.readResourceDirectory(e,t))},[r.addLog,r.onAuthorizationRequired]),u=(0,h.useCallback)(async()=>{let e=tk(r,"list prompts");r.addLog("info","Listing prompts");let t=await tx(r,()=>e.listPrompts());r.setPrompts(t.prompts||[])},[r.addLog,r.onAuthorizationRequired]),p=(0,h.useCallback)(async()=>{if("ready"===r.stateRef.current&&r.connectionRef.current)try{r.setTools(await tx(r,()=>r.connectionRef.current.listTools())||[])}catch(e){r.addLog("error","Failed to refresh tools:",e)}},[r.addLog,r.onAuthorizationRequired]),f=(0,h.useCallback)(async()=>{if("ready"===r.stateRef.current&&r.connectionRef.current)try{let e=await tx(r,()=>r.connectionRef.current.listAllResources());r.setResources(e.resources||[])}catch(e){r.addLog("warn","Failed to refresh resources:",e)}},[r.addLog,r.onAuthorizationRequired]),m=(0,h.useCallback)(async()=>{if("ready"===r.stateRef.current&&r.connectionRef.current)try{let e=await tx(r,()=>r.connectionRef.current.listPrompts());r.setPrompts(e.prompts||[])}catch(e){r.addLog("warn","Failed to refresh prompts:",e)}},[r.addLog,r.onAuthorizationRequired]),g=(0,h.useCallback)(async()=>{if("ready"===r.stateRef.current&&r.connectionRef.current)try{let e=await tx(r,()=>r.connectionRef.current.listAllSkills());r.setSkills(e.skills)}catch(e){r.setSkills([]),r.addLog("debug","Skills are unavailable after refresh:",e)}},[r.addLog,r.onAuthorizationRequired]),b=(0,h.useCallback)(async()=>{let e=tk(r,"refresh resource templates"),t=await tx(r,()=>e.listResourceTemplates());r.isMounted()&&r.setResourceTemplates(t.resourceTemplates||[])},[r.addLog,r.onAuthorizationRequired]),v=(0,h.useCallback)(()=>Promise.all([p(),f(),b(),m()]).then(()=>void 0),[p,f,b,m]),{callTool:i,listResources:o,readResource:s,listSkills:a,getSkill:l,readResourceDirectory:c,listPrompts:u,refreshTools:p,refreshResources:f,refreshPrompts:m,refreshSkills:g,refreshResourceTemplates:b,refreshAll:v,getPrompt:(0,h.useCallback)(async(e,t)=>{let i=tk(r,"get prompt");return tx(r,()=>i.getPrompt(e,t||{}))},[r.addLog,r.onAuthorizationRequired]),complete:(0,h.useCallback)(async e=>{let t=tk(r,"request completion");return tx(r,()=>t.complete(e))},[r.addLog,r.onAuthorizationRequired])}),tN=(0,h.useCallback)(async(e=!1)=>{e||tL("info","Disconnecting..."),ts.current=!1,tu.current&&clearTimeout(tu.current),tu.current=null;let t=tc.current,r=tr.current;if(r)try{let e=r===tr.current?ti.current:null;e&&e._healthCheckCleanup&&(e._healthCheckCleanup(),e._healthCheckCleanup=null),e&&await r.closeSession(tC)}catch(t){e||tL("warn","Error closing connection:",t)}let i=tc.current!==t;tr.current!==r||i||(tr.current=null,ti.current=null),!ta.current||e||i||(ex("discovering"),eA([]),eM([]),eO([]),eN([]),e$([]),e4(void 0),e8(void 0),e7(void 0),eF(void 0),eW(void 0),eJ(void 0),eY(void 0),eX(void 0),e0({}))},[tL]),tj=(0,h.useCallback)((e,t)=>{tL("error",e,t??"");let r=t&&"code"in t?t.code:void 0,i=eg.enabled&&!ew?.proxyAddress,n=e.includes("CORS")||e.includes("blocked by CORS policy")||e.includes("Failed to fetch"),o=400===r;if(i&&(n||o||"number"==typeof r&&r>=404&&r<500)&&401!==r&&403!==r)return tL("info",`Direct connection failed with ${n?"CORS error":o?"HTTP 400 (Bad Request)":"HTTP 4xx error"}. Trying with proxy...`),tr.current=null,R||(tn.current=null),tL("debug","Cleared client and auth provider for proxy fallback"),ey({proxyAddress:eg.proxyAddress}),ta.current&&ex("discovering"),setTimeout(()=>{ta.current&&tw.current?.()},1e3),!0;if(ta.current){tL("info","Setting state to FAILED:",e),ex("failed"),e4(e);let t=tn.current?.getLastAttemptedAuthUrl?.();t&&(e8(t),tL("info","Manual authentication URL may be available.",t))}return ts.current=!1,y&&tm.getInstance().trackUseMcpConnection({url:y,transportType:eo,success:!1,errorType:t?.name||"UnknownError",hasOAuth:!!tn.current,hasSampling:tP.current,hasElicitation:tU.current}).catch(()=>{}),!1},[tL,y,eo,eg,ew,R]),t$=(0,h.useCallback)(async()=>
39{if(!w||!y)return void tL("debug",w?"No server URL provided, skipping connection.":"Connection disabled via enabled flag.");if(ts.current)return void tL("debug","Connection attempt already in progress.");if(!ta.current)return void tL("debug","Connect called after unmount, aborting.");if(ts.current=!0,tc.current+=1,tl.current+=1,tg.current!==y&&(tg.current=y,tf.current=void 0,tt(void 0)),e4(void 0),e8(void 0),ty.current=null,ex("discovering"),eA([]),eM([]),eO([]),eN([]),e$([]),eF(void 0),eW(void 0),eJ(void 0),eY(void 0),eX(void 0),e0({}),tL("info",`Connecting attempt #${tl.current} to ${y}...`),!tn.current){let{provider:e,oauthProxyUrl:t}=tS({effectiveOAuthUrl:eR,storageKeyPrefix:_,oauthClientConfig:em,callbackUrl:C,preventAutoAuth:M,useRedirectFlow:q,gatewayUrl:eC,oauthProxyUrl:x,onPopupWindow:L,proxyOAuthRequests:!0,staticClientInfo:eu,clientMetadataUrl:el,scope:ec});tn.current=e,t&&tL("debug",`OAuth BFF enabled: ${t}`),tL("debug",`BrowserOAuthClientProvider initialized with URL: ${eR}, proxy: ${t?"enabled":"disabled"}, gateway: ${eC?"enabled":"disabled"}`)}tr.current?tL("debug","BrowserMCPClient already exists, reusing."):(tr.current=new tv,tL("debug","BrowserMCPClient initialized in connect."));let e=async t=>{var r;if(!ta.current)return tL("debug","Connection attempt aborted - component unmounted"),"failed";tL("info",`Attempting connection with transport: ${t}`),tL("debug",`Client ref status at start of tryConnectWithTransport: ${tr.current?"initialized":"NULL"}`);try{let e,i={url:y,timeout:O,clientInfo:ef,...(e=tn.current?.getProxyFetch?.(j)??j)?{fetch:e}:{},...eh&&{clientOptions:eh},...void 0!==D&&{protocolNegotiation:D},detectMixedAuth:I,...T?{reconnectionOptions:T}:!1===U?{reconnectionOptions:{maxRetries:0}}:{}};if(eC&&(i.gatewayUrl=eC,tL("debug",`Using proxy gateway: ${eC} for target: ${y}`)),eS&&Object.keys(eS).length>0&&(i.headers=eS),!tr.current){if(!ta.current)return tL("debug","Connection aborted - component unmounted, client cleaned up"),"failed";let e=Error("Client not initialized - this is a bug in the connection flow");throw tL("error","Client ref is null in tryConnectWithTransport but component is still mounted"),e}tr.current.addServer(tC,{...i,authProvider:tn.current,onSampling:tP.current?tM:void 0,onElicitation:tU.current?tI:void 0,onNotification:e=>{if(tL("debug","Notification received:",e.method,e),tq(e),"notifications/tools/list_changed"===e.method)tL("info","Tools list changed, auto-refreshing..."),tH.refreshTools().catch(e=>tL("warn","Auto-refresh tools failed:",e));else if("notifications/resources/list_changed"===e.method){tL("info","Resources list changed, auto-refreshing...");let e=ef.capabilities?.extensions,t=eh?.capabilities?.extensions,r=t?.[eE]!==void 0||e?.[eE]!==void 0;Promise.all([tH.refreshResources(),...r?[tH.refreshSkills()]:[]]).catch(e=>tL("warn","Auto-refresh resources failed:",e))}else"notifications/prompts/list_changed"===e.method&&(tL("info","Prompts list changed, auto-refreshing..."),tH.refreshPrompts().catch(e=>tL("warn","Auto-refresh prompts failed:",e)))},wrapTransport:H?e=>(tL("debug","Applying transport wrapper for server:",tC,"url:",y),H(e,N??y)):void 0});let n=await tr.current.connect(tC);if(ti.current=n,!ta.current)return tL("debug","Connection aborted after connection creation - component unmounted"),"failed";if(tL("info","â
Successfully connected to MCP server"),tL("info","Server info:",n.info.server),tL("info","Server capabilities:",n.info.capabilities),eb.enabled&&!1!==eb.healthCheckInterval){let e,t,i,o,s;r={gatewayUrl:eC,url:y,allHeaders:eS,getAuthHeaders:async()=>{try{let e=await tn.current?.tokens?.();if(e?.access_token){let t=e.token_type||"bearer";return{Authorization:`${t.charAt(0).toUpperCase()+t.slice(1)} ${e.access_token}`}}}catch{}return{}},isMountedRef:ta,stateRef:tp,autoReconnectRef:tb,setState:ex,addLog:tL,connect:t$,defaultReconnectDelay:eb.initialDelay,healthCheckIntervalMs:eb.healthCheckInterval,healthCheckTimeoutMs:eb.healthCheckTimeout},e=null,t=Date.now(),i=!1,o=r.healthCheckIntervalMs??1e4,s=r.healthCheckTimeoutMs??3e4,e=setInterval(async()=>
39{if(!i){if(!r.isMountedRef.current||"ready"!==r.stateRef.current){e&&(clearInterval(e),e=null);return}try{let n=r.gatewayUrl||r.url;if(!n)return;let o=r.getAuthHeaders?await r.getAuthHeaders():{},s={...r.allHeaders,...o,...r.gatewayUrl&&r.url?{"X-Target-URL":r.url}:{}},a=await fetch(n,{method:"HEAD",headers:s,signal:AbortSignal.timeout(5e3)});if(405===a.status||404===a.status){i=!0,t=Date.now(),e&&(clearInterval(e),e=null);return}if(a.ok||a.status<500)t=Date.now();else throw Error(`Server returned ${a.status}`)}catch{let i=Date.now()-t;i>s&&(r.addLog("warn",`Connection appears to be broken (no response for ${Math.round(i/1e3)}s), attempting to reconnect...`),e&&(clearInterval(e),e=null),r.autoReconnectRef.current&&r.isMountedRef.current&&(r.setState("discovering"),r.addLog("info","Auto-reconnecting to MCP server..."),setTimeout(()=>{r.isMountedRef.current&&"discovering"===r.stateRef.current&&r.connect()},"number"==typeof r.autoReconnectRef.current?r.autoReconnectRef.current:r.defaultReconnectDelay)))}}},o),n._healthCheckCleanup=()=>{e&&(clearInterval(e),e=null)}}tm.getInstance().trackUseMcpConnection({url:y,transportType:t,success:!0,hasOAuth:!!tn.current,hasSampling:tP.current,hasElicitation:tU.current}).catch(()=>{}),eA(n.tools||[]);let{server:o,capabilities:s,protocolEra:a,protocolVersion:l,instructions:c,extensions:u,authorization:d}=n.info;if(d&&(tt(d),tf.current=d),eJ(a),eY(l),eX(c),e0(u),o&&(tL("debug","Server info:",o),eF(o),to.current=tR({serverInfo:o,url:y,isMounted:()=>ta.current,setServerInfo:eF,addLog:tL})),s&&(tL("debug","Server capabilities:",s),eW(s)),tn.current){let e;try{e=await tn.current.tokens?.()}catch(t){tL("warn","Failed to read OAuth tokens:",t),e=void 0}if(!ta.current)return tL("debug","Connection aborted after token fetch for auth tokens - component unmounted"),"failed";if(e?.access_token){if(tf.current?.mode==="mixed"){let e={...tf.current,authenticated:!0};tt(e),tf.current=e}let t=function(e){try{let t=JSON.parse(atob(e.access_token?.split(".")[1]??""));if("number"==typeof t.exp)return 1e3*t.exp}catch{}return"number"==typeof e.expires_in?Date.now()+1e3*e.expires_in:void 0}(e),r=null,i=null,n=null;try{r=await tn.current.getTokenEndpoint?.()??null}catch{r=null}try{i=await tn.current.getResource?.()??null}catch{i=null}try{n=await tn.current.getClientCredentials?.()??null}catch{n=null}if(!ta.current)return tL("debug","Skipping state update - component unmounted"),"failed";e7({access_token:e.access_token,token_type:e.token_type||"Bearer",expires_at:t,refresh_token:e.refresh_token,scope:e.scope,...r?{token_endpoint:r}:{},...i?{resource:i}:{},...n?.client_id?{client_id:n.client_id}:{},...n?.client_secret?{client_secret:n.client_secret}:{}})}}ty.current=t,ex("ready");let h=()=>{if(!ta.current||ti.current!==n)return;let e=n.discoverAuthorization?.();e&&e.then(e=>{e&&ta.current&&ti.current===n&&(tf.current=e,tt(e))})};"function"==typeof globalThis.requestAnimationFrame?globalThis.requestAnimationFrame(()=>{setTimeout(h,0)}):setTimeout(h,0);let[p,f,m]=await Promise.all([n.listAllResources().catch(e=>(tL("warn","Failed to load initial resources:",e),{resources:[]})),n.listPrompts().catch(e=>(tL("warn","Failed to load initial prompts:",e),{prompts:[]})),n.supports("resources")?n.listResourceTemplates().catch(e=>(tL("warn","Failed to load initial resource templates:",e),{resourceTemplates:[]})):Promise.resolve({resourceTemplates:[]})]);if(!ta.current)return tL("debug","Connection aborted after discovery - component unmounted"),"failed";if(eM(p.resources||[]),eN(f.prompts||[]),eO(m.resourceTemplates||[]),ta.current)if(void 0!==u["io.modelcontextprotocol/skills"])try{let e=await n.listAllSkills();ta.current&&e$(e.skills)}catch(e){tL("warn","Failed to load initial skills:",e),ta.current&&e$([])}else e$([]);return"success"}catch(a){let r,i=a?.message||String(a),n=tn.current?.getLastAttemptedAuthUrl?.();if(n&&tn.current&&M)return tL("info","OAuth already discovered (stored auth URL present); awaiting manual authentication."),ta.current&&(ex("pending_auth"),e8(n)),ts.current=!1,"auth_redirect";let o=(r=(a instanceof Error?a.message:String(a)).toLowerCase()).includes("oauth discovery failed")||r.includes("oauth-authorization-server")||r.includes("not valid json")||r.includes("404")&&(r.includes("openid-configuration")||r.includes("oauth-protected-resources")||r.includes("oauth-authorization-url")||r.includes("register"))||r.includes("invalid oauth error response")&&r.includes("not found"),s=eL(a);if(o&&en&&Object.keys(en).length>0)return tj("Authentication failed (HTTP 401). Server does not support OAuth. Check your Authorization header value is correct."),"failed";if(o&&(!en||0===Object.keys(en).length))return tj("Authentication required (HTTP 401). Server does not support OAuth. Add an Authorization header in the Custom Headers section (e.g., Authorization: Bearer YOUR_API_KEY)."),"failed";if(s){if(o)return tj("Authentication required (HTTP 401). Server does not support OAuth. Add an Authorization header in the Custom Headers section (e.g., Authorization: Bearer YOUR_API_KEY)."),"failed";if(tn.current){if(tL("info","Authentication required. OAuth provider available."),M){if(tL("info","Waiting for user to initiate authentication flow..."),ta.current){ex("pending_auth");let e=tn.current?.getLastAttemptedAuthUrl?.();e&&(e8(e),tL("info","Retrieved stored auth URL for manual authentication"))}return ts.current=!1,"auth_redirect"}tL("info","Triggering automatic OAuth authentication flow...");try{let r=await (0,d.auth)(tn.current,{serverUrl:y,fetchFn:tn.current.getProxyFetch?.()});if("REDIRECT"===r){let e=tn.current,t=await e.getAuthorizationResponse?.(),r=t?.code??await e.getAuthorizationCode?.();if("string"!=typeof r)throw Error("Authorization code not captured by headless provider");await (0,d.auth)(tn.current,{serverUrl:y,authorizationCode:r,...t?.iss!==void 0?{iss:t.iss}:{},fetchFn:tn.current.getProxyFetch?.()})}return tL("info","OAuth flow completed, reconnecting..."),await e(t)}catch(t){let e=t instanceof Error?t.message:String(t);return tj(`Automatic OAuth authentication failed: ${e}`,t instanceof Error?t:Error(String(t))),"failed"}}if(en&&Object.keys(en).length>0)return tj("Authentication failed: Server returned 401 Unauthorized. Check your Authorization header value is correct."),"failed";return tj("Authentication required: Server returned 401 Unauthorized. Add an Authorization header in the Custom Headers section (e.g., Authorization: Bearer YOUR_API_KEY)."),"failed"}return tj(i,a instanceof Error?a:Error(String(a)))?"auth_redirect":"failed"}},t="failed";tL("debug","Connecting via streamable HTTP"),("success"===(t=await e("http"))||"failed"===t||"auth_redirect"===t)&&(ts.current=!1),tL("debug",`Connection sequence finished with status: ${t}`)}
39,[tL,tj,tN,y,_,C,em.name,em.version,em.uri,em.logo_uri,eu,el,ec,en,eo,M,I,q,L,w,O,ef,eh,D,eC,x,eS,eR,tM,tI,tq]);(0,h.useEffect)(()=>{tw.current=t$,tE.current=tj},[t$,tj]);let tD=(0,h.useCallback)(()=>{"failed"===tp.current?(tL("info","Retry requested..."),tw.current?.()):tL("warn",`Retry called but state is not 'failed' (state: ${tp.current}). Ignoring.`)},[tL]),tF=(0,h.useCallback)(async()=>{tL("info","Manual authentication requested...");let e=tp.current,t="ready"===e&&tf.current?.mode==="mixed";if("failed"===e)tL("info","Attempting to reconnect and authenticate via retry..."),tD();else if("pending_auth"!==e&&("ready"!==e||tf.current?.mode!=="mixed"||tf.current.authenticated))if("authenticating"===e){tL("warn","Already attempting authentication. Check for blocked popups or wait for timeout.");let e=tn.current?.getLastAttemptedAuthUrl?.();e&&!e5&&(e8(e),tL("info","Manual authentication URL retrieved:",e))}else tL("info",`Client not in a state requiring manual authentication trigger (state: ${e}). If needed, try disconnecting and reconnecting.`);else{tL("info","Proceeding with authentication...");try{let e;if(t_(tn.current,"Auth Provider not available for manual auth"),t_(y,"Server URL is required for authentication"),R){tL("info","Using provided authProvider for manual authentication");let e=new URL(y),t=e.origin+e.pathname.replace(/\/+$/,"");await (0,d.auth)(tn.current,{serverUrl:t,fetchFn:tn.current.getProxyFetch?.()}),tw.current?.();return}let r=tn.current.clearStorage?.()??0;tL("info",`Cleared ${r} OAuth storage item(s) for fresh authentication`),ex("authenticating");let i=null,n=null,{provider:o,oauthProxyUrl:s}=tS({effectiveOAuthUrl:eR,storageKeyPrefix:_,oauthClientConfig:em,callbackUrl:C,preventAutoAuth:!1,useRedirectFlow:q,gatewayUrl:eC,oauthProxyUrl:x,onPopupWindow:(e,t,r)=>{i=r;try{n=new URL(e).searchParams.get("state")}catch{}L?.(e,t,r)},proxyOAuthRequests:!0,staticClientInfo:eu,clientMetadataUrl:el,scope:ec});s&&tL("info","Scoped OAuth proxy fetch enabled for manual auth"),tn.current=o,tL("info","Triggering fresh OAuth authorization...");let a=new URL(y),l=a.origin+a.pathname.replace(/\/+$/,""),c=await (0,d.auth)(o,{serverUrl:l,fetchFn:o.getProxyFetch?.()});if("AUTHORIZED"===c){tL("info","OAuth flow completed (tokens obtained)"),ts.current=!1,tw.current?.();return}if("REDIRECT"!==c)throw Error(`Unexpected OAuth auth() result: ${c}`);tL("info","OAuth authorization redirect initiated");let u=o.getLastAttemptedAuthUrl?.();if(u&&(e8(u),tL("info","Updated auth URL for fallback:",u),!n))try{n=new URL(u).searchParams.get("state")}catch{}if(q)return;let h=o.getKey?.("tokens");if(!h)return void tL("warn","Could not derive tokens storage key; relying on callback listener.");th.current=!0;try{e=await eI({popup:i,state:n,tokensKey:h})}finally{th.current=!1}if(!ta.current)return;switch(e.kind){case"success":tL("info","Authentication succeeded; reconnecting to MCP server..."),ts.current=!1,tw.current?.();break;case"cancelled":tL("warn",t?"Authentication popup was closed before completing. Public tools remain available.":"Authentication popup was closed before completing. Returning to pending_auth."),ex(t?"ready":"pending_auth");break;case"timeout":tL("warn",t?"Authentication timed out waiting for the popup. Public tools remain available.":"Authentication timed out waiting for the popup. Returning to pending_auth."),ex(t?"ready":"pending_auth");break;case"error":tj(`Authentication failed: ${e.error}`)}}catch(t){if(!ta.current)return;let e=t instanceof Error?t:Error(String(t));tj(`Manual authentication failed: ${e.message}`,e)}}},[tL,tD,tj,e5,y,q,L,_,em.name,em.uri,em.logo_uri,eu,el,ec,C,ef,R]),tK=(0,h.useCallback)(()=>{if(tn.current?.clearStorage){let e=tn.current.clearStorage();tL("info",`Cleared ${e} item(s) from localStorage for ${y}.`),e8(void 0),tN()}else tL("warn","Auth provider not initialized, cannot clear storage.")},[y,tL,tN]);(0,h.useEffect)(()=>{if("u"<typeof window)return;let e=(e,t)=>{if(th.current)return void tL("debug",`Ignoring auth callback via ${t}; manual popup flow owns this result.`);let r=tn.current?.serverUrlHash;if(e?.serverUrlHash&&r&&e.serverUrlHash!==r)return void tL("debug",`Ignoring auth callback via ${t} for a different server.`);if(tL("info",`Received auth callback via ${t}.`,e),tu.current&&clearTimeout(tu.current),tu.current=null,e?.success)tL("info","Authentication successful via popup. Reconnecting client..."),ts.current&&tL("debug","Connection attempt already in progress, resetting flag to allow reconnection."),ts.current=!1,setTimeout(()=>{ta.current&&(tL("debug","Initiating reconnection after successful auth callback."),tw.current?.())},100);else{if("authenticating"!==tp.current&&"pending_auth"!==tp.current)return void tL("debug",`Ignoring stale auth failure callback (state=${tp.current}).`);tE.current?.(`Authentication failed in callback: ${e?.error||"Unknown reason."}`)}},t=t=>{t.origin!==window.location.origin||t.data?.type===eT&&e(t.data,"postMessage")};window.addEventListener("message",t),tL("debug","Auth callback message listener added.");let r=null,i=t=>{t.data?.type===eT&&e(t.data,"BroadcastChannel")};if("u">typeof BroadcastChannel)try{(r=new BroadcastChannel(eU)).addEventListener("message",i),tL("debug","Auth callback BroadcastChannel listener added.")}catch(e){tL("warn","Failed to open auth callback BroadcastChannel; lost-opener popups will not reach this client.",e),r=null}return()=>{if(window.removeEventListener("message",t),tL("debug","Auth callback message listener removed."),r){try{r.removeEventListener("message",i),r.close()}catch{}tL("debug","Auth callback BroadcastChannel listener removed.")}tu.current&&clearTimeout(tu.current)}},[tL]),(0,h.useEffect)(()=>
39{if(ta.current=!0,!w||!y)return tL("debug",w?"No server URL provided, skipping connection.":"Connection disabled via enabled flag."),ex("discovering"),()=>{ta.current=!1};if(tL("debug","useMcp mounted, initiating connection."),tl.current=0,R)tn.current=R,tL("debug","Using externally provided authProvider");else if(!tn.current||tn.current.serverUrl!==eR){let{provider:e,oauthProxyUrl:t}=tS({effectiveOAuthUrl:eR,storageKeyPrefix:_,oauthClientConfig:em,callbackUrl:C,preventAutoAuth:M,useRedirectFlow:q,gatewayUrl:eC,oauthProxyUrl:x,onPopupWindow:L,proxyOAuthRequests:!0,staticClientInfo:eu,clientMetadataUrl:el,scope:ec});tn.current=e,t&&tL("debug",`OAuth proxy URL in effect: ${t}`),tL("debug",`BrowserOAuthClientProvider initialized/updated with URL: ${eR}, proxy: ${t?"enabled":"disabled"}, gateway: ${eC?"enabled":"disabled"}`)}return t$(),()=>{ta.current=!1,tL("debug","useMcp unmounting, disconnecting."),tN(!0)}},[y,w,_,C,em.name,em.version,em.uri,em.logo_uri,eu,el,ec,q,ef,eR,ei,eg.proxyAddress,R]);let tW=(0,h.useRef)(tD),tV=(0,h.useRef)(tL);(0,h.useEffect)(()=>{tW.current=tD,tV.current=tL},[tD,tL]),(0,h.useEffect)(()=>{let e=null;if("failed"===ek&&P&&tl.current>0){if(!td.current){td.current=!0;let t="number"==typeof P?P:5e3;tV.current("info",`Connection failed, auto-retrying in ${t}ms...`),e=setTimeout(()=>{td.current=!1,ta.current&&"failed"===tp.current&&tW.current()},t)}}else"failed"!==ek&&(td.current=!1);return()=>{e&&(clearTimeout(e),td.current=!1)}},[ek,P]);let tB=(0,h.useCallback)(async()=>"ready"!==tp.current?(tL("warn","Cannot ensure icon loaded - not connected"),null):eD?.icon?eD.icon:to.current?(tL("debug","Waiting for icon to finish loading..."),await to.current):(tL("debug","No icon available and no loading in progress"),null),[eD,tL]);return{state:ek,name:eD?.name||y||"",tools:ez,resources:eP,resourceTemplates:eq,prompts:eH,skills:ej,serverInfo:eD,capabilities:eK,protocolEra:eV,protocolVersion:eG,instructions:eZ,extensions:eQ,error:e1,log:e3,authUrl:e5,authTokens:e9,authorization:te,client:tr.current,...tH,retry:tD,disconnect:tN,authenticate:tF,clearStorage:tK,ensureIconLoaded:tB}}var tz=null;
39function tA(e,t,r,i){if("u"<typeof document)return;document.body.innerHTML="";let n=document.createElement("div");n.style.fontFamily="sans-serif",n.style.padding="20px";let o=document.createElement("h1");o.textContent=e,n.appendChild(o);let s=document.createElement("p");s.textContent=t,r&&(s.style.color="red",s.style.backgroundColor="#ffebeb",s.style.border="1px solid red",s.style.padding="10px",s.style.borderRadius="4px"),n.appendChild(s);let a=document.createElement("a");if(a.href="#",a.textContent="Close this window",a.onclick=e=>(e.preventDefault(),window.close(),!1),n.appendChild(a),i){let e=document.createTextNode(" or "),t=document.createElement("a");t.href=i,t.textContent="return to the app",n.append(e,t)}document.body.appendChild(n)}async function tP(e){let t,r=new eX,i=`:state_${e}`,n=`_state_${e}`,o=(await r.keys()).find(e=>e.endsWith(i)||e.endsWith(n)),s=o?await r.get(o):null;if(!o||!s)throw Error(`Invalid or expired OAuth state "${e}".`);try{t=JSON.parse(s)}catch{throw await r.remove(o),Error("Failed to parse stored OAuth state.")}return{key:o,value:t,store:r}}function tU(e,t){let r=new URL(e);r.searchParams.set("auth_error","oauth_callback_failed"),r.searchParams.set("auth_error_description",t),window.location.href=r.toString()}
39function tT(e,t,r,i){let n={type:eT,success:e,...e?{}:{error:t??"Unknown error"},...i.state?{state:i.state}:{},...i.serverUrlHash?{serverUrlHash:i.serverUrlHash}:{}},o=r?.returnUrl,s=r?.flowType==="popup"||"u">typeof window&&window.name.startsWith("mcp_auth_");if(r?.flowType==="redirect"&&o)return void(e?window.location.href=o:tU(o,t??"Authentication failed."));if(window.opener&&!window.opener.closed){window.opener.postMessage(n,window.location.origin),window.close();return}if(s){let r;if("u">typeof BroadcastChannel)try{(r=new BroadcastChannel(eU)).postMessage(n)}catch(e){console.warn("[mcp-callback] Failed to broadcast callback result:",e)}finally{r&&setTimeout(()=>{try{r?.close()}catch{}},0)}tA(e?"Authentication Successful!":"Authentication Error",e?"You're authenticated. You can close this window and return to the app.":t??"Authentication failed.",!e,o);try{window.close()}catch{}return}o?e?window.location.href=o:tU(o,t??"Authentication failed."):e?window.location.href="/":tA("Authentication Error",t??"Authentication failed.",!0)}async function tM(){let e=new URLSearchParams(window.location.search),t=e.get("state"),r=null,i=null,n=null,o=null;try{if(!t)throw Error("OAuth callback is missing the state parameter.");let s=await tP(t);if(r=s.key,i=s.store,!(n=s.value).expiry||n.expiry<Date.now())throw await i.remove(r),Error("OAuth state has expired. Please start authentication again.");if(!n.providerOptions)throw Error("Stored OAuth state is missing provider options.");let{serverUrl:a,...l}=n.providerOptions;o=new e8(a,l);let c=new d.StreamableHTTPClientTransport(new URL(a),{authProvider:o,fetch:o.getProxyFetch()});await c.finishAuth(e),await i.remove(r),tT(!0,void 0,n,{state:t,serverUrlHash:n.serverUrlHash})}catch(s){let e=s instanceof Error?s.message:String(s);console.error("[mcp-callback] OAuth callback failed:",s),r&&i&&await i.remove(r),o&&await (i??new eX).remove(o.getKey("last_auth_url")),tT(!1,e,n,{state:t,serverUrlHash:n?.serverUrlHash})}}eb();var tI=5*6e4,tq=n.get("McpClientProvider"),tL=(0,h.createContext)(null);function tO(e,t){return JSON.stringify(e)===JSON.stringify(t)}function tH(e,t){return e.id===t.id&&tO(eP(e),eP(t))&&e.name===t.name&&e.state===t.state&&e.error===t.error&&e.authUrl===t.authUrl&&tO(e.authTokens,t.authTokens)&&tO(e.authorization,t.authorization)&&e.protocolEra===t.protocolEra&&e.protocolVersion===t.protocolVersion&&tO(e.serverInfo,t.serverInfo)&&tO(e.capabilities,t.capabilities)&&e.instructions===t.instructions&&tO(e.extensions,t.extensions)&&tO(e.tools,t.tools)&&tO(e.resources,t.resources)&&tO(e.resourceTemplates,t.resourceTemplates)&&tO(e.prompts,t.prompts)&&tO(e.skills,t.skills)&&tO(e.notifications,t.notifications)&&e.unreadNotificationCount===t.unreadNotificationCount&&tO(e.pendingSamplingRequests,t.pendingSamplingRequests)&&tO(e.pendingElicitationRequests,t.pendingElicitationRequests)&&e.client===t.client}function tN({id:e,options:t,defaultCallbackUrl:r,defaultOAuthProxyUrl:i,defaultProxyConfig:n,defaultAutoProxyFallback:o,clientInfo:s,cachedMetadata:a,onUpdate:l,onUpdateConfig:c,onUpdateDisplayName:u,onReconnect:d,rpcWrapTransport:p,onGlobalSamplingRequest:f,onGlobalElicitationRequest:m}){let{displayName:g,onSamplingRequest:b,onElicitationRequest:v,onNotificationReceived:y,wrapTransport:w}=t,C=(0,h.useMemo)(()=>{let{displayName:l,onSamplingRequest:c,onElicitationRequest:u,onNotificationReceived:d,wrapTransport:h,...p}=t;return{...p,callbackUrl:p.callbackUrl||r,oauthProxyUrl:p.oauthProxyUrl||i,proxyConfig:p.proxyConfig||n,autoProxyFallback:void 0!==p.autoProxyFallback?p.autoProxyFallback:o,clientInfo:p.clientInfo?s?{...s,...p.clientInfo}:p.clientInfo:s,_initialServerInfo:a,serverId:e}},[t,r,i,n,o,s,a]),_=(0,h.useMemo)(()=>{if(p||w)return t=>{let r=t;return p&&(r=p(r,e)),w&&(r=w(r,e)),r}},[p,w,e]),R=function(e){let[t,r]=(0,h.useState)([]),[i,n]=(0,h.useState)([]),[o,s]=(0,h.useState)([]),a=(0,h.useRef)(0),l=(0,h.useRef)(0),c=(0,h.useRef)(new Map),u=(0,h.useRef)(new Map),d=(0,h.useCallback)(e=>{for(let t of c.current.values())clearTimeout(t.timeout),t.reject(Error(e));
39for(let t of(c.current.clear(),u.current.values()))clearTimeout(t.timeout),t.reject(Error(e));u.current.clear(),n([]),s([])},[]);(0,h.useEffect)(()=>()=>d("MCP server connection was removed"),[d]);let p=(0,h.useCallback)(t=>{let i={id:globalThis.crypto?.randomUUID?.()??`${Date.now()}-${Math.random()}`,method:t.method,params:t.params,timestamp:Date.now(),read:!1};r(e=>[i,...e].slice(0,500)),e.onNotificationReceived?.(i)},[e.onNotificationReceived]),f=(0,h.useCallback)((e,t)=>{let r=c.current.get(e);r&&(clearTimeout(r.timeout),c.current.delete(e),n(t=>t.filter(t=>t.id!==e)),r.resolve(t))},[]),m=(0,h.useCallback)((e,t)=>{let r=c.current.get(e);r&&(clearTimeout(r.timeout),c.current.delete(e),n(t=>t.filter(t=>t.id!==e)),r.reject(Error(t??"User rejected sampling request")))},[]),g=(0,h.useCallback)(t=>new Promise((r,i)=>{let o=`sampling-${a.current++}`,s={id:o,request:{method:"sampling/createMessage",params:t},timestamp:Date.now(),serverName:e.serverName},l=setTimeout(()=>m(o,"Sampling request timed out"),tI);c.current.set(o,{resolve:r,reject:i,timeout:l}),n(e=>[...e,s]),e.onSamplingRequest?.(s),e.onGlobalSamplingRequest?.(s,e.serverId,e.serverName,f,m)}),[f,e,m]),b=(0,h.useCallback)((e,t)=>{let r=u.current.get(e);r&&(clearTimeout(r.timeout),u.current.delete(e),s(t=>t.filter(t=>t.id!==e)),r.resolve(t))},[]),v=(0,h.useCallback)((e,t)=>{let r=u.current.get(e);r&&(clearTimeout(r.timeout),u.current.delete(e),s(t=>t.filter(t=>t.id!==e)),r.reject(Error(t??"User rejected elicitation request")))},[]),y=(0,h.useCallback)(t=>new Promise((r,i)=>{let n=`elicitation-${l.current++}`,o={id:n,request:t,timestamp:Date.now(),serverName:e.serverName},a=setTimeout(()=>v(n,"Elicitation request timed out"),tI);u.current.set(n,{resolve:r,reject:i,timeout:a}),s(e=>[...e,o]),e.onElicitationRequest?.(o),e.onGlobalElicitationRequest?.(o,e.serverId,e.serverName,b,v)}),[b,e,v]),w=(0,h.useCallback)(e=>{r(t=>t.map(t=>t.id===e?{...t,read:!0}:t))},[]),C=(0,h.useCallback)(()=>r(e=>e.map(e=>({...e,read:!0}))),[]),_=(0,h.useCallback)(()=>r([]),[]);return{notifications:t,pendingSamplingRequests:i,pendingElicitationRequests:o,unreadNotificationCount:t.filter(e=>!e.read).length,markNotificationRead:w,markAllNotificationsRead:C,clearNotifications:_,approveSampling:f,rejectSampling:m,approveElicitation:b,rejectElicitation:v,onNotification:p,onSampling:g,onElicitation:y,rejectAll:d}}({serverId:e,serverName:g||e,onNotificationReceived:y,onSamplingRequest:b,onElicitationRequest:v,onGlobalSamplingRequest:f,onGlobalElicitationRequest:m}),S=tE({...C,onNotification:R.onNotification,onSampling:R.onSampling,onElicitation:R.onElicitation,wrapTransport:_});(0,h.useEffect)(()=>{"ready"!==S.state&&R.rejectAll("MCP server connection is no longer active")},[S.state,R.rejectAll]);let k=(0,h.useCallback)(t=>c(e,t),[e,c]),x=(0,h.useCallback)(r=>{let i=t.proxyConfig?.proxyAddress?.trim();return"proxy"===t.connectionMode&&i?c(e,{proxyConfig:{...t.proxyConfig,proxyAddress:i,...r?{headers:r}:{}},headers:void 0}):c(e,{headers:r})},[e,t.connectionMode,t.proxyConfig,c]),E=(0,h.useCallback)(t=>u(e,t),[e,u]),z=(0,h.useCallback)(()=>d(e),[e,d]),A=(0,h.useRef)(l),P=(0,h.useRef)(null);return(0,h.useEffect)(()=>{A.current=l},[l]),(0,h.useEffect)(()=>{let r={...eP(t),...S,id:e,displayName:g||t.displayName||e,notifications:R.notifications,unreadNotificationCount:R.unreadNotificationCount,markNotificationRead:R.markNotificationRead,markAllNotificationsRead:R.markAllNotificationsRead,clearNotifications:R.clearNotifications,pendingSamplingRequests:R.pendingSamplingRequests,approveSampling:R.approveSampling,rejectSampling:R.rejectSampling,pendingElicitationRequests:R.pendingElicitationRequests,approveElicitation:R.approveElicitation,rejectElicitation:R.rejectElicitation,updateConfig:k,setHeaders:x,setDisplayName:E,reconnect:z},i=P.current;i&&tH(i,r)?tq.debug(`[McpServerWrapper ${e}] No meaningful changes detected, skipping onUpdate`):(P.current=r,A.current(r))},[e,g,t,t.url,S.state,S.error,S.authUrl,S.tools,S.resources,S.resourceTemplates,S.prompts,S.skills,S.serverInfo,S.capabilities,S.protocolEra,S.protocolVersion,S.instructions,S.extensions,S.authTokens,S.authorization,R,k,x,E,z]),null}function tj(){let e=(0,h.useContext)(tL);if(!e)throw Error("useMcpClient must be used within a McpClientProvider");return e}function t$(e){let t={};if(!e)return t;for(let[r,i]of Object.entries(e))if("string"==typeof i&&(i.trim().startsWith("[")||i.trim().startsWith("{")))try{t[r]=JSON.parse(i)}catch{t[r]=i}else t[r]=i;return t}ex();var tD=`<script> 40(function () { 41 var files = new Map();
42 var pendingRequests = new Map(); 43 var requestId = 0; 44 var hostConnected = false; 45 var fallbackTimer; 46 var api = window.openai || {}; 47 48 function dispatchGlobals(globals) { 49 Object.assign(api, globals); 50 window.dispatchEvent(new CustomEvent("openai:set_globals", { 51 detail: { globals: globals } 52 })); 53 } 54 55 function applyHostContext(context) { 56 if (!context || typeof context !== "object") return; 57 var globals = {}; 58 if (context.theme !== undefined) globals.theme = context.theme; 59 if (context.displayMode !== undefined) globals.displayMode = context.displayMode; 60 if (context.locale !== undefined) globals.locale = context.locale; 61 if (context.view !== undefined) globals.view = context.view; 62 if (context.safeAreaInsets !== undefined) { 63 globals.safeArea = { insets: context.safeAreaInsets }; 64 } 65 if (context.containerDimensions && context.containerDimensions.maxHeight !== undefined) { 66 globals.maxHeight = context.containerDimensions.maxHeight; 67 } 68 if (context.platform !== undefined || context.deviceCapabilities !== undefined) { 69 globals.userAgent = { 70 device: { 71 type: context.platform === "mobile" ? "mobile" : "desktop" 72 }, 73 capabilities: { 74 hover: !!(context.deviceCapabilities && context.deviceCapabilities.hover), 75 touch: !!(context.deviceCapabilities && context.deviceCapabilities.touch) 76 } 77 }; 78 } 79 dispatchGlobals(globals); 80 } 81 82 function markHostConnected(result) { 83 hostConnected = true; 84 clearTimeout(fallbackTimer); 85 if (result && result.hostContext) applyHostContext(result.hostContext); 86 } 87 88 function postMessage(message) { 89 if (window.parent === window) { 90 throw new Error("window.openai compatibility APIs require an iframe host"); 91 } 92 window.parent.postMessage(message, "*"); 93 } 94 95 function sendRequest(method, params) { 96 var id = "mcp-use-openai-compat-" + (++requestId); 97 return new Promise(function (resolve, reject) { 98 pendingRequests.set(id, { resolve: resolve, reject: reject }); 99 postMessage({ jsonrpc: "2.0", id: id, method: method, params: params }); 100 window.setTimeout(function () { 101 var pending = pendingRequests.get(id); 102 if (!pending) return; 103 pendingRequests.delete(id); 104 pending.reject(new Error("Request timeout: " + method)); 105 }, 30000); 106 }); 107 } 108 109 function sendNotification(method, params) { 110 postMessage({ jsonrpc: "2.0", method: method, params: params }); 111 } 112 113 window.addEventListener("message", function (event) { 114 if (event.source !== window.parent) return; 115 var message = event.data; 116 if (!message || message.jsonrpc !== "2.0") return; 117 118 if (message.id !== undefined && (message.result !== undefined || message.error !== undefined)) { 119 var pending = pendingRequests.get(message.id); 120 if (pending) { 121 pendingRequests.delete(message.id); 122 if (message.error) pending.reject(new Error(message.error.message || "Host request failed")); 123 else pending.resolve(message.result); 124 return; 125 } 126 if (message.result && (message.result.hostInfo || message.result.hostContext)) { 127 markHostConnected(message.result); 128 } 129 return; 130 } 131 132 if (message.id !== undefined || typeof message.method !== "string") return; 133 var params = message.params || {}; 134 switch (message.method) { 135 case "ui/notifications/tool-input": 136 markHostConnected(); 137 dispatchGlobals({ toolInput: params.arguments || {} }); 138 break; 139 case "ui/notifications/tool-input-partial": 140 // window.openai has no partial-input global. Do not expose incomplete 141 // or approval-gated arguments as if the final tool input had arrived. 142 markHostConnected(); 143 break; 144 case "ui/notifications/tool-result": 145 markHostConnected(); 146 dispatchGlobals({ 147 // OpenAI defines toolOutput as structuredContent, not the complete 148 // CallToolResult envelope. Keep that envelope (including hidden 149 // _meta) in toolResponseMetadata instead. 150 toolOutput: params.structuredContent === undefined ? null : params.structuredContent, 151 toolResponseMetadata: params 152 }); 153 break; 154 case "ui/notifications/host-context-changed": 155 markHostConnected(); 156 applyHostContext(params); 157 break; 158 } 159 }); 160 161 api.toolInput = api.toolInput === undefined ? null : api.toolInput; 162 api.toolOutput = api.toolOutput === undefined ? null : api.toolOutput; 163 api.toolResponseMetadata = 164 api.toolResponseMetadata === undefined ? null : api.toolResponseMetadata; 165 api.widgetState = api.widgetState === undefined ? null : api.widgetState; 166 api.theme = api.theme || "light"; 167 api.displayMode = api.displayMode || "inline"; 168 api.safeArea = api.safeArea || { 169 insets: { top: 0, right: 0, bottom: 0, left: 0 } 170 }; 171 api.maxHeight = api.maxHeight || 600; 172 api.userAgent = api.userAgent || { 173 device: { type: "desktop" }, 174 capabilities: { hover: true, touch: false } 175 }; 176 api.locale = api.locale || "en"; 177 178 api.callTool = api.callTool || function (name, args) { 179 return sendRequest("tools/call", { name: name, arguments: args || {} }); 180 }; 181 api.sendFollowUpMessage = api.sendFollowUpMessage || function (request) { 182 return sendRequest("ui/message", { 183 role: "user", 184 content: [{ type: "text", text: request.prompt }] 185 }); 186 }; 187 api.openExternal = api.openExternal || function (request) { 188 return sendRequest("ui/open-link", { url: request.href }); 189 }; 190 api.requestDisplayMode = api.requestDisplayMode || function (request) { 191 return sendRequest("ui/request-display-mode", { mode: request.mode }); 192 }; 193 api.setWidgetState = api.setWidgetState || function (state) { 194 dispatchGlobals({ widgetState: state }); 195 // The Apps SDK setter is promise-based. Keep the local state update 196 // synchronous, but return a promise so legacy useWidget() code can safely 197 // await or chain .catch() on the compatibility API. 198 return Promise.resolve(); 199 }; 200 api.notifyIntrinsicHeight = api.notifyIntrinsicHeight || function (height) { 201 sendNotification("ui/notifications/size-changed", { height: height }); 202 return Promise.resolve(); 203 }; 204 api.uploadFile = api.uploadFile || async function (file) { 205 var fileId = crypto.randomUUID(); 206 files.set(fileId, file); 207 return { fileId: fileId }; 208 }; 209 api.getFileDownloadUrl = api.getFileDownloadUrl || async function (ref) { 210 var file = files.get(ref.fileId); 211 if (!file) { 212 throw new Error("File not found: " + ref.fileId); 213 } 214 return { downloadUrl: URL.createObjectURL(file) }; 215 }; 216 window.openai = api; 217 218 // Native V2 views initialize their own MCP Apps bridge. Only initialize this 219 // compatibility bridge when no other guest handshake appears, so the file 220 // helpers remain safe for both V2 views and legacy useWidget() bundles. 221 fallbackTimer = window.setTimeout(function () { 222 if (hostConnected) return; 223 sendRequest("ui/initialize", { 224 appCapabilities: {}, 225 appInfo: { name: "mcp-use-openai-compat", version: "1.0.0" }, 226 protocolVersion: ${JSON.stringify(M)} 227 }).then(function (result) { 228 markHostConnected(result); 229 sendNotification("ui/notifications/initialized", {}); 230 }).catch(function (error) { 231 console.warn("[window.openai compatibility] Failed to initialize:", error); 232 }); 233 }, 1000); 234})(); 235</script>`;function tF(e,t){let r=e.toLowerCase(),i=0;for(;i<r.length;){let n=r.indexOf(t,i);if(-1===n)break;let o=r[n+t.length];if(">"===o||" "===o||" "===o||"\n"===o||"\r"===o||"\f"===o){let r;for(let i=n+t.length;i<e.length;i++){let t=e[i];if(r){t===r&&(r=void 0);continue}if('"'===t||"'"===t){r=t;continue}if(">"===t)return i+1}break}i=n+t.length}}function tK(e,t,r){return e.slice(0,t)+r+e.slice(t)}function tW(e,t){let{cspMode:r,permissions:i,widgetCsp:n}=t;e.searchParams.set("v",JSON.stringify({cspMode:r,permissions:i,widgetCsp:n})),e.searchParams.set("csp_mode",r),i&&Object.keys(i).length>0&&e.searchParams.set("permissions",JSON.stringify(i)),n&&Object.keys(n).length>0&&e.searchParams.set("widget_csp",JSON.stringify(n))}var tV=`<!doctype html> 236<html> 237 <head> 238 <meta charset="utf-8" /> 239 <meta 240 http-equiv="Content-Security-Policy" 241 content="default-src 'self'; img-src * data: blob: 'unsafe-inline'; media-src * blob: data:; font-src * blob: data:;
241 script-src * 'wasm-unsafe-eval' 'unsafe-inline' 'unsafe-eval' blob: data:; style-src * blob: data: 'unsafe-inline'; connect-src * data: blob: about:; frame-src * blob: data: http://localhost:* https://localhost:* http://127.0.0.1:* https://127.0.0.1:*;" 242 /> 243 <title>MCP Apps Sandbox Proxy</title> 244 <style> 245 html, body { margin: 0; padding: 0; height: 100%; width: 100%; overflow: hidden; } 246 * { box-sizing: border-box; } 247 iframe { display: block; background-color: transparent; border: 0px none transparent; padding: 0px; width: 100%; height: 100%; } 248 </style> 249 </head> 250 <body> 251 <script> 252 function sanitizeDomain(domain) { 253 if (typeof domain !== "string") return ""; 254 return domain.replace(/['"<>;]/g, "").trim(); 255 } 256 257 function buildAllowAttribute(permissions) { 258 if (!permissions) return ""; 259 const allowList = []; 260 if (permissions.camera) allowList.push("camera *"); 261 if (permissions.microphone) allowList.push("microphone *"); 262 if (permissions.geolocation) allowList.push("geolocation *"); 263 if (permissions.clipboardWrite) allowList.push("clipboard-write *"); 264 return allowList.join("; "); 265 } 266 267 function buildCSP(csp) { 268 if (!csp) { 269 return [ 270 "default-src 'none'", 271 "script-src 'unsafe-inline'", 272 "style-src 'unsafe-inline'", 273 "img-src data:", 274 "font-src data:", 275 "media-src data:", 276 "connect-src 'none'", 277 "frame-src 'none'", 278 "object-src 'none'", 279 "base-uri 'none'", 280 ].join("; "); 281 } 282 283 const connectDomains = (csp.connectDomains || []).map(sanitizeDomain).filter(Boolean); 284 const resourceDomains = (csp.resourceDomains || []).map(sanitizeDomain).filter(Boolean); 285 const frameDomains = (csp.frameDomains || []).map(sanitizeDomain).filter(Boolean); 286 const baseUriDomains = (csp.baseUriDomains || []).map(sanitizeDomain).filter(Boolean); 287 const scriptDirectives = (csp.scriptDirectives || []).filter(function(d) { return typeof d === "string" && d.length > 0; }); 288 289 const connectSrc = connectDomains.length > 0 ? connectDomains.join(" ") : "'none'"; 290 const resourceSrc = resourceDomains.length > 0 ? ["data:", "blob:", ...resourceDomains].join(" ") : "data: blob:"; 291 const frameSrc = frameDomains.length > 0 ? frameDomains.join(" ") : "'none'"; 292 const baseUri = baseUriDomains.length > 0 ? baseUriDomains.join(" ") : "'none'"; 293 const scriptSrcParts = ["'unsafe-inline'", "'unsafe-eval'", resourceSrc]; 294 if (scriptDirectives.length > 0) scriptSrcParts.push(scriptDirectives.join(" ")); 295 296 return [ 297 "default-src 'none'", 298 "script-src " + scriptSrcParts.join(" "), 299 "style-src 'unsafe-inline' " + resourceSrc, 300 "img-src " + resourceSrc, 301 "font-src " + resourceSrc, 302 "media-src " + resourceSrc, 303 "connect-src " + connectSrc, 304 "frame-src " + frameSrc, 305 "object-src 'none'", 306 "base-uri " + baseUri, 307 ].join("; "); 308 } 309 310 function buildViolationListenerScript() { 311 return \`<script> 312document.addEventListener('securitypolicyviolation', function(e) { 313 var violation = { 314 type: 'mcp-apps:csp-violation', 315 directive: e.violatedDirective, 316 blockedUri: e.blockedURI, 317 sourceFile: e.sourceFile || null, 318 lineNumber: e.lineNumber || null, 319 columnNumber: e.columnNumber || null, 320 effectiveDirective: e.effectiveDirective, 321 originalPolicy: e.originalPolicy, 322 disposition: e.disposition, 323 timestamp: Date.now() 324 }; 325 console.warn('[MCP Apps CSP Violation]', violation.directive, ':', violation.blockedUri); 326 window.parent.postMessage(violation, '*'); 327}); 328 329function serializeConsoleArgs(args) { 330 try { 331 return Array.from(args || []).map(function(arg) { 332 if (arg instanceof Error) { 333 return { 334 type: 'Error', 335 message: arg.message, 336 stack: arg.stack, 337 name: arg.name, 338 }; 339 } 340 if (typeof arg === 'object' && arg !== null) { 341 try { 342 return JSON.parse(JSON.stringify(arg)); 343 } catch (e) { 344 return String(arg); 345 } 346 } 347 return arg; 348 }); 349 } catch (e) { 350 return [String(args)]; 351 } 352} 353
354function sendConsoleToParent(level, args) { 355 try { 356 window.parent.postMessage({ 357 type: 'iframe-console-log', 358 level: level, 359 args: serializeConsoleArgs(args), 360 timestamp: new Date().toISOString(), 361 url: window.location.href, 362 }, '*'); 363 } catch (e) {} 364} 365 366var originalConsoleError = console.error.bind(console); 367console.error = function() { 368 var args = Array.from(arguments); 369 originalConsoleError.apply(console, args); 370 sendConsoleToParent('error', args); 371}; 372 373window.addEventListener('error', function(event) { 374 sendConsoleToParent('error', [{ 375 message: event.message, 376 filename: event.filename, 377 lineno: event.lineno, 378 colno: event.colno, 379 error: event.error ? { 380 message: event.error.message, 381 stack: event.error.stack, 382 name: event.error.name, 383 } : null, 384 }]); 385}); 386 387window.addEventListener('unhandledrejection', function(event) { 388 sendConsoleToParent('error', [{ 389 message: 'Unhandled Promise Rejection', 390 reason: event.reason ? String(event.reason) : 'Unknown', 391 error: event.reason instanceof Error ? { 392 message: event.reason.message, 393 stack: event.reason.stack, 394 name: event.reason.name, 395 } : null, 396 }]); 397}); 398</\` + \`script>\`; 399 } 400 401 function injectCSP(html, cspValue) { 402 const cspMeta = '<meta http-equiv="Content-Security-Policy" content="' + cspValue + '">'; 403 const violationListener = buildViolationListenerScript(); 404 const injection = cspMeta + violationListener; 405 406 if (html.includes("<head>")) { 407 return html.replace("<head>", "<head>" + injection); 408 } else if (html.includes("<HEAD>")) { 409 return html.replace("<HEAD>", "<HEAD>" + injection); 410 } else if (html.includes("<html>")) { 411 return html.replace("<html>", "<html><head>" + injection + "</head>"); 412 } else if (html.includes("<HTML>")) { 413 return html.replace("<HTML>", "<HTML><head>" + injection + "</head>"); 414 } else if (html.includes("<!DOCTYPE") || html.includes("<!doctype")) { 415 return html.replace(/(<!DOCTYPE[^>]*>|<!doctype[^>]*>)/i, "$1<head>" + injection + "</head>"); 416 } else { 417 return injection + html; 418 } 419 } 420 421 // Query params from host (csp_mode, permissions, widget_csp). AppFrame only 422 // sends { html, csp } in sandbox-resource-ready; we carry the rest on the URL. 423 // Blob URLs cannot reliably carry search params, so the CDN shell injects 424 // window.__SANDBOX_SEARCH__ via buildSandboxProxyBlobHtml. 425 const query = new URLSearchParams( 426 typeof window.__SANDBOX_SEARCH__ === "string" 427 ? window.__SANDBOX_SEARCH__ 428 : location.search 429 ); 430 const queryCspMode = query.get("csp_mode") || "permissive"; 431 let queryPermissions = null; 432 let queryWidgetCsp = null; 433 try { 434 const rawPerm = query.get("permissions"); 435 if (rawPerm) queryPermissions = JSON.parse(rawPerm); 436 } catch (e) {} 437 try { 438 const rawCsp = query.get("widget_csp"); 439 if (rawCsp) queryWidgetCsp = JSON.parse(rawCsp); 440 } catch (e) {} 441 442 const inner = document.createElement("iframe"); 443 inner.style = "width:100%; height:100%; border:none;"; 444 inner.setAttribute("sandbox", "allow-scripts allow-same-origin allow-forms"); 445 document.body.appendChild(inner); 446 447 window.addEventListener("message", async (event) => { 448 if (event.source === window.parent) { 449 if (event.data && event.data.method === "ui/notifications/sandbox-resource-ready") { 450 const params = event.data.params || {}; 451 const html = params.html; 452 const sandbox = params.sandbox; 453 // Prefer message csp when present; fall back to URL widget_csp 454 const csp = params.csp != null ? params.csp : queryWidgetCsp; 455 const permissions = params.permissions != null ? params.permissions : queryPermissions; 456 const permissive = 457 typeof params.permissive === "boolean" 458 ? params.permissive 459 : queryCspMode === "permissive";
460 if (typeof sandbox === "string") { 461 inner.setAttribute("sandbox", sandbox); 462 } 463 const allowAttribute = buildAllowAttribute(permissions); 464 if (allowAttribute) { 465 inner.setAttribute("allow", allowAttribute); 466 } 467 if (typeof html === "string") { 468 if (permissive) { 469 const permissiveCsp = [ 470 "default-src * 'unsafe-inline' 'unsafe-eval' data: blob: filesystem: about:", 471 "script-src * 'unsafe-inline' 'unsafe-eval' data: blob:", 472 "style-src * 'unsafe-inline' data: blob:", 473 "img-src * data: blob: https: http:", 474 "media-src * data: blob: https: http:", 475 "font-src * data: blob: https: http:", 476 "connect-src * data: blob: https: http: ws: wss: about:", 477 "frame-src * data: blob: https: http: about:", 478 "object-src * data: blob:", 479 "base-uri *", 480 "form-action *", 481 ].join("; "); 482 const processedHtml = injectCSP(html, permissiveCsp); 483 inner.srcdoc = processedHtml; 484 } else { 485 const cspValue = buildCSP(csp); 486 const processedHtml = injectCSP(html, cspValue); 487 inner.srcdoc = processedHtml; 488 } 489 } 490 } else { 491 if (inner && inner.contentWindow) { 492 inner.contentWindow.postMessage(event.data, "*"); 493 } 494 } 495 } else if (event.source === inner.contentWindow) { 496 window.parent.postMessage(event.data, "*"); 497 } 498 }); 499 500 window.parent.postMessage({ 501 jsonrpc: "2.0", 502 method: "ui/notifications/sandbox-proxy-ready", 503 params: {}, 504 }, "*"); 505 </script> 506 </body> 507</html>`,tB="data-mcp-widget-fullscreen",tJ="data-mcp-widget-display-mode";async function tG(e,t){if(!e)throw Error("This host surface does not support ui/message");if(0===t.length)throw Error("ui/message requires at least one content block");await e(t)}function tY(e){let t=e?.ui;return t&&"object"==typeof t&&"resourceUri"in t&&"string"==typeof t.resourceUri?t.resourceUri:null}var tZ={name:"mcp-use-client",version:"2.0.0"};function tX(){return h.default.createElement("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":!0},h.default.createElement("path",{d:"M18 6 6 18"}),h.default.createElement("path",{d:"m6 6 12 12"}))}function tQ(e,t){return new Promise((r,i)=>{let n=()=>{window.removeEventListener("message",o),t?.signal?.removeEventListener("abort",s)},o=t=>{t.source===e.contentWindow&&t.data?.method==="ui/notifications/sandbox-proxy-ready"&&(n(),r())},s=()=>{n(),i(Error("View sandbox initialization was aborted"))};t?.signal?.aborted?s():(t?.signal?.addEventListener("abort",s,{once:!0}),window.addEventListener("message",o))})}function t0(e,t){let r=t$(t);return Object.keys(r).length>0?{..."object"==typeof e&&null!==e?e:{},structuredContent:r}:null==e?null:e}var t1=(0,h.memo)(function({viewId:e,source:t,sandboxUrl:r,toolName:i="view",toolInput:n,toolOutput:o,partialToolInput:s,customProps:a,cancelled:l,hostInfo:c=tZ,hostContext:u,hostCapabilities:d,messageCapabilities:p,modelContextCapabilities:f,cspMode:m="widget-declared",displayMode:g,onDisplayModeChange:b,inlineMaxWidth:v=768,chromeless:y,onMessage:w,onSamplingRequest:C,onDownloadFile:_,onAppToolsChanged:R,onModelContextUpdate:S,onLog:k,onReady:x,onLifecycleChange:E,onError:z,onCspViolation:A,onResourceResolved:P,wrapTransport:U,toolCallTimeout:T=6e5,mockOpenAiFileApis:M=!1,onInlineHeightChange:I,fullscreenHeader:q,renderFullscreenClose:L,className:O,testId:H="mcp-app-frame",invoking:N,invoked:j}){let $=(0,h.useRef)(null),D=(0,h.useRef)(null),F=(0,h.useRef)(null),K=(0,h.useRef)(new Map),W=(0,h.useRef)("live"===t.kind?t.connection:null),[V,B]=(0,h.useState)(null),[J,G]=(0,h.useState)(null),[Y,Z]=(0,h.useState)(null),[X,Q]=(0,h.useState)(0),[ee,et]=(0,h.useState)(400),[er,ei]=(0,h.useState)("inline"),en=g??er,eo=void 0!==w,es=void 0!==S,ea=void 0!==k,el=void 0!==C,ed=void 0!==_,ep=(0,h.useMemo)(()=>({...function({hasConnection:e,hasMessageHandler:t,hasModelContextHandler:r,hasLogHandler:i,hasSamplingHandler:n,hasDownloadHandler:o,messageCapabilities:s,modelContextCapabilities:a}){return{openLinks:{},...e?{serverTools:{},serverResources:{}}:{},...i?{logging:{}}:{},...n?{sampling:{}}:{},...o?{downloadFile:{}}:{},...r?{updateModelContext:a??{text:{}}}:{},...t?{message:s??{text:{}}}:{}}}({hasConnection:"live"===t.kind,hasMessageHandler:eo,hasModelContextHandler:es,hasLogHandler:ea,hasSamplingHandler:el,hasDownloadHandler:ed,messageCapabilities:p,modelContextCapabilities:f}),...d}),[d,ea,el,ed,eo,es,p,f,t.kind]),ef=(0,h.useMemo)(()=>u&&u.displayMode!==en?{...u,displayMode:en}:u,[u,en]),em=(0,h.useRef)(ef);em.current=ef;let eg=(0,h.useRef)(w);eg.current=w;let eb=(0,h.useRef)(C);eb.current=C;let ev=(0,h.useRef)(_);ev.current=_;let ey=(0,h.useRef)(R);ey.current=R;let ew=(0,h.useRef)(n);ew.current=n;let eC=(0,h.useRef)(s);eC.current=s;let e_=(0,h.useRef)(o);e_.current=o;let eR=(0,h.useRef)(a);eR.current=a;let eS=(0,h.useRef)(P);eS.current=P;let ek=(0,h.useRef)(S);ek.current=S;let ex=(0,h.useRef)(k);ex.current=k;let eE=(0,h.useRef)(z);eE.current=z;let ez=(0,h.useRef)(A);ez.current=A;let eA=(0,h.useRef)(x);eA.current=x;let eP=(0,h.useRef)(E);eP.current=E;let eU=(0,h.useRef)(I);eU.current=I;let eT=(0,h.useRef)(r);eT.current=r;let eM=(0,h.useRef)(m);eM.current=m;let eI=(0,h.useRef)(M);eI.current=M;let eq=(0,h.useCallback)(e=>{var t;let r,i,n,o=eT.current;if(o)return"function"==typeof o?o(e):o;return t={cspMode:eM.current,permissions:e.permissions,widgetCsp:e.declaredCsp},tW(i=new URL("https://sandbox.invalid/"),t),r=JSON.stringify(i.search).replace(/</g,"\\u003c"),n=tV.replace(` const scriptSrcParts = ["'unsafe-inline'", "'unsafe-eval'", resourceSrc]; 508`,` const scriptSrcParts = ["'unsafe-inline'", resourceSrc]; 509`).replace("<body>","<body><script>window.__SANDBOX_SEARCH__ = "+r+";</script>"),new URL(URL.createObjectURL(new Blob([n],{type:"text/html"})))},[]),{handleDisplayModeChange:eL,fullscreenShellClassName:eO,pipShellClassName:eH,isFullscreen:eN,isPip:ej}=function({displayMode:e,setDisplayMode:t}){let r="fullscreen"===e,i="pip"===e;return(0,h.useEffect)(()=>
509{if("u">typeof document){if("pip"===e||"fullscreen"===e)return document.documentElement.setAttribute(tJ,e),"fullscreen"===e?document.documentElement.setAttribute(tB,""):document.documentElement.removeAttribute(tB),()=>{document.documentElement.removeAttribute(tJ),document.documentElement.removeAttribute(tB)};document.documentElement.removeAttribute(tJ),document.documentElement.removeAttribute(tB)}},[e]),{handleDisplayModeChange:(0,h.useCallback)(e=>t(e),[t]),fullscreenShellClassName:r?"fixed inset-0 z-[200] w-full h-full min-h-0 bg-background flex flex-col [&:fullscreen]:h-full [&:fullscreen]:w-full [&:fullscreen]:bg-background":void 0,pipShellClassName:i?"fixed top-4 left-1/2 -translate-x-1/2 z-[200] rounded-3xl w-full min-w-[300px] h-[400px] shadow-2xl border overflow-hidden bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/80 flex flex-col":void 0,isFullscreen:r,isPip:i}}({containerRef:F,displayMode:en,setDisplayMode:(0,h.useCallback)(e=>{b?b(e):ei(e)},[b])}),e$=(0,h.useRef)(eL);e$.current=eL;let eD=(0,h.useRef)(en);eD.current=en;let eF="live"===t.kind?t.resourceUri:void 0,eK="preloaded"===t.kind?t.html:void 0;"live"===t.kind&&(W.current=t.connection),(0,h.useEffect)(()=>{let e=!1;eP.current?.({status:"resolving"});let r=e=>{B(e),eP.current?.({status:"sandbox-loading"});let t=eq(e);G(e=>e?.href===t.href?e:t),eS.current?.(e)};if("preloaded"===t.kind)return void r({html:t.html,declaredCsp:t.csp,csp:"permissive"===m?void 0:t.csp,permissions:t.permissions,prefersBorder:t.prefersBorder??!1,mimeType:"text/html;profile=mcp-app",mimeTypeValid:!0,mimeTypeWarning:null});let{connection:i,resourceUri:n}=t;return W.current=i,(async()=>{try{let t=await i.readResource(n);if(e)return;let o=i.resources?.find(e=>e.uri===n),s=function(e){let t,{resourceResult:r,listingResource:i,cspMode:n,resourceUri:o}=e,s=(Array.isArray(r?.contents)?r.contents:[])[0],a="";if(s&&(t=s.mimeType,"string"==typeof s.text?a=s.text:"string"==typeof s.blob&&(a=atob(s.blob))),!a)throw Error("No HTML content in resource");let l=i?._meta?.ui,c=s?._meta?.ui,u=l||c?{...l,...c}:void 0,d=u?.csp,h=u?.permissions,p=u?.prefersBorder??!1,f=t===ec,m=f?null:t?`Invalid MIME type "${t}" - SEP-1865 requires "${ec}"`:`Missing MIME type - SEP-1865 requires "${ec}"`;return m&&console.warn("[ViewRenderer] MIME type validation:",m,{resourceUri:o}),{html:a,declaredCsp:d,csp:"permissive"===n?void 0:d,permissions:h,prefersBorder:p,mimeType:t,mimeTypeValid:f,mimeTypeWarning:m}}({resourceResult:t,listingResource:o,cspMode:m,resourceUri:n});if(!s.mimeTypeValid){let e=s.mimeTypeWarning||'Invalid MIME type - SEP-1865 requires "text/html;profile=mcp-app"';Z(e),eP.current?.({status:"error",error:e});return}r(s)}catch(t){if(e)return;Z(t instanceof Error?t.message:"Failed to prepare view"),eP.current?.({status:"error",error:t instanceof Error?t.message:"Failed to prepare view"})}})(),()=>{e=!0}},[t.kind,eF,eK,m,eq]),(0,h.useEffect)(()=>{if(!J||"blob:"!==J.protocol)return;let e=K.current.get(J.href);return e&&(clearTimeout(e),K.current.delete(J.href)),()=>{let e=setTimeout(()=>{URL.revokeObjectURL(J.href),K.current.delete(J.href)},1e3);K.current.set(J.href,e)}},[J]);let eW=J?.protocol==="blob:",eV=!J||eW?null:(()=>{try{return J.origin}catch{return null}})();(0,h.useEffect)(()=>{if(!eV&&!eW)return;let e=e=>{let t=$.current;if(t?.contentWindow&&e.source===t.contentWindow&&(eW||e.origin===eV||"*"===eV)){if(e.data?.type==="mcp-apps:csp-violation")return void ez.current?.({directive:e.data.directive,effectiveDirective:e.data.effectiveDirective,blockedUri:e.data.blockedUri,sourceFile:e.data.sourceFile,lineNumber:e.data.lineNumber,columnNumber:e.data.columnNumber,originalPolicy:e.data.originalPolicy,timestamp:e.data.timestamp||Date.now()});if(e.data?.type==="iframe-console-log"){e.stopImmediatePropagation(),ex.current?.({level:e.data.level??"log",data:e.data.args});return}}};return window.addEventListener("message",e,!0),()=>window.removeEventListener("message",e,!0)},[eV,eW]),(0,h.useEffect)(()=>{if(!V||!J)return;let t=$.current;if(!t)return;let r=!1,i=null,n=new AbortController;return(async()=>{try{var o,s;let a,l;eP.current?.({status:"connecting"}),t.setAttribute("sandbox","allow-scripts allow-same-origin allow-forms");let u=function(e){if(!e)return"";let t=[];return e.camera&&t.push("camera"),e.microphone&&t.push("microphone"),e.geolocation&&t.push("geolocation"),e.clipboardWrite&&t.push("clipboard-write"),t.join("; ")}(V.permissions);if(u&&t.setAttribute("allow",u),"blob:"===J.protocol){let e=await fetch(J.href),i=await e.text();if(r||n.signal.aborted)return;let o=tQ(t,{signal:n.signal});t.srcdoc=i,await o}else{let e=tQ(t,{signal:n.signal});t.src=J.href,await e}if(r||n.signal.aborted)return;let d={...ep,sandbox:{csp:"permissive"===m?void 0:V.csp,permissions:V.permissions}};i=new eh(null,c,d,{hostContext:em.current}),d.message&&(i.onmessage=async({content:e})=>(await tG(eg.current,e),{})),d.sampling&&(i.oncreatesamplingmessage=async e=>{let t=eb.current;if(!t)throw Error("This host surface does not support sampling");return t(e)}),d.downloadFile&&(i.ondownloadfile=async e=>{let t=ev.current;if(!t)throw Error("This host surface does not support downloads");return t(e)}),i.onopenlink=async({url:e})=>(e&&window.open(e,"_blank","noopener,noreferrer"),{}),d.serverTools&&(i.oncalltool=async({name:e,arguments:t})=>{let r=W.current;if(!r)throw Error("Server connection not available");var n=r.tools;let o=n?.find(t=>t.name===e);if(!o)throw Error(`Tool "${e}" is not available to this app`);let s=o._meta?.ui?.visibility;if(s&&!s.includes("app"))throw Error(`Tool "${e}" is not available to this app`);try{return await r.callTool(e,t||{},{timeout:T,resetTimeoutOnProgress:!0})}catch(e){throw i?.sendToolCancelled({reason:e instanceof Error?e.message:String(e)}),e}}
509),d.serverResources&&(i.onreadresource=async({uri:e})=>{let t=W.current;if(!t)throw Error("Server connection not available");return await t.readResource(e)},i.onlistresources=async()=>{let e=W.current;if(!e)throw Error("Server connection not available");return{resources:[...e.resources??[]]}}),i.onrequestdisplaymode=async({mode:e})=>{let t=function({requested:e,current:t,hostAvailable:r,appAvailable:i}){return(r??["inline"]).includes(e)&&(i??["inline"]).includes(e)?e:t}({requested:e??"inline",current:eD.current,hostAvailable:em.current?.availableDisplayModes,appAvailable:i?.getAppCapabilities()?.availableDisplayModes});return await e$.current(t),{mode:t}},d.updateModelContext&&(i.onupdatemodelcontext=async({content:e,structuredContent:t})=>{if(!ek.current)throw Error("This host surface does not support model context updates");return await ek.current({content:e,structuredContent:t}),{}}),d.logging&&(i.onloggingmessage=async({level:e,data:t})=>(ex.current?.({level:e,data:t}),{})),i.onsizechange=async({height:e})=>{"inline"===eD.current&&void 0!==e&&(et(e),eU.current?.(e))};let h=null,p=async()=>{let e=ey.current;if(!i||!e)return;let t=i.getAppCapabilities();if(!t?.tools)return void e(null);let n=await i.listTools({});if(r||!i)return;let o=JSON.stringify(n.tools);if(o===h)return;h=o;let s=i;e({tools:n.tools,callTool:(e,t)=>s.callTool({name:e,arguments:t??{}})})};i.setNotificationHandler("notifications/tools/list_changed",async()=>{await p()});let f=async()=>{if(!i||r)return;let e=eC.current,t=void 0!==e_.current&&null!==e_.current;if(e&&!t)await i.sendToolInputPartial({arguments:e});else{let e={...ew.current,...t$(eR.current)};await i.sendToolInput({arguments:e})}let n=t0(e_.current,eR.current);n&&await i.sendToolResult(n)},g=(o=i,s=e=>{if(r)return;let t=e instanceof Error?e.message:"Failed to synchronize view state";eE.current?.(t),eP.current?.({status:"error",error:t})},a=o.oninitialized,l=!1,new Promise((e,t)=>{o.oninitialized=(...r)=>{a?.(...r);let i=Promise.resolve().then(f);if(!l){l=!0,i.then(e,t);return}i.catch(s)}})),b=new eu(t.contentWindow,t.contentWindow);if(U&&(b=U(b,e)),await i.connect(b),r||(await i.sendSandboxResourceReady({html:eI.current?function(e){let t=tF(e,"<head");if(void 0!==t)return tK(e,t,tD);let r=tF(e,"<html");if(void 0!==r)return tK(e,r,"<head>"+tD+"</head>");let i=tF(e,"<!doctype");return void 0!==i?tK(e,i,"<head>"+tD+"</head>"):tD+e}(V.html):V.html,csp:V.csp,permissions:V.permissions}),await g,r))return;D.current=i,Q(e=>e+1),eP.current?.({status:"initialized"}),await p(),eP.current?.({status:"ready"})}catch(e){if(!r&&!n.signal.aborted){let t=e instanceof Error?e.message:"Failed to connect view";Z(t),eE.current?.(t),eP.current?.({status:"error",error:t})}}})(),()=>{r=!0,n.abort();let e=i;D.current=null,ey.current?.(null),e&&(eP.current?.({status:"tearing-down"}),(async()=>{try{await Promise.race([e.teardownResource({}),new Promise((e,t)=>setTimeout(()=>t(Error("teardown timeout")),2e3))])}catch{}finally{e.close().catch(()=>{}),eP.current?.({status:"closed"})}})())}},[V,J,c,ep,m,e,U,T,M]),(0,h.useEffect)(()=>{let e=D.current;e&&0!==X&&ef&&e.setHostContext(ef)},[ef,X]),(0,h.useEffect)(()=>{let e=D.current;e&&0!==X&&s&&null==o&&e.sendToolInputPartial({arguments:s})},[X,s,o]),(0,h.useEffect)(()=>{let e=D.current;if(!e||0===X||s&&null==o)return;let t={...n,...t$(a)};e.sendToolInput({arguments:t})},[X,n,s,a,o]),(0,h.useEffect)(()=>{let e=D.current;if(!e||0===X)return;let t=t0(o,a);t&&e.sendToolResult(t)},[X,o,a]),(0,h.useEffect)(()=>{let e=D.current;e&&0!==X&&l&&e.sendToolCancelled({reason:"Cancelled by user"})},[l,X]);let eB=(0,h.useRef)(!1);(0,h.useEffect)(()=>{eB.current||0===X||(eB.current=!0,eA.current?.())},[X]);let eJ=null!==V&&V.prefersBorder&&"fullscreen"!==en;if(Y)return h.default.createElement("div",{className:O},h.default.createElement("div",{className:"border border-red-200/50 dark:border-red-800/50 bg-red-50/30 dark:bg-red-950/20 rounded-lg p-4"},h.default.createElement("p",{className:"text-sm text-red-600 dark:text-red-400"},"Failed to load view: ",Y)));if(!V)return h.default.createElement("div",{className:O},h.default.createElement("div",{className:"flex items-center justify-center w-full h-[200px]"},h.default.createElement("span",{className:"text-sm text-muted-foreground"},"Loading viewâ¦")));let eG=eO??eH??"flex group flex-1 items-center justify-center",eY={height:eN||ej?"100%":`${ee}px`,width:"100%",maxWidth:"inline"===en?`${v}px`:"100%",transition:eN||ej?void 0:"height 300ms ease-out"}
509,eZ=h.default.createElement("div",{ref:F,className:eN?`${eG} flex flex-col`:eG,style:ej?{height:400,maxWidth:700,zIndex:100}:eN?{zIndex:100}:void 0},eN&&h.default.createElement("header",{className:"grid shrink-0 items-center border-b border-zinc-200 bg-background px-3 dark:border-zinc-700",style:{height:50,gridTemplateColumns:"auto 1fr auto"}},L?L({onClick:()=>void eL("inline"),"data-testid":"debugger-exit-fullscreen-button","aria-label":"Exit fullscreen"}):h.default.createElement("button",{type:"button","data-testid":"debugger-exit-fullscreen-button","aria-label":"Exit fullscreen",className:"flex size-8 cursor-pointer items-center justify-center rounded-full border border-zinc-200 bg-background text-foreground shadow-sm hover:bg-muted dark:border-zinc-700",onClick:()=>void eL("inline")},h.default.createElement(tX,null)),h.default.createElement("div",{className:"flex min-w-0 items-center justify-center gap-2 px-2"},q?.iconUrl?h.default.createElement("img",{src:q.iconUrl,alt:"",className:"size-6 shrink-0 rounded-md object-contain"}):null,h.default.createElement("span",{className:"truncate text-sm font-medium text-foreground"},q?.title??i)),h.default.createElement("div",{className:"size-8 shrink-0","aria-hidden":!0})),ej&&(L?h.default.createElement("div",{className:"absolute right-3 top-3",style:{zIndex:110}},L({onClick:()=>void eL("inline"),"data-testid":"debugger-exit-pip-button","aria-label":"Exit picture-in-picture"})):h.default.createElement("button",{type:"button","data-testid":"debugger-exit-pip-button","aria-label":"Exit picture-in-picture",className:"absolute right-3 top-3 z-[110] flex size-8 cursor-pointer items-center justify-center rounded-full border border-border bg-background/90 text-foreground shadow-sm backdrop-blur-sm hover:bg-background",style:{zIndex:110},onClick:()=>void eL("inline")},h.default.createElement(tX,null))),h.default.createElement("div",{className:eN?"relative flex min-h-0 w-full flex-1 flex-col":ej?"relative w-full h-full min-h-0 flex flex-1 flex-col":"relative w-full flex flex-1 justify-center items-center"},!ej&&!eN&&(N||j)&&h.default.createElement("div",{className:"absolute -top-8 left-2 z-10 whitespace-nowrap pointer-events-none text-xs text-muted-foreground"},N&&!o?N:j),h.default.createElement("div",{"data-testid":H,"data-mcp-app-tool":i,className:"fullscreen"===en?"w-full h-full overflow-hidden":"w-full overflow-hidden",style:eY},h.default.createElement("iframe",{ref:$,title:`MCP App: ${i}`,className:eJ?"w-full h-full bg-transparent border border-border rounded-xl":"w-full h-full bg-transparent border-0"}))));return h.default.createElement("div",{className:O},eZ)},function(e,t){return e.viewId===t.viewId&&e.source===t.source&&e.sandboxUrl===t.sandboxUrl&&e.displayMode===t.displayMode&&e.cancelled===t.cancelled&&e.toolInput===t.toolInput&&e.toolOutput===t.toolOutput&&e.partialToolInput===t.partialToolInput&&e.customProps===t.customProps&&e.hostContext===t.hostContext&&e.hostCapabilities===t.hostCapabilities&&e.messageCapabilities===t.messageCapabilities&&e.modelContextCapabilities===t.modelContextCapabilities&&e.onMessage===t.onMessage&&e.onSamplingRequest===t.onSamplingRequest&&e.onDownloadFile===t.onDownloadFile&&e.onAppToolsChanged===t.onAppToolsChanged&&e.onModelContextUpdate===t.onModelContextUpdate&&e.cspMode===t.cspMode&&e.mockOpenAiFileApis===t.mockOpenAiFileApis&&e.onInlineHeightChange===t.onInlineHeightChange&&e.fullscreenHeader===t.fullscreenHeader&&e.renderFullscreenClose===t.renderFullscreenClose&&e.className===t.className&&e.onReady===t.onReady&&e.onLifecycleChange===t.onLifecycleChange&&!0});e.s(["McpClientProvider",0,function({children:e,mcpServers:t,defaultCallbackUrl:r,defaultOAuthProxyUrl:i,defaultProxyConfig:n,defaultAutoProxyFallback:o=!1,defaultServerConfig:s,clientInfo:a,storageProvider:l,enableRpcLogging:c=!1,onServerAdded:u,onServerRemoved:d,onServerStateChange:p,onSamplingRequest:f,onElicitationRequest:m}){let[g,b]=(0,h.useState)([]),[v,y]=(0,h.useState)([]),[w,C]=(0,h.useState)({}),[_,R]=(0,h.useState)(!1),S=(0,h.useRef)(!1),k=(0,h.useRef)([]);(0,h.useEffect)(()=>{k.current=v},[v]);let x=(0,h.useRef)({}),[E,z]=(0,h.useState)(void 0),[A,P]=(0,h.useState)(!1);(0,h.useEffect)(()=>
509{if(!c||"u"<typeof window){z(void 0),P(!0);return}Promise.resolve().then(()=>(ex(),ev)).then(e=>{tq.debug("[McpClientProvider] RPC logger loaded"),z(()=>e.wrapTransportForLogging),P(!0)}).catch(e=>{tq.error("[McpClientProvider] Failed to load RPC logger:",e),z(void 0),P(!0)})},[c]),(0,h.useEffect)(()=>{A?S.current||(S.current=!0,(async()=>{if(tq.debug("[McpClientProvider] Loading servers, storageProvider:",!!l,"mcpServers:",t),!l){if(t){let e=Object.entries(t).map(([e,t])=>({id:e,options:t}));tq.debug("[McpClientProvider] Loaded from mcpServers prop:",e.length),b(e)}R(!0);return}try{let e=await Promise.resolve(l.getServers());if(tq.debug("[McpClientProvider] Loaded from storage:",Object.keys(e).length),l.getServerMetadata)try{let t=Object.keys(e).map(async e=>{let t=await Promise.resolve(l.getServerMetadata(e));return[e,t]}),r=await Promise.all(t);x.current=Object.fromEntries(r.filter(e=>void 0!==e[1])),tq.debug("[McpClientProvider] Loaded cached metadata for",Object.keys(x.current).length,"servers")}catch(e){tq.warn("[McpClientProvider] Failed to load cached metadata:",e)}let r={...e,...t},i=Object.entries(r).map(([e,t])=>({id:e,options:t}));tq.debug("[McpClientProvider] Total servers after merge:",i.length),b(i),R(!0)}catch(e){tq.error("[McpClientProvider] Failed to load from storage:",e),t&&b(Object.entries(t).map(([e,t])=>({id:e,options:t}))),R(!0)}})()):tq.debug("[McpClientProvider] Waiting for RPC logging to be ready before loading servers")},[l,t,A]),(0,h.useEffect)(()=>{l&&_&&(async()=>{try{let e=g.reduce((e,t)=>{var r;return e[t.id]=(r=t.options,eA(r)),e},{});await Promise.resolve(l.setServers(e))}catch(e){tq.error("[McpClientProvider] Failed to save to storage:",e)}})()},[g,l,_]);let U=(0,h.useCallback)(e=>{tq.debug(`[McpClientProvider] handleServerUpdate called for server ${e.id}`,{toolCount:e.tools.length,state:e.state});let t=[];y(r=>{let i=r.findIndex(t=>t.id===e.id);if(-1===i)return tq.debug(`[McpClientProvider] Adding new server ${e.id} to state`),t.push(()=>u?.(e.id,e)),[...r,e];let n=r[i],o=n.state!==e.state,s=n.serverInfo!==e.serverInfo;if(tq.debug(`[McpClientProvider] Comparing server ${e.id}:`,{toolsChanged:n.tools!==e.tools,currentToolCount:n.tools.length,updatedToolCount:e.tools.length,stateChanged:o}),tH(n,e))return tq.debug(`[McpClientProvider] No changes detected for server ${e.id}, skipping update`),r;if(tq.debug(`[McpClientProvider] Updating server ${e.id} in state`),o&&t.push(()=>p?.(e.id,e.state)),s&&e.serverInfo&&l?.setServerMetadata){let t={name:e.serverInfo.name,version:e.serverInfo.version,title:e.serverInfo.title,websiteUrl:e.serverInfo.websiteUrl,icons:e.serverInfo.icons,icon:e.serverInfo.icon};x.current[e.id]=t,Promise.resolve(l.setServerMetadata(e.id,t)).catch(e=>{tq.error("[McpClientProvider] Failed to save server metadata:",e)})}let a=[...r];return a[i]=e,a}),t.length>0&&queueMicrotask(()=>{t.forEach(e=>e())})},[u,p,l]),T=(0,h.useCallback)((e,t)=>{b(r=>r.find(t=>t.id===e)?r:(tq.debug("[McpClientProvider] Adding new server to configs:",e),[...r,{id:e,options:t}]))},[]),M=(0,h.useCallback)(async(e,t)=>{let r=k.current.find(t=>t.id===e);if(y(t=>t.filter(t=>t.id!==e)),b(t=>t.filter(t=>t.id!==e)),C(t=>{let{[e]:r,...i}=t;return i}),r?.disconnect&&await r.disconnect(),t?.clearCredentials&&r?.clearStorage&&await r.clearStorage(),c){let{clearRpcLogs:t}=await Promise.resolve().then(()=>(ex(),ev));t(e)}d?.(e)},[c,d]),I=(0,h.useCallback)(async(e,t)=>{let r=g.find(t=>t.id===e);if(!r)return void tq.warn(`[McpClientProvider] Cannot update server "${e}" - not found`);let i={...r.options,...t};if(tO(eP(r.options),eP(i)))return;let n=k.current.find(t=>t.id===e);await n?.disconnect(),y(t=>t.filter(t=>t.id!==e)),b(t=>t.map(t=>t.id===e?{id:e,options:i}:t)),C(t=>({...t,[e]:(t[e]??0)+1}))},[g]),q=(0,h.useCallback)(async e=>{if(!g.find(t=>t.id===e))return void tq.warn(`[McpClientProvider] Cannot reconnect server "${e}" - not found`);let t=k.current.find(t=>t.id===e);await t?.disconnect(),y(t=>t.filter(t=>t.id!==e)),C(t=>({...t,[e]:(t[e]??0)+1}))},[g]),L=(0,h.useCallback)(async(e,t)=>new Promise(r=>{let i=g.find(t=>
509t.id===e);if(!i){tq.warn(`[McpClientProvider] Cannot update server metadata for "${e}" - not found`),r();return}let n={...i.options,displayName:t.name};y(r=>r.map(r=>r.id===e?{...r,displayName:t.name}:r)),b(t=>{let i=t.map(t=>t.id===e?{id:e,options:n}:t);return setTimeout(()=>r(),0),i})}),[g]),O=(0,h.useCallback)(e=>v.find(t=>t.id===e),[v]),H=(0,h.useMemo)(()=>({servers:v,addServer:T,removeServer:M,updateServerMetadata:L,updateServer:I,getServer:O,storageLoaded:_}),[v,T,M,L,I,O,_]),{capabilities:N,...j}=a||{},$=(0,h.useMemo)(()=>Object.keys(j).length?j:void 0,[a]),D=(0,h.useMemo)(()=>g.map(e=>{let t=s?{...s,...e.options}:e.options;return N&&(t={...t,clientOptions:{...t.clientOptions,capabilities:{...N,...t.clientOptions?.capabilities}}}),{id:e.id,options:t}}),[g,N,s]),F="u">typeof window&&/\/oauth\/callback\/?$/.test(window.location.pathname);return h.default.createElement(tL.Provider,{value:H},e,!F&&D.map(e=>h.default.createElement(tN,{key:`${e.id}-v${w[e.id]??0}`,id:e.id,options:e.options,defaultCallbackUrl:r,defaultOAuthProxyUrl:i,defaultProxyConfig:n,defaultAutoProxyFallback:o,clientInfo:$,cachedMetadata:x.current[e.id],onUpdate:U,onUpdateConfig:I,onUpdateDisplayName:(e,t)=>L(e,{name:t}),onReconnect:q,rpcWrapTransport:E,onGlobalSamplingRequest:f,onGlobalElicitationRequest:m})))},"ViewRenderer",0,t1,"buildViewSandboxUrl",0,function(e,t){let r=new URL(e.href);return tW(r,t),r},"getViewResourceUri",0,tY,"isOAuthInteractionRequired",0,eO,"isToolVisibleToModel",0,function(e){if(!e._meta||"object"!=typeof e._meta)return!0;let t=e._meta.ui;if(!t||"object"!=typeof t)return!0;let r=t.visibility;return!Array.isArray(r)||r.some(e=>"model"===e)},"isViewResource",0,function(e){return e===ec},"isViewTool",0,function(e){return null!==tY(e)},"onMcpAuthorization",0,function(){return tz||(tz=tM()),tz},"useMcp",0,tE,"useMcpClient",0,tj,"useMcpServer",0,function(e){let{servers:t}=tj();return(0,h.useMemo)(()=>t.find(t=>t.id===e),[e,t])}],566038)}]); 510 511//# chunkId=db97438d-9145-57c5-be8e-30fde126fbfa
Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.