@mcp-use/inspector 20.0.0-beta.8 → 20.0.0-beta.9
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -18
- package/dist/cdn/{ChatTab-C-Ysv6Zf.js → ChatTab-CU-Gf-GY.js} +6 -6
- package/dist/cdn/{ConnectionSettingsForm-CNuMa6jp.js → ConnectionSettingsForm-C4fEbp4v.js} +1 -1
- package/dist/cdn/{ConnectionSettingsTab-qSVQ1aIF.js → ConnectionSettingsTab-DXUrhGfL.js} +1 -1
- package/dist/cdn/{MCPAppsDebugControls-BpP-Ifap.js → MCPAppsDebugControls-Dp_o3k-P.js} +2 -2
- package/dist/cdn/{MarkdownRenderer-CK_6n3T9.js → MarkdownRenderer-COhmp4fm.js} +1 -1
- package/dist/cdn/{McpAppsViewPanel-jlsYQ7uS.js → McpAppsViewPanel-CMQZ28xs.js} +2 -2
- package/dist/cdn/{OAuthCallback--NZdLoWx.js → OAuthCallback-ClEnwZ9o.js} +1 -1
- package/dist/cdn/{PromptsTab-DSGYL32k.js → PromptsTab-DPjWr6W0.js} +1 -1
- package/dist/cdn/{ResourcesTab-d3wxN7xC.js → ResourcesTab-D8hOTjDs.js} +5 -5
- package/dist/cdn/{SamplingTab-DETdWNJk.js → SamplingTab-e1G8Qx1k.js} +3 -3
- package/dist/cdn/{ToolsTab-BMcnfEWg.js → ToolsTab-jNn6Cz6A.js} +4 -4
- package/dist/cdn/{ViewPreview-CBhrVdwx.js → ViewPreview-BpQYOKES.js} +2 -2
- package/dist/cdn/{dist-SxRsB1iS.js → dist-8Z7HZAGn.js} +2 -2
- package/dist/cdn/{index-browser-Dm3R1Mfe.js → index-browser-nWAQnCTk.js} +112 -200
- package/dist/cdn/inspector.js +5 -5
- package/dist/cdn/{react-Bl-hSkvn.js → react-8UPT_kVF.js} +521 -607
- package/dist/cdn/{telemetry-DjQn_Xm9.js → telemetry-X2tRdL3U.js} +37 -69
- package/dist/cdn/{useConfig-B_adtnP1.js → useConfig-BMqxaGDa.js} +2 -2
- package/dist/cdn/{useViewHostProps-CDOm2w6u.js → useViewHostProps-DMArgRGs.js} +1 -1
- package/dist/cli.js +1 -1
- package/dist/client/index.js +1 -6
- package/dist/client/telemetry/init.d.ts.map +1 -1
- package/dist/server/cdn-shell.js +2 -2
- package/dist/server/{chunk-BD3ROXCC.js → chunk-3WVGQOQX.js} +1 -1
- package/dist/server/{chunk-XTVIGRTB.js → chunk-BIKA6WIX.js} +1 -1
- package/dist/server/{chunk-BPXKTFQ5.js → chunk-KB6CHWZ4.js} +1 -1
- package/dist/server/cli.js +2 -2
- package/dist/server/index.js +3 -3
- package/dist/server/middleware.js +3 -3
- package/dist/server/version.js +1 -1
- package/dist/web/assets/{ChatTab-DxD-KLW_.js → ChatTab-fclW7HPg.js} +1 -1
- package/dist/web/assets/{ConnectionSettingsTab-pO6p0U0f.js → ConnectionSettingsTab-DNl63AkH.js} +1 -1
- package/dist/web/assets/{ElicitationTab-o5_z6gqe.js → ElicitationTab-B73XazTU.js} +1 -1
- package/dist/web/assets/{MCPAppsDebugControls-CZW1uZdH.js → MCPAppsDebugControls-BYLu5GRy.js} +1 -1
- package/dist/web/assets/{ManufactOAuthCallback-BnWhf5bW.js → ManufactOAuthCallback-Dp3icsBc.js} +1 -1
- package/dist/web/assets/{MarkdownRenderer-gUUHRIm1.js → MarkdownRenderer-CcvZ7qUS.js} +1 -1
- package/dist/web/assets/{McpAppsViewPanel-CDJDb4t-.js → McpAppsViewPanel-KD_ZnjfO.js} +1 -1
- package/dist/web/assets/{NotificationsTab-CkJ5E_sR.js → NotificationsTab-CV9kw9j-.js} +1 -1
- package/dist/web/assets/{OAuthCallback-Dv_mFcua.js → OAuthCallback-C9J2xEkV.js} +1 -1
- package/dist/web/assets/{PromptsTab-CLwWFf6d.js → PromptsTab-irNacYfj.js} +1 -1
- package/dist/web/assets/{ResourcesTab-B8cnuq-m.js → ResourcesTab-C-4Fd-HY.js} +1 -1
- package/dist/web/assets/{SamplingTab-BjYHYRHX.js → SamplingTab-B7bM9cnF.js} +1 -1
- package/dist/web/assets/{ServerMetadataTab-CPlclbb7.js → ServerMetadataTab-CnGUw9uD.js} +1 -1
- package/dist/web/assets/{ToolsTab-BSSwvp4Q.js → ToolsTab-DBHJRY9V.js} +1 -1
- package/dist/web/assets/{ViewPreview-C_LJdgt9.js → ViewPreview-D7NNsxbe.js} +1 -1
- package/dist/web/assets/{checkbox-BuuDhnpk.js → checkbox-C9WZqT8k.js} +1 -1
- package/dist/web/assets/{dist-C39gcmyH.js → dist-ChWdPMRV.js} +3 -3
- package/dist/web/assets/{index-CyvvaDNR.js → index-B5OxiZlj.js} +13 -13
- package/dist/web/assets/{shared-Chk1rURG.js → shared-BWLzd0mh.js} +1 -1
- package/dist/web/assets/{tabs-subtle-CK4nucyB.js → tabs-subtle-DkVoZG5s.js} +1 -1
- package/dist/web/assets/{useConfig-CgQbKjVT.js → useConfig-CTtYs2lN.js} +1 -1
- package/dist/web/assets/{useViewHostProps-DFI7Ywo7.js → useViewHostProps-DOJOoXbY.js} +1 -1
- package/dist/web/index.html +2 -2
- package/package.json +4 -4
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/ChatTab-
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/ChatTab-fclW7HPg.js","assets/react-CU_d2d5K.js","assets/button-C8Xa2k4x.js","assets/createLucideIcon-BEHeJH0M.js","assets/FormContext-sV-yByKz.js","assets/input-C0OQCUZy.js","assets/select-D6jzbLJn.js","assets/AnimatePresence-FfDQQNFJ.js","assets/label-CI7JWQOo.js","assets/tabs-subtle-DkVoZG5s.js","assets/refresh-cw-B5iaAZKn.js","assets/MarkdownRenderer-CcvZ7qUS.js","assets/checkbox-C9WZqT8k.js","assets/dist-ChWdPMRV.js","assets/useConfig-CTtYs2lN.js","assets/schemaHelpers-DLNTQr_6.js","assets/McpAppsViewPanel-KD_ZnjfO.js","assets/WidgetWrapper-cv_BM1bY.js","assets/useViewHostProps-DOJOoXbY.js","assets/textarea-CRTXuRmE.js","assets/ToolsTab-DBHJRY9V.js","assets/MCPAppsDebugControls-BYLu5GRy.js","assets/maximize-2-Br1WQzT2.js","assets/sparkles-BGYTDThM.js","assets/zap-BDWHCVHU.js","assets/code-B14rVdNt.js","assets/shared-BWLzd0mh.js","assets/ListTabHeader-CrGae306.js","assets/maximize-CJNgRe6S.js","assets/save-TM6fvNrt.js","assets/PromptsTab-irNacYfj.js","assets/ResourcesTab-C-4Fd-HY.js","assets/brush-DX0UZ_pI.js","assets/SamplingTab-B7bM9cnF.js","assets/ElicitationTab-B73XazTU.js","assets/NotificationsTab-CV9kw9j-.js","assets/ServerMetadataTab-CnGUw9uD.js","assets/inspector-settings-layout-yjKRJDai.js","assets/ConnectionSettingsTab-DNl63AkH.js","assets/OAuthCallback-C9J2xEkV.js","assets/ManufactOAuthCallback-Dp3icsBc.js","assets/ViewPreview-D7NNsxbe.js"])))=>i.map(i=>d[i]);
|
|
2
2
|
import{a as e,i as t,n,s as r,t as i}from"./react-CU_d2d5K.js";import{$ as a,$n as o,A as s,At as c,B as l,Bn as u,Ct as d,D as f,Dn as p,Dt as m,E as h,En as g,F as _,G as v,Gt as y,I as b,It as x,J as S,K as C,Kn as w,Kt as T,L as E,Lt as ee,M as D,Mn as te,Mt as ne,N as re,Nn as O,Nt as ie,O as k,Ot as A,P as j,Pn as ae,Pt as oe,Q as se,R as ce,Rn as M,Rt as N,S as le,St as ue,T as de,Tn as fe,Tt as pe,U as me,Un as he,Ut as ge,Wn as _e,X as ve,Y as ye,Yn as be,Z as xe,Zn as P,_ as Se,_t as Ce,a as we,an as Te,ar as Ee,at as De,b as Oe,c as ke,cr as Ae,ct as je,dt as Me,et as Ne,f as Pe,ft as Fe,g as Ie,gt as Le,h as Re,hn as ze,ht as Be,i as Ve,in as He,ir as Ue,it as We,j as Ge,jt as Ke,k as qe,kn as Je,kt as Ye,lt as Xe,m as Ze,mn as Qe,mt as $e,n as et,nr as tt,o as nt,on as rt,or as it,ot as at,pt as ot,q as st,qt as ct,r as lt,rn as ut,rr as dt,rt as ft,s as pt,sr as F,st as mt,t as ht,tt as gt,ut as _t,v as vt,vt as yt,w as bt,wn as xt,wt as St,x as Ct,y as wt,yt as Tt,z as Et,zn as Dt}from"./input-C0OQCUZy.js";import{n as Ot,t as I}from"./createLucideIcon-BEHeJH0M.js";import{B as kt,D as At,H as L,M as jt,O as Mt,V as Nt,_ as Pt,a as Ft,c as It,d as Lt,g as Rt,h as zt,j as Bt,m as Vt,o as Ht,p as Ut,s as Wt,t as Gt,u as Kt,v as qt,z as Jt}from"./button-C8Xa2k4x.js";import{n as Yt,t as Xt}from"./label-CI7JWQOo.js";import{b as Zt,l as Qt,r as $t,t as en}from"./AnimatePresence-FfDQQNFJ.js";import{C as tn,S as nn,T as rn,_ as an,a as on,b as sn,c as cn,d as ln,f as un,g as dn,h as fn,i as pn,l as mn,m as hn,n as gn,p as _n,r as vn,t as yn,u as bn,v as xn,w as Sn,x as Cn,y as wn}from"./select-D6jzbLJn.js";import{c as Tn,i as En,l as Dn,o as On,r as kn,t as An}from"./FormContext-sV-yByKz.js";(function(){let e=document.createElement(`link`).relList;if(e&&e.supports&&e.supports(`modulepreload`))return;for(let e of document.querySelectorAll(`link[rel="modulepreload"]`))n(e);new MutationObserver(e=>{for(let t of e)if(t.type===`childList`)for(let e of t.addedNodes)e.tagName===`LINK`&&e.rel===`modulepreload`&&n(e)}).observe(document,{childList:!0,subtree:!0});function t(e){let t={};return e.integrity&&(t.integrity=e.integrity),e.referrerPolicy&&(t.referrerPolicy=e.referrerPolicy),e.crossOrigin===`use-credentials`?t.credentials=`include`:e.crossOrigin===`anonymous`?t.credentials=`omit`:t.credentials=`same-origin`,t}function n(e){if(e.ep)return;e.ep=!0;let n=t(e);fetch(e.href,n)}})();var jn=n((e=>{function t(e,t){var n=e.length;e.push(t);a:for(;0<n;){var r=n-1>>>1,a=e[r];if(0<i(a,t))e[r]=t,e[n]=a,n=r;else break a}}function n(e){return e.length===0?null:e[0]}function r(e){if(e.length===0)return null;var t=e[0],n=e.pop();if(n!==t){e[0]=n;a:for(var r=0,a=e.length,o=a>>>1;r<o;){var s=2*(r+1)-1,c=e[s],l=s+1,u=e[l];if(0>i(c,n))l<a&&0>i(u,c)?(e[r]=u,e[l]=n,r=l):(e[r]=c,e[s]=n,r=s);else if(l<a&&0>i(u,n))e[r]=u,e[l]=n,r=l;else break a}}return t}function i(e,t){var n=e.sortIndex-t.sortIndex;return n===0?e.id-t.id:n}if(e.unstable_now=void 0,typeof performance==`object`&&typeof performance.now==`function`){var a=performance;e.unstable_now=function(){return a.now()}}else{var o=Date,s=o.now();e.unstable_now=function(){return o.now()-s}}var c=[],l=[],u=1,d=null,f=3,p=!1,m=!1,h=!1,g=!1,_=typeof setTimeout==`function`?setTimeout:null,v=typeof clearTimeout==`function`?clearTimeout:null,y=typeof setImmediate<`u`?setImmediate:null;function b(e){for(var i=n(l);i!==null;){if(i.callback===null)r(l);else if(i.startTime<=e)r(l),i.sortIndex=i.expirationTime,t(c,i);else break;i=n(l)}}function x(e){if(h=!1,b(e),!m)if(n(c)!==null)m=!0,S||(S=!0,D());else{var t=n(l);t!==null&&re(x,t.startTime-e)}}var S=!1,C=-1,w=5,T=-1;function E(){return g?!0:!(e.unstable_now()-T<w)}function ee(){if(g=!1,S){var t=e.unstable_now();T=t;var i=!0;try{a:{m=!1,h&&(h=!1,v(C),C=-1),p=!0;var a=f;try{b:{for(b(t),d=n(c);d!==null&&!(d.expirationTime>t&&E());){var o=d.callback;if(typeof o==`function`){d.callback=null,f=d.priorityLevel;var s=o(d.expirationTime<=t);if(t=e.unstable_now(),typeof s==`function`){d.callback=s,b(t),i=!0;break b}d===n(c)&&r(c),b(t)}else r(c);d=n(c)}if(d!==null)i=!0;else{var u=n(l);u!==null&&re(x,u.startTime-t),i=!1}}break a}finally{d=null,f=a,p=!1}i=void 0}}finally{i?D():S=!1}}}var D;if(typeof y==`function`)D=function(){y(ee)};else if(typeof MessageChannel<`u`){var te=new MessageChannel,ne=te.port2;te.port1.onmessage=ee,D=function(){ne.postMessage(null)}}else D=function(){_(ee,0)};function re(t,n){C=_(function(){t(e.unstable_now())},n)}e.unstable_IdlePriority=5,e.unstable_ImmediatePriority=1,e.unstable_LowPriority=4,e.unstable_NormalPriority=3,e.unstable_Profiling=null,e.unstable_UserBlockingPriority=2,e.unstable_cancelCallback=function(e){e.callback=null},e.unstable_forceFrameRate=function(e){0>e||125<e?console.error(`forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported`):w=0<e?Math.floor(1e3/e):5},e.unstable_getCurrentPriorityLevel=function(){return f},e.unstable_next=function(e){switch(f){case 1:case 2:case 3:var t=3;break;default:t=f}var n=f;f=t;try{return e()}finally{f=n}},e.unstable_requestPaint=function(){g=!0},e.unstable_runWithPriority=function(e,t){switch(e){case 1:case 2:case 3:case 4:case 5:break;default:e=3}var n=f;f=e;try{return t()}finally{f=n}},e.unstable_scheduleCallback=function(r,i,a){var o=e.unstable_now();switch(typeof a==`object`&&a?(a=a.delay,a=typeof a==`number`&&0<a?o+a:o):a=o,r){case 1:var s=-1;break;case 2:s=250;break;case 5:s=1073741823;break;case 4:s=1e4;break;default:s=5e3}return s=a+s,r={id:u++,callback:i,priorityLevel:r,startTime:a,expirationTime:s,sortIndex:-1},a>o?(r.sortIndex=a,t(l,r),n(c)===null&&r===n(l)&&(h?(v(C),C=-1):h=!0,re(x,a-o))):(r.sortIndex=s,t(c,r),m||p||(m=!0,S||(S=!0,D()))),r},e.unstable_shouldYield=E,e.unstable_wrapCallback=function(e){var t=f;return function(){var n=f;f=t;try{return e.apply(this,arguments)}finally{f=n}}}})),Mn=n(((e,t)=>{t.exports=jn()})),Nn=n((e=>{var t=Mn(),n=i(),r=Ae();function a(e){var t=`https://react.dev/errors/`+e;if(1<arguments.length){t+=`?args[]=`+encodeURIComponent(arguments[1]);for(var n=2;n<arguments.length;n++)t+=`&args[]=`+encodeURIComponent(arguments[n])}return`Minified React error #`+e+`; visit `+t+` for the full message or use the non-minified dev environment for full errors and additional helpful warnings.`}function o(e){return!(!e||e.nodeType!==1&&e.nodeType!==9&&e.nodeType!==11)}function s(e){var t=e,n=e;if(e.alternate)for(;t.return;)t=t.return;else{e=t;do t=e,t.flags&4098&&(n=t.return),e=t.return;while(e)}return t.tag===3?n:null}function c(e){if(e.tag===13){var t=e.memoizedState;if(t===null&&(e=e.alternate,e!==null&&(t=e.memoizedState)),t!==null)return t.dehydrated}return null}function l(e){if(e.tag===31){var t=e.memoizedState;if(t===null&&(e=e.alternate,e!==null&&(t=e.memoizedState)),t!==null)return t.dehydrated}return null}function u(e){if(s(e)!==e)throw Error(a(188))}function d(e){var t=e.alternate;if(!t){if(t=s(e),t===null)throw Error(a(188));return t===e?e:null}for(var n=e,r=t;;){var i=n.return;if(i===null)break;var o=i.alternate;if(o===null){if(r=i.return,r!==null){n=r;continue}break}if(i.child===o.child){for(o=i.child;o;){if(o===n)return u(i),e;if(o===r)return u(i),t;o=o.sibling}throw Error(a(188))}if(n.return!==r.return)n=i,r=o;else{for(var c=!1,l=i.child;l;){if(l===n){c=!0,n=i,r=o;break}if(l===r){c=!0,r=i,n=o;break}l=l.sibling}if(!c){for(l=o.child;l;){if(l===n){c=!0,n=o,r=i;break}if(l===r){c=!0,r=o,n=i;break}l=l.sibling}if(!c)throw Error(a(189))}}if(n.alternate!==r)throw Error(a(190))}if(n.tag!==3)throw Error(a(188));return n.stateNode.current===n?e:t}function f(e){var t=e.tag;if(t===5||t===26||t===27||t===6)return e;for(e=e.child;e!==null;){if(t=f(e),t!==null)return t;e=e.sibling}return null}var p=Object.assign,m=Symbol.for(`react.element`),h=Symbol.for(`react.transitional.element`),g=Symbol.for(`react.portal`),_=Symbol.for(`react.fragment`),v=Symbol.for(`react.strict_mode`),y=Symbol.for(`react.profiler`),b=Symbol.for(`react.consumer`),x=Symbol.for(`react.context`),S=Symbol.for(`react.forward_ref`),C=Symbol.for(`react.suspense`),w=Symbol.for(`react.suspense_list`),T=Symbol.for(`react.memo`),E=Symbol.for(`react.lazy`),ee=Symbol.for(`react.activity`),D=Symbol.for(`react.memo_cache_sentinel`),te=Symbol.iterator;function ne(e){return typeof e!=`object`||!e?null:(e=te&&e[te]||e[`@@iterator`],typeof e==`function`?e:null)}var re=Symbol.for(`react.client.reference`);function O(e){if(e==null)return null;if(typeof e==`function`)return e.$$typeof===re?null:e.displayName||e.name||null;if(typeof e==`string`)return e;switch(e){case _:return`Fragment`;case y:return`Profiler`;case v:return`StrictMode`;case C:return`Suspense`;case w:return`SuspenseList`;case ee:return`Activity`}if(typeof e==`object`)switch(e.$$typeof){case g:return`Portal`;case x:return e.displayName||`Context`;case b:return(e._context.displayName||`Context`)+`.Consumer`;case S:var t=e.render;return e=e.displayName,e||=(e=t.displayName||t.name||``,e===``?`ForwardRef`:`ForwardRef(`+e+`)`),e;case T:return t=e.displayName||null,t===null?O(e.type)||`Memo`:t;case E:t=e._payload,e=e._init;try{return O(e(t))}catch{}}return null}var ie=Array.isArray,k=n.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,A=r.__DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,j={pending:!1,data:null,method:null,action:null},ae=[],oe=-1;function se(e){return{current:e}}function ce(e){0>oe||(e.current=ae[oe],ae[oe]=null,oe--)}function M(e,t){oe++,ae[oe]=e.current,e.current=t}var N=se(null),le=se(null),ue=se(null),de=se(null);function fe(e,t){switch(M(ue,t),M(le,e),M(N,null),t.nodeType){case 9:case 11:e=(e=t.documentElement)&&(e=e.namespaceURI)?ef(e):0;break;default:if(e=t.tagName,t=t.namespaceURI)t=ef(t),e=tf(t,e);else switch(e){case`svg`:e=1;break;case`math`:e=2;break;default:e=0}}ce(N),M(N,e)}function pe(){ce(N),ce(le),ce(ue)}function me(e){e.memoizedState!==null&&M(de,e);var t=N.current,n=tf(t,e.type);t!==n&&(M(le,e),M(N,n))}function he(e){le.current===e&&(ce(N),ce(le)),de.current===e&&(ce(de),up._currentValue=j)}var ge,_e;function ve(e){if(ge===void 0)try{throw Error()}catch(e){var t=e.stack.trim().match(/\n( *(at )?)/);ge=t&&t[1]||``,_e=-1<e.stack.indexOf(`
|
|
3
3
|
at`)?` (<anonymous>)`:-1<e.stack.indexOf(`@`)?`@unknown:0:0`:``}return`
|
|
4
4
|
`+ge+e+_e}var ye=!1;function be(e,t){if(!e||ye)return``;ye=!0;var n=Error.prepareStackTrace;Error.prepareStackTrace=void 0;try{var r={DetermineComponentFrameRoot:function(){try{if(t){var n=function(){throw Error()};if(Object.defineProperty(n.prototype,"props",{set:function(){throw Error()}}),typeof Reflect==`object`&&Reflect.construct){try{Reflect.construct(n,[])}catch(e){var r=e}Reflect.construct(e,[],n)}else{try{n.call()}catch(e){r=e}e.call(n.prototype)}}else{try{throw Error()}catch(e){r=e}(n=e())&&typeof n.catch==`function`&&n.catch(function(){})}}catch(e){if(e&&r&&typeof e.stack==`string`)return[e.stack,r.stack]}return[null,null]}};r.DetermineComponentFrameRoot.displayName=`DetermineComponentFrameRoot`;var i=Object.getOwnPropertyDescriptor(r.DetermineComponentFrameRoot,`name`);i&&i.configurable&&Object.defineProperty(r.DetermineComponentFrameRoot,"name",{value:`DetermineComponentFrameRoot`});var a=r.DetermineComponentFrameRoot(),o=a[0],s=a[1];if(o&&s){var c=o.split(`
|
|
@@ -154,7 +154,7 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
|
|
|
154
154
|
`;break;case`id`:s=t.includes(`\0`)?void 0:t;break;case`retry`:/^\d+$/.test(t)?r(parseInt(t,10)):n(new tS(`Invalid \`retry\` value: "${t}"`,{type:`invalid-retry`,value:t,line:i}));break;default:n(new tS(`Unknown field "${e.length>20?`${e.slice(0,20)}\u2026`:e}"`,{type:`unknown-field`,field:e,value:t,line:i}));break}}function p(){c.length>0&&t({id:s,event:l||void 0,data:c.endsWith(`
|
|
155
155
|
`)?c.slice(0,-1):c}),s=void 0,c=``,l=``}function m(e={}){a&&e.consume&&d(a),o=!0,s=void 0,c=``,l=``,a=``}return{feed:u,reset:m}}function iS(e){let t=[],n=``,r=0;for(;r<e.length;){let i=e.indexOf(`\r`,r),a=e.indexOf(`
|
|
156
156
|
`,r),o=-1;if(i!==-1&&a!==-1?o=Math.min(i,a):i===-1?a!==-1&&(o=a):o=i===e.length-1?-1:i,o===-1){n=e.slice(r);break}else{let n=e.slice(r,o);t.push(n),r=o+1,e[r-1]===`\r`&&e[r]===`
|
|
157
|
-
`&&r++}}return[t,n]}var aS=class extends TransformStream{constructor({onError:e,onRetry:t,onComment:n}={}){let r;super({start(i){r=rS({onEvent:e=>{i.enqueue(e)},onError(t){e===`terminate`?i.error(t):typeof e==`function`&&e(t)},onRetry:t,onComment:n})},transform(e){r.feed(e)}})}},oS=`modulepreload`,sS=function(e){return`/inspector/`+e},cS={},lS=function(e,t,n){let r=Promise.resolve();if(t&&t.length>0){let e=document.getElementsByTagName(`link`),i=document.querySelector(`meta[property=csp-nonce]`),a=i?.nonce||i?.getAttribute(`nonce`);function o(e){return Promise.all(e.map(e=>Promise.resolve(e).then(e=>({status:`fulfilled`,value:e}),e=>({status:`rejected`,reason:e}))))}r=o(t.map(t=>{if(t=sS(t,n),t in cS)return;cS[t]=!0;let r=t.endsWith(`.css`),i=r?`[rel="stylesheet"]`:``;if(n)for(let n=e.length-1;n>=0;n--){let i=e[n];if(i.href===t&&(!r||i.rel===`stylesheet`))return}else if(document.querySelector(`link[href="${t}"]${i}`))return;let o=document.createElement(`link`);if(o.rel=r?`stylesheet`:oS,r||(o.as=`script`),o.crossOrigin=``,o.href=t,a&&o.setAttribute(`nonce`,a),document.head.appendChild(o),r)return new Promise((e,n)=>{o.addEventListener(`load`,e),o.addEventListener(`error`,()=>n(Error(`Unable to preload CSS for ${t}`)))})}))}function i(e){let t=new Event(`vite:preloadError`,{cancelable:!0});if(t.payload=e,window.dispatchEvent(t),!t.defaultPrevented)throw e}return r.then(t=>{for(let e of t||[])e.status===`rejected`&&i(e.reason);return e().catch(i)})},uS=class extends Error{static{Object.defineProperty(this,"mcpBrand",{value:`mcp.OAuthClientFlowError`})}static[Symbol.hasInstance](e){return K_(this,e)}static isInstance(e){if(typeof this!=`function`)throw TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`");return K_(this,e)}constructor(e){super(e),this.name=new.target.name,G_(this,new.target)}},dS=class extends uS{static{Object.defineProperty(this,"mcpBrand",{value:`mcp.IssuerMismatchError`})}kind;expected;received;constructor(e,t,n){super(`Issuer mismatch in ${e===`metadata`?`authorization server metadata (RFC 8414 §3.3)`:`authorization response (RFC 9207)`}: expected ${JSON.stringify(t)}, received ${JSON.stringify(n)}`),this.kind=e,this.expected=t,this.received=n}},fS=class extends uS{static{Object.defineProperty(this,"mcpBrand",{value:`mcp.RegistrationRejectedError`})}status;body;submittedMetadata;constructor(e){super(`Dynamic Client Registration rejected (HTTP ${e.status}): ${e.body}`),this.status=e.status,this.body=e.body,this.submittedMetadata=e.submittedMetadata}},pS=class extends uS{static{Object.defineProperty(this,"mcpBrand",{value:`mcp.InsecureTokenEndpointError`})}tokenEndpoint;constructor(e){super(`Refusing to send credentials to non-https token endpoint '${e}'. OAuth token requests MUST use TLS (localhost / 127.0.0.1 / ::1 are exempt).`),this.tokenEndpoint=e}},mS=class extends uS{static{Object.defineProperty(this,"mcpBrand",{value:`mcp.AuthorizationServerMismatchError`})}constructor(e,t){super(`Authorization server changed between redirect and callback (redirected to ${JSON.stringify(e)}, callback resolved ${JSON.stringify(t)}); refusing to send authorization_code/code_verifier to a different token endpoint`),this.recordedIssuer=e,this.currentIssuer=t}},hS=class extends uS{static{Object.defineProperty(this,"mcpBrand",{value:`mcp.InsufficientScopeError`})}requiredScope;resourceMetadataUrl;errorDescription;constructor(e){super(`Insufficient scope${e.requiredScope?`: required "${e.requiredScope}"`:``}`),this.requiredScope=e.requiredScope,this.resourceMetadataUrl=e.resourceMetadataUrl,this.errorDescription=e.errorDescription}};function gS(e,t,n){if(e!==void 0)return e.issuer===void 0?(n?.canPersistStamp!==!1&&console.warn(`[mcp-sdk] SEP-2352: stored OAuth credential has no 'issuer' stamp (pre-upgrade storage or provider not round-tripping the value). SEP-2352 isolation is inactive for this read; ensure your provider round-trips the issuer field.`),e):_S(e.issuer,t)?e:void 0}function _S(e,t){return e===t||e.endsWith(`/`)&&e.slice(0,-1)===t||t.endsWith(`/`)&&t.slice(0,-1)===e}function vS(e){if(e==null)return!1;let t=e;return typeof t.tokens==`function`&&typeof t.clientInformation==`function`}async function yS(e,t,n){let{resourceMetadataUrl:r,scope:i}=KS(t.response);if(await BS(e,{serverUrl:t.serverUrl,resourceMetadataUrl:r,scope:i,fetchFn:t.fetchFn,...n})!==`AUTHORIZED`)throw new xS}function bS(e,t){return{token:async()=>(await e.tokens())?.access_token,onUnauthorized:async n=>yS(e,n,t)}}var xS=class extends Error{static{Object.defineProperty(this,"mcpBrand",{value:`mcp.UnauthorizedError`})}static[Symbol.hasInstance](e){return K_(this,e)}static isInstance(e){if(typeof this!=`function`)throw TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`");return K_(this,e)}constructor(e){super(e??`Unauthorized`),this.name=`UnauthorizedError`,G_(this,new.target)}};function SS(e){return e?.authorization_response_iss_parameter_supported===!0}function CS({iss:e,expectedIssuer:t,issParameterSupported:n}){if(t!==void 0){if(e===void 0){if(n)throw new dS(`authorization_response`,t,void 0);return}if(e!==t)throw new dS(`authorization_response`,t,e)}}function wS(...e){let t=new Set;for(let n of e)if(n)for(let e of n.split(/\s+/))e&&t.add(e);return t.size>0?[...t].join(` `):void 0}function TS(e,t){if(!e)return!1;let n=new Set((t??``).split(/\s+/).filter(Boolean));for(let t of e.split(/\s+/))if(t&&!n.has(t))return!0;return!1}async function ES(e,t,n,r,i){if(typeof e==`string`)return{authorizationCode:e,iss:t};let a=e.get(`iss`)??void 0,o=e.get(`code`);if(o)return{authorizationCode:o,iss:a};let s=(await n.discoveryState?.())?.authorizationServerMetadata;if(!s)try{s=(await nC(r,i)).authorizationServerMetadata}catch{s=void 0}if(!s)throw new xS(`Authorization callback failed and the issuer could not be verified`);CS({iss:a,expectedIssuer:s.issuer,issParameterSupported:SS(s)});let c=e.get(`error`);throw c?new J_(c,e.get(`error_description`)??c,e.get(`error_uri`)??void 0):new xS("Authorization callback contained neither `code` nor `error`")}function DS(e){return[`client_secret_basic`,`client_secret_post`,`none`].includes(e)}var OS=`code`,kS=`S256`;function AS(e,t){let n=e.client_secret!==void 0;return`token_endpoint_auth_method`in e&&e.token_endpoint_auth_method&&DS(e.token_endpoint_auth_method)&&(t.length===0||t.includes(e.token_endpoint_auth_method))?e.token_endpoint_auth_method:t.length===0?n?`client_secret_basic`:`none`:n&&t.includes(`client_secret_basic`)?`client_secret_basic`:n&&t.includes(`client_secret_post`)?`client_secret_post`:t.includes(`none`)?`none`:n?`client_secret_post`:`none`}function jS(e,t,n,r){let{client_id:i,client_secret:a}=t;switch(e){case`client_secret_basic`:MS(i,a,n);return;case`client_secret_post`:NS(i,a,r);return;case`none`:PS(i,r);return;default:throw Error(`Unsupported client authentication method: ${e}`)}}function MS(e,t,n){if(!t)throw Error(`client_secret_basic authentication requires a client_secret`);let r=btoa(`${e}:${t}`);n.set(`Authorization`,`Basic ${r}`)}function NS(e,t,n){n.set(`client_id`,e),t&&n.set(`client_secret`,t)}function PS(e,t){t.set(`client_id`,e)}function FS(e){return e===`localhost`||e===`127.0.0.1`||e===`[::1]`||e===`::1`}function IS(e){let t=new URL(String(e));if(t.protocol!==`https:`&&!FS(t.hostname))throw new pS(t.href);return t}function LS(e){for(let t of e??[]){let e;try{e=new URL(t)}catch{continue}if(e.protocol!==`http:`&&e.protocol!==`https:`||FS(e.hostname))return`native`}return`web`}function RS(e){let t=e.clientMetadata;return{...t,grant_types:t.grant_types??(e.redirectUrl===void 0?void 0:[`authorization_code`,`refresh_token`]),application_type:t.application_type??LS(t.redirect_uris)}}async function zS(e){let t=e instanceof Response?e.status:void 0,n=e instanceof Response?await e.text():e;try{let e=L_.parse(JSON.parse(n));return J_.fromResponse(e)}catch(e){let r=`${t?`HTTP ${t}: `:``}Invalid OAuth error response: ${e}. Raw body: ${n}`;return new J_(q_.ServerError,r)}}async function BS(e,t){try{return await HS(e,t)}catch(n){if(n instanceof J_){if(n.code===q_.InvalidClient||n.code===q_.UnauthorizedClient)return await e.invalidateCredentials?.(`client`),await e.invalidateCredentials?.(`tokens`),await HS(e,t);if(n.code===q_.InvalidGrant)return await e.invalidateCredentials?.(`tokens`),await HS(e,t)}throw n}}function VS(e){let{requestedScope:t,resourceMetadata:n,authServerMetadata:r,clientMetadata:i}=e,a=t||n?.scopes_supported?.join(` `)||i.scope;return a&&r?.scopes_supported?.includes(`offline_access`)&&!a.split(` `).includes(`offline_access`)&&i.grant_types?.includes(`refresh_token`)&&(a=`${a} offline_access`),a}async function HS(e,{serverUrl:t,authorizationCode:n,iss:r,scope:i,resourceMetadataUrl:a,fetchFn:o,skipIssuerMetadataValidation:s,forceReauthorization:c}){let l=RS(e),u=await e.discoveryState?.(),d,f,p,m,h=a;if(!h&&u?.resourceMetadataUrl&&(h=new URL(u.resourceMetadataUrl)),u?.authorizationServerUrl){if(f=u.authorizationServerUrl,d=u.resourceMetadata,p=u.authorizationServerMetadata??await tC(f,{fetchFn:o,skipIssuerValidation:s}),!d)try{d=await JS(t,{resourceMetadataUrl:h},o)}catch(e){if(e instanceof TypeError)throw e}(p!==u.authorizationServerMetadata||d!==u.resourceMetadata)&&await e.saveDiscoveryState?.({authorizationServerUrl:String(f),resourceMetadataUrl:h?.toString(),resourceMetadata:d,authorizationServerMetadata:p})}else{let e=await nC(t,{resourceMetadataUrl:h,fetchFn:o,skipIssuerMetadataValidation:s});f=e.authorizationServerUrl,p=e.authorizationServerMetadata,d=e.resourceMetadata,m={authorizationServerUrl:String(f),resourceMetadataUrl:h?.toString(),resourceMetadata:d,authorizationServerMetadata:p}}let g=p?.issuer??String(f),_={issuer:g};if(await e.saveAuthorizationServerUrl?.(g),n!==void 0){let t=u?.authorizationServerMetadata?.issuer??u?.authorizationServerUrl;if(t===void 0){if(e.saveDiscoveryState!==void 0)throw new mS(`discoveryState was not available on the callback leg; ensure your provider persists discoveryState alongside codeVerifier`,g);console.warn(`[mcp-sdk] OAuthClientProvider does not implement saveDiscoveryState()/discoveryState(); the SEP-2352 callback-leg authorization-server binding cannot be checked. Implement discoveryState (persist alongside codeVerifier) — see docs/migration/upgrade-to-v2.md §SEP-2352.`)}else if(!_S(t,g))throw new mS(t,g)}m&&await e.saveDiscoveryState?.(m);let v=await GS(t,e,d);v&&await e.saveResourceUrl?.(String(v));let y=VS({requestedScope:i,resourceMetadata:d,authServerMetadata:p,clientMetadata:e.clientMetadata}),b=await Promise.resolve(e.clientInformation(_)),x=gS(b,g,{canPersistStamp:e.saveClientInformation!==void 0});if(x===void 0&&b?.issuer&&e.saveClientInformation===void 0)throw new mS(b.issuer,g);if(x&&x.issuer===void 0&&(x={...x,issuer:g},await e.saveClientInformation?.(x,_)),!x){if(n!==void 0)throw Error(`Existing OAuth client information is required when exchanging an authorization code`);let t=p?.client_id_metadata_document_supported===!0,r=e.clientMetadataUrl;if(r&&!WS(r))throw new J_(q_.InvalidClientMetadata,`clientMetadataUrl must be a valid HTTPS URL with a non-root pathname, got: ${r}`);if(t&&r)x={client_id:r,issuer:g},await e.saveClientInformation?.(x,_);else{if(!e.saveClientInformation)throw Error(`OAuth client information must be saveable for dynamic registration`);x={...await cC(f,{metadata:p,clientMetadata:l,scope:y,fetchFn:o}),issuer:g},await e.saveClientInformation(x,_)}}let S=!e.redirectUrl;if(n!==void 0||S){n!==void 0&&CS({iss:r,expectedIssuer:p?.issuer,issParameterSupported:SS(p)});let t=await sC(e,f,{metadata:p,resource:v,authorizationCode:n,iss:r,scope:y,fetchFn:o});return await e.saveTokens({...t,issuer:g},_),`AUTHORIZED`}let C=gS(await e.tokens(_),g);if(C&&C.issuer===void 0&&(C={...C,issuer:g},await e.saveTokens(C,_)),C?.refresh_token&&!c)try{let t=await oC(f,{metadata:p,clientInformation:x,refreshToken:C.refresh_token,resource:v,addClientAuthentication:e.addClientAuthentication,fetchFn:o});return await e.saveTokens({...t,issuer:g},_),`AUTHORIZED`}catch(e){if(e instanceof pS||!(!(e instanceof J_)||e.code===q_.ServerError))throw e}let w=e.state?await e.state():void 0,{authorizationUrl:T,codeVerifier:E}=await rC(f,{metadata:p,clientInformation:x,state:w,redirectUrl:e.redirectUrl,scope:y,resource:v});return await e.saveCodeVerifier(E),await e.redirectToAuthorization(T),`REDIRECT`}function US(e){if(e&&!WS(e))throw new J_(q_.InvalidClientMetadata,`clientMetadataUrl must be a valid HTTPS URL with a non-root pathname, got: ${e}`)}function WS(e){if(!e)return!1;try{let t=new URL(e);return t.protocol===`https:`&&t.pathname!==`/`}catch{return!1}}async function GS(e,t,n){let r=Q_(e);if(t.validateResourceURL)return await t.validateResourceURL(r,n?.resource);if(n){if(!$_({requestedResource:r,configuredResource:n.resource}))throw Error(`Protected resource ${n.resource} does not match expected ${r} (or origin)`);return new URL(n.resource)}}function KS(e){let t=e.headers.get(`WWW-Authenticate`);if(!t)return{};let[n,r]=t.split(` `);if(n?.toLowerCase()!==`bearer`||!r)return{};let i=qS(e,`resource_metadata`)||void 0,a;if(i)try{a=new URL(i)}catch{}let o=qS(e,`scope`)||void 0,s=qS(e,`error`)||void 0,c=qS(e,`error_description`)||void 0;return{resourceMetadataUrl:a,scope:o,error:s,errorDescription:c}}function qS(e,t){let n=e.headers.get(`WWW-Authenticate`);if(!n)return null;let r=new RegExp(String.raw`${t}=(?:"([^"]+)"|([^\s,]+))`),i=n.match(r);if(i){let e=i[1]||i[2];if(e)return e}return null}async function JS(e,t,n=fetch){let r=await $S(e,`oauth-protected-resource`,n,{protocolVersion:t?.protocolVersion,metadataUrl:t?.resourceMetadataUrl});if(!r||r.status===404)throw await r?.text?.().catch(()=>{}),Error(`Resource server does not implement OAuth 2.0 Protected Resource Metadata.`);if(!r.ok)throw await r.text?.().catch(()=>{}),Error(`HTTP ${r.status} trying to load well-known OAuth protected resource metadata.`);return j_.parse(await r.json())}async function YS(e,t,n=fetch){try{return await n(e,{headers:t})}catch(r){if(!(r instanceof TypeError))throw r;if(t)try{return await n(e,{})}catch(e){if(!(e instanceof TypeError))throw e;return}return}}function XS(e,t=``,n={}){return t.endsWith(`/`)&&(t=t.slice(0,-1)),n.prependPathname?`${t}/.well-known/${e}`:`/.well-known/${e}${t}`}async function ZS(e,t,n=fetch){return await YS(e,{"MCP-Protocol-Version":t},n)}function QS(e,t){return e?t===`/`?!1:e.status>=400&&e.status<500||e.status===502:!0}async function $S(e,t,n,r){let i=new URL(e),a=r?.protocolVersion??`2025-11-25`,o;if(r?.metadataUrl)o=new URL(r.metadataUrl);else{let e=XS(t,i.pathname);o=new URL(e,r?.metadataServerUrl??i),o.search=i.search}let s=await ZS(o,a,n);return!r?.metadataUrl&&QS(s,i.pathname)&&(s=await ZS(new URL(`/.well-known/${t}`,i),a,n)),s}function eC(e){let t=typeof e==`string`?new URL(e):e,n=t.pathname!==`/`,r=[];if(!n)return r.push({url:new URL(`/.well-known/oauth-authorization-server`,t.origin),type:`oauth`},{url:new URL(`/.well-known/openid-configuration`,t.origin),type:`oidc`}),r;let i=t.pathname;return i.endsWith(`/`)&&(i=i.slice(0,-1)),r.push({url:new URL(`/.well-known/oauth-authorization-server${i}`,t.origin),type:`oauth`},{url:new URL(`/.well-known/openid-configuration${i}`,t.origin),type:`oidc`},{url:new URL(`${i}/.well-known/openid-configuration`,t.origin),type:`oidc`}),r}async function tC(e,{fetchFn:t=fetch,protocolVersion:n=_m,skipIssuerValidation:r=!1}={}){let i={"MCP-Protocol-Version":n,Accept:`application/json`},a=eC(e);for(let{url:n,type:o}of a){let a=await YS(n,i,t);if(!a)continue;if(!a.ok){if(await a.text?.().catch(()=>{}),a.status>=400&&a.status<500||a.status===502)continue;throw Error(`HTTP ${a.status} trying to load ${o===`oauth`?`OAuth`:`OpenID provider`} metadata from ${n}`)}let s=o===`oauth`?M_.parse(await a.json()):P_.parse(await a.json());if(!r){let t=typeof e==`string`?e:e.href;if(!(s.issuer===t||t.endsWith(`/`)&&s.issuer===t.slice(0,-1)))throw new dS(`metadata`,t,s.issuer)}return s}}async function nC(e,t){let n,r;try{n=await JS(e,{resourceMetadataUrl:t?.resourceMetadataUrl},t?.fetchFn),n.authorization_servers&&n.authorization_servers.length>0&&(r=n.authorization_servers[0])}catch(e){if(e instanceof TypeError)throw e}r||=String(new URL(`/`,e));let i=await tC(r,{fetchFn:t?.fetchFn,skipIssuerValidation:t?.skipIssuerMetadataValidation});return{authorizationServerUrl:r,authorizationServerMetadata:i,resourceMetadata:n}}async function rC(e,{metadata:t,clientInformation:n,redirectUrl:r,scope:i,state:a,resource:o}){let s;if(t){if(s=new URL(t.authorization_endpoint),!t.response_types_supported.includes(OS))throw Error(`Incompatible auth server: does not support response type ${OS}`);if(t.code_challenge_methods_supported&&!t.code_challenge_methods_supported.includes(kS))throw Error(`Incompatible auth server: does not support code challenge method ${kS}`)}else s=new URL(`/authorize`,e);let c=await eS(),l=c.code_verifier,u=c.code_challenge;return s.searchParams.set(`response_type`,OS),s.searchParams.set(`client_id`,n.client_id),s.searchParams.set(`code_challenge`,u),s.searchParams.set(`code_challenge_method`,kS),s.searchParams.set(`redirect_uri`,String(r)),a&&s.searchParams.set(`state`,a),i&&s.searchParams.set(`scope`,i),i?.split(` `).includes(`offline_access`)&&s.searchParams.append(`prompt`,`consent`),o&&s.searchParams.set(`resource`,o.href),{authorizationUrl:s,codeVerifier:l}}function iC(e,t,n){return new URLSearchParams({grant_type:`authorization_code`,code:e,code_verifier:t,redirect_uri:String(n)})}async function aC(e,{metadata:t,tokenRequestParams:n,clientInformation:r,addClientAuthentication:i,resource:a,fetchFn:o}){let s=IS(t?.token_endpoint??new URL(`/token`,e)),c=new Headers({"Content-Type":`application/x-www-form-urlencoded`,Accept:`application/json`});a&&n.set(`resource`,a.href),i?await i(c,n,s,t):r&&jS(AS(r,t?.token_endpoint_auth_methods_supported??[]),r,c,n);let l=await(o??fetch)(s,{method:`POST`,headers:c,body:n});if(!l.ok)throw await zS(l);let u=await l.json();try{return F_.parse(u)}catch(e){throw typeof u==`object`&&u&&`error`in u?await zS(JSON.stringify(u)):e}}async function oC(e,{metadata:t,clientInformation:n,refreshToken:r,resource:i,addClientAuthentication:a,fetchFn:o}){return{refresh_token:r,...await aC(e,{metadata:t,tokenRequestParams:new URLSearchParams({grant_type:`refresh_token`,refresh_token:r}),clientInformation:n,addClientAuthentication:a,resource:i,fetchFn:o})}}async function sC(e,t,{metadata:n,resource:r,authorizationCode:i,iss:a,scope:o,fetchFn:s}={}){i!==void 0&&CS({iss:a,expectedIssuer:n?.issuer,issParameterSupported:SS(n)});let c=o??e.clientMetadata.scope,l;if(e.prepareTokenRequest&&(l=await e.prepareTokenRequest(c)),!l){if(!i)throw Error(`Either provider.prepareTokenRequest() or authorizationCode is required`);if(!e.redirectUrl)throw Error(`redirectUrl is required for authorization_code flow`);l=iC(i,await e.codeVerifier(),e.redirectUrl)}let u=await e.clientInformation({issuer:n?.issuer??String(t)});return aC(t,{metadata:n,tokenRequestParams:l,clientInformation:u??void 0,addClientAuthentication:e.addClientAuthentication,resource:r,fetchFn:s})}async function cC(e,{metadata:t,clientMetadata:n,scope:r,fetchFn:i}){let a;if(t){if(!t.registration_endpoint)throw Error(`Incompatible auth server: does not support dynamic client registration`);a=new URL(t.registration_endpoint)}else a=new URL(`/register`,e);let o={...n,...r===void 0?{}:{scope:r}},s=await(i??fetch)(a,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(o)});if(!s.ok)throw new fS({status:s.status,body:await s.text(),submittedMetadata:o});return V_.parse(await s.json())}var lC=new Set([`tools/list`,`prompts/list`,`resources/list`,`resources/templates/list`,`server/discover`]),uC=class{_entries=new Map;_maxEntries;_stamp=0;_cappedSize=0;constructor(e){this._maxEntries=e?.maxEntries??512}get size(){return this._entries.size}get(e){return this._entries.get(dC(e))}set(e,t){let n=dC(e),r=lC.has(e.method),i=!this._entries.has(n);if(!r&&i&&this._maxEntries>0&&this._cappedSize>=this._maxEntries){for(let e of this._entries.keys())if(!lC.has(e.slice(0,e.indexOf(`\0`)))){this._entries.delete(e),this._cappedSize--;break}}let a=++this._stamp;return this._entries.set(n,{...t,stamp:a}),i&&!r&&this._cappedSize++,a}delete(e){this._entries.delete(dC(e))&&!lC.has(e.method)&&this._cappedSize--}evict(e){let t=`${e}\0`,n=lC.has(e);for(let e of this._entries.keys())e.startsWith(t)&&(this._entries.delete(e),n||this._cappedSize--)}clear(){this._entries.clear(),this._cappedSize=0}};function dC(e){return`${e.method}\0${JSON.stringify([e.partition??``,e.params??``])}`}function fC(e,t){return t===void 0?e:`${e}\0${t}`}var pC=864e5,mC=class{_evictionGeneration=new Map;_toolIndex;_toolOutputValidatorIndex;_serverIdentity=``;constructor(e,t,n=()=>{},r=``,i=Date.now){this._store=e,this._isUserSupplied=t,this._reportError=n,this._cachePartition=r,this._now=i}now(){return this._now()}setServerIdentity(e){this._serverIdentity=e}_partitionFor(e){return JSON.stringify([this._serverIdentity,e===`public`?``:this._cachePartition])}async _probe(e,t){let n={method:e,params:t??``},r=this._partitionFor(`private`),i=await this._store.get({...n,partition:r});if(i!==void 0)return i;let a=this._partitionFor(`public`);if(a===r)return;let o=await this._store.get({...n,partition:a});return o?.scope===`public`?o:void 0}async evict(e){this._evictionGeneration.set(e,(this._evictionGeneration.get(e)??0)+1),await this._deleteBoth(e,``)}async _deleteBoth(e,t){let n=this._partitionFor(`private`),r=this._partitionFor(`public`);try{await this._store.delete({method:e,params:t,partition:n})}catch(e){this._reportError(e)}if(r!==n)try{await this._store.delete({method:e,params:t,partition:r})}catch(e){this._reportError(e)}}async evictKey(e,t){let n=fC(e,t),r=this._evictionGeneration.get(n);r!==void 0&&this._evictionGeneration.set(n,r+1),await this._deleteBoth(e,t)}captureGeneration(e,t){let n=fC(e,t),r=this._evictionGeneration.get(n)??0;return this._evictionGeneration.set(n,r),r}async write(e,t,n,r){if((this._evictionGeneration.get(fC(e,r?.params))??0)!==n)return;let i=r?.params??``,a=this._partitionFor(`private`),o=this._partitionFor(`public`),s=(r?.scope??`private`)===`public`?o:a;try{await this._store.set({method:e,params:i,partition:s},{value:hC(t),expiresAt:r?.expiresAt,scope:r?.scope})}catch(e){this._reportError(e)}if(o!==a)try{await this._store.delete({method:e,params:i,partition:s===a?o:a})}catch(e){this._reportError(e)}}async read(e,t){let n=await this._probe(e,t);if(!(n?.expiresAt===void 0||!(n.expiresAt>this.now())))try{let e=JSON.parse(n.value);if(typeof e!=`object`||!e||Array.isArray(e))throw TypeError(`cached document is not an object`);return{value:e}}catch(n){this._reportError(n),await this._deleteBoth(e,t??``);return}}resetForReconnect(){this._isUserSupplied||this._store.clear(),this._evictionGeneration.clear(),this._toolIndex=void 0,this._toolOutputValidatorIndex=void 0,this._serverIdentity=``}async toolDefinition(e){let t=await this._probe(`tools/list`);if(t===void 0){this._toolIndex=void 0;return}if(this._toolIndex?.stamp!==t.stamp){let e=this._decodeListTools(t),n=new Map;if(e!==void 0)for(let t of e.tools)n.set(t.name,t);this._toolIndex={stamp:t.stamp,byName:n}}return this._toolIndex.byName.get(e)}async outputValidator(e,t){let n=await this._probe(`tools/list`);if(n===void 0){this._toolOutputValidatorIndex=void 0;return}if(this._toolOutputValidatorIndex?.stamp!==n.stamp){let e=this._decodeListTools(n)??{tools:[]},r=new Map;for(let n of e.tools){let e=t(n);e!==void 0&&r.set(n.name,e)}this._toolOutputValidatorIndex={stamp:n.stamp,byName:r}}return this._toolOutputValidatorIndex.byName.get(e)}_decodeListTools(e){try{let t=JSON.parse(e.value);if(!Array.isArray(t?.tools)||!t.tools.every(e=>typeof e==`object`&&!!e))throw TypeError(`cached tools/list document has a malformed tools array`);return t}catch(e){this._reportError(e);return}}};function hC(e){let t;try{t=JSON.stringify(e)}catch(e){throw TypeError(`cache value is not JSON-serializable: ${e instanceof Error?e.message:String(e)}`)}if(typeof t!=`string`)throw TypeError(`cache value is not JSON-serializable: it has no JSON representation`);return t}var gC=-32022,_C=new Set([-32001,-32020,-32021]);function vC(e,t){switch(e.kind){case`result`:return yC(e.result,t);case`rpc-error`:return bC(e,t);case`http-error`:return xC(e,t);case`network-error`:return SC(e.error,t);case`auth-required`:return{kind:`error`,error:e.error};case`timeout`:return t.transportKind===`stdio`?{kind:`legacy`}:{kind:`error`,error:new X_(Y_.RequestTimeout,`Version negotiation probe timed out after ${e.timeoutMs}ms`,{timeout:e.timeoutMs})}}}function yC(e,t){let n=wy(Cy).validateResult(`server/discover`,e);if(!n.ok)return{kind:`legacy`};let r=n.value.supportedVersions,i=t.clientModernVersions.find(e=>r.includes(e));return i===void 0?t.fallbackAvailable?{kind:`legacy`}:{kind:`error`,error:new Gv({supported:[...r],requested:t.requestedVersion})}:{kind:`modern`,version:i,discover:n.value}}function bC(e,t){let{code:n,message:r,data:i}=e;if(n===gC){let e=TC(i);if(e===void 0)return{kind:`legacy`};let n=new Gv({supported:e,requested:EC(i)??t.requestedVersion},r),a=iv(e),o=t.clientModernVersions.find(e=>a.includes(e));return o===void 0?a.length>0?{kind:`error`,error:n}:t.fallbackAvailable?{kind:`legacy`}:{kind:`error`,error:n}:{kind:`corrective`,version:o,error:n}}return _C.has(n),{kind:`legacy`}}function xC(e,t){let n=DC(e.body);return n===void 0?{kind:`legacy`}:bC(n,t)}function SC(e,t){return t.environment===`browser`&&CC(e)?{kind:`legacy`}:{kind:`error`,error:new X_(Y_.EraNegotiationFailed,`Version negotiation probe failed: ${wC(e)}`,{cause:e})}}function CC(e){return e instanceof TypeError||e instanceof Error&&e.name===`TypeError`}function wC(e){return e instanceof Error?e.message:String(e)}function TC(e){if(typeof e!=`object`||!e)return;let t=e.supported;if(!(!Array.isArray(t)||t.length===0||!t.every(e=>typeof e==`string`)))return t}function EC(e){if(typeof e!=`object`||!e)return;let t=e.requested;return typeof t==`string`?t:void 0}function DC(e){if(e===void 0||e===``)return;let t;try{t=JSON.parse(e)}catch{return}if(typeof t!=`object`||!t)return;let n=t.error;if(typeof n!=`object`||!n)return;let{code:r,message:i,data:a}=n;if(typeof r==`number`)return{code:r,message:typeof i==`string`?i:``,data:a}}var OC=`legacy`;function kC(e,t){let n=e?.mode??OC;if(n===`legacy`)return{kind:`legacy`};let r=e?.probe??{};if(typeof n==`object`){if(!nv(n.pin))throw TypeError(`versionNegotiation: { pin: '${n.pin}' } is not a modern protocol revision — pinning is for 2026-07-28 and later; omit versionNegotiation (or use mode: 'legacy') for 2025-era servers.`);return{kind:`pin`,version:n.pin,probe:r}}let i=t?iv(t):[];return{kind:`auto`,modernVersions:i.length>0?i:[...tv],fallbackAvailable:t?rv(t).length>0:!0,probe:r}}function AC(){let e=globalThis;return e.window!==void 0&&e.document!==void 0?`browser`:`node`}function jC(e){return`stderr`in e&&`pid`in e?`stdio`:`http`}var MC=class e{_pending;_probeCounter=0;_savedOnMessage;_savedOnError;_savedOnClose;_closeDelivered=!1;constructor(e){this._transport=e,this._savedOnMessage=e.onmessage,this._savedOnError=e.onerror,this._savedOnClose=e.onclose}static async open(t){let n=new e(t);t.onmessage=e=>{let t=n._pending;if(t!==void 0&&(My(e)||Ny(e))&&e.id===t.id){n._pending=void 0,My(e)?t.resolve({kind:`response`,result:e.result}):t.resolve({kind:`response`,error:e.error});return}},t.onerror=e=>{n._savedOnError?.(e)},t.onclose=()=>{let e=n._pending;e!==void 0&&(n._pending=void 0,e.resolve({kind:`closed`})),n._closeDelivered=!0,n._savedOnClose?.()};try{await t.start()}catch(e){throw n.detach(),e}return n}async exchange(e,t){let n=`server-discover-probe-${++this._probeCounter}`;return new Promise(r=>{let i=!1,a=e=>{i||(i=!0,clearTimeout(o),this._pending?.id===n&&(this._pending=void 0),r(e))},o=setTimeout(()=>a({kind:`timeout`}),t);this._pending={id:n,resolve:a},this._transport.send(e(n)).catch(e=>a({kind:`send-error`,error:e}))})}detach(){this._pending=void 0,this._transport.onmessage=this._savedOnMessage,this._transport.onerror=this._savedOnError,this._transport.onclose=this._closeDelivered?void 0:this._savedOnClose}release(){this.detach();let e=this._transport,t=e.start.bind(e),n=!0;e.start=async()=>{if(n){n=!1,e.start=t;return}return t()}}};function NC(e,t,n,r){return{jsonrpc:`2.0`,id:e,method:`server/discover`,params:{_meta:wy(t).outboundEnvelope({protocolVersion:t,clientInfo:n,clientCapabilities:r})}}}function PC(e,t){switch(e.kind){case`response`:return e.error===void 0?{kind:`result`,result:e.result}:{kind:`rpc-error`,...e.error};case`send-error`:{let t=e.error;if(t instanceof Z_){let e=t.data?.text;return{kind:`http-error`,status:t.data.status,body:typeof e==`string`?e:void 0}}return t instanceof xS||t instanceof Error&&t.name===`UnauthorizedError`?{kind:`auth-required`,error:t}:{kind:`network-error`,error:t}}case`closed`:return{kind:`network-error`,error:Error(`Connection closed during the version negotiation probe`)};case`timeout`:return{kind:`timeout`,timeoutMs:t}}}async function FC(e,t){let n=e.probe.timeoutMs??t.defaultTimeoutMs,r=Math.max(0,e.probe.maxRetries??0),i=e.kind===`pin`?[e.version]:e.modernVersions,a=e.kind===`auto`&&e.fallbackAvailable,o=await MC.open(t.transport),s=async()=>{let s=i[0],c=!1,l=r;for(;;){let r=await o.exchange(e=>NC(e,s,t.clientInfo,t.capabilities),n);if(r.kind===`timeout`&&l>0){l--;continue}let u=vC(PC(r,n),{clientModernVersions:i,requestedVersion:s,fallbackAvailable:a,environment:t.environment,transportKind:t.transportKind});switch(u.kind){case`modern`:return{era:`modern`,version:u.version,discover:u.discover};case`corrective`:if(c)throw u.error;c=!0,s=u.version;continue;case`legacy`:if(e.kind===`pin`)throw new X_(Y_.EraNegotiationFailed,`Version negotiation failed: the server did not offer pinned protocol version ${e.version} via server/discover (no fallback in pin mode)`);if(!e.fallbackAvailable)throw new X_(Y_.EraNegotiationFailed,`Version negotiation failed: the server gave no modern evidence and this client supports no pre-2026-07-28 protocol version to fall back to`);return{era:`legacy`};case`error`:throw u.error}}},c;try{c=await s()}catch(e){throw o.detach(),e}return o.release(),c}function IC(e,t){if(!(!e||typeof t!=`object`||!t)){if(e.type===`object`&&e.properties&&typeof e.properties==`object`){let n=t,r=e.properties;for(let e of Object.keys(r)){let t=r[e];n[e]===void 0&&Object.prototype.hasOwnProperty.call(t,`default`)&&(n[e]=t.default),n[e]!==void 0&&IC(t,n[e])}}if(Array.isArray(e.anyOf))for(let n of e.anyOf)typeof n!=`boolean`&&IC(n,t);if(Array.isArray(e.oneOf))for(let n of e.oneOf)typeof n!=`boolean`&&IC(n,t)}}function LC(e){if(!e)return{supportsFormMode:!1,supportsUrlMode:!1};let t=e.form!==void 0,n=e.url!==void 0;return{supportsFormMode:t||!t&&!n,supportsUrlMode:n}}var RC={"notifications/tools/list_changed":[`tools/list`],"notifications/prompts/list_changed":[`prompts/list`],"notifications/resources/list_changed":[`resources/list`,`resources/templates/list`]},zC=64,BC=class extends Jb{_serverCapabilities;_serverVersion;_capabilities;_instructions;_jsonSchemaValidator;_cache;_defaultCacheTtlMs;_listMaxPages;_listChangedDebounceTimers=new Map;_listChangedConfig;_enforceStrictCapabilities;_versionNegotiation;_supportedProtocolVersionsOption;_inputRequiredDriverConfig;_listenState=new Map;_nextListenId=0;_autoOpenedSubscription;_discoverResult;_resetConnectionState(){if(this._negotiatedProtocolVersion=void 0,this._serverCapabilities=void 0,this._serverVersion=void 0,this._instructions=void 0,this._discoverResult=void 0,this._autoOpenedSubscription=void 0,this._listenState.size>0){let e=new X_(Y_.ConnectionClosed,`subscriptions/listen: client reconnected or closed; subscription state from the previous connection was reset`);for(let t of this._listenState.values())t.settle({cause:`remote`,error:e})}this._listenState.clear();for(let e of this._listChangedDebounceTimers.values())clearTimeout(e);this._listChangedDebounceTimers.clear(),this._cache.resetForReconnect()}async close(){try{await super.close()}finally{this._resetConnectionState()}}constructor(e,t){super(t),this._clientInfo=e,this._capabilities=t?.capabilities?{...t.capabilities}:{},this._jsonSchemaValidator=t?.jsonSchemaValidator??new Jx,this._enforceStrictCapabilities=t?.enforceStrictCapabilities??!1,this._versionNegotiation=t?.versionNegotiation,this._supportedProtocolVersionsOption=t?.supportedProtocolVersions,this._inputRequiredDriverConfig=kb(t?.inputRequired),this._cache=new mC(t?.responseCacheStore??new uC,t?.responseCacheStore!==void 0,e=>this._reportStoreError(e),t?.cachePartition??``),this._defaultCacheTtlMs=t?.defaultCacheTtlMs??0,this._listMaxPages=t?.listMaxPages??zC,t?.listChanged&&(this._listChangedConfig=t.listChanged)}buildContext(e,t){return e}_shouldDropInbound(e){if(this._negotiatedProtocolVersion!==void 0&&nv(this._negotiatedProtocolVersion)&&Ay(e))return`drop`}_outboundMetaEnvelope(){let e=this._negotiatedProtocolVersion;if(e!==void 0)return this._wireCodec().outboundEnvelope({protocolVersion:e,clientInfo:this._clientInfo,clientCapabilities:this._capabilities})}_resolveNonCompleteResult(e,t){return this._inputRequiredDriverConfig.autoFulfill?rx({getRequestHandler:e=>this._getRequestHandler(e),buildContext:e=>this.buildContext(e,void 0),sessionId:this.transport?.sessionId},this._inputRequiredDriverConfig,e,t):Promise.reject(new X_(Y_.UnsupportedResultType,`Unsupported result type 'input_required' for ${t.request.method}: multi-round-trip auto-fulfilment is not enabled on this instance — pass allowInputRequired: true to handle it manually, or enable inputRequired.autoFulfill`,{resultType:`input_required`,method:t.request.method}))}_setupListChangedHandlers(e){e.tools&&this._serverCapabilities?.tools?.listChanged&&this._setupListChangedHandler(`tools`,`notifications/tools/list_changed`,e.tools,async()=>(await this.listTools(void 0,{cacheMode:`refresh`})).tools),e.prompts&&this._serverCapabilities?.prompts?.listChanged&&this._setupListChangedHandler(`prompts`,`notifications/prompts/list_changed`,e.prompts,async()=>(await this.listPrompts(void 0,{cacheMode:`refresh`})).prompts),e.resources&&this._serverCapabilities?.resources?.listChanged&&this._setupListChangedHandler(`resources`,`notifications/resources/list_changed`,e.resources,async()=>(await this.listResources(void 0,{cacheMode:`refresh`})).resources)}registerCapabilities(e){if(this.transport)throw Error(`Cannot register capabilities after connecting to transport`);this._capabilities=Xb(this._capabilities,e)}setVersionNegotiation(e){if(this.transport)throw Error(`Cannot configure version negotiation after connecting to transport`);this._versionNegotiation=e}_wrapHandler(e,t){return e===`elicitation/create`?async(e,n)=>{let r=wy(this._negotiatedProtocolVersion),i=r.validateRequest(`elicitation/create`,e);if(!i.ok&&i.reason===`not-in-era`&&(i=r.validateInputRequest(`elicitation/create`,e)),!i.ok)throw new Hv(i.reason===`not-in-era`?Vv.InternalError:Vv.InvalidParams,i.reason===`not-in-era`?`No wire schema for elicitation/create in the resolved era`:`Invalid elicitation request: ${i.message}`);let{params:a}=i.value;a.mode=a.mode??`form`;let{supportsFormMode:o,supportsUrlMode:s}=LC(this._capabilities.elicitation);if(a.mode===`form`&&!o)throw new Hv(Vv.InvalidParams,`Client does not support form-mode elicitation requests`);if(a.mode===`url`&&!s)throw new Hv(Vv.InvalidParams,`Client does not support URL-mode elicitation requests`);let c=await t(e,n),l=r.validateResult(`elicitation/create`,c);if(!l.ok&&l.reason===`not-in-era`&&(l=r.validateInputResponse(`elicitation/create`,c)),!l.ok)throw new Hv(l.reason===`not-in-era`?Vv.InternalError:Vv.InvalidParams,l.reason===`not-in-era`?`No wire schema for elicitation/create in the resolved era`:`Invalid elicitation result: ${l.message}`);let u=l.value,d=a.mode===`form`?a.requestedSchema:void 0;if(a.mode===`form`&&u.action===`accept`&&u.content&&d&&this._capabilities.elicitation?.form?.applyDefaults)try{IC(d,u.content)}catch{}return u}:e===`sampling/createMessage`?async(e,n)=>{let r=wy(this._negotiatedProtocolVersion),i=r.validateRequest(`sampling/createMessage`,e);if(!i.ok&&i.reason===`not-in-era`&&(i=r.validateInputRequest(`sampling/createMessage`,e)),!i.ok)throw new Hv(i.reason===`not-in-era`?Vv.InternalError:Vv.InvalidParams,i.reason===`not-in-era`?`No wire schema for sampling/createMessage in the resolved era`:`Invalid sampling request: ${i.message}`);let{params:a}=i.value,o=await t(e,n),s=!!(a.tools||a.toolChoice),c=r.samplingResultVariant(s,o);if(!c.ok&&c.reason===`not-in-era`&&(c=r.validateInputResponse(`sampling/createMessage`,o)),!c.ok)throw new Hv(c.reason===`not-in-era`?Vv.InternalError:Vv.InvalidParams,c.reason===`not-in-era`?`No result schema for sampling/createMessage in the resolved era`:`Invalid sampling result: ${c.message}`);return c.value}:t}assertCapability(e,t){if(!this._serverCapabilities?.[e])throw new X_(Y_.CapabilityNotSupported,`Server does not support ${e} (required for ${t})`)}async connect(e,t){if(t?.prior!==void 0)return this._connectFromPrior(e,t.prior);let n=kC(this._versionNegotiation,this._supportedProtocolVersionsOption);if(n.kind!==`legacy`)return this._connectNegotiated(e,n,t);if(await super.connect(e),e.sessionId!==void 0){let t=this._negotiatedProtocolVersion;t!==void 0&&e.setProtocolVersion?.(t);return}this._resetConnectionState(),await this._legacyHandshake(e,t)}async _legacyHandshake(e,t){let n=rv(this._supportedProtocolVersions);try{let r=n[0];if(r===void 0)throw new X_(Y_.EraNegotiationFailed,`Cannot run the initialize handshake: supportedProtocolVersions contains no pre-2026-07-28 protocol version`);let i=await this.request({method:`initialize`,params:{protocolVersion:r,capabilities:this._capabilities,clientInfo:this._clientInfo}},t);if(i===void 0)throw Error(`Server sent invalid initialize result: ${i}`);if(!n.includes(i.protocolVersion))throw Error(`Server's protocol version is not supported: ${i.protocolVersion}`);this._serverCapabilities=i.capabilities,this._serverVersion=i.serverInfo,this._cache.setServerIdentity(this._deriveServerIdentity(e)),e.setProtocolVersion&&e.setProtocolVersion(i.protocolVersion),this._instructions=i.instructions,await this.notification({method:`notifications/initialized`}),this._negotiatedProtocolVersion=i.protocolVersion,this._listChangedConfig&&this._setupListChangedHandlers(this._listChangedConfig)}catch(e){throw this.close(),e}}async _connectNegotiated(e,t,n){if(e.sessionId!==void 0){await super.connect(e);let t=this._negotiatedProtocolVersion;t!==void 0&&e.setProtocolVersion&&e.setProtocolVersion(t);return}this._resetConnectionState();let r;try{r=await FC(t,{transport:e,clientInfo:this._clientInfo,capabilities:this._capabilities,environment:AC(),transportKind:jC(e),defaultTimeoutMs:n?.timeout??6e4})}catch(t){throw await e.close().catch(()=>{}),t}if(await super.connect(e),r.era===`legacy`){await this._legacyHandshake(e,n);return}if(this._serverCapabilities=r.discover.capabilities,this._serverVersion=r.discover.serverInfo,this._cache.setServerIdentity(this._deriveServerIdentity(e)),this._instructions=r.discover.instructions,this._discoverResult=r.discover,this._negotiatedProtocolVersion=r.version,e.setProtocolVersion&&e.setProtocolVersion(r.version),this._listChangedConfig){let e=this._listChangedConfig,t=this._serverCapabilities,r={...e.tools&&t?.tools?.listChanged&&{tools:e.tools},...e.prompts&&t?.prompts?.listChanged&&{prompts:e.prompts},...e.resources&&t?.resources?.listChanged&&{resources:e.resources}},i=!0;try{this._setupListChangedHandlers(r)}catch(e){i=!1,this.onerror?.(e instanceof Error?e:Error(String(e)))}let a=i?{...r.tools&&{toolsListChanged:!0},...r.prompts&&{promptsListChanged:!0},...r.resources&&{resourcesListChanged:!0}}:{};if(Object.keys(a).length>0){let e=new AbortController,t=()=>e.abort(n?.signal?.reason);n?.signal?.aborted&&t(),n?.signal?.addEventListener(`abort`,t);try{this._autoOpenedSubscription=await this.listen(a,{timeout:n?.timeout,signal:e.signal})}catch(e){if(n?.signal?.aborted)throw await this.close().catch(()=>{}),e;this.onerror?.(e instanceof Error?e:Error(String(e)))}finally{n?.signal?.removeEventListener(`abort`,t)}}}}async _connectFromPrior(e,t){this._resetConnectionState();let n=this._supportedProtocolVersionsOption,r=(n&&iv(n).length>0?iv(n):tv).find(e=>t.supportedVersions.includes(e));if(r===void 0)throw new X_(Y_.EraNegotiationFailed,`connect({ prior }) requires a 2026-07-28+ mutual protocol version; the supplied DiscoverResult and this client's supportedProtocolVersions have no modern overlap. Use versionNegotiation: { mode: 'auto' } for legacy-era fallback.`);if(await super.connect(e),this._discoverResult=t,this._serverCapabilities=t.capabilities,this._serverVersion=t.serverInfo,this._cache.setServerIdentity(this._deriveServerIdentity(e)),this._instructions=t.instructions,this._negotiatedProtocolVersion=r,e.setProtocolVersion?.(r),this._listChangedConfig)try{this._setupListChangedHandlers(this._listChangedConfig)}catch(e){this.onerror?.(e instanceof Error?e:Error(String(e)))}}getServerCapabilities(){return this._serverCapabilities}getServerVersion(){return this._serverVersion}_deriveServerIdentity(e){let t=this._serverVersion;return t===void 0?e.sessionId??``:`${t.name}@${t.version}`}getNegotiatedProtocolVersion(){return this._negotiatedProtocolVersion}getProtocolEra(){let e=this._negotiatedProtocolVersion;if(e!==void 0)return nv(e)?`modern`:`legacy`}getInstructions(){return this._instructions}getDiscoverResult(){return this._discoverResult}assertCapabilityForMethod(e){switch(e){case`logging/setLevel`:if(!this._serverCapabilities?.logging)throw new X_(Y_.CapabilityNotSupported,`Server does not support logging (required for ${e})`);break;case`prompts/get`:case`prompts/list`:if(!this._serverCapabilities?.prompts)throw new X_(Y_.CapabilityNotSupported,`Server does not support prompts (required for ${e})`);break;case`resources/list`:case`resources/templates/list`:case`resources/read`:case`resources/subscribe`:case`resources/unsubscribe`:if(!this._serverCapabilities?.resources)throw new X_(Y_.CapabilityNotSupported,`Server does not support resources (required for ${e})`);if(e===`resources/subscribe`&&!this._serverCapabilities.resources.subscribe)throw new X_(Y_.CapabilityNotSupported,`Server does not support resource subscriptions (required for ${e})`);break;case`tools/call`:case`tools/list`:if(!this._serverCapabilities?.tools)throw new X_(Y_.CapabilityNotSupported,`Server does not support tools (required for ${e})`);break;case`completion/complete`:if(!this._serverCapabilities?.completions)throw new X_(Y_.CapabilityNotSupported,`Server does not support completions (required for ${e})`);break;case`initialize`:break;case`server/discover`:break;case`ping`:break}}assertNotificationCapability(e){switch(e){case`notifications/roots/list_changed`:if(!this._capabilities.roots?.listChanged)throw new X_(Y_.CapabilityNotSupported,`Client does not support roots list changed notifications (required for ${e})`);break;case`notifications/initialized`:break;case`notifications/cancelled`:break;case`notifications/progress`:break}}assertRequestHandlerCapability(e){switch(e){case`sampling/createMessage`:if(!this._capabilities.sampling)throw new X_(Y_.CapabilityNotSupported,`Client does not support sampling capability (required for ${e})`);break;case`elicitation/create`:if(!this._capabilities.elicitation)throw new X_(Y_.CapabilityNotSupported,`Client does not support elicitation capability (required for ${e})`);break;case`roots/list`:if(!this._capabilities.roots)throw new X_(Y_.CapabilityNotSupported,`Client does not support roots capability (required for ${e})`);break;case`ping`:break}}async ping(e){return this.request({method:`ping`},e)}async discover(e){let t=await this._requestWithSchema({method:`server/discover`},lh,e);return this._discoverResult=t,t}async complete(e,t){return this.request({method:`completion/complete`,params:e},t)}async setLoggingLevel(e,t){return this.request({method:`logging/setLevel`,params:{level:e}},t)}async getPrompt(e,t){return this.request({method:`prompts/get`,params:e},t)}async listPrompts(e,t){if(!this._serverCapabilities?.prompts&&!this._enforceStrictCapabilities)return console.debug(`Client.listPrompts() called but server does not advertise prompts capability - returning empty list`),{prompts:[]};if(e?.cursor!==void 0)return this.request({method:`prompts/list`,params:e},t);let n=await this._serveFromCache(`prompts/list`,void 0,t);return n===void 0?this._listAllPages(`prompts/list`,e,t,(e,t)=>e.prompts.push(...t.prompts)):n}async listResources(e,t){if(!this._serverCapabilities?.resources&&!this._enforceStrictCapabilities)return console.debug(`Client.listResources() called but server does not advertise resources capability - returning empty list`),{resources:[]};if(e?.cursor!==void 0)return this.request({method:`resources/list`,params:e},t);let n=await this._serveFromCache(`resources/list`,void 0,t);return n===void 0?this._listAllPages(`resources/list`,e,t,(e,t)=>e.resources.push(...t.resources)):n}async listResourceTemplates(e,t){if(!this._serverCapabilities?.resources&&!this._enforceStrictCapabilities)return console.debug(`Client.listResourceTemplates() called but server does not advertise resources capability - returning empty list`),{resourceTemplates:[]};if(e?.cursor!==void 0)return this.request({method:`resources/templates/list`,params:e},t);let n=await this._serveFromCache(`resources/templates/list`,void 0,t);return n===void 0?this._listAllPages(`resources/templates/list`,e,t,(e,t)=>e.resourceTemplates.push(...t.resourceTemplates)):n}async _listAllPages(e,t,n,r,i){let a=n?.cacheMode===`bypass`,o=this._cache.captureGeneration(e),s=await this.request({method:e,...t&&{params:{...t}}},n),c=s.nextCursor,l=new Set,u=1;for(;c!==void 0&&!l.has(c);){if(this._listMaxPages!==0&&u>=this._listMaxPages)throw new X_(Y_.ListPaginationExceeded,`${e}: exceeded listMaxPages (${this._listMaxPages}); server pagination did not terminate`,{method:e,listMaxPages:this._listMaxPages});l.add(c);let i=await this.request({method:e,params:{...t,cursor:c}},n);r(s,i),c=i.nextCursor,u++}return delete s.nextCursor,i?.(s),a||await this._cache.write(e,s,o,this._freshness(s)),s}_freshness(e,t){let n=e,r=typeof n.ttlMs==`number`?n.ttlMs:this._defaultCacheTtlMs,i=n.cacheScope===`public`?`public`:`private`;return{expiresAt:this._cache.now()+Math.min(Math.max(0,r),pC),scope:i,params:t}}async _serveFromCache(e,t,n){if(n?.cacheMode===`bypass`||n?.cacheMode===`refresh`)return;let r=await this._cache.read(e,t).catch(e=>void this._reportStoreError(e));if(r!==void 0){if(n?.signal?.aborted){let e=n.signal.reason;throw e instanceof X_?e:new X_(Y_.RequestTimeout,String(e))}return r.value}}_reportStoreError(e){this.onerror?.(e instanceof Error?e:Error(String(e)))}_compileOutputValidator(e){if(e.outputSchema)try{return{ok:!0,validator:this._jsonSchemaValidator.getValidator(e.outputSchema)}}catch(e){return{ok:!1,compileError:e}}}async _resolveXMcpHeaderScan(e,t){let n=t??await this._cache.toolDefinition(e);return n===void 0?void 0:Vy(n.inputSchema)}async readResource(e,t){let n=await this._serveFromCache(`resources/read`,e.uri,t);if(n!==void 0)return n;let r=this._cache.captureGeneration(`resources/read`,e.uri),i=await this.request({method:`resources/read`,params:e},t);if(t?.cacheMode!==`bypass`){let n=this._freshness(i,e.uri);n.expiresAt>this._cache.now()?await this._cache.write(`resources/read`,i,r,n):t?.cacheMode===`refresh`&&await this._cache.evictKey(`resources/read`,e.uri)}return i}async subscribeResource(e,t){return this.request({method:`resources/subscribe`,params:e},t)}async unsubscribeResource(e,t){return this.request({method:`resources/unsubscribe`,params:e},t)}async listen(e,t){if(this.transport===void 0)throw new X_(Y_.NotConnected,`Not connected`);let n=this._negotiatedProtocolVersion;if(n===void 0||!nv(n))throw new X_(Y_.MethodNotSupportedByProtocolVersion,`subscriptions/listen requires a 2026-07-28-era connection (negotiated: ${n??`none`}). On a 2025-era connection, change notifications are delivered unsolicited: use ClientOptions.listChanged and resources/subscribe instead.`,{method:`subscriptions/listen`,protocolVersion:n});if(t?.signal?.aborted){let e=t.signal.reason;throw e instanceof X_?e:new X_(Y_.RequestTimeout,String(e))}let r=new AbortController,i=`listen:${this._nextListenId++}`,a=`opening`,o,s,c,l,u=new Promise((e,t)=>{c=e,l=t}),d,f=new Promise(e=>{d=e}),p=e=>{if(a===`closed`)return;let n=a===`opening`;if(o!==void 0&&(clearTimeout(o),o=void 0),`ack`in e){a=`open`,c(e.ack);return}a=`closed`,s!==void 0&&t?.signal?.removeEventListener(`abort`,s),this._listenState.delete(i),r.abort(),d(e.cause),n&&l(e.error??new X_(Y_.ConnectionClosed,`subscriptions/listen closed before the server acknowledged`))},m=async()=>{r.abort(),await this.notification({method:`notifications/cancelled`,params:{requestId:i}}).catch(()=>{})},h=async()=>{a!==`closed`&&(p({cause:`local`}),await m())};this._listenState.set(i,{settle:p});let g=t?.timeout??6e4;if(o=setTimeout(()=>{p({cause:`remote`,error:new X_(Y_.RequestTimeout,`subscriptions/listen ack timed out`,{timeout:g})}),m().catch(()=>{})},g),t?.signal){let e=t.signal;s=()=>{if(a===`closed`)return;let t=e.reason;p({cause:`local`,error:t instanceof Error?t:Error(String(t??`Aborted`))}),m().catch(()=>{})},e.addEventListener(`abort`,s,{once:!0})}let _={jsonrpc:`2.0`,id:i,method:`subscriptions/listen`,params:{_meta:{...this._outboundMetaEnvelope()},notifications:e}};try{await this.transport.send(_,{requestSignal:r.signal,onRequestStreamEnd:()=>p({cause:`remote`,error:Error(`subscriptions/listen: stream ended`)})})}catch(e){p({cause:`remote`,error:e instanceof Error?e:Error(String(e))})}return{honoredFilter:await u,close:h,closed:f}}get autoOpenedSubscription(){return this._autoOpenedSubscription}_onnotification(e,t){let n=Object.hasOwn(RC,e.method)?RC[e.method]:void 0;if(e.method===`notifications/resources/updated`){let t=e.params?.uri;typeof t==`string`&&this._cache.evictKey(`resources/read`,t)}else if(n!==void 0)for(let e of n)this._cache.evict(e);if(e.method===`notifications/subscriptions/acknowledged`){let t=e.params?._meta?.[Cm],n=typeof t==`string`?this._listenState.get(t):void 0;if(n!==void 0){let t=this._wireCodec().validateNotification(`notifications/subscriptions/acknowledged`,e);n.settle({ack:t.ok?t.value.params.notifications:{}});return}}if(e.method===`notifications/cancelled`){let t=e.params?.requestId,n=typeof t==`string`?this._listenState.get(t):void 0;if(n!==void 0){n.settle({cause:`remote`,error:Error(`subscriptions/listen: server cancelled the subscription`)});return}}super._onnotification(e,t)}_onresponse(e){let t=e.id,n=typeof t==`string`?this._listenState.get(t):void 0;if(n!==void 0){Ny(e)?n.settle({cause:`remote`,error:Hv.fromError(e.error.code,e.error.message,e.error.data)}):n.settle({cause:`graceful`,error:new X_(Y_.ConnectionClosed,`subscriptions/listen: server closed the subscription gracefully before acknowledging`)});return}super._onresponse(e)}_onclose(){if(this._listenState.size>0){let e=new X_(Y_.ConnectionClosed,`Connection closed`);for(let t of this._listenState.values())t.settle({cause:`remote`,error:e});this._listenState.clear()}super._onclose()}async callTool(e,t){let n=this.getProtocolEra()===`modern`&&AC()!==`browser`,r=async()=>{if(!n)return t;let r;try{r=await this._resolveXMcpHeaderScan(e.name,t?.toolDefinition)}catch(e){this._reportStoreError(e)}if(!r?.valid||r.declarations.length===0)return t;let i=Qy(r.declarations,e.arguments);return Object.keys(i).length===0?t:{...t,headers:{...t?.headers,...i}}},i=t?.toolDefinition===void 0?await this._cache.outputValidator(e.name,e=>this._compileOutputValidator(e)).catch(e=>void this._reportStoreError(e)):this._compileOutputValidator(t.toolDefinition),a=()=>{if(i===void 0||i.ok)return;let t=i.compileError,n=(t instanceof Error?t.message:String(t)).slice(0,200);throw new Hv(Vv.InvalidParams,`Tool '${e.name}' has an invalid outputSchema: ${n}`)};a();let o;try{o=await this.request({method:`tools/call`,params:e},await r())}catch(s){let c=s instanceof Hv&&s.code===-32020;if(!n||!c||t?.toolDefinition!==void 0)throw s;let l={signal:t?.signal,timeout:t?.timeout,cacheMode:`refresh`};await this._cache.evict(`tools/list`),await this.listTools(void 0,l).catch(e=>this._reportStoreError(e)),i=await this._cache.outputValidator(e.name,e=>this._compileOutputValidator(e)).catch(e=>void this._reportStoreError(e)),a(),o=await this.request({method:`tools/call`,params:e},await r())}let s=i!==void 0&&i.ok?i.validator:void 0;if(s){if(o.structuredContent===void 0&&!o.isError)throw new Hv(Vv.InvalidRequest,`Tool ${e.name} has an output schema but did not return structured content`);if(o.structuredContent!==void 0&&!o.isError)try{let e=s(o.structuredContent);if(!e.valid)throw new Hv(Vv.InvalidParams,`Structured content does not match the tool's output schema: ${e.errorMessage}`)}catch(e){throw e instanceof Hv?e:new Hv(Vv.InvalidParams,`Failed to validate structured content: ${e instanceof Error?e.message:String(e)}`)}}return o}async listTools(e,t){if(!this._serverCapabilities?.tools&&!this._enforceStrictCapabilities)return console.debug(`Client.listTools() called but server does not advertise tools capability - returning empty list`),{tools:[]};if(e?.cursor!==void 0){let n=await this.request({method:`tools/list`,params:e},t);return this._excludeInvalidXMcpHeaderTools(n),n}let n=await this._serveFromCache(`tools/list`,void 0,t);return n===void 0?this._listAllPages(`tools/list`,e,t,(e,t)=>e.tools.push(...t.tools),e=>this._excludeInvalidXMcpHeaderTools(e)):n}_excludeInvalidXMcpHeaderTools(e){if(this.getProtocolEra()!==`modern`||!this.transport||jC(this.transport)===`stdio`)return;let t=e.tools.filter(e=>{let t=Vy(e.inputSchema);return t.valid?!0:(console.warn(`[mcp-sdk] excluding tool '${e.name}' from tools/list: invalid x-mcp-header declaration — ${t.reason}`),!1)});t.length!==e.tools.length&&(e.tools=t)}_setupListChangedHandler(e,t,n,r){let i=$y(yg,n);if(!i.success)throw Error(`Invalid ${e} listChanged options: ${i.error.message}`);if(typeof n.onChanged!=`function`)throw TypeError(`Invalid ${e} listChanged options: onChanged must be a function`);let{autoRefresh:a,debounceMs:o}=i.data,{onChanged:s}=n,c=async()=>{if(!a){s(null,null);return}try{s(null,await r())}catch(e){s(e instanceof Error?e:Error(String(e)),null)}};this.setNotificationHandler(t,()=>{if(o){let t=this._listChangedDebounceTimers.get(e);t&&clearTimeout(t);let n=setTimeout(c,o);this._listChangedDebounceTimers.set(e,n)}else c()})}async sendRootsListChanged(){return this.notification({method:`notifications/roots/list_changed`})}};(class extends Error{static{Object.defineProperty(this,"mcpBrand",{value:`mcp.SseError`})}static[Symbol.hasInstance](e){return K_(this,e)}static isInstance(e){if(typeof this!=`function`)throw TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`");return K_(this,e)}constructor(e,t,n){super(`SSE error: ${t}`),this.code=e,this.event=n,G_(this,new.target)}});var VC=1,HC={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2},UC=new Set([`authorization`,`content-type`,`mcp-protocol-version`,`mcp-method`,`mcp-name`,`mcp-session-id`]);function WC(e,t){if(typeof AbortSignal.any==`function`)return AbortSignal.any([e,t]);let n=new AbortController;if(e.aborted)return n.abort(e.reason),n.signal;if(t.aborted)return n.abort(t.reason),n.signal;let r=()=>{e.removeEventListener(`abort`,i),t.removeEventListener(`abort`,a)};function i(){r(),n.abort(e.reason)}function a(){r(),n.abort(t.reason)}return e.addEventListener(`abort`,i,{once:!0}),t.addEventListener(`abort`,a,{once:!0}),n.signal}var GC=class{_abortController;_url;_resourceMetadataUrl;_scope;_requestInit;_authProvider;_oauthProvider;_skipIssuerMetadataValidation;_fetch;_fetchWithInit;_sessionId;_reconnectionOptions;_protocolVersion;_onInsufficientScope;_maxStepUpRetries;_serverRetryMs;_reconnectionScheduler;_cancelReconnection;onclose;onerror;onmessage;hasPerRequestStream=!0;constructor(e,t){this._url=e,this._resourceMetadataUrl=void 0,this._scope=void 0,this._requestInit=t?.requestInit,this._skipIssuerMetadataValidation=t?.skipIssuerMetadataValidation,vS(t?.authProvider)?(this._oauthProvider=t.authProvider,this._authProvider=bS(t.authProvider,{skipIssuerMetadataValidation:t.skipIssuerMetadataValidation})):this._authProvider=t?.authProvider,this._fetch=t?.fetch,this._fetchWithInit=cx(t?.fetch,t?.requestInit),this._sessionId=t?.sessionId,this._protocolVersion=t?.protocolVersion,this._reconnectionOptions=t?.reconnectionOptions??HC,this._reconnectionScheduler=t?.reconnectionScheduler,this._onInsufficientScope=t?.onInsufficientScope??`reauthorize`,this._maxStepUpRetries=Math.max(0,t?.maxStepUpRetries??VC)}async _stepUpAuthorize(e,t){if(this._onInsufficientScope===`throw`||!this._oauthProvider)throw new hS({requiredScope:e.scope,resourceMetadataUrl:e.resourceMetadataUrl,errorDescription:e.errorDescription});if(t>=this._maxStepUpRetries)throw new Z_(Y_.ClientHttpForbidden,`Server returned 403 insufficient_scope after step-up re-authorization (retry limit ${this._maxStepUpRetries} reached)`,{status:403,statusText:e.statusText??`Forbidden`,text:e.text});e.resourceMetadataUrl&&(this._resourceMetadataUrl=e.resourceMetadataUrl);let n=await this._oauthProvider.tokens(),r=wS(this._scope,n?.scope,e.scope);this._scope=r;let i=TS(r,n?.scope);return BS(this._oauthProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:r,forceReauthorization:i,fetchFn:this._fetchWithInit,skipIssuerMetadataValidation:this._skipIssuerMetadataValidation})}async _commonHeaders(){let e={},t=await this._authProvider?.token();t&&(e.Authorization=`Bearer ${t}`),this._sessionId&&(e[`mcp-session-id`]=this._sessionId),this._protocolVersion&&(e[`mcp-protocol-version`]=this._protocolVersion);let n=sx(this._requestInit?.headers);return new Headers({...e,...n})}_applyBodyDerivedHeaders(e,t){if(Array.isArray(t)||!Ay(t))return;let n=t.params?._meta?.[bm];if(typeof n!=`string`)return;e.set(`mcp-protocol-version`,n),e.set(`mcp-method`,t.method);let r=t.params,i=t.method===`resources/read`?typeof r?.uri==`string`?r.uri:void 0:typeof r?.name==`string`?r.name:void 0;i!==void 0&&e.set(`mcp-name`,Xy(i))}_isModernEnvelopedRequest(e){if(Array.isArray(e)||!Ay(e))return!1;let t=e.params?._meta?.[bm];return typeof t==`string`&&nv(t)}async _startOrAuthSse(e,t=!1,n=0){let{resumptionToken:r,requestSignal:i}=e,a=()=>this._abortController?.signal.aborted===!0||i?.aborted===!0;try{let a=await this._commonHeaders(),o=[...a.get(`accept`)?.split(`,`).map(e=>e.trim().toLowerCase())??[],`text/event-stream`];a.set(`accept`,[...new Set(o)].join(`, `)),r&&a.set(`last-event-id`,r);let s=this._abortController?.signal,c=i!==void 0&&s!==void 0?WC(s,i):i??s,l=await(this._fetch??fetch)(this._url,{...this._requestInit,method:`GET`,headers:a,signal:c});if(!l.ok){if(l.status===401&&this._authProvider){if(l.headers.has(`www-authenticate`)){let{resourceMetadataUrl:e,scope:t}=KS(l);this._resourceMetadataUrl=e,this._scope=wS(this._scope,t)}if(this._authProvider.onUnauthorized&&!t)return await this._authProvider.onUnauthorized({response:l,serverUrl:this._url,fetchFn:this._fetchWithInit}),await l.text?.().catch(()=>{}),this._startOrAuthSse(e,!0,n);throw await l.text?.().catch(()=>{}),t?new Z_(Y_.ClientHttpAuthentication,`Server returned 401 after re-authentication`,{status:401,statusText:l.statusText}):new xS}if(l.status===403){let{resourceMetadataUrl:r,scope:i,error:a,errorDescription:o}=KS(l);if(a===`insufficient_scope`){let a=await l.text?.().catch(()=>null);if(await this._stepUpAuthorize({scope:i,resourceMetadataUrl:r,errorDescription:o,statusText:l.statusText,text:a},n)!==`AUTHORIZED`)throw new xS;return this._startOrAuthSse(e,t,n+1)}}if(await l.text?.().catch(()=>{}),l.status===405){e.onRequestStreamEnd?.();return}throw new Z_(Y_.ClientHttpFailedToOpenStream,`Failed to open SSE stream: ${l.statusText}`,{status:l.status,statusText:l.statusText})}this._handleSseStream(l.body,e,!0)}catch(e){throw a()||this.onerror?.(e),e}}_getNextReconnectionDelay(e){if(this._serverRetryMs!==void 0)return this._serverRetryMs;let t=this._reconnectionOptions.initialReconnectionDelay,n=this._reconnectionOptions.reconnectionDelayGrowFactor,r=this._reconnectionOptions.maxReconnectionDelay;return Math.min(t*n**+e,r)}_scheduleReconnection(e,t=0){let n=this._reconnectionOptions.maxRetries;if(t>=n){this.onerror?.(Error(`Maximum reconnection attempts (${n}) exceeded.`)),e.onRequestStreamEnd?.();return}let r=this._getNextReconnectionDelay(t),i=()=>{this._cancelReconnection=void 0,!(this._abortController?.signal.aborted||e.requestSignal?.aborted)&&this._startOrAuthSse(e).catch(n=>{if(!(this._abortController?.signal.aborted||e.requestSignal?.aborted)){this.onerror?.(Error(`Failed to reconnect SSE stream: ${n instanceof Error?n.message:String(n)}`));try{this._scheduleReconnection(e,t+1)}catch(e){this.onerror?.(e instanceof Error?e:Error(String(e)))}}})};if(this._reconnectionScheduler){let e=this._reconnectionScheduler(i,r,t);this._cancelReconnection=typeof e==`function`?e:void 0}else{let e=setTimeout(i,r);this._cancelReconnection=()=>clearTimeout(e)}}_handleSseStream(e,t,n){if(!e){t.onRequestStreamEnd?.();return}let{onresumptiontoken:r,replayMessageId:i,requestSignal:a,onRequestStreamEnd:o}=t,s=()=>this._abortController?.signal.aborted===!0||a?.aborted===!0,c,l=!1,u=!1;(async()=>{try{let t=e.pipeThrough(new TextDecoderStream).pipeThrough(new aS({onRetry:e=>{this._serverRetryMs=e}})).getReader();for(;;){let{value:e,done:n}=await t.read();if(n)break;if(e.id&&(c=e.id,l=!0,r?.(e.id)),e.data&&(!e.event||e.event===`message`))try{let t=Wm.parse(JSON.parse(e.data));(My(t)||Ny(t))&&(u=!0,i!==void 0&&(t.id=i)),this.onmessage?.(t)}catch(e){this.onerror?.(e)}}(n||l)&&!u&&this._abortController&&!s()?this._scheduleReconnection({resumptionToken:c,onresumptiontoken:r,replayMessageId:i,requestSignal:a,onRequestStreamEnd:o},0):s()||o?.()}catch(e){if(s())return;if(this.onerror?.(Error(`SSE stream disconnected: ${e}`)),(n||l)&&!u&&this._abortController&&!s())try{this._scheduleReconnection({resumptionToken:c,onresumptiontoken:r,replayMessageId:i,requestSignal:a,onRequestStreamEnd:o},0)}catch(e){this.onerror?.(Error(`Failed to reconnect: ${e instanceof Error?e.message:String(e)}`)),o?.()}else o?.()}})()}async start(){if(this._abortController)throw Error(`StreamableHTTPClientTransport already started! If using Client class, note that connect() calls start() automatically.`);this._abortController=new AbortController}async finishAuth(e,t){if(!this._oauthProvider)throw new xS(`finishAuth requires an OAuthClientProvider`);let{authorizationCode:n,iss:r}=await ES(e,t,this._oauthProvider,this._url,{fetchFn:this._fetchWithInit,resourceMetadataUrl:this._resourceMetadataUrl});if(await BS(this._oauthProvider,{serverUrl:this._url,authorizationCode:n,iss:r,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit,skipIssuerMetadataValidation:this._skipIssuerMetadataValidation})!==`AUTHORIZED`)throw new xS(`Failed to authorize`)}async close(){try{this._cancelReconnection?.()}finally{this._cancelReconnection=void 0,this._abortController?.abort(),this.onclose?.()}}async send(e,t){return this._send(e,t,!1)}async _send(e,t,n,r=0){try{let{resumptionToken:i,onresumptiontoken:a}=t||{};if(i){this._startOrAuthSse({resumptionToken:i,replayMessageId:Ay(e)?e.id:void 0,requestSignal:t?.requestSignal}).catch(e=>this.onerror?.(e));return}let o=await this._commonHeaders();this._applyBodyDerivedHeaders(o,e);let s=Array.isArray(e)?e.some(e=>Fy(e)):Fy(e);if(s&&o.delete(`mcp-session-id`),t?.headers!==void 0)for(let[e,n]of Object.entries(t.headers))UC.has(e.toLowerCase())||o.set(e,n);o.set(`content-type`,`application/json`);let c=[...o.get(`accept`)?.split(`,`).map(e=>e.trim().toLowerCase())??[],`application/json`,`text/event-stream`];o.set(`accept`,[...new Set(c)].join(`, `));let l=this._abortController?.signal,u=t?.requestSignal!==void 0&&l!==void 0?WC(l,t.requestSignal):t?.requestSignal??l,d={...this._requestInit,method:`POST`,headers:o,body:JSON.stringify(e),signal:u},f=await(this._fetch??fetch)(this._url,d);if(s&&f.ok&&(this._sessionId=f.headers.get(`mcp-session-id`)||void 0),!f.ok){if(f.status===401&&this._authProvider){if(f.headers.has(`www-authenticate`)){let{resourceMetadataUrl:e,scope:t}=KS(f);this._resourceMetadataUrl=e,this._scope=wS(this._scope,t)}if(this._authProvider.onUnauthorized&&!n)return await this._authProvider.onUnauthorized({response:f,serverUrl:this._url,fetchFn:this._fetchWithInit}),await f.text?.().catch(()=>{}),this._send(e,t,!0,r);throw await f.text?.().catch(()=>{}),n?new Z_(Y_.ClientHttpAuthentication,`Server returned 401 after re-authentication`,{status:401,statusText:f.statusText}):new xS}let i=await f.text?.().catch(()=>null);if(f.status===403){let{resourceMetadataUrl:a,scope:o,error:s,errorDescription:c}=KS(f);if(s===`insufficient_scope`){if(await this._stepUpAuthorize({scope:o,resourceMetadataUrl:a,errorDescription:c,statusText:f.statusText,text:i},r)!==`AUTHORIZED`)throw new xS;return this._send(e,t,n,r+1)}}if(f.status===400&&typeof i==`string`&&this._isModernEnvelopedRequest(e))try{let t=Wm.parse(JSON.parse(i)),n=(Array.isArray(e)?e:[e]).filter(e=>Ay(e));if(Ny(t)&&n.some(e=>e.id===t.id)){this.onmessage?.(t);return}}catch{}throw new Z_(Y_.ClientHttpNotImplemented,`Error POSTing to endpoint: ${i}`,{status:f.status,statusText:f.statusText,text:i})}if(f.status===202){await f.text?.().catch(()=>{}),Iy(e)&&this._startOrAuthSse({resumptionToken:void 0}).catch(e=>this.onerror?.(e));return}let p=(Array.isArray(e)?e:[e]).some(e=>`method`in e&&`id`in e&&e.id!==void 0),m=f.headers.get(`content-type`),h=ox(m);if(p)if(h===`text/event-stream`)this._handleSseStream(f.body,{onresumptiontoken:a,requestSignal:t?.requestSignal,onRequestStreamEnd:t?.onRequestStreamEnd},!1);else if(h===`application/json`){let e=await f.json(),t=Array.isArray(e)?e.map(e=>Wm.parse(e)):[Wm.parse(e)];for(let e of t)this.onmessage?.(e)}else throw await f.text?.().catch(()=>{}),new X_(Y_.ClientHttpUnexpectedContent,`Unexpected content type: ${m}`,{contentType:m});else await f.text?.().catch(()=>{})}catch(e){throw t?.requestSignal?.aborted!==!0&&this.onerror?.(e),e}}get sessionId(){return this._sessionId}async terminateSession(){if(this._sessionId)try{let e=await this._commonHeaders(),t={...this._requestInit,method:`DELETE`,headers:e,signal:this._abortController?.signal},n=await(this._fetch??fetch)(this._url,t);if(await n.text?.().catch(()=>{}),!n.ok&&n.status!==405)throw new Z_(Y_.ClientHttpFailedToTerminateSession,`Failed to terminate session: ${n.statusText}`,{status:n.status,statusText:n.statusText});this._sessionId=void 0}catch(e){throw this.onerror?.(e),e}}setProtocolVersion(e){this._protocolVersion=e}get protocolVersion(){return this._protocolVersion}async resumeStream(e,t){await this._startOrAuthSse({resumptionToken:e,onresumptiontoken:t?.onresumptiontoken})}},KC=t({BaseConnector:()=>lT,BrowserOAuthClientProvider:()=>Kw,DialectJsonSchemaValidator:()=>sT,HttpConnector:()=>fT,MCPClient:()=>xT,MCPConnection:()=>_T,MCPSession:()=>_T,POSTHOG_API_KEY:()=>mw,POSTHOG_HOST:()=>pw,SCARF_GATEWAY_URL:()=>hw,Tel:()=>zw,Telemetry:()=>Rw,VERSION:()=>iw,capturePostHog:()=>Cw,captureScarf:()=>ww,completeOAuthFlow:()=>eT,createOAuthProvider:()=>qw,getPackageVersion:()=>aw,isUnauthorized:()=>$w,logger:()=>Q,normalizeClientInfo:()=>gT,resolveCallbacks:()=>pT,setTelemetrySource:()=>Bw,shouldAutoProvisionOAuth:()=>mT,telFetch:()=>fw}),qC;function JC(e){qC=e}function YC(e,t){qC?.addServer(e,t)}function XC(e){qC?.removeServer(e)}var ZC;function QC(e){ZC=e}function $C(e){ZC?.(e)}var ew=[`silent`,`error`,`warn`,`info`,`http`,`verbose`,`debug`,`silly`],tw={silent:``,error:`❌`,warn:`⚠️`,info:`ℹ️`,http:`🌐`,verbose:`📝`,debug:`🔍`,silly:`🤪`};function nw(){let e;try{e=typeof process<`u`?{}.MCP_USE_LOG_LEVEL??{}.DEBUG:void 0}catch{}let t=e?.trim().toLowerCase();return t===`2`?`debug`:t&&ew.includes(t)?t:`info`}var rw=class{constructor(e=`mcp-use`,t=`info`,n=`minimal`){this.name=e,this.level=t,this.format=n}write(e,t,n){if(this.level===`silent`||ew.indexOf(e)>ew.indexOf(this.level))return;let r=n.map(e=>{if(typeof e==`string`)return e;try{return JSON.stringify(e)}catch{return String(e)}}).join(` `),i=r?`${t} ${r}`:t,a=new Date().toLocaleTimeString(`en-US`,{hour12:!1}),o=this.format===`minimal`?e:e.toUpperCase(),s=this.format===`emoji`?` ${tw[e]}`:``,c=`${a} [${this.name}]${s} ${o}: ${i}`;(e===`error`?console.error:e===`warn`?console.warn:e===`info`?console.info:e===`debug`?console.debug:console.log)(c)}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}},Q=class{static instances={};static currentFormat=`minimal`;static currentLevel;static get(e=`mcp-use`){return this.instances[e]??=new rw(e,this.currentLevel??nw(),this.currentFormat)}static configure({level:e=nw(),format:t=`minimal`}={}){this.currentLevel=e,this.currentFormat=t;for(let n of Object.values(this.instances))n.level=e,n.format=t}static setDebug(e){let t=e===2||e===!0?`debug`:`info`;this.currentLevel=t;for(let e of Object.values(this.instances))e.level=t;try{typeof process<`u`&&({}.MCP_USE_LOG_LEVEL=t)}catch{}}static setFormat(e){this.configure({format:e})}}.get(),iw=`2.0.0-beta.4`;function aw(){return iw}var ow=class{},sw=class extends ow{constructor(e){super(),this.data=e}get name(){return`mcp_agent_execution`}get properties(){return{execution_method:this.data.executionMethod,query:this.data.query,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,server_identifiers:this.data.serverIdentifiers,total_tools_available:this.data.totalToolsAvailable,tools_available_names:this.data.toolsAvailableNames,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,tools_used_names:this.data.toolsUsedNames??null,response:this.data.response??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}}},cw=class extends ow{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}}},lw=class extends ow{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}}},uw=class extends ow{constructor(e){super(),this.data=e}get name(){return`client_add_server`}get properties(){let{serverName:e,serverConfig:t}=this.data,n=t.url;return{server_name:e,server_url_domain:n?this._extractHostname(n):null,transport:t.transport??null,has_auth:!!(t.authToken||t.authProvider)}}_extractHostname(e){try{return new URL(e).hostname}catch{return null}}},dw=class extends ow{constructor(e){super(),this.data=e}get name(){return`client_remove_server`}get properties(){return{server_name:this.data.serverName}}};async function fw(e,t){try{await fetch(e,t)}catch{}}var pw=`https://eu.i.posthog.com`,mw=`phc_lyTtbYwvkdSbrcMQNPiKiiRWrrM1seyKIMjycSvItEI`,hw=`https://mcpuse.gateway.scarf.sh/events-ts`,gw=`https://mcpuse.gateway.scarf.sh/simple/`,_w=1800,vw=new Set([`query`,`response`,`messages`]);function yw(e){if(e==null)return``;if(typeof e==`string`)return e;if(typeof e==`number`||typeof e==`boolean`)return String(e);try{return JSON.stringify(e)}catch{return String(e)}}function bw(e,t=gw){let n=new URLSearchParams;for(let[t,r]of Object.entries(e)){let e=yw(r);vw.has(t)&&e.length>120&&(e=`${e.slice(0,117)}...`),e!==``&&n.set(t,e)}let r=`${t}${t.includes(`?`)?`&`:`?`}${n.toString()}`;if(r.length<=_w)return r;let i=[...n.keys()].sort((e,t)=>(n.get(t)?.length??0)-(n.get(e)?.length??0));for(let e of i){if(r.length<=_w)break;e===`event`||e===`user_id`||(n.delete(e),r=`${t}${t.includes(`?`)?`&`:`?`}${n.toString()}`)}return r.slice(0,_w)}function xw(e,t){return fw(t,{method:`POST`,headers:{"Content-Type":`application/json`},keepalive:!0,body:JSON.stringify(e)})}function Sw(e,t){try{let n=bw(e,t),r=new Image;r.referrerPolicy=`no-referrer-when-downgrade`,r.src=n}catch{}return Promise.resolve()}function Cw(e){let t=e.host??`https://eu.i.posthog.com`,n=e.apiKey??`phc_lyTtbYwvkdSbrcMQNPiKiiRWrrM1seyKIMjycSvItEI`;return fw(`${t}/i/v0/e/`,{method:`POST`,headers:{"Content-Type":`application/json`},keepalive:!0,body:JSON.stringify({api_key:n,event:e.event,distinct_id:e.distinctId,properties:e.properties,timestamp:new Date().toISOString()})})}function ww(e,t=hw){return typeof window<`u`?Sw(e,t===`https://mcpuse.gateway.scarf.sh/events-ts`?gw:t):xw(e,t)}function Tw(){return globalThis.crypto.randomUUID()}function Ew(){let e=new Uint8Array(8);return globalThis.crypto.getRandomValues(e),Array.from(e,e=>e.toString(16).padStart(2,`0`)).join(``)}function Dw(e,t){let n=e=>e.split(`-`)[0].split(`.`).map(e=>parseInt(e,10)||0),r=n(e),i=n(t),a=Math.max(r.length,i.length);for(let e=0;e<a;e++){let t=r[e]??0,n=i[e]??0;if(t!==n)return t>n}return!1}var Ow=`mcp_use_user_id`,kw=`phc_lyTtbYwvkdSbrcMQNPiKiiRWrrM1seyKIMjycSvItEI`,Aw=`https://eu.i.posthog.com`,jw=null;function Mw(){return typeof localStorage<`u`&&typeof localStorage.getItem==`function`&&typeof localStorage.setItem==`function`&&typeof localStorage.removeItem==`function`}function Nw(){if(!Mw())return null;try{localStorage.setItem(`__mcp_use_test__`,`1`),localStorage.removeItem(`__mcp_use_test__`)}catch{return null}return{getUserId(){try{return localStorage.getItem(Ow)}catch{return null}},setUserId(e){try{localStorage.setItem(Ow,e)}catch{}},getDownloadedVersion:()=>null,setDownloadedVersion:()=>void 0}}function Pw(){try{return globalThis.Bun===void 0?globalThis.Deno===void 0?typeof navigator<`u`&&navigator.userAgent?.includes(`Cloudflare-Workers`)?`cloudflare-workers`:globalThis.EdgeRuntime===void 0?typeof window<`u`&&typeof document<`u`?`browser`:typeof process<`u`&&process.versions?.node!==void 0?`node`:`unknown`:`edge`:`deno`:`bun`}catch{return`unknown`}}function Fw(){if(typeof process<`u`&&{}.MCP_USE_TELEMETRY_SOURCE)return{}.MCP_USE_TELEMETRY_SOURCE;try{if(Mw())return localStorage.getItem(`MCP_USE_TELEMETRY_SOURCE`)??void 0}catch{}}function Iw(){if(typeof window<`u`&&window.__MCP_USE_ANONYMIZED_TELEMETRY__===!1||typeof process<`u`&&{}.MCP_USE_ANONYMIZED_TELEMETRY?.toLowerCase()===`false`)return!0;try{if(Mw()&&localStorage.getItem(`MCP_USE_ANONYMIZED_TELEMETRY`)===`false`)return!0}catch{}return!1}function Lw(){try{return`session-${Tw()}`}catch{return`session-${Date.now()}-${Ew()}`}}var Rw=class e{static instance=null;UNKNOWN_USER_ID=`UNKNOWN_USER_ID`;_currUserId=null;_telemetryEnabled=!1;_pending=new Set;_scarfEnabled=!1;_runtimeEnvironment;_storageCapability;_storage;_fsBacked;_source;_productVersion;constructor(){this._runtimeEnvironment=Pw(),this._fsBacked=jw!==null,this._storage=jw??Nw()??null,this._storageCapability=this._storage?`persistent`:`session-only`,this._source=Fw()||this._runtimeEnvironment;let e=Iw(),t=this._runtimeEnvironment!==`unknown`;e?(this._telemetryEnabled=!1,Q.debug(`Telemetry disabled via opt-out`)):t?(Q.debug(`Anonymized telemetry enabled. Set MCP_USE_ANONYMIZED_TELEMETRY=false to disable.`),this._telemetryEnabled=!0,this._scarfEnabled=!0,this._fsBacked&&setTimeout(()=>{this.trackPackageDownload({triggered_by:`initialization`}).catch(e=>Q.debug(`Failed to track package download: ${e}`))},0)):(this._telemetryEnabled=!1,Q.debug(`Telemetry disabled - unknown environment: ${this._runtimeEnvironment}`))}get runtimeEnvironment(){return this._runtimeEnvironment}get storageCapability(){return this._storageCapability}static getInstance(){return e.instance||=new e,e.instance}setSource(e){this._source=e;try{Mw()&&localStorage.setItem(`MCP_USE_TELEMETRY_SOURCE`,e)}catch{}Q.debug(`Telemetry source set to: ${e}`)}getSource(){return this._source}setProductVersion(e){this._productVersion=e}get isEnabled(){return this._telemetryEnabled||this._scarfEnabled}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=Tw();return this._storage.setUserId(t),this._currUserId=t,t}this._currUserId=Lw()}catch{this._currUserId=this.UNKNOWN_USER_ID}return this._currUserId}async capture(e){if(!this._telemetryEnabled&&!this._scarfEnabled)return;let t=this.userId,n={...e.properties,mcp_use_version:this._productVersion??aw(),language:`typescript`,source:this._source,runtime:this._runtimeEnvironment};if(this._telemetryEnabled){let r=Cw({host:Aw,apiKey:kw,event:e.name,distinctId:t,properties:n});this._pending.add(r),r.finally(()=>this._pending.delete(r))}if(this._scarfEnabled){let r=ww({...n,user_id:t,event:e.name});this._pending.add(r),r.finally(()=>this._pending.delete(r))}}async trackPackageDownload(e){if(!this._scarfEnabled||!this._fsBacked||!this._storage)return;let t=aw(),n=this._storage.getDownloadedVersion(),r=!1,i=!1;n?Dw(t,n)&&(i=!0,this._storage.setDownloadedVersion(t)):(i=!0,r=!0,this._storage.setDownloadedVersion(t)),i&&await ww({...e||{},mcp_use_version:t,user_id:this.userId,event:`package_download`,first_download:r,language:`typescript`,source:this._source,runtime:this._runtimeEnvironment})}async trackAgentExecution(e){this.isEnabled&&await this.capture(new sw(e))}async trackMCPClientInit(e){this.isEnabled&&await this.capture(new cw(e))}async trackConnectorInit(e){this.isEnabled&&await this.capture(new lw(e))}async trackClientAddServer(e,t){this.isEnabled&&await this.capture(new uw({serverName:e,serverConfig:t}))}async trackClientRemoveServer(e){this.isEnabled&&await this.capture(new dw({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&&Cw({host:Aw,apiKey:kw,event:`$identify`,distinctId:e,properties:{$set:t??{}}})}reset(){this._currUserId=null}flush(){Promise.allSettled([...this._pending])}async shutdown(){try{await Promise.allSettled([...this._pending]),Q.debug(`Telemetry fetch captures flushed`)}catch(e){Q.debug(`Error flushing telemetry captures: ${e}`)}}},zw=Rw;function Bw(e){zw.getInstance().setSource(e)}JC({addServer:(e,t)=>Rw.getInstance().trackClientAddServer(e,t).catch(()=>void 0),removeServer:e=>Rw.getInstance().trackClientRemoveServer(e).catch(()=>void 0)}),QC(e=>Rw.getInstance().trackConnectorInit(e).catch(()=>void 0));function Vw(e){let t=()=>{throw Error(`Invalid url to pass to open(): ${e}`)},n;try{n=new URL(e)}catch{t()}return n.protocol!==`https:`&&n.protocol!==`http:`&&t(),n.hostname!==encodeURIComponent(n.hostname)&&t(),n.username&&=encodeURIComponent(n.username),n.password&&=encodeURIComponent(n.password),n.pathname=n.pathname.slice(0,1)+encodeURIComponent(n.pathname.slice(1)).replace(/%2f/gi,`/`),n.search=n.search.slice(0,1)+Array.from(n.searchParams.entries()).map(Hw).join(`&`),n.hash=n.hash.slice(0,1)+encodeURIComponent(n.hash.slice(1)),n.href}function Hw([e,t]){return`${encodeURIComponent(e)}${t.length>0?`=${encodeURIComponent(t)}`:``}`}var Uw=class{get(e){return localStorage.getItem(e)}set(e,t){localStorage.setItem(e,t)}remove(e){localStorage.removeItem(e)}keys(){let e=[];for(let t=0;t<localStorage.length;t++){let n=localStorage.key(t);n&&e.push(n)}return e}},Ww=class e{serverUrl;storageKeyPrefix;serverUrlHash;clientName;clientUri;logoUri;callbackUrl;clientMetadataUrl;scope;store;allowClientSecret;constructor(t,n,r){US(n.clientMetadataUrl),this.serverUrl=t,this.storageKeyPrefix=n.storageKeyPrefix||`mcp:auth`,this.serverUrlHash=e.hashString(t),this.clientName=n.clientName||`mcp-use`,this.clientUri=n.clientUri||(typeof window<`u`?window.location.origin:`https://mcp-use.com`),this.logoUri=n.logoUri||`https://mcp-use.com/logo.png`,this.callbackUrl=Vw(n.callbackUrl||(typeof window<`u`?new URL(`/oauth/callback`,window.location.origin).toString():`/oauth/callback`)),this.clientMetadataUrl=n.clientMetadataUrl,this.scope=n.scope,this.store=r,this.allowClientSecret=n.allowClientSecret??!0}getKey(e){return`${this.storageKeyPrefix}_${this.serverUrlHash}_${e}`}static hashString(e){let t=0;for(let n=0;n<e.length;n++){let r=e.charCodeAt(n);t=(t<<5)-t+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 n=this.credentialKey(e,t),r=await this.store.get(n);if(!r&&t){let r=this.credentialKey(e),i=await this.store.get(r);if(i)try{let e=JSON.parse(i);if(!e.issuer||e.issuer===t.issuer){let i={...e,issuer:t.issuer},a=JSON.stringify(i);return await this.store.set(n,a),await this.store.set(r,a),{key:n,value:i}}}catch{await this.store.remove(r)}return}if(r)try{return{key:n,value:JSON.parse(r)}}catch(t){console.warn(`[${this.storageKeyPrefix}] Failed to parse ${e.replace(`_`,` `)}:`,t),await this.store.remove(n);return}}async tokens(e){return(await this.readCredential(`tokens`,e))?.value}async saveTokens(e,t){let n=JSON.stringify(e);await this.store.set(this.credentialKey(`tokens`,t),n),t&&await this.store.set(this.credentialKey(`tokens`),n),await this.store.remove(this.getKey(`code_verifier`)),await this.store.remove(this.getKey(`last_auth_url`))}async clientInformation(e){let t=await this.readCredential(`client_info`,e);if(!t)return;let{key:n,value:r}=t;try{if(!this.allowClientSecret&&r.client_secret){await this.store.remove(n),e&&await this.store.remove(this.credentialKey(`client_info`)),console.warn(`[${this.storageKeyPrefix}] Removed OAuth client information containing a browser client_secret.`);return}let t=Array.isArray(r.redirect_uris)?r.redirect_uris:[];if(!(t.length===0||t.includes(this.redirectUrl))){console.info(`[${this.storageKeyPrefix}] Invalidating cached OAuth client info due to redirect URI mismatch.`),await this.store.remove(n),await this.store.remove(this.credentialKey(`tokens`,e)),await this.store.remove(this.getKey(`last_auth_url`));return}return r}catch{await this.store.remove(n);return}}async saveClientInformation(e,t){let n=e;if(!this.allowClientSecret&&n.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(e);await this.store.set(this.credentialKey(`client_info`,t),r),t&&await this.store.set(this.credentialKey(`client_info`),r)}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}async invalidateCredentials(e){let t=async e=>{let t=`${this.getKey(e)}_`;for(let n of await this.store.keys())(n===this.getKey(e)||n.startsWith(t))&&await this.store.remove(n)};switch(e){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(`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`));break;default:break}}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 n=globalThis.crypto.randomUUID(),r=`${this.storageKeyPrefix}:state_${n}`,i={serverUrlHash:this.serverUrlHash,expiry:Date.now()+1e3*60*10,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`,n);let a=Vw(e.toString());return await this.store.set(r,JSON.stringify(i)),await this.store.set(this.getKey(`last_auth_url`),a),a}async getTokenEndpoint(){return(await this.discoveryState())?.authorizationServerMetadata?.token_endpoint??null}};async function Gw(e){return typeof e==`string`?e:e instanceof URLSearchParams||e instanceof FormData?Object.fromEntries(e.entries()):e instanceof Blob?await e.text():e}var Kw=class{serverUrl;staticClientInfo;session;preventAutoAuth;useRedirectFlow;oauthProxyUrl;connectionUrl;proxyOAuthRequests;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.session=new Ww(e,{...t,allowClientSecret:!1},new Uw),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)}reanchorWellKnownUrl(e){if(!this.connectionUrl)return e;try{let t=new URL(e),n=new URL(this.connectionUrl);if(t.origin!==n.origin||!t.pathname.startsWith(`/.well-known/`))return e;let r=new URL(this.serverUrl),[i,...a]=t.pathname.slice(13).split(`/`);if(!i)return e;let o=a.length?`/${a.join(`/`)}`:``,s=n.pathname.replace(/\/+$/,``),c=r.pathname.replace(/\/+$/,``),l=o&&o===s?c:o;return`${r.origin}/.well-known/${i}${l}${t.search}`}catch{return e}}getProxyFetch(e){if(!this.proxyOAuthRequests||!this.oauthProxyUrl)return e;let t=e??globalThis.fetch.bind(globalThis),n=this.oauthProxyUrl,r=new Set,i=!1;return async(e,a)=>{let o=typeof e==`string`?e:e instanceof URL?e.toString():e.url,s=this.reanchorWellKnownUrl(o),c;try{c=new URL(s).pathname}catch{return await t(e,a)}let l=c.includes(`/.well-known/`);if(!i){i=!0;let e=(await this.discoveryState())?.authorizationServerMetadata;for(let t of[`registration_endpoint`,`token_endpoint`,`revocation_endpoint`,`introspection_endpoint`])typeof e?.[t]==`string`&&r.add(e[t])}let u=r.has(s)||/\/(?:register|registration|token|revoke|revocation|introspect|introspection)\/?$/.test(c);if(!l&&!u)return await t(e,a);try{let r=new URL(s),i=new URL(n);if(r.origin===i.origin&&(r.pathname.startsWith(i.pathname)||s.includes(`/inspector/api/oauth`)))return await t(e,a)}catch{}let d=l?`${n}/metadata?serverUrl=${encodeURIComponent(this.serverUrl)}&url=${encodeURIComponent(s)}`:`${n}/proxy`;if(l){let e=await t(d,{...a,method:`GET`});try{let t=await e.clone().json();for(let e of[`registration_endpoint`,`token_endpoint`,`revocation_endpoint`,`introspection_endpoint`])typeof t[e]==`string`&&r.add(t[e])}catch{}return e}let f=a?.body?await Gw(a.body):void 0,p=await(await t(d,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({serverUrl:this.serverUrl,url:s,method:a?.method||`POST`,headers:a?.headers?Object.fromEntries(new Headers(a.headers)):{},body:f})})).json();return new Response(JSON.stringify(p.body),{status:p.status,statusText:p.statusText,headers:new Headers(p.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.session.saveTokens(e,t)}async clientInformation(e){return this.staticClientInfo?this.staticClientInfo:this.session.clientInformation(e)}async saveClientInformation(e,t){if(!this.staticClientInfo)return this.session.saveClientInformation(e,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)}discoveryState(){return this.session.discoveryState()}getTokenEndpoint(){return this.session.getTokenEndpoint()}async getClientCredentials(){let e=await this.clientInformation();return e?.client_id?{client_id:e.client_id}:null}async prepareAuthorizationUrl(e){return 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:typeof window<`u`?window.location.href:void 0})}async redirectToAuthorization(e){let t=await this.prepareAuthorizationUrl(e);if(this.preventAutoAuth){console.info(`[${this.storageKeyPrefix}] Auto-auth prevented. Authorization URL stored for manual trigger.`);return}if(this.useRedirectFlow){console.info(`[${this.storageKeyPrefix}] Redirecting to authorization URL (full-page redirect).`),window.location.href=t;return}let n=`width=600,height=700,resizable=yes,scrollbars=yes,status=yes`;try{let e=window.open(t,`mcp_auth_${this.serverUrlHash}`,n);this.onPopupWindow&&this.onPopupWindow(t,n,e),!e||e.closed||e.closed===void 0?console.warn(`[${this.storageKeyPrefix}] Popup likely blocked by browser. Manual navigation might be required using the stored URL.`):(e.focus(),console.info(`[${this.storageKeyPrefix}] Redirecting to authorization URL in popup.`))}catch(e){console.error(`[${this.storageKeyPrefix}] Error opening popup window:`,e)}}getLastAttemptedAuthUrl(){let e=localStorage.getItem(this.getKey(`last_auth_url`));return e?Vw(e):null}clearStorage(){let e=`${this.storageKeyPrefix}_${this.serverUrlHash}_`,t=`${this.storageKeyPrefix}:state_`,n=[],r=0;for(let r=0;r<localStorage.length;r++){let i=localStorage.key(r);if(i){if(i.startsWith(e))n.push(i);else if(i.startsWith(t))try{let e=localStorage.getItem(i);e&&JSON.parse(e).serverUrlHash===this.serverUrlHash&&n.push(i)}catch(e){console.warn(`[${this.storageKeyPrefix}] Error parsing state key ${i} during clearStorage:`,e)}}}return[...new Set(n)].forEach(e=>{localStorage.removeItem(e),r++}),r}};async function qw(e,t={}){return new Kw(e,t)}var Jw=`mcp_auth_callback`,Yw=`mcp_auth_callback`;function Xw(e){try{return typeof localStorage<`u`&&!!localStorage.getItem(e)}catch{return!1}}function Zw({popup:e,state:t,tokensKey:n,timeoutMs:r=5*6e4,closePollMs:i=1e3,closeGraceMs:a=2e4,expectedOrigin:o=typeof window<`u`?window.location.origin:``}){return new Promise(s=>{let c=!1,l=null,u=null,d=null,f=null,p=()=>{if(l&&=(clearInterval(l),null),u&&=(clearTimeout(u),null),d&&=(clearTimeout(d),null),typeof window<`u`&&(window.removeEventListener(`message`,g),window.removeEventListener(`storage`,v)),f){try{f.removeEventListener(`message`,_),f.close()}catch{}f=null}},m=e=>{c||(c=!0,p(),s(e))},h=e=>{!e||e.type!==Yw||e.state&&t&&e.state!==t||(e.success?m({kind:`success`}):m({kind:`error`,error:e.error??`Authentication failed in callback.`}))},g=e=>{o&&e.origin!==o||h(e.data)},_=e=>{h(e.data)},v=e=>{e.key===n&&e.newValue&&m({kind:`success`})};if(typeof window<`u`&&(window.addEventListener(`message`,g),window.addEventListener(`storage`,v)),typeof BroadcastChannel<`u`)try{f=new BroadcastChannel(Jw),f.addEventListener(`message`,_)}catch{f=null}e&&(l=setInterval(()=>{if(c)return;let t=!1;try{t=e.closed}catch{t=!1}if(t){if(l&&=(clearInterval(l),null),Xw(n)){m({kind:`success`});return}d=setTimeout(()=>{m(Xw(n)?{kind:`success`}:{kind:`cancelled`})},a)}},i)),u=setTimeout(()=>{m(Xw(n)?{kind:`success`}:{kind:`timeout`})},r)})}var Qw=5*6e4;function $w(e,t=0){if(!e||t>5)return!1;if(e instanceof xS)return!0;if(e instanceof Error){if(e.code===401||e.name===`UnauthorizedError`)return!0;let n=e.message??``;if(n.includes(`401`)||n.includes(`Unauthorized`)||e.cause&&$w(e.cause,t+1))return!0;let r=e.data;if(r?.cause&&$w(r.cause,t+1))return!0}return!1}async function eT(e,t,n={}){let r=e,i=n.timeoutMs??Qw,a=n.fetchFn??r.getProxyFetch?.()??void 0;if(!r.hasPendingFlow){let n=await BS(e,{serverUrl:t,fetchFn:a});if(n===`AUTHORIZED`)return;if(n!==`REDIRECT`)throw Error(`Unexpected OAuth auth() result: ${n}`)}if(typeof r.getAuthorizationCode==`function`){await BS(e,{serverUrl:t,authorizationCode:await r.getAuthorizationCode(),fetchFn:a});return}await tT(r,i)}async function tT(e,t){if(typeof window>`u`)throw Error(`OAuth redirect requires a browser environment or a provider with getAuthorizationCode()`);if(e.useRedirectFlow)return;let n=e.getKey?.(`tokens`);if(!n)throw Error(`Browser OAuth provider must expose getKey() for token storage`);let r=null,i=e.getLastAttemptedAuthUrl?.();if(i)try{r=new URL(i).searchParams.get(`state`)}catch{}let a=await Zw({popup:null,state:r,tokensKey:n,timeoutMs:t});switch(a.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(a.error);default:throw Error(`Unexpected OAuth popup result`)}}var nT=`http://json-schema.org/draft-04/schema`,rT=new Set([`http://json-schema.org/draft-07/schema`,`https://json-schema.org/draft-07/schema`]),iT=new Set([`https://json-schema.org/draft/2019-09/schema`,`http://json-schema.org/draft/2019-09/schema`]),aT=new Set([`https://json-schema.org/draft/2020-12/schema`,`http://json-schema.org/draft/2020-12/schema`]);function oT(e){if(!(`$schema`in e)||typeof e.$schema!=`string`)return`2020-12`;let t=e.$schema.replace(/#$/,``);if(t===nT)return`4`;if(rT.has(t))return`7`;if(iT.has(t))return`2019-09`;if(aT.has(t))return`2020-12`}var sT=class{getValidator(e){let t=oT(e);return(t===void 0?new Jx:new Jx({draft:t})).getValidator(e)}},cT={"~standard":{version:1,vendor:`mcp-use`,validate:e=>({value:e})}},lT=class{client=null;connectionManager=null;toolsCache=null;capabilitiesCache=null;serverInfoCache=null;connected=!1;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){let t=this.constructor.name;$C({connectorType:t,...e})}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){Q.error(`Error in notification handler:`,e)}}async handleListChanged(e,t,n){if(t){Q.warn(`[Auto] ${e} refresh failed:`,t);return}e===`notifications/tools/list_changed`&&n&&(this.toolsCache=[...n]),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();break;default:break}await this.forwardNotification(e)};let e=this.client._notificationHandlers;for(let t of[`notifications/progress`,`notifications/cancelled`]){let n=e.get(t);n&&e.set(t,async e=>{await n(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&&typeof e==`object`&&e.method===`notifications/progress`&&this.forwardRoundProgress(e.params),await t?.(e)}}forwardRoundProgress(e){if(this.activeProgressHandlers.size===1){let[t]=this.activeProgressHandlers;t?.(e)}}async refreshToolsCache(){if(this.client)try{Q.debug(`[Auto] Refreshing tools cache due to list_changed notification`);let e=await this.client.listTools();this.toolsCache=e.tools??[],Q.debug(`[Auto] Refreshed tools cache: ${this.toolsCache.length} tools`)}catch(e){Q.warn(`[Auto] Failed to refresh tools cache:`,e)}}async onResourcesListChanged(){Q.debug(`[Auto] Resources list changed - clients should re-fetch if needed`)}async onPromptsListChanged(){Q.debug(`[Auto] Prompts list changed - clients should re-fetch if needed`)}async setRoots(e){this.rootsCache=[...e],this.client&&(Q.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()=>(Q.debug(`Server requested roots list, returning ${this.rootsCache.length} root(s)`),{roots:this.rootsCache}))}setupSamplingHandler(){if(!this.client){Q.debug(`setupSamplingHandler: No client available`);return}let e=this.opts.onSampling;if(!e){Q.debug(`setupSamplingHandler: No sampling callback provided`);return}Q.debug(`setupSamplingHandler: Setting up sampling request handler`),this.client.setRequestHandler(`sampling/createMessage`,async t=>(Q.debug(`Server requested sampling, forwarding to callback`),await e(t.params))),Q.debug(`setupSamplingHandler: Sampling handler registered successfully`)}setupElicitationHandler(){if(!this.client){Q.debug(`setupElicitationHandler: No client available`);return}let e=this.opts.onElicitation;if(!e){Q.debug(`setupElicitationHandler: No elicitation callback provided`);return}Q.debug(`setupElicitationHandler: Setting up elicitation request handler`),this.client.setRequestHandler(`elicitation/create`,async t=>(Q.debug(`Server requested elicitation, forwarding to callback`),await e(t.params))),Q.debug(`setupElicitationHandler: Elicitation handler registered successfully`)}async disconnect(){if(!this.connected){Q.debug(`Not connected to MCP implementation`);return}Q.debug(`Disconnecting from MCP implementation`),await this.cleanupResources(),this.connected=!1,Q.debug(`Disconnected from MCP implementation`)}get isClientConnected(){return this.client!=null}async initialize(e=this.opts.defaultRequestOptions??{}){if(!this.client)throw Error(`MCP client is not connected`);Q.debug(`Caching server capabilities & tools`);let t=this.client.getServerCapabilities();this.capabilitiesCache=t||null;let n=this.client.getServerVersion();this.serverInfoCache=n?{name:n.name,version:n.version,title:n.title,description:n.description,websiteUrl:n.websiteUrl,icons:n.icons}:null;try{let t=await this.client.listTools(void 0,e);this.toolsCache=t.tools??[],Q.debug(`Fetched ${this.toolsCache.length} tools from server`)}catch(e){let t=e;t.code===-32601?Q.debug(`Server does not implement tools/list, assuming no tools`):Q.debug(`Failed to list tools, assuming empty:`,t.message),this.toolsCache=[]}return Q.debug(`Server capabilities:`,t),Q.debug(`Server info:`,n),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,n){if(!this.client)throw Error(`MCP client is not connected`);let r=n?{...n}:void 0;r?.resetTimeoutOnProgress&&!r.onprogress&&(r.onprogress=()=>{},Q.debug(`[BaseConnector] Added onprogress callback for tool '${e}' to enable progressToken`)),Q.debug(`Calling tool '${e}' with args`,t);let i=r?.onprogress;i&&this.activeProgressHandlers.add(i);try{let n=await this.client.callTool({name:e,arguments:t},r);return Q.debug(`Tool '${e}' returned`,n),n}finally{i&&this.activeProgressHandlers.delete(i)}}async listTools(e){if(!this.client)throw Error(`MCP client is not connected`);Q.debug(`[listTools] Fetching fresh tools from server...`);let t=await this.client.listTools(void 0,e),n=t.tools?[...t.tools]:[];return Q.debug(`[listTools] Returned ${n.length} tools:`,n.map(e=>e.name)),n}async listResources(e,t){if(!this.client)throw Error(`MCP client is not connected`);return Q.debug(`Listing resources`,e?`with cursor: ${e}`:``),await this.client.listResources({cursor:e},t)}async listAllResources(e){if(!this.client)throw Error(`MCP client is not connected`);if(!this.capabilitiesCache?.resources)return Q.debug(`Server does not advertise resources capability, skipping`),{resources:[]};try{Q.debug(`Listing all resources (with auto-pagination)`);let t=[],n;do{let r=await this.client.listResources({cursor:n},e);t.push(...r.resources||[]),n=r.nextCursor}while(n);return{resources:t}}catch(e){if(e.code===-32601)return Q.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 Q.debug(`Listing resource templates`),await this.client.listResourceTemplates(void 0,e)}async complete(e,t){if(!this.client)throw Error(`MCP client is not connected`);Q.debug(`[complete] Requesting completions for:`,e.ref);let n=await this.client.complete(e,t);return Q.debug(`[complete] Received ${n.completion.values.length} suggestions`),n}async readResource(e,t){if(!this.client)throw Error(`MCP client is not connected`);return Q.debug(`Reading resource ${e}`),await this.client.readResource({uri:e},t)}async subscribeToResource(e,t){if(!this.client)throw Error(`MCP client is not connected`);return Q.debug(`Subscribing to resource: ${e}`),await this.client.subscribeResource({uri:e},t)}async unsubscribeFromResource(e,t){if(!this.client)throw Error(`MCP client is not connected`);return Q.debug(`Unsubscribing from resource: ${e}`),await this.client.unsubscribeResource({uri:e},t)}async listPrompts(){if(!this.client)throw Error(`MCP client is not connected`);if(!this.capabilitiesCache?.prompts)return Q.debug(`Server does not advertise prompts capability, skipping`),{prompts:[]};try{return Q.debug(`Listing prompts`),await this.client.listPrompts()}catch(e){if(e.code===-32601)return Q.debug(`Server advertised prompts but method not found`),{prompts:[]};throw e}}async getPrompt(e,t){if(!this.client)throw Error(`MCP client is not connected`);return Q.debug(`Getting prompt ${e}`),await this.client.getPrompt({name:e,arguments:t})}async request(e,t=null,n){if(!this.client)throw Error(`MCP client is not connected`);return Q.debug(`Sending raw request '${e}' with params`,t),await this.client.request({method:e,params:t??{}},cT,n)}async cleanupResources(){let e=[];if(this.client)try{typeof this.client.close==`function`&&await this.client.close()}catch(t){let n=`Error closing client: ${t}`;Q.warn(n),e.push(n)}finally{this.client=null}if(this.connectionManager)try{await this.connectionManager.stop()}catch(t){let n=`Error stopping connection manager: ${t}`;Q.warn(n),e.push(n)}finally{this.connectionManager=null}this.toolsCache=null,e.length&&Q.warn(`Resource cleanup finished with ${e.length} issue(s)`)}};function uT(e,t=0){if(!e||t>5)return!1;if(e instanceof xS||e instanceof Z_&&e.status===401)return!0;if(e instanceof Error){if(e.cause&&uT(e.cause,t+1))return!0;let n=e instanceof X_?e.data:void 0;if(n?.cause&&uT(n.cause,t+1))return!0}return!1}function dT(e,t,n,r){let i=new URL(e),a=t.replace(/\/$/,``);return async(e,t)=>{let o=new Request(e,t),s=new URL(o.url);if(!(s.origin===i.origin&&s.pathname===i.pathname))return n(o);let c=new Headers(o.headers);c.set(`X-Target-URL`,o.url),r&&c.set(`X-Server-Id`,r);let l=o.method===`GET`||o.method===`HEAD`?void 0:await o.clone().arrayBuffer();return n(new Request(a,{method:o.method,headers:c,body:l,signal:o.signal,redirect:`manual`}))}}var fT=class extends lT{baseUrl;headers;timeout;customFetch;clientInfo;protocolNegotiation;gatewayUrl;serverId;reconnectionOptions;transportType=null;streamableTransport=null;constructor(e,t={}){super(t);let n=e.replace(/\/$/,``);this.baseUrl=n,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;let r=t.fetch??globalThis.fetch.bind(globalThis);this.customFetch=this.gatewayUrl?dT(n,this.gatewayUrl,r,this.serverId):t.fetch,this.clientInfo=t.clientInfo??{name:`http-connector`,version:`1.0.0`},this.protocolNegotiation=t.protocolNegotiation??`auto`,this.reconnectionOptions=t.reconnectionOptions}buildClientOptions(){return{...this.opts.clientOptions||{},jsonSchemaValidator:this.opts.clientOptions?.jsonSchemaValidator??new sT,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 Z_?e:e instanceof Error&&e.cause instanceof Z_?e.cause:null}classifyStreamableHttpFailure(e){let t=`Unknown error`,n=!1,r,i=this.unwrapStreamableError(e);if(i){let e=i.status;return n=e===401,r=e,e===400&&i.message.includes(`Missing session ID`)?(t=`Server requires session ID (FastMCP compatibility)`,Q.warn(`\u26A0\uFE0F ${t}`)):e===404||e===405?(t=`Server returned ${e} - server likely doesn't support streamable HTTP`,Q.debug(t)):(t=`Server returned ${e}: ${i.message}`,Q.debug(t)),{fallbackReason:t,is401Error:n,httpStatusCode:r}}if(e instanceof Error){let r=e.toString(),i=e.message||``;n=uT(e)||r.includes(`401`)||i.includes(`Unauthorized`),r.includes(`Missing session ID`)||r.includes(`Bad Request: Missing session ID`)||i.includes(`FastMCP session ID error`)?(t=`Server requires session ID (FastMCP compatibility)`,Q.warn(`\u26A0\uFE0F ${t}`)):r.includes(`405 Method Not Allowed`)||r.includes(`404 Not Found`)?(t=`Server doesn't support streamable HTTP (405/404)`,Q.debug(t)):(t=`Streamable HTTP failed: ${e.message}`,Q.debug(t))}return{fallbackReason:t,is401Error:n,httpStatusCode:r}}async connect(){if(this.connected){Q.debug(`Already connected to MCP implementation`);return}let e=this.baseUrl;Q.debug(`Connecting to MCP implementation via HTTP: ${e}`);try{await this.connectWithStreamableHttp(e),Q.debug(`✅ Successfully connected via streamable HTTP`)}catch(e){Q.debug(`Streamable HTTP connect failed`,e);let{fallbackReason:t,is401Error:n,httpStatusCode:r}=this.classifyStreamableHttpFailure(e);if(await this.cleanupResources(),n){Q.info(`Authentication required`);let e=Error(`Authentication required`);throw e.code=401,e}let i=Error(`Could not connect via streamable HTTP: ${t}`);throw r!==void 0&&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,n]=e.body.tee();return(async()=>{let e=n.getReader(),t=new TextDecoder,r=``;try{for(;;){let{done:n,value:i}=await e.read();if(n)break;r+=t.decode(i,{stream:!0});let a=r.split(/\r?\n\r?\n/);r=a.pop()??``;for(let e of a)for(let t of e.split(/\r?\n/))if(t.startsWith(`data:`))try{let e=JSON.parse(t.slice(5).trim());e.method===`notifications/progress`&&this.forwardRoundProgress(e.params)}catch{}}}catch(e){e instanceof DOMException&&e.name===`AbortError`||Q.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{Q.debug(`[HttpConnector] Connecting with Streamable HTTP`,{baseUrl:e,originalUrl:this.baseUrl,gatewayUrl:this.gatewayUrl||`none`,authProviderUrl:this.opts.authProvider&&`serverUrl`in this.opts.authProvider&&typeof this.opts.authProvider.serverUrl==`string`?this.opts.authProvider.serverUrl:`none`,headers:this.headers});let t,n=new Promise(e=>{t=e}),r=this.customFetch??globalThis.fetch.bind(globalThis),i=new GC(new URL(e),{authProvider:this.opts.authProvider,fetch:async(e,n)=>{let i=await r(e,n),a=n?.method??(e instanceof Request?e.method:`GET`),o=new Headers(e instanceof Request?e.headers:void 0);return new Headers(n?.headers).forEach((e,t)=>{o.set(t,e)}),a.toUpperCase()===`GET`&&i.ok&&i.headers.get(`content-type`)?.includes(`text/event-stream`)&&t?.(),o.get(`mcp-method`)===`subscriptions/listen`?i:this.observeSseProgress(i)},requestInit:{headers:this.headers},reconnectionOptions:{maxReconnectionDelay:3e4,initialReconnectionDelay:1e3,reconnectionDelayGrowFactor:1.5,maxRetries:2,...this.reconnectionOptions}}),a=i;if(this.opts.wrapTransport){let e=this.baseUrl;a=this.opts.wrapTransport(a,e)}let o=this.buildClientOptions();Q.debug(`Creating Client with capabilities:`,JSON.stringify(o.capabilities,null,2)),this.client=new BC(this.clientInfo,o),this.setupRootsHandler(),this.setupSamplingHandler(),this.setupElicitationHandler(),Q.debug(`Roots/sampling/elicitation handlers registered before connect`);try{let e;if(await Promise.race([this.client.connect(a),new Promise((t,n)=>{e=setTimeout(()=>n(Error(`MCP connection timed out after ${this.timeout}ms`)),this.timeout)})]).finally(()=>{e!==void 0&&clearTimeout(e)}),(this.client.getProtocolEra?.()??`legacy`)===`legacy`&&i.sessionId){let e,t=await Promise.race([n.then(()=>!0),new Promise(t=>e=setTimeout(()=>t(!1),Math.min(this.timeout,5e3)))]);e&&clearTimeout(e),t||Q.warn(`Legacy server push stream did not attach before connect completed`)}let t=i.sessionId;t&&Q.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 n=Error(`Session ID error: ${t}. The SDK should automatically extract session ID from initialize response.`);throw n.cause=e,n}}throw e}this.streamableTransport=i,this.connectionManager={stop:async()=>{if(this.streamableTransport)try{await this.streamableTransport.close()}catch(e){Q.warn(`Error closing Streamable HTTP transport: ${e}`)}finally{this.streamableTransport=null}}},this.connected=!0,this.transportType=`streamable-http`,this.setupNotificationHandler(),Q.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&&this.protocolEra!==`modern`){let e;try{await Promise.race([this.streamableTransport.terminateSession().then(()=>!0),new Promise(t=>e=setTimeout(()=>t(!1),Math.min(this.timeout,5e3)))])||Q.debug(`Timed out terminating legacy HTTP session; closing transport`)}catch(e){Q.debug(`Error terminating Streamable HTTP session: ${e}`)}finally{e&&clearTimeout(e)}}await super.cleanupResources()}};function pT(e,t){return{onSampling:e?.onSampling??t?.onSampling,onElicitation:e?.onElicitation??t?.onElicitation,onNotification:e?.onNotification??t?.onNotification}}function mT(e){if(!(`url`in e)||typeof e.url!=`string`||e.authProvider||e.authToken||e.oauth===!1)return!1;let t=e.headers;if(t){for(let e of Object.keys(t))if(e.toLowerCase()===`authorization`)return!1}return!0}function hT(){return{name:`mcp-use`,title:`mcp-use`,version:aw(),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`}}function gT(e){let t=hT();if(!e||typeof e!=`object`)return t;let n=e;return!n.name||!n.version?t:{...t,...n}}var _T=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){e===`notification`&&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 protocolEra(){return this.connector.protocolEra}get negotiatedProtocolVersion(){return this.connector.negotiatedProtocolVersion}get info(){let e=this.protocolEra,t=this.negotiatedProtocolVersion,n=this.serverInfo;if(!e||!t||!n)throw Error(`MCP connection is not initialized`);let r=this.serverCapabilities,i=r.extensions&&typeof r.extensions==`object`&&!Array.isArray(r.extensions)?r.extensions:{};return{protocolEra:e,protocolVersion:t,server:n,capabilities:r,instructions:this.connector.instructions,extensions:i}}supports(e){return e in this.serverCapabilities}async callTool(e,t={},n){return this.connector.callTool(e,t,n)}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){return this.connector.getPrompt(e,t)}async request(e,t=null,n){return this.connector.request(e,t,n)}};function vT(e){return!!e&&typeof e==`object`&&`redirectUrl`in e&&`clientMetadata`in e}var yT=class{config={};sessions={};activeSessions=[];constructor(e){e&&(this.config=e)}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,YC(e,t)}async removeServer(e){this.config.mcpServers?.[e]&&(await this.closeSession(e),delete this.config.mcpServers[e],XC(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 n=this.config.mcpServers??{};if(Object.keys(n).length===0&&Q.warn(`No MCP servers defined in config`),!n[e])throw Error(`Server '${e}' not found in config`);let r={...n[e]},i;if(mT(r)){let e=r.oauth===!1?void 0:r.oauth??{};i=await this.createDefaultOAuthProvider(r.url,e),r={...r,authProvider:i}}else `authProvider`in r&&r.authProvider&&vT(r.authProvider)&&(i=r.authProvider);let a=async()=>{let e=new _T(await Promise.resolve(this.createConnectorFromConfig(r)));return t&&await e.initialize(),e},o;try{o=await a()}catch(n){let s=r;if(!t||!i||!(`url`in s)||!$w(n)||i.preventAutoAuth)throw n;Q.info(`[MCPClient] Unauthorized connecting to '${e}'; completing OAuth\u2026`),await eT(i,s.url),o=await a()}return this.sessions[e]=o,this.activeSessions.includes(e)||this.activeSessions.push(e),o}async connect(e){return this.createSession(e)}async createAllSessions(e=!0){let t=this.config.mcpServers??{};Object.keys(t).length===0&&Q.warn(`No MCP servers defined in config`);for(let n of Object.keys(t))await this.createSession(n,e);return this.sessions}async connectAll(){return this.createAllSessions()}getSession(e){return this.sessions[e]||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){Q.warn(`No session exists for server ${e}, nothing to close`);return}try{Q.debug(`Closing session for server ${e}`),await t.disconnect()}catch(t){Q.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 n of e)try{Q.debug(`Closing session for server ${n}`),await this.closeSession(n)}catch(e){let r=`Failed to close session for server '${n}': ${e}`;Q.error(r),t.push(r)}t.length?Q.error(`Encountered ${t.length} errors while closing sessions`):Q.debug(`All sessions closed successfully`)}async close(){await this.closeAllSessions()}};function bT(e){let t=Object.keys(e.mcpServers??{});zw.getInstance().trackMCPClientInit({codeMode:!1,sandbox:!1,allCallbacks:!1,verify:!1,servers:t,numServers:t.length,isBrowser:!0}).catch(e=>Q.debug(`Failed to track BrowserMCPClient init: ${e}`))}var xT=class e extends yT{static getPackageVersion(){return aw()}constructor(e){super(e),bT(this.config)}static fromDict(t){return new e(t)}async createDefaultOAuthProvider(e,t={}){return qw(e,t)}createConnectorFromConfig(e){let{url:t,headers:n,fetch:r,authToken:i,authProvider:a,wrapTransport:o,clientOptions:s,protocolNegotiation:c,timeout:l,gatewayUrl:u,serverId:d,reconnectionOptions:f}=e;if(!t)throw Error(`Server URL is required`);let p=this.config,m=pT(e,p),h=gT(e.clientInfo??this.config.clientInfo),g={headers:n,fetch:r??globalThis.fetch.bind(globalThis),authToken:i,authProvider:a,wrapTransport:o,clientOptions:s,onSampling:m.onSampling,onElicitation:m.onElicitation,onNotification:m.onNotification,protocolNegotiation:c,timeout:l,clientInfo:h,gatewayUrl:u,serverId:d,reconnectionOptions:f};return Q.debug(`[BrowserMCPClient] Connector options prepared (clientOptions: ${s?`provided`:`none`})`),new fT(t,g)}},ST=`mcp_inspector_telemetry_disabled`,CT=`mcp_inspector_telemetry_user_id`,wT=`mcp_inspector_telemetry_download_version`,TT=`MCP_USE_ANONYMIZED_TELEMETRY`,ET=`mcp_use_user_id`;function DT(){return typeof localStorage<`u`&&typeof localStorage.getItem==`function`&&typeof localStorage.setItem==`function`}function OT(){if(typeof window>`u`)return`standalone`;let e=window.__MCP_INSPECTOR_MODE__;return e===`standalone`||e===`embedded`||e===`cloud`?e:`standalone`}function kT(e,t){let n=e=>e.split(`-`)[0].split(`.`).map(e=>parseInt(e,10)||0),r=n(e),i=n(t),a=Math.max(r.length,i.length);for(let e=0;e<a;e++){let t=r[e]??0,n=i[e]??0;if(t!==n)return t>n}return!1}function AT(){if(DT())try{if(localStorage.getItem(ST)===`true`&&localStorage.getItem(TT)!==`false`&&localStorage.setItem(TT,`false`),!localStorage.getItem(ET)){let e=localStorage.getItem(CT);e&&localStorage.setItem(ET,e)}}catch{}}async function jT(){if(!(typeof window>`u`||!DT()))try{let e=zw.getInstance();if(!e.isEnabled)return;let t=Lo(),n=!1,r=!1,i=localStorage.getItem(wT);if(i?kT(t,i)&&(n=!0,localStorage.setItem(wT,t)):(n=!0,r=!0,localStorage.setItem(wT,t)),!n)return;ww({triggered_by:`initialization`,mcp_use_version:t,user_id:e.userId,event:`package_download`,first_download:r,language:`typescript`,source:`inspector`,package:`inspector`,mode:OT()},hw)}catch{}}function MT(){AT(),Bw(`inspector`),zw.getInstance().setProductVersion(Lo()),jT()}function NT(){if(typeof window>`u`)return`standalone`;let e=window.__MCP_INSPECTOR_MODE__;return e===`standalone`||e===`embedded`||e===`cloud`?e:`standalone`}async function PT(e){await zw.getInstance().capture({name:e.name,properties:{...e.properties,package:`inspector`,mode:NT()}})}async function FT(e){await PT(new xo(e))}var IT=`io.modelcontextprotocol/related-task`,LT=`io.modelcontextprotocol/subscriptionId`,RT=lm(()=>J([V(),H(),U(),Tp(),Y(V(),RT),G(RT)])),zT=Y(V(),RT),BT=J([V(),H().int()]),VT=V(),HT=K({ttl:H().optional()}),UT=K({taskId:V()}),WT=q({progressToken:BT.optional(),[IT]:UT.optional()}),GT=K({_meta:WT.optional()}),KT=GT.extend({task:HT.optional()}),qT=K({method:V(),params:GT.loose().optional()}),JT=K({_meta:WT.optional()}),YT=K({method:V(),params:JT.loose().optional()}),XT=q({_meta:WT.optional()}),ZT=J([V(),H().int()]),QT=K({jsonrpc:X(`2.0`),id:ZT,...qT.shape}).strict(),$T=K({jsonrpc:X(`2.0`),...YT.shape}).strict(),eE=K({jsonrpc:X(`2.0`),id:ZT,result:XT}).strict(),tE=K({jsonrpc:X(`2.0`),id:ZT.optional(),error:K({code:H().int(),message:V(),data:W().optional()})}).strict(),nE=J([QT,$T,eE,tE]);J([eE,tE]);var rE=XT.strict(),iE=JT.extend({requestId:ZT.optional(),reason:V().optional()}),aE=YT.extend({method:X(`notifications/cancelled`),params:iE}),oE=K({icons:G(K({src:V(),mimeType:V().optional(),sizes:G(V()).optional(),theme:Bp([`light`,`dark`]).optional()})).optional()}),sE=K({name:V(),title:V().optional()}),cE=sE.extend({...sE.shape,...oE.shape,version:V(),websiteUrl:V().optional(),description:V().optional()}),lE=pm(e=>e&&typeof e==`object`&&!Array.isArray(e)&&Object.keys(e).length===0?{form:{}}:e,Lp(K({form:Lp(K({applyDefaults:U().optional()}),zT).optional(),url:zT.optional()}),zT.optional())),uE=q({list:zT.optional(),cancel:zT.optional(),requests:q({sampling:q({createMessage:zT.optional()}).optional(),elicitation:q({create:zT.optional()}).optional()}).optional()}),dE=q({list:zT.optional(),cancel:zT.optional(),requests:q({tools:q({call:zT.optional()}).optional()}).optional()}),fE=K({experimental:Y(V(),zT).optional(),sampling:K({context:zT.optional(),tools:zT.optional()}).optional(),elicitation:lE.optional(),roots:K({listChanged:U().optional()}).optional(),tasks:uE.optional(),extensions:Y(V(),zT).optional()}),pE=GT.extend({protocolVersion:V(),capabilities:fE,clientInfo:cE}),mE=qT.extend({method:X(`initialize`),params:pE}),hE=K({experimental:Y(V(),zT).optional(),logging:zT.optional(),completions:zT.optional(),prompts:K({listChanged:U().optional()}).optional(),resources:K({subscribe:U().optional(),listChanged:U().optional()}).optional(),tools:K({listChanged:U().optional()}).optional(),tasks:dE.optional(),extensions:Y(V(),zT).optional()}),gE=XT.extend({protocolVersion:V(),capabilities:hE,serverInfo:cE,instructions:V().optional()}),_E=YT.extend({method:X(`notifications/initialized`),params:JT.optional()}),vE=qT.extend({method:X(`server/discover`),params:GT.optional()}),yE=XT.extend({supportedVersions:G(V()),capabilities:hE,serverInfo:cE,instructions:V().optional()}),bE=qT.extend({method:X(`ping`),params:GT.optional()}),xE=K({progress:H(),total:Z(H()),message:Z(V())}),SE=K({...JT.shape,...xE.shape,progressToken:BT}),CE=YT.extend({method:X(`notifications/progress`),params:SE}),wE=GT.extend({cursor:VT.optional()}),TE=qT.extend({params:wE.optional()}),EE=XT.extend({nextCursor:VT.optional()}),DE=K({uri:V(),mimeType:Z(V()),_meta:Y(V(),W()).optional()}),OE=DE.extend({text:V()}),kE=V().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:`Invalid Base64 string`}),AE=DE.extend({blob:kE}),jE=Bp([`user`,`assistant`]),ME=K({audience:G(jE).optional(),priority:H().min(0).max(1).optional(),lastModified:Tf({offset:!0}).optional()}),NE=K({...sE.shape,...oE.shape,uri:V(),description:Z(V()),mimeType:Z(V()),size:Z(H()),annotations:ME.optional(),_meta:Z(q({}))}),PE=K({...sE.shape,...oE.shape,uriTemplate:V(),description:Z(V()),mimeType:Z(V()),annotations:ME.optional(),_meta:Z(q({}))}),FE=TE.extend({method:X(`resources/list`)}),IE=EE.extend({resources:G(NE)}),LE=TE.extend({method:X(`resources/templates/list`)}),RE=EE.extend({resourceTemplates:G(PE)}),zE=GT.extend({uri:V()}),BE=zE,VE=qT.extend({method:X(`resources/read`),params:BE}),HE=XT.extend({contents:G(J([OE,AE]))}),UE=YT.extend({method:X(`notifications/resources/list_changed`),params:JT.optional()}),WE=zE,GE=qT.extend({method:X(`resources/subscribe`),params:WE}),KE=zE,qE=qT.extend({method:X(`resources/unsubscribe`),params:KE}),JE=K({toolsListChanged:U().optional(),promptsListChanged:U().optional(),resourcesListChanged:U().optional(),resourceSubscriptions:G(V()).optional()}),YE=GT.extend({notifications:JE}),XE=qT.extend({method:X(`subscriptions/listen`),params:YE}),ZE=JT.extend({notifications:JE}),QE=YT.extend({method:X(`notifications/subscriptions/acknowledged`),params:ZE}),$E=q({[LT]:ZT}),eD=XT.extend({_meta:$E}),tD=JT.extend({uri:V()}),nD=YT.extend({method:X(`notifications/resources/updated`),params:tD}),rD=K({name:V(),description:Z(V()),required:Z(U())}),iD=K({...sE.shape,...oE.shape,description:Z(V()),arguments:Z(G(rD)),_meta:Z(q({}))}),aD=TE.extend({method:X(`prompts/list`)}),oD=EE.extend({prompts:G(iD)}),sD=GT.extend({name:V(),arguments:Y(V(),V()).optional()}),cD=qT.extend({method:X(`prompts/get`),params:sD}),lD=K({type:X(`text`),text:V(),annotations:ME.optional(),_meta:Y(V(),W()).optional()}),uD=K({type:X(`image`),data:kE,mimeType:V(),annotations:ME.optional(),_meta:Y(V(),W()).optional()}),dD=K({type:X(`audio`),data:kE,mimeType:V(),annotations:ME.optional(),_meta:Y(V(),W()).optional()}),fD=K({type:X(`tool_use`),name:V(),id:V(),input:Y(V(),W()),_meta:Y(V(),W()).optional()}),pD=K({type:X(`resource`),resource:J([OE,AE]),annotations:ME.optional(),_meta:Y(V(),W()).optional()}),mD=NE.extend({type:X(`resource_link`)}),hD=J([lD,uD,dD,mD,pD]),gD=K({role:jE,content:hD}),_D=XT.extend({description:V().optional(),messages:G(gD)}),vD=YT.extend({method:X(`notifications/prompts/list_changed`),params:JT.optional()}),yD=K({title:V().optional(),readOnlyHint:U().optional(),destructiveHint:U().optional(),idempotentHint:U().optional(),openWorldHint:U().optional()}),bD=K({taskSupport:Bp([`required`,`optional`,`forbidden`]).optional()}),xD=K({...sE.shape,...oE.shape,description:V().optional(),inputSchema:K({type:X(`object`),properties:Y(V(),RT).optional(),required:G(V()).optional()}).catchall(W()),outputSchema:q({$schema:V().optional()}).optional(),annotations:yD.optional(),execution:bD.optional(),_meta:Y(V(),W()).optional()}),SD=TE.extend({method:X(`tools/list`)}),CD=EE.extend({tools:G(xD)}),wD=XT.extend({content:G(hD).default([]),structuredContent:W().optional(),isError:U().optional()});wD.or(XT.extend({toolResult:W()}));var TD=KT.extend({name:V(),arguments:Y(V(),W()).optional()}),ED=qT.extend({method:X(`tools/call`),params:TD}),DD=YT.extend({method:X(`notifications/tools/list_changed`),params:JT.optional()});K({autoRefresh:U().default(!0),debounceMs:H().int().nonnegative().default(300)});var OD=Bp([`debug`,`info`,`notice`,`warning`,`error`,`critical`,`alert`,`emergency`]),kD=GT.extend({level:OD}),AD=qT.extend({method:X(`logging/setLevel`),params:kD}),jD=JT.extend({level:OD,logger:V().optional(),data:W()}),MD=YT.extend({method:X(`notifications/message`),params:jD}),ND=K({hints:G(K({name:V().optional()})).optional(),costPriority:H().min(0).max(1).optional(),speedPriority:H().min(0).max(1).optional(),intelligencePriority:H().min(0).max(1).optional()}),PD=K({mode:Bp([`auto`,`required`,`none`]).optional()}),FD=K({type:X(`tool_result`),toolUseId:V().describe(`The unique identifier for the corresponding tool call.`),content:G(hD),structuredContent:W().optional(),isError:U().optional(),_meta:Y(V(),W()).optional()}),ID=Fp(`type`,[lD,uD,dD]),LD=Fp(`type`,[lD,uD,dD,fD,FD]),RD=K({role:jE,content:J([LD,G(LD)]),_meta:Y(V(),W()).optional()}),zD=KT.extend({messages:G(RD),modelPreferences:ND.optional(),systemPrompt:V().optional(),includeContext:Bp([`none`,`thisServer`,`allServers`]).optional(),temperature:H().optional(),maxTokens:H().int(),stopSequences:G(V()).optional(),metadata:zT.optional(),tools:G(xD).optional(),toolChoice:PD.optional()}),BD=qT.extend({method:X(`sampling/createMessage`),params:zD}),VD=XT.extend({model:V(),stopReason:Z(Bp([`endTurn`,`stopSequence`,`maxTokens`]).or(V())),role:jE,content:ID}),HD=XT.extend({model:V(),stopReason:Z(Bp([`endTurn`,`stopSequence`,`maxTokens`,`toolUse`]).or(V())),role:jE,content:J([LD,G(LD)])}),UD=K({type:X(`boolean`),title:V().optional(),description:V().optional(),default:U().optional()}),WD=K({type:X(`string`),title:V().optional(),description:V().optional(),minLength:H().optional(),maxLength:H().optional(),format:Bp([`email`,`uri`,`date`,`date-time`]).optional(),default:V().optional()}),GD=K({type:Bp([`number`,`integer`]),title:V().optional(),description:V().optional(),minimum:H().optional(),maximum:H().optional(),default:H().optional()}),KD=K({type:X(`string`),title:V().optional(),description:V().optional(),enum:G(V()),default:V().optional()}),qD=K({type:X(`string`),title:V().optional(),description:V().optional(),oneOf:G(K({const:V(),title:V()})),default:V().optional()}),JD=J([J([K({type:X(`string`),title:V().optional(),description:V().optional(),enum:G(V()),enumNames:G(V()).optional(),default:V().optional()}),J([KD,qD]),J([K({type:X(`array`),title:V().optional(),description:V().optional(),minItems:H().optional(),maxItems:H().optional(),items:K({type:X(`string`),enum:G(V())}),default:G(V()).optional()}),K({type:X(`array`),title:V().optional(),description:V().optional(),minItems:H().optional(),maxItems:H().optional(),items:K({anyOf:G(K({const:V(),title:V()}))}),default:G(V()).optional()})])]),UD,WD,GD]),YD=J([KT.extend({mode:X(`form`).optional(),message:V(),requestedSchema:K({type:X(`object`),properties:Y(V(),JD),required:G(V()).optional()}).catchall(W())}),KT.extend({mode:X(`url`),message:V(),elicitationId:V(),url:V().url()})]),XD=qT.extend({method:X(`elicitation/create`),params:YD}),ZD=JT.extend({elicitationId:V()}),QD=YT.extend({method:X(`notifications/elicitation/complete`),params:ZD}),$D=XT.extend({action:Bp([`accept`,`decline`,`cancel`]),content:pm(e=>e===null?void 0:e,Y(V(),J([V(),H(),U(),G(V())])).optional())}),eO=K({type:X(`ref/resource`),uri:V()}),tO=K({type:X(`ref/prompt`),name:V()}),nO=GT.extend({ref:J([tO,eO]),argument:K({name:V(),value:V()}),context:K({arguments:Y(V(),V()).optional()}).optional()}),rO=qT.extend({method:X(`completion/complete`),params:nO}),iO=XT.extend({completion:q({values:G(V()).max(100),total:Z(H().int()),hasMore:Z(U())})}),aO=K({uri:V().startsWith(`file://`),name:V().optional(),_meta:Y(V(),W()).optional()}),oO=qT.extend({method:X(`roots/list`),params:GT.optional()}),sO=XT.extend({roots:G(aO)}),cO=YT.extend({method:X(`notifications/roots/list_changed`),params:JT.optional()});q({ttl:H().optional(),pollInterval:H().optional()});var lO=Bp([`working`,`input_required`,`completed`,`failed`,`cancelled`]),uO=K({taskId:V(),status:lO,ttl:J([H(),Tp()]),createdAt:V(),lastUpdatedAt:V(),pollInterval:Z(H()),statusMessage:Z(V())});XT.extend({task:uO});var dO=JT.merge(uO);YT.extend({method:X(`notifications/tasks/status`),params:dO}),qT.extend({method:X(`tasks/get`),params:GT.extend({taskId:V()})}),XT.merge(uO),qT.extend({method:X(`tasks/result`),params:GT.extend({taskId:V()})}),XT.loose(),TE.extend({method:X(`tasks/list`)}),EE.extend({tasks:G(uO)}),qT.extend({method:X(`tasks/cancel`),params:GT.extend({taskId:V()})}),XT.merge(uO),J([bE,mE,vE,rO,AD,cD,aD,FE,LE,VE,GE,qE,XE,ED,SD]),J([aE,CE,_E,cO]),J([rE,VD,HD,$D,sO]),J([bE,BD,XD,oO]),J([aE,CE,MD,nD,UE,DD,vD,QE,QD]),J([rE,gE,yE,iO,_D,oD,IE,RE,HE,wD,CD,eD]);var fO=np().superRefine((e,t)=>{if(!URL.canParse(e))return t.addIssue({code:mm.custom,message:`URL must be parseable`,fatal:!0}),Yo}).refine(e=>{let t=new URL(e);return t.protocol!==`javascript:`&&t.protocol!==`data:`&&t.protocol!==`vbscript:`},{message:`URL cannot use javascript:, data:, or vbscript: scheme`});q({resource:V().url(),authorization_servers:G(fO).optional(),jwks_uri:V().url().optional(),scopes_supported:G(V()).optional(),bearer_methods_supported:G(V()).optional(),resource_signing_alg_values_supported:G(V()).optional(),resource_name:V().optional(),resource_documentation:V().optional(),resource_policy_uri:V().url().optional(),resource_tos_uri:V().url().optional(),tls_client_certificate_bound_access_tokens:U().optional(),authorization_details_types_supported:G(V()).optional(),dpop_signing_alg_values_supported:G(V()).optional(),dpop_bound_access_tokens_required:U().optional()});var pO=q({issuer:V(),authorization_endpoint:fO,token_endpoint:fO,registration_endpoint:fO.optional(),scopes_supported:G(V()).optional(),response_types_supported:G(V()),response_modes_supported:G(V()).optional(),grant_types_supported:G(V()).optional(),token_endpoint_auth_methods_supported:G(V()).optional(),token_endpoint_auth_signing_alg_values_supported:G(V()).optional(),service_documentation:fO.optional(),revocation_endpoint:fO.optional(),revocation_endpoint_auth_methods_supported:G(V()).optional(),revocation_endpoint_auth_signing_alg_values_supported:G(V()).optional(),introspection_endpoint:V().optional(),introspection_endpoint_auth_methods_supported:G(V()).optional(),introspection_endpoint_auth_signing_alg_values_supported:G(V()).optional(),code_challenge_methods_supported:G(V()).optional(),client_id_metadata_document_supported:U().optional(),authorization_response_iss_parameter_supported:U().optional().catch(void 0)});K({...q({issuer:V(),authorization_endpoint:fO,token_endpoint:fO,userinfo_endpoint:fO.optional(),jwks_uri:fO,registration_endpoint:fO.optional(),scopes_supported:G(V()).optional(),response_types_supported:G(V()),response_modes_supported:G(V()).optional(),grant_types_supported:G(V()).optional(),acr_values_supported:G(V()).optional(),subject_types_supported:G(V()),id_token_signing_alg_values_supported:G(V()),id_token_encryption_alg_values_supported:G(V()).optional(),id_token_encryption_enc_values_supported:G(V()).optional(),userinfo_signing_alg_values_supported:G(V()).optional(),userinfo_encryption_alg_values_supported:G(V()).optional(),userinfo_encryption_enc_values_supported:G(V()).optional(),request_object_signing_alg_values_supported:G(V()).optional(),request_object_encryption_alg_values_supported:G(V()).optional(),request_object_encryption_enc_values_supported:G(V()).optional(),token_endpoint_auth_methods_supported:G(V()).optional(),token_endpoint_auth_signing_alg_values_supported:G(V()).optional(),display_values_supported:G(V()).optional(),claim_types_supported:G(V()).optional(),claims_supported:G(V()).optional(),service_documentation:V().optional(),claims_locales_supported:G(V()).optional(),ui_locales_supported:G(V()).optional(),claims_parameter_supported:U().optional(),request_parameter_supported:U().optional(),request_uri_parameter_supported:U().optional(),require_request_uri_registration:U().optional(),op_policy_uri:fO.optional(),op_tos_uri:fO.optional(),client_id_metadata_document_supported:U().optional(),authorization_response_iss_parameter_supported:U().optional().catch(void 0)}).shape,...pO.pick({code_challenge_methods_supported:!0}).shape}),K({access_token:V(),id_token:V().optional(),token_type:V(),expires_in:gm().optional(),scope:V().optional(),refresh_token:V().optional()}).strip(),K({issued_token_type:X(`urn:ietf:params:oauth:token-type:id-jag`),access_token:V(),token_type:V().optional(),expires_in:H().optional(),scope:V().optional()}).strip(),K({error:V(),error_description:V().optional(),error_uri:V().optional()});var mO=fO.optional().or(X(``).transform(()=>void 0)),hO=K({redirect_uris:G(fO),token_endpoint_auth_method:V().optional(),grant_types:G(V()).optional(),response_types:G(V()).optional(),application_type:V().optional(),client_name:V().optional(),client_uri:fO.optional(),logo_uri:mO,scope:V().optional(),contacts:G(V()).optional(),tos_uri:mO,policy_uri:V().optional(),jwks_uri:fO.optional(),jwks:Dp().optional(),software_id:V().optional(),software_version:V().optional(),software_statement:V().optional()}).strip(),gO=K({client_id:V(),client_secret:V().optional(),client_id_issued_at:H().optional(),client_secret_expires_at:H().optional()}).strip();hO.merge(gO),K({error:V(),error_description:V().optional()}).strip(),K({token:V(),token_type_hint:V().optional()}).strip(),(t=>typeof e<`u`?e:typeof Proxy<`u`?new Proxy(t,{get:(t,n)=>(typeof e<`u`?e:t)[n]}):t)(function(t){if(typeof e<`u`)return e.apply(this,arguments);throw Error(`Dynamic require of "`+t+`" is not supported`)});var _O=class{_eventSlots=new Map;setHandler(e,t){let n=this._ensureEventSlot(e);n.onHandler&&t&&console.warn(`[MCP Apps] on${String(e)} handler replaced. Use addEventListener("${String(e)}", …) to add multiple listeners without replacing.`),n.onHandler=t}getHandler(e){return this._eventSlots.get(e)?.onHandler}addEventListener(e,t){this._ensureEventSlot(e).listeners.push(t)}removeEventListener(e,t){let n=this._eventSlots.get(e);if(!n)return;let r=n.listeners.indexOf(t);r!==-1&&n.listeners.splice(r,1)}dispatch(e,t){let n=this._eventSlots.get(e);if(n){n.onHandler?.(t);for(let e of[...n.listeners])e(t)}}_ensureEventSlot(e){let t=this._eventSlots.get(e);return t||(t={listeners:[]},this._eventSlots.set(e,t)),t}},vO=`2026-01-26`,yO=J([X(`light`),X(`dark`)]).describe(`Color theme preference for the host environment.`),bO=J([X(`inline`),X(`fullscreen`),X(`pip`)]).describe(`Display mode for UI presentation.`),xO=Y(J([X(`--color-background-primary`),X(`--color-background-secondary`),X(`--color-background-tertiary`),X(`--color-background-inverse`),X(`--color-background-ghost`),X(`--color-background-info`),X(`--color-background-danger`),X(`--color-background-success`),X(`--color-background-warning`),X(`--color-background-disabled`),X(`--color-text-primary`),X(`--color-text-secondary`),X(`--color-text-tertiary`),X(`--color-text-inverse`),X(`--color-text-ghost`),X(`--color-text-info`),X(`--color-text-danger`),X(`--color-text-success`),X(`--color-text-warning`),X(`--color-text-disabled`),X(`--color-border-primary`),X(`--color-border-secondary`),X(`--color-border-tertiary`),X(`--color-border-inverse`),X(`--color-border-ghost`),X(`--color-border-info`),X(`--color-border-danger`),X(`--color-border-success`),X(`--color-border-warning`),X(`--color-border-disabled`),X(`--color-ring-primary`),X(`--color-ring-secondary`),X(`--color-ring-inverse`),X(`--color-ring-info`),X(`--color-ring-danger`),X(`--color-ring-success`),X(`--color-ring-warning`),X(`--font-sans`),X(`--font-mono`),X(`--font-weight-normal`),X(`--font-weight-medium`),X(`--font-weight-semibold`),X(`--font-weight-bold`),X(`--font-text-xs-size`),X(`--font-text-sm-size`),X(`--font-text-md-size`),X(`--font-text-lg-size`),X(`--font-heading-xs-size`),X(`--font-heading-sm-size`),X(`--font-heading-md-size`),X(`--font-heading-lg-size`),X(`--font-heading-xl-size`),X(`--font-heading-2xl-size`),X(`--font-heading-3xl-size`),X(`--font-text-xs-line-height`),X(`--font-text-sm-line-height`),X(`--font-text-md-line-height`),X(`--font-text-lg-line-height`),X(`--font-heading-xs-line-height`),X(`--font-heading-sm-line-height`),X(`--font-heading-md-line-height`),X(`--font-heading-lg-line-height`),X(`--font-heading-xl-line-height`),X(`--font-heading-2xl-line-height`),X(`--font-heading-3xl-line-height`),X(`--border-radius-xs`),X(`--border-radius-sm`),X(`--border-radius-md`),X(`--border-radius-lg`),X(`--border-radius-xl`),X(`--border-radius-full`),X(`--border-width-regular`),X(`--shadow-hairline`),X(`--shadow-sm`),X(`--shadow-md`),X(`--shadow-lg`)]).describe(`CSS variable keys available to MCP apps for theming.`).describe(`Style variables for theming MCP apps.
|
|
157
|
+
`&&r++}}return[t,n]}var aS=class extends TransformStream{constructor({onError:e,onRetry:t,onComment:n}={}){let r;super({start(i){r=rS({onEvent:e=>{i.enqueue(e)},onError(t){e===`terminate`?i.error(t):typeof e==`function`&&e(t)},onRetry:t,onComment:n})},transform(e){r.feed(e)}})}},oS=`modulepreload`,sS=function(e){return`/inspector/`+e},cS={},lS=function(e,t,n){let r=Promise.resolve();if(t&&t.length>0){let e=document.getElementsByTagName(`link`),i=document.querySelector(`meta[property=csp-nonce]`),a=i?.nonce||i?.getAttribute(`nonce`);function o(e){return Promise.all(e.map(e=>Promise.resolve(e).then(e=>({status:`fulfilled`,value:e}),e=>({status:`rejected`,reason:e}))))}r=o(t.map(t=>{if(t=sS(t,n),t in cS)return;cS[t]=!0;let r=t.endsWith(`.css`),i=r?`[rel="stylesheet"]`:``;if(n)for(let n=e.length-1;n>=0;n--){let i=e[n];if(i.href===t&&(!r||i.rel===`stylesheet`))return}else if(document.querySelector(`link[href="${t}"]${i}`))return;let o=document.createElement(`link`);if(o.rel=r?`stylesheet`:oS,r||(o.as=`script`),o.crossOrigin=``,o.href=t,a&&o.setAttribute(`nonce`,a),document.head.appendChild(o),r)return new Promise((e,n)=>{o.addEventListener(`load`,e),o.addEventListener(`error`,()=>n(Error(`Unable to preload CSS for ${t}`)))})}))}function i(e){let t=new Event(`vite:preloadError`,{cancelable:!0});if(t.payload=e,window.dispatchEvent(t),!t.defaultPrevented)throw e}return r.then(t=>{for(let e of t||[])e.status===`rejected`&&i(e.reason);return e().catch(i)})},uS=class extends Error{static{Object.defineProperty(this,"mcpBrand",{value:`mcp.OAuthClientFlowError`})}static[Symbol.hasInstance](e){return K_(this,e)}static isInstance(e){if(typeof this!=`function`)throw TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`");return K_(this,e)}constructor(e){super(e),this.name=new.target.name,G_(this,new.target)}},dS=class extends uS{static{Object.defineProperty(this,"mcpBrand",{value:`mcp.IssuerMismatchError`})}kind;expected;received;constructor(e,t,n){super(`Issuer mismatch in ${e===`metadata`?`authorization server metadata (RFC 8414 §3.3)`:`authorization response (RFC 9207)`}: expected ${JSON.stringify(t)}, received ${JSON.stringify(n)}`),this.kind=e,this.expected=t,this.received=n}},fS=class extends uS{static{Object.defineProperty(this,"mcpBrand",{value:`mcp.RegistrationRejectedError`})}status;body;submittedMetadata;constructor(e){super(`Dynamic Client Registration rejected (HTTP ${e.status}): ${e.body}`),this.status=e.status,this.body=e.body,this.submittedMetadata=e.submittedMetadata}},pS=class extends uS{static{Object.defineProperty(this,"mcpBrand",{value:`mcp.InsecureTokenEndpointError`})}tokenEndpoint;constructor(e){super(`Refusing to send credentials to non-https token endpoint '${e}'. OAuth token requests MUST use TLS (localhost / 127.0.0.1 / ::1 are exempt).`),this.tokenEndpoint=e}},mS=class extends uS{static{Object.defineProperty(this,"mcpBrand",{value:`mcp.AuthorizationServerMismatchError`})}constructor(e,t){super(`Authorization server changed between redirect and callback (redirected to ${JSON.stringify(e)}, callback resolved ${JSON.stringify(t)}); refusing to send authorization_code/code_verifier to a different token endpoint`),this.recordedIssuer=e,this.currentIssuer=t}},hS=class extends uS{static{Object.defineProperty(this,"mcpBrand",{value:`mcp.InsufficientScopeError`})}requiredScope;resourceMetadataUrl;errorDescription;constructor(e){super(`Insufficient scope${e.requiredScope?`: required "${e.requiredScope}"`:``}`),this.requiredScope=e.requiredScope,this.resourceMetadataUrl=e.resourceMetadataUrl,this.errorDescription=e.errorDescription}};function gS(e,t,n){if(e!==void 0)return e.issuer===void 0?(n?.canPersistStamp!==!1&&console.warn(`[mcp-sdk] SEP-2352: stored OAuth credential has no 'issuer' stamp (pre-upgrade storage or provider not round-tripping the value). SEP-2352 isolation is inactive for this read; ensure your provider round-trips the issuer field.`),e):_S(e.issuer,t)?e:void 0}function _S(e,t){return e===t||e.endsWith(`/`)&&e.slice(0,-1)===t||t.endsWith(`/`)&&t.slice(0,-1)===e}function vS(e){if(e==null)return!1;let t=e;return typeof t.tokens==`function`&&typeof t.clientInformation==`function`}async function yS(e,t,n){let{resourceMetadataUrl:r,scope:i}=KS(t.response);if(await BS(e,{serverUrl:t.serverUrl,resourceMetadataUrl:r,scope:i,fetchFn:t.fetchFn,...n})!==`AUTHORIZED`)throw new xS}function bS(e,t){return{token:async()=>(await e.tokens())?.access_token,onUnauthorized:async n=>yS(e,n,t)}}var xS=class extends Error{static{Object.defineProperty(this,"mcpBrand",{value:`mcp.UnauthorizedError`})}static[Symbol.hasInstance](e){return K_(this,e)}static isInstance(e){if(typeof this!=`function`)throw TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`");return K_(this,e)}constructor(e){super(e??`Unauthorized`),this.name=`UnauthorizedError`,G_(this,new.target)}};function SS(e){return e?.authorization_response_iss_parameter_supported===!0}function CS({iss:e,expectedIssuer:t,issParameterSupported:n}){if(t!==void 0){if(e===void 0){if(n)throw new dS(`authorization_response`,t,void 0);return}if(e!==t)throw new dS(`authorization_response`,t,e)}}function wS(...e){let t=new Set;for(let n of e)if(n)for(let e of n.split(/\s+/))e&&t.add(e);return t.size>0?[...t].join(` `):void 0}function TS(e,t){if(!e)return!1;let n=new Set((t??``).split(/\s+/).filter(Boolean));for(let t of e.split(/\s+/))if(t&&!n.has(t))return!0;return!1}async function ES(e,t,n,r,i){if(typeof e==`string`)return{authorizationCode:e,iss:t};let a=e.get(`iss`)??void 0,o=e.get(`code`);if(o)return{authorizationCode:o,iss:a};let s=(await n.discoveryState?.())?.authorizationServerMetadata;if(!s)try{s=(await nC(r,i)).authorizationServerMetadata}catch{s=void 0}if(!s)throw new xS(`Authorization callback failed and the issuer could not be verified`);CS({iss:a,expectedIssuer:s.issuer,issParameterSupported:SS(s)});let c=e.get(`error`);throw c?new J_(c,e.get(`error_description`)??c,e.get(`error_uri`)??void 0):new xS("Authorization callback contained neither `code` nor `error`")}function DS(e){return[`client_secret_basic`,`client_secret_post`,`none`].includes(e)}var OS=`code`,kS=`S256`;function AS(e,t){let n=e.client_secret!==void 0;return`token_endpoint_auth_method`in e&&e.token_endpoint_auth_method&&DS(e.token_endpoint_auth_method)&&(t.length===0||t.includes(e.token_endpoint_auth_method))?e.token_endpoint_auth_method:t.length===0?n?`client_secret_basic`:`none`:n&&t.includes(`client_secret_basic`)?`client_secret_basic`:n&&t.includes(`client_secret_post`)?`client_secret_post`:t.includes(`none`)?`none`:n?`client_secret_post`:`none`}function jS(e,t,n,r){let{client_id:i,client_secret:a}=t;switch(e){case`client_secret_basic`:MS(i,a,n);return;case`client_secret_post`:NS(i,a,r);return;case`none`:PS(i,r);return;default:throw Error(`Unsupported client authentication method: ${e}`)}}function MS(e,t,n){if(!t)throw Error(`client_secret_basic authentication requires a client_secret`);let r=btoa(`${e}:${t}`);n.set(`Authorization`,`Basic ${r}`)}function NS(e,t,n){n.set(`client_id`,e),t&&n.set(`client_secret`,t)}function PS(e,t){t.set(`client_id`,e)}function FS(e){return e===`localhost`||e===`127.0.0.1`||e===`[::1]`||e===`::1`}function IS(e){let t=new URL(String(e));if(t.protocol!==`https:`&&!FS(t.hostname))throw new pS(t.href);return t}function LS(e){for(let t of e??[]){let e;try{e=new URL(t)}catch{continue}if(e.protocol!==`http:`&&e.protocol!==`https:`||FS(e.hostname))return`native`}return`web`}function RS(e){let t=e.clientMetadata;return{...t,grant_types:t.grant_types??(e.redirectUrl===void 0?void 0:[`authorization_code`,`refresh_token`]),application_type:t.application_type??LS(t.redirect_uris)}}async function zS(e){let t=e instanceof Response?e.status:void 0,n=e instanceof Response?await e.text():e;try{let e=L_.parse(JSON.parse(n));return J_.fromResponse(e)}catch(e){let r=`${t?`HTTP ${t}: `:``}Invalid OAuth error response: ${e}. Raw body: ${n}`;return new J_(q_.ServerError,r)}}async function BS(e,t){try{return await HS(e,t)}catch(n){if(n instanceof J_){if(n.code===q_.InvalidClient||n.code===q_.UnauthorizedClient)return await e.invalidateCredentials?.(`client`),await e.invalidateCredentials?.(`tokens`),await HS(e,t);if(n.code===q_.InvalidGrant)return await e.invalidateCredentials?.(`tokens`),await HS(e,t)}throw n}}function VS(e){let{requestedScope:t,resourceMetadata:n,authServerMetadata:r,clientMetadata:i}=e,a=t||n?.scopes_supported?.join(` `)||i.scope;return a&&r?.scopes_supported?.includes(`offline_access`)&&!a.split(` `).includes(`offline_access`)&&i.grant_types?.includes(`refresh_token`)&&(a=`${a} offline_access`),a}async function HS(e,{serverUrl:t,authorizationCode:n,iss:r,scope:i,resourceMetadataUrl:a,fetchFn:o,skipIssuerMetadataValidation:s,forceReauthorization:c}){let l=RS(e),u=await e.discoveryState?.(),d,f,p,m,h=a;if(!h&&u?.resourceMetadataUrl&&(h=new URL(u.resourceMetadataUrl)),u?.authorizationServerUrl){if(f=u.authorizationServerUrl,d=u.resourceMetadata,p=u.authorizationServerMetadata??await tC(f,{fetchFn:o,skipIssuerValidation:s}),!d)try{d=await JS(t,{resourceMetadataUrl:h},o)}catch(e){if(e instanceof TypeError)throw e}(p!==u.authorizationServerMetadata||d!==u.resourceMetadata)&&await e.saveDiscoveryState?.({authorizationServerUrl:String(f),resourceMetadataUrl:h?.toString(),resourceMetadata:d,authorizationServerMetadata:p})}else{let e=await nC(t,{resourceMetadataUrl:h,fetchFn:o,skipIssuerMetadataValidation:s});f=e.authorizationServerUrl,p=e.authorizationServerMetadata,d=e.resourceMetadata,m={authorizationServerUrl:String(f),resourceMetadataUrl:h?.toString(),resourceMetadata:d,authorizationServerMetadata:p}}let g=p?.issuer??String(f),_={issuer:g};if(await e.saveAuthorizationServerUrl?.(g),n!==void 0){let t=u?.authorizationServerMetadata?.issuer??u?.authorizationServerUrl;if(t===void 0){if(e.saveDiscoveryState!==void 0)throw new mS(`discoveryState was not available on the callback leg; ensure your provider persists discoveryState alongside codeVerifier`,g);console.warn(`[mcp-sdk] OAuthClientProvider does not implement saveDiscoveryState()/discoveryState(); the SEP-2352 callback-leg authorization-server binding cannot be checked. Implement discoveryState (persist alongside codeVerifier) — see docs/migration/upgrade-to-v2.md §SEP-2352.`)}else if(!_S(t,g))throw new mS(t,g)}m&&await e.saveDiscoveryState?.(m);let v=await GS(t,e,d);v&&await e.saveResourceUrl?.(String(v));let y=VS({requestedScope:i,resourceMetadata:d,authServerMetadata:p,clientMetadata:e.clientMetadata}),b=await Promise.resolve(e.clientInformation(_)),x=gS(b,g,{canPersistStamp:e.saveClientInformation!==void 0});if(x===void 0&&b?.issuer&&e.saveClientInformation===void 0)throw new mS(b.issuer,g);if(x&&x.issuer===void 0&&(x={...x,issuer:g},await e.saveClientInformation?.(x,_)),!x){if(n!==void 0)throw Error(`Existing OAuth client information is required when exchanging an authorization code`);let t=p?.client_id_metadata_document_supported===!0,r=e.clientMetadataUrl;if(r&&!WS(r))throw new J_(q_.InvalidClientMetadata,`clientMetadataUrl must be a valid HTTPS URL with a non-root pathname, got: ${r}`);if(t&&r)x={client_id:r,issuer:g},await e.saveClientInformation?.(x,_);else{if(!e.saveClientInformation)throw Error(`OAuth client information must be saveable for dynamic registration`);x={...await cC(f,{metadata:p,clientMetadata:l,scope:y,fetchFn:o}),issuer:g},await e.saveClientInformation(x,_)}}let S=!e.redirectUrl;if(n!==void 0||S){n!==void 0&&CS({iss:r,expectedIssuer:p?.issuer,issParameterSupported:SS(p)});let t=await sC(e,f,{metadata:p,resource:v,authorizationCode:n,iss:r,scope:y,fetchFn:o});return await e.saveTokens({...t,issuer:g},_),`AUTHORIZED`}let C=gS(await e.tokens(_),g);if(C&&C.issuer===void 0&&(C={...C,issuer:g},await e.saveTokens(C,_)),C?.refresh_token&&!c)try{let t=await oC(f,{metadata:p,clientInformation:x,refreshToken:C.refresh_token,resource:v,addClientAuthentication:e.addClientAuthentication,fetchFn:o});return await e.saveTokens({...t,issuer:g},_),`AUTHORIZED`}catch(e){if(e instanceof pS||!(!(e instanceof J_)||e.code===q_.ServerError))throw e}let w=e.state?await e.state():void 0,{authorizationUrl:T,codeVerifier:E}=await rC(f,{metadata:p,clientInformation:x,state:w,redirectUrl:e.redirectUrl,scope:y,resource:v});return await e.saveCodeVerifier(E),await e.redirectToAuthorization(T),`REDIRECT`}function US(e){if(e&&!WS(e))throw new J_(q_.InvalidClientMetadata,`clientMetadataUrl must be a valid HTTPS URL with a non-root pathname, got: ${e}`)}function WS(e){if(!e)return!1;try{let t=new URL(e);return t.protocol===`https:`&&t.pathname!==`/`}catch{return!1}}async function GS(e,t,n){let r=Q_(e);if(t.validateResourceURL)return await t.validateResourceURL(r,n?.resource);if(n){if(!$_({requestedResource:r,configuredResource:n.resource}))throw Error(`Protected resource ${n.resource} does not match expected ${r} (or origin)`);return new URL(n.resource)}}function KS(e){let t=e.headers.get(`WWW-Authenticate`);if(!t)return{};let[n,r]=t.split(` `);if(n?.toLowerCase()!==`bearer`||!r)return{};let i=qS(e,`resource_metadata`)||void 0,a;if(i)try{a=new URL(i)}catch{}let o=qS(e,`scope`)||void 0,s=qS(e,`error`)||void 0,c=qS(e,`error_description`)||void 0;return{resourceMetadataUrl:a,scope:o,error:s,errorDescription:c}}function qS(e,t){let n=e.headers.get(`WWW-Authenticate`);if(!n)return null;let r=new RegExp(String.raw`${t}=(?:"([^"]+)"|([^\s,]+))`),i=n.match(r);if(i){let e=i[1]||i[2];if(e)return e}return null}async function JS(e,t,n=fetch){let r=await $S(e,`oauth-protected-resource`,n,{protocolVersion:t?.protocolVersion,metadataUrl:t?.resourceMetadataUrl});if(!r||r.status===404)throw await r?.text?.().catch(()=>{}),Error(`Resource server does not implement OAuth 2.0 Protected Resource Metadata.`);if(!r.ok)throw await r.text?.().catch(()=>{}),Error(`HTTP ${r.status} trying to load well-known OAuth protected resource metadata.`);return j_.parse(await r.json())}async function YS(e,t,n=fetch){try{return await n(e,{headers:t})}catch(r){if(!(r instanceof TypeError))throw r;if(t)try{return await n(e,{})}catch(e){if(!(e instanceof TypeError))throw e;return}return}}function XS(e,t=``,n={}){return t.endsWith(`/`)&&(t=t.slice(0,-1)),n.prependPathname?`${t}/.well-known/${e}`:`/.well-known/${e}${t}`}async function ZS(e,t,n=fetch){return await YS(e,{"MCP-Protocol-Version":t},n)}function QS(e,t){return e?t===`/`?!1:e.status>=400&&e.status<500||e.status===502:!0}async function $S(e,t,n,r){let i=new URL(e),a=r?.protocolVersion??`2025-11-25`,o;if(r?.metadataUrl)o=new URL(r.metadataUrl);else{let e=XS(t,i.pathname);o=new URL(e,r?.metadataServerUrl??i),o.search=i.search}let s=await ZS(o,a,n);return!r?.metadataUrl&&QS(s,i.pathname)&&(s=await ZS(new URL(`/.well-known/${t}`,i),a,n)),s}function eC(e){let t=typeof e==`string`?new URL(e):e,n=t.pathname!==`/`,r=[];if(!n)return r.push({url:new URL(`/.well-known/oauth-authorization-server`,t.origin),type:`oauth`},{url:new URL(`/.well-known/openid-configuration`,t.origin),type:`oidc`}),r;let i=t.pathname;return i.endsWith(`/`)&&(i=i.slice(0,-1)),r.push({url:new URL(`/.well-known/oauth-authorization-server${i}`,t.origin),type:`oauth`},{url:new URL(`/.well-known/openid-configuration${i}`,t.origin),type:`oidc`},{url:new URL(`${i}/.well-known/openid-configuration`,t.origin),type:`oidc`}),r}async function tC(e,{fetchFn:t=fetch,protocolVersion:n=_m,skipIssuerValidation:r=!1}={}){let i={"MCP-Protocol-Version":n,Accept:`application/json`},a=eC(e);for(let{url:n,type:o}of a){let a=await YS(n,i,t);if(!a)continue;if(!a.ok){if(await a.text?.().catch(()=>{}),a.status>=400&&a.status<500||a.status===502)continue;throw Error(`HTTP ${a.status} trying to load ${o===`oauth`?`OAuth`:`OpenID provider`} metadata from ${n}`)}let s=o===`oauth`?M_.parse(await a.json()):P_.parse(await a.json());if(!r){let t=typeof e==`string`?e:e.href;if(!(s.issuer===t||t.endsWith(`/`)&&s.issuer===t.slice(0,-1)))throw new dS(`metadata`,t,s.issuer)}return s}}async function nC(e,t){let n,r;try{n=await JS(e,{resourceMetadataUrl:t?.resourceMetadataUrl},t?.fetchFn),n.authorization_servers&&n.authorization_servers.length>0&&(r=n.authorization_servers[0])}catch(e){if(e instanceof TypeError)throw e}r||=String(new URL(`/`,e));let i=await tC(r,{fetchFn:t?.fetchFn,skipIssuerValidation:t?.skipIssuerMetadataValidation});return{authorizationServerUrl:r,authorizationServerMetadata:i,resourceMetadata:n}}async function rC(e,{metadata:t,clientInformation:n,redirectUrl:r,scope:i,state:a,resource:o}){let s;if(t){if(s=new URL(t.authorization_endpoint),!t.response_types_supported.includes(OS))throw Error(`Incompatible auth server: does not support response type ${OS}`);if(t.code_challenge_methods_supported&&!t.code_challenge_methods_supported.includes(kS))throw Error(`Incompatible auth server: does not support code challenge method ${kS}`)}else s=new URL(`/authorize`,e);let c=await eS(),l=c.code_verifier,u=c.code_challenge;return s.searchParams.set(`response_type`,OS),s.searchParams.set(`client_id`,n.client_id),s.searchParams.set(`code_challenge`,u),s.searchParams.set(`code_challenge_method`,kS),s.searchParams.set(`redirect_uri`,String(r)),a&&s.searchParams.set(`state`,a),i&&s.searchParams.set(`scope`,i),i?.split(` `).includes(`offline_access`)&&s.searchParams.append(`prompt`,`consent`),o&&s.searchParams.set(`resource`,o.href),{authorizationUrl:s,codeVerifier:l}}function iC(e,t,n){return new URLSearchParams({grant_type:`authorization_code`,code:e,code_verifier:t,redirect_uri:String(n)})}async function aC(e,{metadata:t,tokenRequestParams:n,clientInformation:r,addClientAuthentication:i,resource:a,fetchFn:o}){let s=IS(t?.token_endpoint??new URL(`/token`,e)),c=new Headers({"Content-Type":`application/x-www-form-urlencoded`,Accept:`application/json`});a&&n.set(`resource`,a.href),i?await i(c,n,s,t):r&&jS(AS(r,t?.token_endpoint_auth_methods_supported??[]),r,c,n);let l=await(o??fetch)(s,{method:`POST`,headers:c,body:n});if(!l.ok)throw await zS(l);let u=await l.json();try{return F_.parse(u)}catch(e){throw typeof u==`object`&&u&&`error`in u?await zS(JSON.stringify(u)):e}}async function oC(e,{metadata:t,clientInformation:n,refreshToken:r,resource:i,addClientAuthentication:a,fetchFn:o}){return{refresh_token:r,...await aC(e,{metadata:t,tokenRequestParams:new URLSearchParams({grant_type:`refresh_token`,refresh_token:r}),clientInformation:n,addClientAuthentication:a,resource:i,fetchFn:o})}}async function sC(e,t,{metadata:n,resource:r,authorizationCode:i,iss:a,scope:o,fetchFn:s}={}){i!==void 0&&CS({iss:a,expectedIssuer:n?.issuer,issParameterSupported:SS(n)});let c=o??e.clientMetadata.scope,l;if(e.prepareTokenRequest&&(l=await e.prepareTokenRequest(c)),!l){if(!i)throw Error(`Either provider.prepareTokenRequest() or authorizationCode is required`);if(!e.redirectUrl)throw Error(`redirectUrl is required for authorization_code flow`);l=iC(i,await e.codeVerifier(),e.redirectUrl)}let u=await e.clientInformation({issuer:n?.issuer??String(t)});return aC(t,{metadata:n,tokenRequestParams:l,clientInformation:u??void 0,addClientAuthentication:e.addClientAuthentication,resource:r,fetchFn:s})}async function cC(e,{metadata:t,clientMetadata:n,scope:r,fetchFn:i}){let a;if(t){if(!t.registration_endpoint)throw Error(`Incompatible auth server: does not support dynamic client registration`);a=new URL(t.registration_endpoint)}else a=new URL(`/register`,e);let o={...n,...r===void 0?{}:{scope:r}},s=await(i??fetch)(a,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(o)});if(!s.ok)throw new fS({status:s.status,body:await s.text(),submittedMetadata:o});return V_.parse(await s.json())}var lC=new Set([`tools/list`,`prompts/list`,`resources/list`,`resources/templates/list`,`server/discover`]),uC=class{_entries=new Map;_maxEntries;_stamp=0;_cappedSize=0;constructor(e){this._maxEntries=e?.maxEntries??512}get size(){return this._entries.size}get(e){return this._entries.get(dC(e))}set(e,t){let n=dC(e),r=lC.has(e.method),i=!this._entries.has(n);if(!r&&i&&this._maxEntries>0&&this._cappedSize>=this._maxEntries){for(let e of this._entries.keys())if(!lC.has(e.slice(0,e.indexOf(`\0`)))){this._entries.delete(e),this._cappedSize--;break}}let a=++this._stamp;return this._entries.set(n,{...t,stamp:a}),i&&!r&&this._cappedSize++,a}delete(e){this._entries.delete(dC(e))&&!lC.has(e.method)&&this._cappedSize--}evict(e){let t=`${e}\0`,n=lC.has(e);for(let e of this._entries.keys())e.startsWith(t)&&(this._entries.delete(e),n||this._cappedSize--)}clear(){this._entries.clear(),this._cappedSize=0}};function dC(e){return`${e.method}\0${JSON.stringify([e.partition??``,e.params??``])}`}function fC(e,t){return t===void 0?e:`${e}\0${t}`}var pC=864e5,mC=class{_evictionGeneration=new Map;_toolIndex;_toolOutputValidatorIndex;_serverIdentity=``;constructor(e,t,n=()=>{},r=``,i=Date.now){this._store=e,this._isUserSupplied=t,this._reportError=n,this._cachePartition=r,this._now=i}now(){return this._now()}setServerIdentity(e){this._serverIdentity=e}_partitionFor(e){return JSON.stringify([this._serverIdentity,e===`public`?``:this._cachePartition])}async _probe(e,t){let n={method:e,params:t??``},r=this._partitionFor(`private`),i=await this._store.get({...n,partition:r});if(i!==void 0)return i;let a=this._partitionFor(`public`);if(a===r)return;let o=await this._store.get({...n,partition:a});return o?.scope===`public`?o:void 0}async evict(e){this._evictionGeneration.set(e,(this._evictionGeneration.get(e)??0)+1),await this._deleteBoth(e,``)}async _deleteBoth(e,t){let n=this._partitionFor(`private`),r=this._partitionFor(`public`);try{await this._store.delete({method:e,params:t,partition:n})}catch(e){this._reportError(e)}if(r!==n)try{await this._store.delete({method:e,params:t,partition:r})}catch(e){this._reportError(e)}}async evictKey(e,t){let n=fC(e,t),r=this._evictionGeneration.get(n);r!==void 0&&this._evictionGeneration.set(n,r+1),await this._deleteBoth(e,t)}captureGeneration(e,t){let n=fC(e,t),r=this._evictionGeneration.get(n)??0;return this._evictionGeneration.set(n,r),r}async write(e,t,n,r){if((this._evictionGeneration.get(fC(e,r?.params))??0)!==n)return;let i=r?.params??``,a=this._partitionFor(`private`),o=this._partitionFor(`public`),s=(r?.scope??`private`)===`public`?o:a;try{await this._store.set({method:e,params:i,partition:s},{value:hC(t),expiresAt:r?.expiresAt,scope:r?.scope})}catch(e){this._reportError(e)}if(o!==a)try{await this._store.delete({method:e,params:i,partition:s===a?o:a})}catch(e){this._reportError(e)}}async read(e,t){let n=await this._probe(e,t);if(!(n?.expiresAt===void 0||!(n.expiresAt>this.now())))try{let e=JSON.parse(n.value);if(typeof e!=`object`||!e||Array.isArray(e))throw TypeError(`cached document is not an object`);return{value:e}}catch(n){this._reportError(n),await this._deleteBoth(e,t??``);return}}resetForReconnect(){this._isUserSupplied||this._store.clear(),this._evictionGeneration.clear(),this._toolIndex=void 0,this._toolOutputValidatorIndex=void 0,this._serverIdentity=``}async toolDefinition(e){let t=await this._probe(`tools/list`);if(t===void 0){this._toolIndex=void 0;return}if(this._toolIndex?.stamp!==t.stamp){let e=this._decodeListTools(t),n=new Map;if(e!==void 0)for(let t of e.tools)n.set(t.name,t);this._toolIndex={stamp:t.stamp,byName:n}}return this._toolIndex.byName.get(e)}async outputValidator(e,t){let n=await this._probe(`tools/list`);if(n===void 0){this._toolOutputValidatorIndex=void 0;return}if(this._toolOutputValidatorIndex?.stamp!==n.stamp){let e=this._decodeListTools(n)??{tools:[]},r=new Map;for(let n of e.tools){let e=t(n);e!==void 0&&r.set(n.name,e)}this._toolOutputValidatorIndex={stamp:n.stamp,byName:r}}return this._toolOutputValidatorIndex.byName.get(e)}_decodeListTools(e){try{let t=JSON.parse(e.value);if(!Array.isArray(t?.tools)||!t.tools.every(e=>typeof e==`object`&&!!e))throw TypeError(`cached tools/list document has a malformed tools array`);return t}catch(e){this._reportError(e);return}}};function hC(e){let t;try{t=JSON.stringify(e)}catch(e){throw TypeError(`cache value is not JSON-serializable: ${e instanceof Error?e.message:String(e)}`)}if(typeof t!=`string`)throw TypeError(`cache value is not JSON-serializable: it has no JSON representation`);return t}var gC=-32022,_C=new Set([-32001,-32020,-32021]);function vC(e,t){switch(e.kind){case`result`:return yC(e.result,t);case`rpc-error`:return bC(e,t);case`http-error`:return xC(e,t);case`network-error`:return SC(e.error,t);case`auth-required`:return{kind:`error`,error:e.error};case`timeout`:return t.transportKind===`stdio`?{kind:`legacy`}:{kind:`error`,error:new X_(Y_.RequestTimeout,`Version negotiation probe timed out after ${e.timeoutMs}ms`,{timeout:e.timeoutMs})}}}function yC(e,t){let n=wy(Cy).validateResult(`server/discover`,e);if(!n.ok)return{kind:`legacy`};let r=n.value.supportedVersions,i=t.clientModernVersions.find(e=>r.includes(e));return i===void 0?t.fallbackAvailable?{kind:`legacy`}:{kind:`error`,error:new Gv({supported:[...r],requested:t.requestedVersion})}:{kind:`modern`,version:i,discover:n.value}}function bC(e,t){let{code:n,message:r,data:i}=e;if(n===gC){let e=TC(i);if(e===void 0)return{kind:`legacy`};let n=new Gv({supported:e,requested:EC(i)??t.requestedVersion},r),a=iv(e),o=t.clientModernVersions.find(e=>a.includes(e));return o===void 0?a.length>0?{kind:`error`,error:n}:t.fallbackAvailable?{kind:`legacy`}:{kind:`error`,error:n}:{kind:`corrective`,version:o,error:n}}return _C.has(n),{kind:`legacy`}}function xC(e,t){let n=DC(e.body);return n===void 0?{kind:`legacy`}:bC(n,t)}function SC(e,t){return t.environment===`browser`&&CC(e)?{kind:`legacy`}:{kind:`error`,error:new X_(Y_.EraNegotiationFailed,`Version negotiation probe failed: ${wC(e)}`,{cause:e})}}function CC(e){return e instanceof TypeError||e instanceof Error&&e.name===`TypeError`}function wC(e){return e instanceof Error?e.message:String(e)}function TC(e){if(typeof e!=`object`||!e)return;let t=e.supported;if(!(!Array.isArray(t)||t.length===0||!t.every(e=>typeof e==`string`)))return t}function EC(e){if(typeof e!=`object`||!e)return;let t=e.requested;return typeof t==`string`?t:void 0}function DC(e){if(e===void 0||e===``)return;let t;try{t=JSON.parse(e)}catch{return}if(typeof t!=`object`||!t)return;let n=t.error;if(typeof n!=`object`||!n)return;let{code:r,message:i,data:a}=n;if(typeof r==`number`)return{code:r,message:typeof i==`string`?i:``,data:a}}var OC=`legacy`;function kC(e,t){let n=e?.mode??OC;if(n===`legacy`)return{kind:`legacy`};let r=e?.probe??{};if(typeof n==`object`){if(!nv(n.pin))throw TypeError(`versionNegotiation: { pin: '${n.pin}' } is not a modern protocol revision — pinning is for 2026-07-28 and later; omit versionNegotiation (or use mode: 'legacy') for 2025-era servers.`);return{kind:`pin`,version:n.pin,probe:r}}let i=t?iv(t):[];return{kind:`auto`,modernVersions:i.length>0?i:[...tv],fallbackAvailable:t?rv(t).length>0:!0,probe:r}}function AC(){let e=globalThis;return e.window!==void 0&&e.document!==void 0?`browser`:`node`}function jC(e){return`stderr`in e&&`pid`in e?`stdio`:`http`}var MC=class e{_pending;_probeCounter=0;_savedOnMessage;_savedOnError;_savedOnClose;_closeDelivered=!1;constructor(e){this._transport=e,this._savedOnMessage=e.onmessage,this._savedOnError=e.onerror,this._savedOnClose=e.onclose}static async open(t){let n=new e(t);t.onmessage=e=>{let t=n._pending;if(t!==void 0&&(My(e)||Ny(e))&&e.id===t.id){n._pending=void 0,My(e)?t.resolve({kind:`response`,result:e.result}):t.resolve({kind:`response`,error:e.error});return}},t.onerror=e=>{n._savedOnError?.(e)},t.onclose=()=>{let e=n._pending;e!==void 0&&(n._pending=void 0,e.resolve({kind:`closed`})),n._closeDelivered=!0,n._savedOnClose?.()};try{await t.start()}catch(e){throw n.detach(),e}return n}async exchange(e,t){let n=`server-discover-probe-${++this._probeCounter}`;return new Promise(r=>{let i=!1,a=e=>{i||(i=!0,clearTimeout(o),this._pending?.id===n&&(this._pending=void 0),r(e))},o=setTimeout(()=>a({kind:`timeout`}),t);this._pending={id:n,resolve:a},this._transport.send(e(n)).catch(e=>a({kind:`send-error`,error:e}))})}detach(){this._pending=void 0,this._transport.onmessage=this._savedOnMessage,this._transport.onerror=this._savedOnError,this._transport.onclose=this._closeDelivered?void 0:this._savedOnClose}release(){this.detach();let e=this._transport,t=e.start.bind(e),n=!0;e.start=async()=>{if(n){n=!1,e.start=t;return}return t()}}};function NC(e,t,n,r){return{jsonrpc:`2.0`,id:e,method:`server/discover`,params:{_meta:wy(t).outboundEnvelope({protocolVersion:t,clientInfo:n,clientCapabilities:r})}}}function PC(e,t){switch(e.kind){case`response`:return e.error===void 0?{kind:`result`,result:e.result}:{kind:`rpc-error`,...e.error};case`send-error`:{let t=e.error;if(t instanceof Z_){let e=t.data?.text;return{kind:`http-error`,status:t.data.status,body:typeof e==`string`?e:void 0}}return t instanceof xS||t instanceof Error&&t.name===`UnauthorizedError`?{kind:`auth-required`,error:t}:{kind:`network-error`,error:t}}case`closed`:return{kind:`network-error`,error:Error(`Connection closed during the version negotiation probe`)};case`timeout`:return{kind:`timeout`,timeoutMs:t}}}async function FC(e,t){let n=e.probe.timeoutMs??t.defaultTimeoutMs,r=Math.max(0,e.probe.maxRetries??0),i=e.kind===`pin`?[e.version]:e.modernVersions,a=e.kind===`auto`&&e.fallbackAvailable,o=await MC.open(t.transport),s=async()=>{let s=i[0],c=!1,l=r;for(;;){let r=await o.exchange(e=>NC(e,s,t.clientInfo,t.capabilities),n);if(r.kind===`timeout`&&l>0){l--;continue}let u=vC(PC(r,n),{clientModernVersions:i,requestedVersion:s,fallbackAvailable:a,environment:t.environment,transportKind:t.transportKind});switch(u.kind){case`modern`:return{era:`modern`,version:u.version,discover:u.discover};case`corrective`:if(c)throw u.error;c=!0,s=u.version;continue;case`legacy`:if(e.kind===`pin`)throw new X_(Y_.EraNegotiationFailed,`Version negotiation failed: the server did not offer pinned protocol version ${e.version} via server/discover (no fallback in pin mode)`);if(!e.fallbackAvailable)throw new X_(Y_.EraNegotiationFailed,`Version negotiation failed: the server gave no modern evidence and this client supports no pre-2026-07-28 protocol version to fall back to`);return{era:`legacy`};case`error`:throw u.error}}},c;try{c=await s()}catch(e){throw o.detach(),e}return o.release(),c}function IC(e,t){if(!(!e||typeof t!=`object`||!t)){if(e.type===`object`&&e.properties&&typeof e.properties==`object`){let n=t,r=e.properties;for(let e of Object.keys(r)){let t=r[e];n[e]===void 0&&Object.prototype.hasOwnProperty.call(t,`default`)&&(n[e]=t.default),n[e]!==void 0&&IC(t,n[e])}}if(Array.isArray(e.anyOf))for(let n of e.anyOf)typeof n!=`boolean`&&IC(n,t);if(Array.isArray(e.oneOf))for(let n of e.oneOf)typeof n!=`boolean`&&IC(n,t)}}function LC(e){if(!e)return{supportsFormMode:!1,supportsUrlMode:!1};let t=e.form!==void 0,n=e.url!==void 0;return{supportsFormMode:t||!t&&!n,supportsUrlMode:n}}var RC={"notifications/tools/list_changed":[`tools/list`],"notifications/prompts/list_changed":[`prompts/list`],"notifications/resources/list_changed":[`resources/list`,`resources/templates/list`]},zC=64,BC=class extends Jb{_serverCapabilities;_serverVersion;_capabilities;_instructions;_jsonSchemaValidator;_cache;_defaultCacheTtlMs;_listMaxPages;_listChangedDebounceTimers=new Map;_listChangedConfig;_enforceStrictCapabilities;_versionNegotiation;_supportedProtocolVersionsOption;_inputRequiredDriverConfig;_listenState=new Map;_nextListenId=0;_autoOpenedSubscription;_discoverResult;_resetConnectionState(){if(this._negotiatedProtocolVersion=void 0,this._serverCapabilities=void 0,this._serverVersion=void 0,this._instructions=void 0,this._discoverResult=void 0,this._autoOpenedSubscription=void 0,this._listenState.size>0){let e=new X_(Y_.ConnectionClosed,`subscriptions/listen: client reconnected or closed; subscription state from the previous connection was reset`);for(let t of this._listenState.values())t.settle({cause:`remote`,error:e})}this._listenState.clear();for(let e of this._listChangedDebounceTimers.values())clearTimeout(e);this._listChangedDebounceTimers.clear(),this._cache.resetForReconnect()}async close(){try{await super.close()}finally{this._resetConnectionState()}}constructor(e,t){super(t),this._clientInfo=e,this._capabilities=t?.capabilities?{...t.capabilities}:{},this._jsonSchemaValidator=t?.jsonSchemaValidator??new Jx,this._enforceStrictCapabilities=t?.enforceStrictCapabilities??!1,this._versionNegotiation=t?.versionNegotiation,this._supportedProtocolVersionsOption=t?.supportedProtocolVersions,this._inputRequiredDriverConfig=kb(t?.inputRequired),this._cache=new mC(t?.responseCacheStore??new uC,t?.responseCacheStore!==void 0,e=>this._reportStoreError(e),t?.cachePartition??``),this._defaultCacheTtlMs=t?.defaultCacheTtlMs??0,this._listMaxPages=t?.listMaxPages??zC,t?.listChanged&&(this._listChangedConfig=t.listChanged)}buildContext(e,t){return e}_shouldDropInbound(e){if(this._negotiatedProtocolVersion!==void 0&&nv(this._negotiatedProtocolVersion)&&Ay(e))return`drop`}_outboundMetaEnvelope(){let e=this._negotiatedProtocolVersion;if(e!==void 0)return this._wireCodec().outboundEnvelope({protocolVersion:e,clientInfo:this._clientInfo,clientCapabilities:this._capabilities})}_resolveNonCompleteResult(e,t){return this._inputRequiredDriverConfig.autoFulfill?rx({getRequestHandler:e=>this._getRequestHandler(e),buildContext:e=>this.buildContext(e,void 0),sessionId:this.transport?.sessionId},this._inputRequiredDriverConfig,e,t):Promise.reject(new X_(Y_.UnsupportedResultType,`Unsupported result type 'input_required' for ${t.request.method}: multi-round-trip auto-fulfilment is not enabled on this instance — pass allowInputRequired: true to handle it manually, or enable inputRequired.autoFulfill`,{resultType:`input_required`,method:t.request.method}))}_setupListChangedHandlers(e){e.tools&&this._serverCapabilities?.tools?.listChanged&&this._setupListChangedHandler(`tools`,`notifications/tools/list_changed`,e.tools,async()=>(await this.listTools(void 0,{cacheMode:`refresh`})).tools),e.prompts&&this._serverCapabilities?.prompts?.listChanged&&this._setupListChangedHandler(`prompts`,`notifications/prompts/list_changed`,e.prompts,async()=>(await this.listPrompts(void 0,{cacheMode:`refresh`})).prompts),e.resources&&this._serverCapabilities?.resources?.listChanged&&this._setupListChangedHandler(`resources`,`notifications/resources/list_changed`,e.resources,async()=>(await this.listResources(void 0,{cacheMode:`refresh`})).resources)}registerCapabilities(e){if(this.transport)throw Error(`Cannot register capabilities after connecting to transport`);this._capabilities=Xb(this._capabilities,e)}setVersionNegotiation(e){if(this.transport)throw Error(`Cannot configure version negotiation after connecting to transport`);this._versionNegotiation=e}_wrapHandler(e,t){return e===`elicitation/create`?async(e,n)=>{let r=wy(this._negotiatedProtocolVersion),i=r.validateRequest(`elicitation/create`,e);if(!i.ok&&i.reason===`not-in-era`&&(i=r.validateInputRequest(`elicitation/create`,e)),!i.ok)throw new Hv(i.reason===`not-in-era`?Vv.InternalError:Vv.InvalidParams,i.reason===`not-in-era`?`No wire schema for elicitation/create in the resolved era`:`Invalid elicitation request: ${i.message}`);let{params:a}=i.value;a.mode=a.mode??`form`;let{supportsFormMode:o,supportsUrlMode:s}=LC(this._capabilities.elicitation);if(a.mode===`form`&&!o)throw new Hv(Vv.InvalidParams,`Client does not support form-mode elicitation requests`);if(a.mode===`url`&&!s)throw new Hv(Vv.InvalidParams,`Client does not support URL-mode elicitation requests`);let c=await t(e,n),l=r.validateResult(`elicitation/create`,c);if(!l.ok&&l.reason===`not-in-era`&&(l=r.validateInputResponse(`elicitation/create`,c)),!l.ok)throw new Hv(l.reason===`not-in-era`?Vv.InternalError:Vv.InvalidParams,l.reason===`not-in-era`?`No wire schema for elicitation/create in the resolved era`:`Invalid elicitation result: ${l.message}`);let u=l.value,d=a.mode===`form`?a.requestedSchema:void 0;if(a.mode===`form`&&u.action===`accept`&&u.content&&d&&this._capabilities.elicitation?.form?.applyDefaults)try{IC(d,u.content)}catch{}return u}:e===`sampling/createMessage`?async(e,n)=>{let r=wy(this._negotiatedProtocolVersion),i=r.validateRequest(`sampling/createMessage`,e);if(!i.ok&&i.reason===`not-in-era`&&(i=r.validateInputRequest(`sampling/createMessage`,e)),!i.ok)throw new Hv(i.reason===`not-in-era`?Vv.InternalError:Vv.InvalidParams,i.reason===`not-in-era`?`No wire schema for sampling/createMessage in the resolved era`:`Invalid sampling request: ${i.message}`);let{params:a}=i.value,o=await t(e,n),s=!!(a.tools||a.toolChoice),c=r.samplingResultVariant(s,o);if(!c.ok&&c.reason===`not-in-era`&&(c=r.validateInputResponse(`sampling/createMessage`,o)),!c.ok)throw new Hv(c.reason===`not-in-era`?Vv.InternalError:Vv.InvalidParams,c.reason===`not-in-era`?`No result schema for sampling/createMessage in the resolved era`:`Invalid sampling result: ${c.message}`);return c.value}:t}assertCapability(e,t){if(!this._serverCapabilities?.[e])throw new X_(Y_.CapabilityNotSupported,`Server does not support ${e} (required for ${t})`)}async connect(e,t){if(t?.prior!==void 0)return this._connectFromPrior(e,t.prior);let n=kC(this._versionNegotiation,this._supportedProtocolVersionsOption);if(n.kind!==`legacy`)return this._connectNegotiated(e,n,t);if(await super.connect(e),e.sessionId!==void 0){let t=this._negotiatedProtocolVersion;t!==void 0&&e.setProtocolVersion?.(t);return}this._resetConnectionState(),await this._legacyHandshake(e,t)}async _legacyHandshake(e,t){let n=rv(this._supportedProtocolVersions);try{let r=n[0];if(r===void 0)throw new X_(Y_.EraNegotiationFailed,`Cannot run the initialize handshake: supportedProtocolVersions contains no pre-2026-07-28 protocol version`);let i=await this.request({method:`initialize`,params:{protocolVersion:r,capabilities:this._capabilities,clientInfo:this._clientInfo}},t);if(i===void 0)throw Error(`Server sent invalid initialize result: ${i}`);if(!n.includes(i.protocolVersion))throw Error(`Server's protocol version is not supported: ${i.protocolVersion}`);this._serverCapabilities=i.capabilities,this._serverVersion=i.serverInfo,this._cache.setServerIdentity(this._deriveServerIdentity(e)),e.setProtocolVersion&&e.setProtocolVersion(i.protocolVersion),this._instructions=i.instructions,await this.notification({method:`notifications/initialized`}),this._negotiatedProtocolVersion=i.protocolVersion,this._listChangedConfig&&this._setupListChangedHandlers(this._listChangedConfig)}catch(e){throw this.close(),e}}async _connectNegotiated(e,t,n){if(e.sessionId!==void 0){await super.connect(e);let t=this._negotiatedProtocolVersion;t!==void 0&&e.setProtocolVersion&&e.setProtocolVersion(t);return}this._resetConnectionState();let r;try{r=await FC(t,{transport:e,clientInfo:this._clientInfo,capabilities:this._capabilities,environment:AC(),transportKind:jC(e),defaultTimeoutMs:n?.timeout??6e4})}catch(t){throw await e.close().catch(()=>{}),t}if(await super.connect(e),r.era===`legacy`){await this._legacyHandshake(e,n);return}if(this._serverCapabilities=r.discover.capabilities,this._serverVersion=r.discover.serverInfo,this._cache.setServerIdentity(this._deriveServerIdentity(e)),this._instructions=r.discover.instructions,this._discoverResult=r.discover,this._negotiatedProtocolVersion=r.version,e.setProtocolVersion&&e.setProtocolVersion(r.version),this._listChangedConfig){let e=this._listChangedConfig,t=this._serverCapabilities,r={...e.tools&&t?.tools?.listChanged&&{tools:e.tools},...e.prompts&&t?.prompts?.listChanged&&{prompts:e.prompts},...e.resources&&t?.resources?.listChanged&&{resources:e.resources}},i=!0;try{this._setupListChangedHandlers(r)}catch(e){i=!1,this.onerror?.(e instanceof Error?e:Error(String(e)))}let a=i?{...r.tools&&{toolsListChanged:!0},...r.prompts&&{promptsListChanged:!0},...r.resources&&{resourcesListChanged:!0}}:{};if(Object.keys(a).length>0){let e=new AbortController,t=()=>e.abort(n?.signal?.reason);n?.signal?.aborted&&t(),n?.signal?.addEventListener(`abort`,t);try{this._autoOpenedSubscription=await this.listen(a,{timeout:n?.timeout,signal:e.signal})}catch(e){if(n?.signal?.aborted)throw await this.close().catch(()=>{}),e;this.onerror?.(e instanceof Error?e:Error(String(e)))}finally{n?.signal?.removeEventListener(`abort`,t)}}}}async _connectFromPrior(e,t){this._resetConnectionState();let n=this._supportedProtocolVersionsOption,r=(n&&iv(n).length>0?iv(n):tv).find(e=>t.supportedVersions.includes(e));if(r===void 0)throw new X_(Y_.EraNegotiationFailed,`connect({ prior }) requires a 2026-07-28+ mutual protocol version; the supplied DiscoverResult and this client's supportedProtocolVersions have no modern overlap. Use versionNegotiation: { mode: 'auto' } for legacy-era fallback.`);if(await super.connect(e),this._discoverResult=t,this._serverCapabilities=t.capabilities,this._serverVersion=t.serverInfo,this._cache.setServerIdentity(this._deriveServerIdentity(e)),this._instructions=t.instructions,this._negotiatedProtocolVersion=r,e.setProtocolVersion?.(r),this._listChangedConfig)try{this._setupListChangedHandlers(this._listChangedConfig)}catch(e){this.onerror?.(e instanceof Error?e:Error(String(e)))}}getServerCapabilities(){return this._serverCapabilities}getServerVersion(){return this._serverVersion}_deriveServerIdentity(e){let t=this._serverVersion;return t===void 0?e.sessionId??``:`${t.name}@${t.version}`}getNegotiatedProtocolVersion(){return this._negotiatedProtocolVersion}getProtocolEra(){let e=this._negotiatedProtocolVersion;if(e!==void 0)return nv(e)?`modern`:`legacy`}getInstructions(){return this._instructions}getDiscoverResult(){return this._discoverResult}assertCapabilityForMethod(e){switch(e){case`logging/setLevel`:if(!this._serverCapabilities?.logging)throw new X_(Y_.CapabilityNotSupported,`Server does not support logging (required for ${e})`);break;case`prompts/get`:case`prompts/list`:if(!this._serverCapabilities?.prompts)throw new X_(Y_.CapabilityNotSupported,`Server does not support prompts (required for ${e})`);break;case`resources/list`:case`resources/templates/list`:case`resources/read`:case`resources/subscribe`:case`resources/unsubscribe`:if(!this._serverCapabilities?.resources)throw new X_(Y_.CapabilityNotSupported,`Server does not support resources (required for ${e})`);if(e===`resources/subscribe`&&!this._serverCapabilities.resources.subscribe)throw new X_(Y_.CapabilityNotSupported,`Server does not support resource subscriptions (required for ${e})`);break;case`tools/call`:case`tools/list`:if(!this._serverCapabilities?.tools)throw new X_(Y_.CapabilityNotSupported,`Server does not support tools (required for ${e})`);break;case`completion/complete`:if(!this._serverCapabilities?.completions)throw new X_(Y_.CapabilityNotSupported,`Server does not support completions (required for ${e})`);break;case`initialize`:break;case`server/discover`:break;case`ping`:break}}assertNotificationCapability(e){switch(e){case`notifications/roots/list_changed`:if(!this._capabilities.roots?.listChanged)throw new X_(Y_.CapabilityNotSupported,`Client does not support roots list changed notifications (required for ${e})`);break;case`notifications/initialized`:break;case`notifications/cancelled`:break;case`notifications/progress`:break}}assertRequestHandlerCapability(e){switch(e){case`sampling/createMessage`:if(!this._capabilities.sampling)throw new X_(Y_.CapabilityNotSupported,`Client does not support sampling capability (required for ${e})`);break;case`elicitation/create`:if(!this._capabilities.elicitation)throw new X_(Y_.CapabilityNotSupported,`Client does not support elicitation capability (required for ${e})`);break;case`roots/list`:if(!this._capabilities.roots)throw new X_(Y_.CapabilityNotSupported,`Client does not support roots capability (required for ${e})`);break;case`ping`:break}}async ping(e){return this.request({method:`ping`},e)}async discover(e){let t=await this._requestWithSchema({method:`server/discover`},lh,e);return this._discoverResult=t,t}async complete(e,t){return this.request({method:`completion/complete`,params:e},t)}async setLoggingLevel(e,t){return this.request({method:`logging/setLevel`,params:{level:e}},t)}async getPrompt(e,t){return this.request({method:`prompts/get`,params:e},t)}async listPrompts(e,t){if(!this._serverCapabilities?.prompts&&!this._enforceStrictCapabilities)return console.debug(`Client.listPrompts() called but server does not advertise prompts capability - returning empty list`),{prompts:[]};if(e?.cursor!==void 0)return this.request({method:`prompts/list`,params:e},t);let n=await this._serveFromCache(`prompts/list`,void 0,t);return n===void 0?this._listAllPages(`prompts/list`,e,t,(e,t)=>e.prompts.push(...t.prompts)):n}async listResources(e,t){if(!this._serverCapabilities?.resources&&!this._enforceStrictCapabilities)return console.debug(`Client.listResources() called but server does not advertise resources capability - returning empty list`),{resources:[]};if(e?.cursor!==void 0)return this.request({method:`resources/list`,params:e},t);let n=await this._serveFromCache(`resources/list`,void 0,t);return n===void 0?this._listAllPages(`resources/list`,e,t,(e,t)=>e.resources.push(...t.resources)):n}async listResourceTemplates(e,t){if(!this._serverCapabilities?.resources&&!this._enforceStrictCapabilities)return console.debug(`Client.listResourceTemplates() called but server does not advertise resources capability - returning empty list`),{resourceTemplates:[]};if(e?.cursor!==void 0)return this.request({method:`resources/templates/list`,params:e},t);let n=await this._serveFromCache(`resources/templates/list`,void 0,t);return n===void 0?this._listAllPages(`resources/templates/list`,e,t,(e,t)=>e.resourceTemplates.push(...t.resourceTemplates)):n}async _listAllPages(e,t,n,r,i){let a=n?.cacheMode===`bypass`,o=this._cache.captureGeneration(e),s=await this.request({method:e,...t&&{params:{...t}}},n),c=s.nextCursor,l=new Set,u=1;for(;c!==void 0&&!l.has(c);){if(this._listMaxPages!==0&&u>=this._listMaxPages)throw new X_(Y_.ListPaginationExceeded,`${e}: exceeded listMaxPages (${this._listMaxPages}); server pagination did not terminate`,{method:e,listMaxPages:this._listMaxPages});l.add(c);let i=await this.request({method:e,params:{...t,cursor:c}},n);r(s,i),c=i.nextCursor,u++}return delete s.nextCursor,i?.(s),a||await this._cache.write(e,s,o,this._freshness(s)),s}_freshness(e,t){let n=e,r=typeof n.ttlMs==`number`?n.ttlMs:this._defaultCacheTtlMs,i=n.cacheScope===`public`?`public`:`private`;return{expiresAt:this._cache.now()+Math.min(Math.max(0,r),pC),scope:i,params:t}}async _serveFromCache(e,t,n){if(n?.cacheMode===`bypass`||n?.cacheMode===`refresh`)return;let r=await this._cache.read(e,t).catch(e=>void this._reportStoreError(e));if(r!==void 0){if(n?.signal?.aborted){let e=n.signal.reason;throw e instanceof X_?e:new X_(Y_.RequestTimeout,String(e))}return r.value}}_reportStoreError(e){this.onerror?.(e instanceof Error?e:Error(String(e)))}_compileOutputValidator(e){if(e.outputSchema)try{return{ok:!0,validator:this._jsonSchemaValidator.getValidator(e.outputSchema)}}catch(e){return{ok:!1,compileError:e}}}async _resolveXMcpHeaderScan(e,t){let n=t??await this._cache.toolDefinition(e);return n===void 0?void 0:Vy(n.inputSchema)}async readResource(e,t){let n=await this._serveFromCache(`resources/read`,e.uri,t);if(n!==void 0)return n;let r=this._cache.captureGeneration(`resources/read`,e.uri),i=await this.request({method:`resources/read`,params:e},t);if(t?.cacheMode!==`bypass`){let n=this._freshness(i,e.uri);n.expiresAt>this._cache.now()?await this._cache.write(`resources/read`,i,r,n):t?.cacheMode===`refresh`&&await this._cache.evictKey(`resources/read`,e.uri)}return i}async subscribeResource(e,t){return this.request({method:`resources/subscribe`,params:e},t)}async unsubscribeResource(e,t){return this.request({method:`resources/unsubscribe`,params:e},t)}async listen(e,t){if(this.transport===void 0)throw new X_(Y_.NotConnected,`Not connected`);let n=this._negotiatedProtocolVersion;if(n===void 0||!nv(n))throw new X_(Y_.MethodNotSupportedByProtocolVersion,`subscriptions/listen requires a 2026-07-28-era connection (negotiated: ${n??`none`}). On a 2025-era connection, change notifications are delivered unsolicited: use ClientOptions.listChanged and resources/subscribe instead.`,{method:`subscriptions/listen`,protocolVersion:n});if(t?.signal?.aborted){let e=t.signal.reason;throw e instanceof X_?e:new X_(Y_.RequestTimeout,String(e))}let r=new AbortController,i=`listen:${this._nextListenId++}`,a=`opening`,o,s,c,l,u=new Promise((e,t)=>{c=e,l=t}),d,f=new Promise(e=>{d=e}),p=e=>{if(a===`closed`)return;let n=a===`opening`;if(o!==void 0&&(clearTimeout(o),o=void 0),`ack`in e){a=`open`,c(e.ack);return}a=`closed`,s!==void 0&&t?.signal?.removeEventListener(`abort`,s),this._listenState.delete(i),r.abort(),d(e.cause),n&&l(e.error??new X_(Y_.ConnectionClosed,`subscriptions/listen closed before the server acknowledged`))},m=async()=>{r.abort(),await this.notification({method:`notifications/cancelled`,params:{requestId:i}}).catch(()=>{})},h=async()=>{a!==`closed`&&(p({cause:`local`}),await m())};this._listenState.set(i,{settle:p});let g=t?.timeout??6e4;if(o=setTimeout(()=>{p({cause:`remote`,error:new X_(Y_.RequestTimeout,`subscriptions/listen ack timed out`,{timeout:g})}),m().catch(()=>{})},g),t?.signal){let e=t.signal;s=()=>{if(a===`closed`)return;let t=e.reason;p({cause:`local`,error:t instanceof Error?t:Error(String(t??`Aborted`))}),m().catch(()=>{})},e.addEventListener(`abort`,s,{once:!0})}let _={jsonrpc:`2.0`,id:i,method:`subscriptions/listen`,params:{_meta:{...this._outboundMetaEnvelope()},notifications:e}};try{await this.transport.send(_,{requestSignal:r.signal,onRequestStreamEnd:()=>p({cause:`remote`,error:Error(`subscriptions/listen: stream ended`)})})}catch(e){p({cause:`remote`,error:e instanceof Error?e:Error(String(e))})}return{honoredFilter:await u,close:h,closed:f}}get autoOpenedSubscription(){return this._autoOpenedSubscription}_onnotification(e,t){let n=Object.hasOwn(RC,e.method)?RC[e.method]:void 0;if(e.method===`notifications/resources/updated`){let t=e.params?.uri;typeof t==`string`&&this._cache.evictKey(`resources/read`,t)}else if(n!==void 0)for(let e of n)this._cache.evict(e);if(e.method===`notifications/subscriptions/acknowledged`){let t=e.params?._meta?.[Cm],n=typeof t==`string`?this._listenState.get(t):void 0;if(n!==void 0){let t=this._wireCodec().validateNotification(`notifications/subscriptions/acknowledged`,e);n.settle({ack:t.ok?t.value.params.notifications:{}});return}}if(e.method===`notifications/cancelled`){let t=e.params?.requestId,n=typeof t==`string`?this._listenState.get(t):void 0;if(n!==void 0){n.settle({cause:`remote`,error:Error(`subscriptions/listen: server cancelled the subscription`)});return}}super._onnotification(e,t)}_onresponse(e){let t=e.id,n=typeof t==`string`?this._listenState.get(t):void 0;if(n!==void 0){Ny(e)?n.settle({cause:`remote`,error:Hv.fromError(e.error.code,e.error.message,e.error.data)}):n.settle({cause:`graceful`,error:new X_(Y_.ConnectionClosed,`subscriptions/listen: server closed the subscription gracefully before acknowledging`)});return}super._onresponse(e)}_onclose(){if(this._listenState.size>0){let e=new X_(Y_.ConnectionClosed,`Connection closed`);for(let t of this._listenState.values())t.settle({cause:`remote`,error:e});this._listenState.clear()}super._onclose()}async callTool(e,t){let n=this.getProtocolEra()===`modern`&&AC()!==`browser`,r=async()=>{if(!n)return t;let r;try{r=await this._resolveXMcpHeaderScan(e.name,t?.toolDefinition)}catch(e){this._reportStoreError(e)}if(!r?.valid||r.declarations.length===0)return t;let i=Qy(r.declarations,e.arguments);return Object.keys(i).length===0?t:{...t,headers:{...t?.headers,...i}}},i=t?.toolDefinition===void 0?await this._cache.outputValidator(e.name,e=>this._compileOutputValidator(e)).catch(e=>void this._reportStoreError(e)):this._compileOutputValidator(t.toolDefinition),a=()=>{if(i===void 0||i.ok)return;let t=i.compileError,n=(t instanceof Error?t.message:String(t)).slice(0,200);throw new Hv(Vv.InvalidParams,`Tool '${e.name}' has an invalid outputSchema: ${n}`)};a();let o;try{o=await this.request({method:`tools/call`,params:e},await r())}catch(s){let c=s instanceof Hv&&s.code===-32020;if(!n||!c||t?.toolDefinition!==void 0)throw s;let l={signal:t?.signal,timeout:t?.timeout,cacheMode:`refresh`};await this._cache.evict(`tools/list`),await this.listTools(void 0,l).catch(e=>this._reportStoreError(e)),i=await this._cache.outputValidator(e.name,e=>this._compileOutputValidator(e)).catch(e=>void this._reportStoreError(e)),a(),o=await this.request({method:`tools/call`,params:e},await r())}let s=i!==void 0&&i.ok?i.validator:void 0;if(s){if(o.structuredContent===void 0&&!o.isError)throw new Hv(Vv.InvalidRequest,`Tool ${e.name} has an output schema but did not return structured content`);if(o.structuredContent!==void 0&&!o.isError)try{let e=s(o.structuredContent);if(!e.valid)throw new Hv(Vv.InvalidParams,`Structured content does not match the tool's output schema: ${e.errorMessage}`)}catch(e){throw e instanceof Hv?e:new Hv(Vv.InvalidParams,`Failed to validate structured content: ${e instanceof Error?e.message:String(e)}`)}}return o}async listTools(e,t){if(!this._serverCapabilities?.tools&&!this._enforceStrictCapabilities)return console.debug(`Client.listTools() called but server does not advertise tools capability - returning empty list`),{tools:[]};if(e?.cursor!==void 0){let n=await this.request({method:`tools/list`,params:e},t);return this._excludeInvalidXMcpHeaderTools(n),n}let n=await this._serveFromCache(`tools/list`,void 0,t);return n===void 0?this._listAllPages(`tools/list`,e,t,(e,t)=>e.tools.push(...t.tools),e=>this._excludeInvalidXMcpHeaderTools(e)):n}_excludeInvalidXMcpHeaderTools(e){if(this.getProtocolEra()!==`modern`||!this.transport||jC(this.transport)===`stdio`)return;let t=e.tools.filter(e=>{let t=Vy(e.inputSchema);return t.valid?!0:(console.warn(`[mcp-sdk] excluding tool '${e.name}' from tools/list: invalid x-mcp-header declaration — ${t.reason}`),!1)});t.length!==e.tools.length&&(e.tools=t)}_setupListChangedHandler(e,t,n,r){let i=$y(yg,n);if(!i.success)throw Error(`Invalid ${e} listChanged options: ${i.error.message}`);if(typeof n.onChanged!=`function`)throw TypeError(`Invalid ${e} listChanged options: onChanged must be a function`);let{autoRefresh:a,debounceMs:o}=i.data,{onChanged:s}=n,c=async()=>{if(!a){s(null,null);return}try{s(null,await r())}catch(e){s(e instanceof Error?e:Error(String(e)),null)}};this.setNotificationHandler(t,()=>{if(o){let t=this._listChangedDebounceTimers.get(e);t&&clearTimeout(t);let n=setTimeout(c,o);this._listChangedDebounceTimers.set(e,n)}else c()})}async sendRootsListChanged(){return this.notification({method:`notifications/roots/list_changed`})}};(class extends Error{static{Object.defineProperty(this,"mcpBrand",{value:`mcp.SseError`})}static[Symbol.hasInstance](e){return K_(this,e)}static isInstance(e){if(typeof this!=`function`)throw TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`");return K_(this,e)}constructor(e,t,n){super(`SSE error: ${t}`),this.code=e,this.event=n,G_(this,new.target)}});var VC=1,HC={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2},UC=new Set([`authorization`,`content-type`,`mcp-protocol-version`,`mcp-method`,`mcp-name`,`mcp-session-id`]);function WC(e,t){if(typeof AbortSignal.any==`function`)return AbortSignal.any([e,t]);let n=new AbortController;if(e.aborted)return n.abort(e.reason),n.signal;if(t.aborted)return n.abort(t.reason),n.signal;let r=()=>{e.removeEventListener(`abort`,i),t.removeEventListener(`abort`,a)};function i(){r(),n.abort(e.reason)}function a(){r(),n.abort(t.reason)}return e.addEventListener(`abort`,i,{once:!0}),t.addEventListener(`abort`,a,{once:!0}),n.signal}var GC=class{_abortController;_url;_resourceMetadataUrl;_scope;_requestInit;_authProvider;_oauthProvider;_skipIssuerMetadataValidation;_fetch;_fetchWithInit;_sessionId;_reconnectionOptions;_protocolVersion;_onInsufficientScope;_maxStepUpRetries;_serverRetryMs;_reconnectionScheduler;_cancelReconnection;onclose;onerror;onmessage;hasPerRequestStream=!0;constructor(e,t){this._url=e,this._resourceMetadataUrl=void 0,this._scope=void 0,this._requestInit=t?.requestInit,this._skipIssuerMetadataValidation=t?.skipIssuerMetadataValidation,vS(t?.authProvider)?(this._oauthProvider=t.authProvider,this._authProvider=bS(t.authProvider,{skipIssuerMetadataValidation:t.skipIssuerMetadataValidation})):this._authProvider=t?.authProvider,this._fetch=t?.fetch,this._fetchWithInit=cx(t?.fetch,t?.requestInit),this._sessionId=t?.sessionId,this._protocolVersion=t?.protocolVersion,this._reconnectionOptions=t?.reconnectionOptions??HC,this._reconnectionScheduler=t?.reconnectionScheduler,this._onInsufficientScope=t?.onInsufficientScope??`reauthorize`,this._maxStepUpRetries=Math.max(0,t?.maxStepUpRetries??VC)}async _stepUpAuthorize(e,t){if(this._onInsufficientScope===`throw`||!this._oauthProvider)throw new hS({requiredScope:e.scope,resourceMetadataUrl:e.resourceMetadataUrl,errorDescription:e.errorDescription});if(t>=this._maxStepUpRetries)throw new Z_(Y_.ClientHttpForbidden,`Server returned 403 insufficient_scope after step-up re-authorization (retry limit ${this._maxStepUpRetries} reached)`,{status:403,statusText:e.statusText??`Forbidden`,text:e.text});e.resourceMetadataUrl&&(this._resourceMetadataUrl=e.resourceMetadataUrl);let n=await this._oauthProvider.tokens(),r=wS(this._scope,n?.scope,e.scope);this._scope=r;let i=TS(r,n?.scope);return BS(this._oauthProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:r,forceReauthorization:i,fetchFn:this._fetchWithInit,skipIssuerMetadataValidation:this._skipIssuerMetadataValidation})}async _commonHeaders(){let e={},t=await this._authProvider?.token();t&&(e.Authorization=`Bearer ${t}`),this._sessionId&&(e[`mcp-session-id`]=this._sessionId),this._protocolVersion&&(e[`mcp-protocol-version`]=this._protocolVersion);let n=sx(this._requestInit?.headers);return new Headers({...e,...n})}_applyBodyDerivedHeaders(e,t){if(Array.isArray(t)||!Ay(t))return;let n=t.params?._meta?.[bm];if(typeof n!=`string`)return;e.set(`mcp-protocol-version`,n),e.set(`mcp-method`,t.method);let r=t.params,i=t.method===`resources/read`?typeof r?.uri==`string`?r.uri:void 0:typeof r?.name==`string`?r.name:void 0;i!==void 0&&e.set(`mcp-name`,Xy(i))}_isModernEnvelopedRequest(e){if(Array.isArray(e)||!Ay(e))return!1;let t=e.params?._meta?.[bm];return typeof t==`string`&&nv(t)}async _startOrAuthSse(e,t=!1,n=0){let{resumptionToken:r,requestSignal:i}=e,a=()=>this._abortController?.signal.aborted===!0||i?.aborted===!0;try{let a=await this._commonHeaders(),o=[...a.get(`accept`)?.split(`,`).map(e=>e.trim().toLowerCase())??[],`text/event-stream`];a.set(`accept`,[...new Set(o)].join(`, `)),r&&a.set(`last-event-id`,r);let s=this._abortController?.signal,c=i!==void 0&&s!==void 0?WC(s,i):i??s,l=await(this._fetch??fetch)(this._url,{...this._requestInit,method:`GET`,headers:a,signal:c});if(!l.ok){if(l.status===401&&this._authProvider){if(l.headers.has(`www-authenticate`)){let{resourceMetadataUrl:e,scope:t}=KS(l);this._resourceMetadataUrl=e,this._scope=wS(this._scope,t)}if(this._authProvider.onUnauthorized&&!t)return await this._authProvider.onUnauthorized({response:l,serverUrl:this._url,fetchFn:this._fetchWithInit}),await l.text?.().catch(()=>{}),this._startOrAuthSse(e,!0,n);throw await l.text?.().catch(()=>{}),t?new Z_(Y_.ClientHttpAuthentication,`Server returned 401 after re-authentication`,{status:401,statusText:l.statusText}):new xS}if(l.status===403){let{resourceMetadataUrl:r,scope:i,error:a,errorDescription:o}=KS(l);if(a===`insufficient_scope`){let a=await l.text?.().catch(()=>null);if(await this._stepUpAuthorize({scope:i,resourceMetadataUrl:r,errorDescription:o,statusText:l.statusText,text:a},n)!==`AUTHORIZED`)throw new xS;return this._startOrAuthSse(e,t,n+1)}}if(await l.text?.().catch(()=>{}),l.status===405){e.onRequestStreamEnd?.();return}throw new Z_(Y_.ClientHttpFailedToOpenStream,`Failed to open SSE stream: ${l.statusText}`,{status:l.status,statusText:l.statusText})}this._handleSseStream(l.body,e,!0)}catch(e){throw a()||this.onerror?.(e),e}}_getNextReconnectionDelay(e){if(this._serverRetryMs!==void 0)return this._serverRetryMs;let t=this._reconnectionOptions.initialReconnectionDelay,n=this._reconnectionOptions.reconnectionDelayGrowFactor,r=this._reconnectionOptions.maxReconnectionDelay;return Math.min(t*n**+e,r)}_scheduleReconnection(e,t=0){let n=this._reconnectionOptions.maxRetries;if(t>=n){this.onerror?.(Error(`Maximum reconnection attempts (${n}) exceeded.`)),e.onRequestStreamEnd?.();return}let r=this._getNextReconnectionDelay(t),i=()=>{this._cancelReconnection=void 0,!(this._abortController?.signal.aborted||e.requestSignal?.aborted)&&this._startOrAuthSse(e).catch(n=>{if(!(this._abortController?.signal.aborted||e.requestSignal?.aborted)){this.onerror?.(Error(`Failed to reconnect SSE stream: ${n instanceof Error?n.message:String(n)}`));try{this._scheduleReconnection(e,t+1)}catch(e){this.onerror?.(e instanceof Error?e:Error(String(e)))}}})};if(this._reconnectionScheduler){let e=this._reconnectionScheduler(i,r,t);this._cancelReconnection=typeof e==`function`?e:void 0}else{let e=setTimeout(i,r);this._cancelReconnection=()=>clearTimeout(e)}}_handleSseStream(e,t,n){if(!e){t.onRequestStreamEnd?.();return}let{onresumptiontoken:r,replayMessageId:i,requestSignal:a,onRequestStreamEnd:o}=t,s=()=>this._abortController?.signal.aborted===!0||a?.aborted===!0,c,l=!1,u=!1;(async()=>{try{let t=e.pipeThrough(new TextDecoderStream).pipeThrough(new aS({onRetry:e=>{this._serverRetryMs=e}})).getReader();for(;;){let{value:e,done:n}=await t.read();if(n)break;if(e.id&&(c=e.id,l=!0,r?.(e.id)),e.data&&(!e.event||e.event===`message`))try{let t=Wm.parse(JSON.parse(e.data));(My(t)||Ny(t))&&(u=!0,i!==void 0&&(t.id=i)),this.onmessage?.(t)}catch(e){this.onerror?.(e)}}(n||l)&&!u&&this._abortController&&!s()?this._scheduleReconnection({resumptionToken:c,onresumptiontoken:r,replayMessageId:i,requestSignal:a,onRequestStreamEnd:o},0):s()||o?.()}catch(e){if(s())return;if(this.onerror?.(Error(`SSE stream disconnected: ${e}`)),(n||l)&&!u&&this._abortController&&!s())try{this._scheduleReconnection({resumptionToken:c,onresumptiontoken:r,replayMessageId:i,requestSignal:a,onRequestStreamEnd:o},0)}catch(e){this.onerror?.(Error(`Failed to reconnect: ${e instanceof Error?e.message:String(e)}`)),o?.()}else o?.()}})()}async start(){if(this._abortController)throw Error(`StreamableHTTPClientTransport already started! If using Client class, note that connect() calls start() automatically.`);this._abortController=new AbortController}async finishAuth(e,t){if(!this._oauthProvider)throw new xS(`finishAuth requires an OAuthClientProvider`);let{authorizationCode:n,iss:r}=await ES(e,t,this._oauthProvider,this._url,{fetchFn:this._fetchWithInit,resourceMetadataUrl:this._resourceMetadataUrl});if(await BS(this._oauthProvider,{serverUrl:this._url,authorizationCode:n,iss:r,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit,skipIssuerMetadataValidation:this._skipIssuerMetadataValidation})!==`AUTHORIZED`)throw new xS(`Failed to authorize`)}async close(){try{this._cancelReconnection?.()}finally{this._cancelReconnection=void 0,this._abortController?.abort(),this.onclose?.()}}async send(e,t){return this._send(e,t,!1)}async _send(e,t,n,r=0){try{let{resumptionToken:i,onresumptiontoken:a}=t||{};if(i){this._startOrAuthSse({resumptionToken:i,replayMessageId:Ay(e)?e.id:void 0,requestSignal:t?.requestSignal}).catch(e=>this.onerror?.(e));return}let o=await this._commonHeaders();this._applyBodyDerivedHeaders(o,e);let s=Array.isArray(e)?e.some(e=>Fy(e)):Fy(e);if(s&&o.delete(`mcp-session-id`),t?.headers!==void 0)for(let[e,n]of Object.entries(t.headers))UC.has(e.toLowerCase())||o.set(e,n);o.set(`content-type`,`application/json`);let c=[...o.get(`accept`)?.split(`,`).map(e=>e.trim().toLowerCase())??[],`application/json`,`text/event-stream`];o.set(`accept`,[...new Set(c)].join(`, `));let l=this._abortController?.signal,u=t?.requestSignal!==void 0&&l!==void 0?WC(l,t.requestSignal):t?.requestSignal??l,d={...this._requestInit,method:`POST`,headers:o,body:JSON.stringify(e),signal:u},f=await(this._fetch??fetch)(this._url,d);if(s&&f.ok&&(this._sessionId=f.headers.get(`mcp-session-id`)||void 0),!f.ok){if(f.status===401&&this._authProvider){if(f.headers.has(`www-authenticate`)){let{resourceMetadataUrl:e,scope:t}=KS(f);this._resourceMetadataUrl=e,this._scope=wS(this._scope,t)}if(this._authProvider.onUnauthorized&&!n)return await this._authProvider.onUnauthorized({response:f,serverUrl:this._url,fetchFn:this._fetchWithInit}),await f.text?.().catch(()=>{}),this._send(e,t,!0,r);throw await f.text?.().catch(()=>{}),n?new Z_(Y_.ClientHttpAuthentication,`Server returned 401 after re-authentication`,{status:401,statusText:f.statusText}):new xS}let i=await f.text?.().catch(()=>null);if(f.status===403){let{resourceMetadataUrl:a,scope:o,error:s,errorDescription:c}=KS(f);if(s===`insufficient_scope`){if(await this._stepUpAuthorize({scope:o,resourceMetadataUrl:a,errorDescription:c,statusText:f.statusText,text:i},r)!==`AUTHORIZED`)throw new xS;return this._send(e,t,n,r+1)}}if(f.status===400&&typeof i==`string`&&this._isModernEnvelopedRequest(e))try{let t=Wm.parse(JSON.parse(i)),n=(Array.isArray(e)?e:[e]).filter(e=>Ay(e));if(Ny(t)&&n.some(e=>e.id===t.id)){this.onmessage?.(t);return}}catch{}throw new Z_(Y_.ClientHttpNotImplemented,`Error POSTing to endpoint: ${i}`,{status:f.status,statusText:f.statusText,text:i})}if(f.status===202){await f.text?.().catch(()=>{}),Iy(e)&&this._startOrAuthSse({resumptionToken:void 0}).catch(e=>this.onerror?.(e));return}let p=(Array.isArray(e)?e:[e]).some(e=>`method`in e&&`id`in e&&e.id!==void 0),m=f.headers.get(`content-type`),h=ox(m);if(p)if(h===`text/event-stream`)this._handleSseStream(f.body,{onresumptiontoken:a,requestSignal:t?.requestSignal,onRequestStreamEnd:t?.onRequestStreamEnd},!1);else if(h===`application/json`){let e=await f.json(),t=Array.isArray(e)?e.map(e=>Wm.parse(e)):[Wm.parse(e)];for(let e of t)this.onmessage?.(e)}else throw await f.text?.().catch(()=>{}),new X_(Y_.ClientHttpUnexpectedContent,`Unexpected content type: ${m}`,{contentType:m});else await f.text?.().catch(()=>{})}catch(e){throw t?.requestSignal?.aborted!==!0&&this.onerror?.(e),e}}get sessionId(){return this._sessionId}async terminateSession(){if(this._sessionId)try{let e=await this._commonHeaders(),t={...this._requestInit,method:`DELETE`,headers:e,signal:this._abortController?.signal},n=await(this._fetch??fetch)(this._url,t);if(await n.text?.().catch(()=>{}),!n.ok&&n.status!==405)throw new Z_(Y_.ClientHttpFailedToTerminateSession,`Failed to terminate session: ${n.statusText}`,{status:n.status,statusText:n.statusText});this._sessionId=void 0}catch(e){throw this.onerror?.(e),e}}setProtocolVersion(e){this._protocolVersion=e}get protocolVersion(){return this._protocolVersion}async resumeStream(e,t){await this._startOrAuthSse({resumptionToken:e,onresumptiontoken:t?.onresumptiontoken})}},KC=t({BaseConnector:()=>$w,BrowserOAuthClientProvider:()=>Iw,DialectJsonSchemaValidator:()=>Zw,HttpConnector:()=>nT,MCPClient:()=>dT,MCPConnection:()=>sT,MCPSession:()=>sT,POSTHOG_API_KEY:()=>mw,POSTHOG_HOST:()=>pw,Tel:()=>kw,Telemetry:()=>Ow,VERSION:()=>iw,capturePostHog:()=>hw,completeOAuthFlow:()=>Ww,createOAuthProvider:()=>Lw,getPackageVersion:()=>aw,isUnauthorized:()=>Uw,logger:()=>Q,normalizeClientInfo:()=>oT,resolveCallbacks:()=>rT,setTelemetrySource:()=>Aw,shouldAutoProvisionOAuth:()=>iT,telFetch:()=>fw}),qC;function JC(e){qC=e}function YC(e,t){qC?.addServer(e,t)}function XC(e){qC?.removeServer(e)}var ZC;function QC(e){ZC=e}function $C(e){ZC?.(e)}var ew=[`silent`,`error`,`warn`,`info`,`http`,`verbose`,`debug`,`silly`],tw={silent:``,error:`❌`,warn:`⚠️`,info:`ℹ️`,http:`🌐`,verbose:`📝`,debug:`🔍`,silly:`🤪`};function nw(){let e;try{e=typeof process<`u`?{}.MCP_USE_LOG_LEVEL??{}.DEBUG:void 0}catch{}let t=e?.trim().toLowerCase();return t===`2`?`debug`:t&&ew.includes(t)?t:`info`}var rw=class{constructor(e=`mcp-use`,t=`info`,n=`minimal`){this.name=e,this.level=t,this.format=n}write(e,t,n){if(this.level===`silent`||ew.indexOf(e)>ew.indexOf(this.level))return;let r=n.map(e=>{if(typeof e==`string`)return e;try{return JSON.stringify(e)}catch{return String(e)}}).join(` `),i=r?`${t} ${r}`:t,a=new Date().toLocaleTimeString(`en-US`,{hour12:!1}),o=this.format===`minimal`?e:e.toUpperCase(),s=this.format===`emoji`?` ${tw[e]}`:``,c=`${a} [${this.name}]${s} ${o}: ${i}`;(e===`error`?console.error:e===`warn`?console.warn:e===`info`?console.info:e===`debug`?console.debug:console.log)(c)}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}},Q=class{static instances={};static currentFormat=`minimal`;static currentLevel;static get(e=`mcp-use`){return this.instances[e]??=new rw(e,this.currentLevel??nw(),this.currentFormat)}static configure({level:e=nw(),format:t=`minimal`}={}){this.currentLevel=e,this.currentFormat=t;for(let n of Object.values(this.instances))n.level=e,n.format=t}static setDebug(e){let t=e===2||e===!0?`debug`:`info`;this.currentLevel=t;for(let e of Object.values(this.instances))e.level=t;try{typeof process<`u`&&({}.MCP_USE_LOG_LEVEL=t)}catch{}}static setFormat(e){this.configure({format:e})}}.get(),iw=`2.0.0-beta.4`;function aw(){return iw}var ow=class{},sw=class extends ow{constructor(e){super(),this.data=e}get name(){return`mcp_agent_execution`}get properties(){return{execution_method:this.data.executionMethod,query:this.data.query,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,server_identifiers:this.data.serverIdentifiers,total_tools_available:this.data.totalToolsAvailable,tools_available_names:this.data.toolsAvailableNames,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,tools_used_names:this.data.toolsUsedNames??null,response:this.data.response??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}}},cw=class extends ow{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}}},lw=class extends ow{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}}},uw=class extends ow{constructor(e){super(),this.data=e}get name(){return`client_add_server`}get properties(){let{serverName:e,serverConfig:t}=this.data,n=t.url;return{server_name:e,server_url_domain:n?this._extractHostname(n):null,transport:t.transport??null,has_auth:!!(t.authToken||t.authProvider)}}_extractHostname(e){try{return new URL(e).hostname}catch{return null}}},dw=class extends ow{constructor(e){super(),this.data=e}get name(){return`client_remove_server`}get properties(){return{server_name:this.data.serverName}}};async function fw(e,t){try{await fetch(e,t)}catch{}}var pw=`https://eu.i.posthog.com`,mw=`phc_lyTtbYwvkdSbrcMQNPiKiiRWrrM1seyKIMjycSvItEI`;function hw(e){let t=e.host??`https://eu.i.posthog.com`,n=e.apiKey??`phc_lyTtbYwvkdSbrcMQNPiKiiRWrrM1seyKIMjycSvItEI`;return fw(`${t}/i/v0/e/`,{method:`POST`,headers:{"Content-Type":`application/json`},keepalive:!0,body:JSON.stringify({api_key:n,event:e.event,distinct_id:e.distinctId,properties:e.properties,timestamp:new Date().toISOString()})})}function gw(){return globalThis.crypto.randomUUID()}function _w(){let e=new Uint8Array(8);return globalThis.crypto.getRandomValues(e),Array.from(e,e=>e.toString(16).padStart(2,`0`)).join(``)}var vw=`mcp_use_user_id`,yw=`phc_lyTtbYwvkdSbrcMQNPiKiiRWrrM1seyKIMjycSvItEI`,bw=`https://eu.i.posthog.com`,xw=null;function Sw(){return typeof localStorage<`u`&&typeof localStorage.getItem==`function`&&typeof localStorage.setItem==`function`&&typeof localStorage.removeItem==`function`}function Cw(){if(!Sw())return null;try{localStorage.setItem(`__mcp_use_test__`,`1`),localStorage.removeItem(`__mcp_use_test__`)}catch{return null}return{getUserId(){try{return localStorage.getItem(vw)}catch{return null}},setUserId(e){try{localStorage.setItem(vw,e)}catch{}}}}function ww(){try{return globalThis.Bun===void 0?globalThis.Deno===void 0?typeof navigator<`u`&&navigator.userAgent?.includes(`Cloudflare-Workers`)?`cloudflare-workers`:globalThis.EdgeRuntime===void 0?typeof window<`u`&&typeof document<`u`?`browser`:typeof process<`u`&&process.versions?.node!==void 0?`node`:`unknown`:`edge`:`deno`:`bun`}catch{return`unknown`}}function Tw(){if(typeof process<`u`&&{}.MCP_USE_TELEMETRY_SOURCE)return{}.MCP_USE_TELEMETRY_SOURCE;try{if(Sw())return localStorage.getItem(`MCP_USE_TELEMETRY_SOURCE`)??void 0}catch{}}function Ew(){if(typeof window<`u`&&window.__MCP_USE_ANONYMIZED_TELEMETRY__===!1||typeof process<`u`&&{}.MCP_USE_ANONYMIZED_TELEMETRY?.toLowerCase()===`false`)return!0;try{if(Sw()&&localStorage.getItem(`MCP_USE_ANONYMIZED_TELEMETRY`)===`false`)return!0}catch{}return!1}function Dw(){try{return`session-${gw()}`}catch{return`session-${Date.now()}-${_w()}`}}var Ow=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=ww(),this._storage=xw??Cw()??null,this._storageCapability=this._storage?`persistent`:`session-only`,this._source=Tw()||this._runtimeEnvironment;let e=Ew(),t=this._runtimeEnvironment!==`unknown`;e?(this._telemetryEnabled=!1,Q.debug(`Telemetry disabled via opt-out`)):t?(Q.debug(`Anonymized telemetry enabled. Set MCP_USE_ANONYMIZED_TELEMETRY=false to disable.`),this._telemetryEnabled=!0):(this._telemetryEnabled=!1,Q.debug(`Telemetry disabled - unknown environment: ${this._runtimeEnvironment}`))}get runtimeEnvironment(){return this._runtimeEnvironment}get storageCapability(){return this._storageCapability}static getInstance(){return e.instance||=new e,e.instance}setSource(e){this._source=e;try{Sw()&&localStorage.setItem(`MCP_USE_TELEMETRY_SOURCE`,e)}catch{}Q.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=gw();return this._storage.setUserId(t),this._currUserId=t,t}this._currUserId=Dw()}catch{this._currUserId=this.UNKNOWN_USER_ID}return this._currUserId}async capture(e){if(!this._telemetryEnabled)return;let t=this.userId,n={...e.properties,mcp_use_version:this._productVersion??aw(),language:`typescript`,source:this._source,runtime:this._runtimeEnvironment},r=hw({host:bw,apiKey:yw,event:e.name,distinctId:t,properties:n});this._pending.add(r),r.finally(()=>this._pending.delete(r))}async trackAgentExecution(e){this.isEnabled&&await this.capture(new sw(e))}async trackMCPClientInit(e){this.isEnabled&&await this.capture(new cw(e))}async trackConnectorInit(e){this.isEnabled&&await this.capture(new lw(e))}async trackClientAddServer(e,t){this.isEnabled&&await this.capture(new uw({serverName:e,serverConfig:t}))}async trackClientRemoveServer(e){this.isEnabled&&await this.capture(new dw({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&&hw({host:bw,apiKey:yw,event:`$identify`,distinctId:e,properties:{$set:t??{}}})}reset(){this._currUserId=null}flush(){Promise.allSettled([...this._pending])}async shutdown(){try{await Promise.allSettled([...this._pending]),Q.debug(`Telemetry fetch captures flushed`)}catch(e){Q.debug(`Error flushing telemetry captures: ${e}`)}}},kw=Ow;function Aw(e){kw.getInstance().setSource(e)}JC({addServer:(e,t)=>Ow.getInstance().trackClientAddServer(e,t).catch(()=>void 0),removeServer:e=>Ow.getInstance().trackClientRemoveServer(e).catch(()=>void 0)}),QC(e=>Ow.getInstance().trackConnectorInit(e).catch(()=>void 0));function jw(e){let t=()=>{throw Error(`Invalid url to pass to open(): ${e}`)},n;try{n=new URL(e)}catch{t()}return n.protocol!==`https:`&&n.protocol!==`http:`&&t(),n.hostname!==encodeURIComponent(n.hostname)&&t(),n.username&&=encodeURIComponent(n.username),n.password&&=encodeURIComponent(n.password),n.pathname=n.pathname.slice(0,1)+encodeURIComponent(n.pathname.slice(1)).replace(/%2f/gi,`/`),n.search=n.search.slice(0,1)+Array.from(n.searchParams.entries()).map(Mw).join(`&`),n.hash=n.hash.slice(0,1)+encodeURIComponent(n.hash.slice(1)),n.href}function Mw([e,t]){return`${encodeURIComponent(e)}${t.length>0?`=${encodeURIComponent(t)}`:``}`}var Nw=class{get(e){return localStorage.getItem(e)}set(e,t){localStorage.setItem(e,t)}remove(e){localStorage.removeItem(e)}keys(){let e=[];for(let t=0;t<localStorage.length;t++){let n=localStorage.key(t);n&&e.push(n)}return e}},Pw=class e{serverUrl;storageKeyPrefix;serverUrlHash;clientName;clientUri;logoUri;callbackUrl;clientMetadataUrl;scope;store;allowClientSecret;constructor(t,n,r){US(n.clientMetadataUrl),this.serverUrl=t,this.storageKeyPrefix=n.storageKeyPrefix||`mcp:auth`,this.serverUrlHash=e.hashString(t),this.clientName=n.clientName||`mcp-use`,this.clientUri=n.clientUri||(typeof window<`u`?window.location.origin:`https://mcp-use.com`),this.logoUri=n.logoUri||`https://mcp-use.com/logo.png`,this.callbackUrl=jw(n.callbackUrl||(typeof window<`u`?new URL(`/oauth/callback`,window.location.origin).toString():`/oauth/callback`)),this.clientMetadataUrl=n.clientMetadataUrl,this.scope=n.scope,this.store=r,this.allowClientSecret=n.allowClientSecret??!0}getKey(e){return`${this.storageKeyPrefix}_${this.serverUrlHash}_${e}`}static hashString(e){let t=0;for(let n=0;n<e.length;n++){let r=e.charCodeAt(n);t=(t<<5)-t+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 n=this.credentialKey(e,t),r=await this.store.get(n);if(!r&&t){let r=this.credentialKey(e),i=await this.store.get(r);if(i)try{let e=JSON.parse(i);if(!e.issuer||e.issuer===t.issuer){let i={...e,issuer:t.issuer},a=JSON.stringify(i);return await this.store.set(n,a),await this.store.set(r,a),{key:n,value:i}}}catch{await this.store.remove(r)}return}if(r)try{return{key:n,value:JSON.parse(r)}}catch(t){console.warn(`[${this.storageKeyPrefix}] Failed to parse ${e.replace(`_`,` `)}:`,t),await this.store.remove(n);return}}async tokens(e){return(await this.readCredential(`tokens`,e))?.value}async saveTokens(e,t){let n=JSON.stringify(e);await this.store.set(this.credentialKey(`tokens`,t),n),t&&await this.store.set(this.credentialKey(`tokens`),n),await this.store.remove(this.getKey(`code_verifier`)),await this.store.remove(this.getKey(`last_auth_url`))}async clientInformation(e){let t=await this.readCredential(`client_info`,e);if(!t)return;let{key:n,value:r}=t;try{if(!this.allowClientSecret&&r.client_secret){await this.store.remove(n),e&&await this.store.remove(this.credentialKey(`client_info`)),console.warn(`[${this.storageKeyPrefix}] Removed OAuth client information containing a browser client_secret.`);return}let t=Array.isArray(r.redirect_uris)?r.redirect_uris:[];if(!(t.length===0||t.includes(this.redirectUrl))){console.info(`[${this.storageKeyPrefix}] Invalidating cached OAuth client info due to redirect URI mismatch.`),await this.store.remove(n),await this.store.remove(this.credentialKey(`tokens`,e)),await this.store.remove(this.getKey(`last_auth_url`));return}return r}catch{await this.store.remove(n);return}}async saveClientInformation(e,t){let n=e;if(!this.allowClientSecret&&n.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(e);await this.store.set(this.credentialKey(`client_info`,t),r),t&&await this.store.set(this.credentialKey(`client_info`),r)}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}async invalidateCredentials(e){let t=async e=>{let t=`${this.getKey(e)}_`;for(let n of await this.store.keys())(n===this.getKey(e)||n.startsWith(t))&&await this.store.remove(n)};switch(e){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(`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`));break;default:break}}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 n=globalThis.crypto.randomUUID(),r=`${this.storageKeyPrefix}:state_${n}`,i={serverUrlHash:this.serverUrlHash,expiry:Date.now()+1e3*60*10,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`,n);let a=jw(e.toString());return await this.store.set(r,JSON.stringify(i)),await this.store.set(this.getKey(`last_auth_url`),a),a}async getTokenEndpoint(){return(await this.discoveryState())?.authorizationServerMetadata?.token_endpoint??null}};async function Fw(e){return typeof e==`string`?e:e instanceof URLSearchParams||e instanceof FormData?Object.fromEntries(e.entries()):e instanceof Blob?await e.text():e}var Iw=class{serverUrl;staticClientInfo;session;preventAutoAuth;useRedirectFlow;oauthProxyUrl;connectionUrl;proxyOAuthRequests;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.session=new Pw(e,{...t,allowClientSecret:!1},new Nw),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)}reanchorWellKnownUrl(e){if(!this.connectionUrl)return e;try{let t=new URL(e),n=new URL(this.connectionUrl);if(t.origin!==n.origin||!t.pathname.startsWith(`/.well-known/`))return e;let r=new URL(this.serverUrl),[i,...a]=t.pathname.slice(13).split(`/`);if(!i)return e;let o=a.length?`/${a.join(`/`)}`:``,s=n.pathname.replace(/\/+$/,``),c=r.pathname.replace(/\/+$/,``),l=o&&o===s?c:o;return`${r.origin}/.well-known/${i}${l}${t.search}`}catch{return e}}getProxyFetch(e){if(!this.proxyOAuthRequests||!this.oauthProxyUrl)return e;let t=e??globalThis.fetch.bind(globalThis),n=this.oauthProxyUrl,r=new Set,i=!1;return async(e,a)=>{let o=typeof e==`string`?e:e instanceof URL?e.toString():e.url,s=this.reanchorWellKnownUrl(o),c;try{c=new URL(s).pathname}catch{return await t(e,a)}let l=c.includes(`/.well-known/`);if(!i){i=!0;let e=(await this.discoveryState())?.authorizationServerMetadata;for(let t of[`registration_endpoint`,`token_endpoint`,`revocation_endpoint`,`introspection_endpoint`])typeof e?.[t]==`string`&&r.add(e[t])}let u=r.has(s)||/\/(?:register|registration|token|revoke|revocation|introspect|introspection)\/?$/.test(c);if(!l&&!u)return await t(e,a);try{let r=new URL(s),i=new URL(n);if(r.origin===i.origin&&(r.pathname.startsWith(i.pathname)||s.includes(`/inspector/api/oauth`)))return await t(e,a)}catch{}let d=l?`${n}/metadata?serverUrl=${encodeURIComponent(this.serverUrl)}&url=${encodeURIComponent(s)}`:`${n}/proxy`;if(l){let e=await t(d,{...a,method:`GET`});try{let t=await e.clone().json();for(let e of[`registration_endpoint`,`token_endpoint`,`revocation_endpoint`,`introspection_endpoint`])typeof t[e]==`string`&&r.add(t[e])}catch{}return e}let f=a?.body?await Fw(a.body):void 0,p=await(await t(d,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({serverUrl:this.serverUrl,url:s,method:a?.method||`POST`,headers:a?.headers?Object.fromEntries(new Headers(a.headers)):{},body:f})})).json();return new Response(JSON.stringify(p.body),{status:p.status,statusText:p.statusText,headers:new Headers(p.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.session.saveTokens(e,t)}async clientInformation(e){return this.staticClientInfo?this.staticClientInfo:this.session.clientInformation(e)}async saveClientInformation(e,t){if(!this.staticClientInfo)return this.session.saveClientInformation(e,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)}discoveryState(){return this.session.discoveryState()}getTokenEndpoint(){return this.session.getTokenEndpoint()}async getClientCredentials(){let e=await this.clientInformation();return e?.client_id?{client_id:e.client_id}:null}async prepareAuthorizationUrl(e){return 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:typeof window<`u`?window.location.href:void 0})}async redirectToAuthorization(e){let t=await this.prepareAuthorizationUrl(e);if(this.preventAutoAuth){console.info(`[${this.storageKeyPrefix}] Auto-auth prevented. Authorization URL stored for manual trigger.`);return}if(this.useRedirectFlow){console.info(`[${this.storageKeyPrefix}] Redirecting to authorization URL (full-page redirect).`),window.location.href=t;return}let n=`width=600,height=700,resizable=yes,scrollbars=yes,status=yes`;try{let e=window.open(t,`mcp_auth_${this.serverUrlHash}`,n);this.onPopupWindow&&this.onPopupWindow(t,n,e),!e||e.closed||e.closed===void 0?console.warn(`[${this.storageKeyPrefix}] Popup likely blocked by browser. Manual navigation might be required using the stored URL.`):(e.focus(),console.info(`[${this.storageKeyPrefix}] Redirecting to authorization URL in popup.`))}catch(e){console.error(`[${this.storageKeyPrefix}] Error opening popup window:`,e)}}getLastAttemptedAuthUrl(){let e=localStorage.getItem(this.getKey(`last_auth_url`));return e?jw(e):null}clearStorage(){let e=`${this.storageKeyPrefix}_${this.serverUrlHash}_`,t=`${this.storageKeyPrefix}:state_`,n=[],r=0;for(let r=0;r<localStorage.length;r++){let i=localStorage.key(r);if(i){if(i.startsWith(e))n.push(i);else if(i.startsWith(t))try{let e=localStorage.getItem(i);e&&JSON.parse(e).serverUrlHash===this.serverUrlHash&&n.push(i)}catch(e){console.warn(`[${this.storageKeyPrefix}] Error parsing state key ${i} during clearStorage:`,e)}}}return[...new Set(n)].forEach(e=>{localStorage.removeItem(e),r++}),r}};async function Lw(e,t={}){return new Iw(e,t)}var Rw=`mcp_auth_callback`,zw=`mcp_auth_callback`;function Bw(e){try{return typeof localStorage<`u`&&!!localStorage.getItem(e)}catch{return!1}}function Vw({popup:e,state:t,tokensKey:n,timeoutMs:r=5*6e4,closePollMs:i=1e3,closeGraceMs:a=2e4,expectedOrigin:o=typeof window<`u`?window.location.origin:``}){return new Promise(s=>{let c=!1,l=null,u=null,d=null,f=null,p=()=>{if(l&&=(clearInterval(l),null),u&&=(clearTimeout(u),null),d&&=(clearTimeout(d),null),typeof window<`u`&&(window.removeEventListener(`message`,g),window.removeEventListener(`storage`,v)),f){try{f.removeEventListener(`message`,_),f.close()}catch{}f=null}},m=e=>{c||(c=!0,p(),s(e))},h=e=>{!e||e.type!==zw||e.state&&t&&e.state!==t||(e.success?m({kind:`success`}):m({kind:`error`,error:e.error??`Authentication failed in callback.`}))},g=e=>{o&&e.origin!==o||h(e.data)},_=e=>{h(e.data)},v=e=>{e.key===n&&e.newValue&&m({kind:`success`})};if(typeof window<`u`&&(window.addEventListener(`message`,g),window.addEventListener(`storage`,v)),typeof BroadcastChannel<`u`)try{f=new BroadcastChannel(Rw),f.addEventListener(`message`,_)}catch{f=null}e&&(l=setInterval(()=>{if(c)return;let t=!1;try{t=e.closed}catch{t=!1}if(t){if(l&&=(clearInterval(l),null),Bw(n)){m({kind:`success`});return}d=setTimeout(()=>{m(Bw(n)?{kind:`success`}:{kind:`cancelled`})},a)}},i)),u=setTimeout(()=>{m(Bw(n)?{kind:`success`}:{kind:`timeout`})},r)})}var Hw=5*6e4;function Uw(e,t=0){if(!e||t>5)return!1;if(e instanceof xS)return!0;if(e instanceof Error){if(e.code===401||e.name===`UnauthorizedError`)return!0;let n=e.message??``;if(n.includes(`401`)||n.includes(`Unauthorized`)||e.cause&&Uw(e.cause,t+1))return!0;let r=e.data;if(r?.cause&&Uw(r.cause,t+1))return!0}return!1}async function Ww(e,t,n={}){let r=e,i=n.timeoutMs??Hw,a=n.fetchFn??r.getProxyFetch?.()??void 0;if(!r.hasPendingFlow){let n=await BS(e,{serverUrl:t,fetchFn:a});if(n===`AUTHORIZED`)return;if(n!==`REDIRECT`)throw Error(`Unexpected OAuth auth() result: ${n}`)}if(typeof r.getAuthorizationCode==`function`){await BS(e,{serverUrl:t,authorizationCode:await r.getAuthorizationCode(),fetchFn:a});return}await Gw(r,i)}async function Gw(e,t){if(typeof window>`u`)throw Error(`OAuth redirect requires a browser environment or a provider with getAuthorizationCode()`);if(e.useRedirectFlow)return;let n=e.getKey?.(`tokens`);if(!n)throw Error(`Browser OAuth provider must expose getKey() for token storage`);let r=null,i=e.getLastAttemptedAuthUrl?.();if(i)try{r=new URL(i).searchParams.get(`state`)}catch{}let a=await Vw({popup:null,state:r,tokensKey:n,timeoutMs:t});switch(a.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(a.error);default:throw Error(`Unexpected OAuth popup result`)}}var Kw=`http://json-schema.org/draft-04/schema`,qw=new Set([`http://json-schema.org/draft-07/schema`,`https://json-schema.org/draft-07/schema`]),Jw=new Set([`https://json-schema.org/draft/2019-09/schema`,`http://json-schema.org/draft/2019-09/schema`]),Yw=new Set([`https://json-schema.org/draft/2020-12/schema`,`http://json-schema.org/draft/2020-12/schema`]);function Xw(e){if(!(`$schema`in e)||typeof e.$schema!=`string`)return`2020-12`;let t=e.$schema.replace(/#$/,``);if(t===Kw)return`4`;if(qw.has(t))return`7`;if(Jw.has(t))return`2019-09`;if(Yw.has(t))return`2020-12`}var Zw=class{getValidator(e){let t=Xw(e);return(t===void 0?new Jx:new Jx({draft:t})).getValidator(e)}},Qw={"~standard":{version:1,vendor:`mcp-use`,validate:e=>({value:e})}},$w=class{client=null;connectionManager=null;toolsCache=null;capabilitiesCache=null;serverInfoCache=null;connected=!1;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){let t=this.constructor.name;$C({connectorType:t,...e})}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){Q.error(`Error in notification handler:`,e)}}async handleListChanged(e,t,n){if(t){Q.warn(`[Auto] ${e} refresh failed:`,t);return}e===`notifications/tools/list_changed`&&n&&(this.toolsCache=[...n]),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();break;default:break}await this.forwardNotification(e)};let e=this.client._notificationHandlers;for(let t of[`notifications/progress`,`notifications/cancelled`]){let n=e.get(t);n&&e.set(t,async e=>{await n(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&&typeof e==`object`&&e.method===`notifications/progress`&&this.forwardRoundProgress(e.params),await t?.(e)}}forwardRoundProgress(e){if(this.activeProgressHandlers.size===1){let[t]=this.activeProgressHandlers;t?.(e)}}async refreshToolsCache(){if(this.client)try{Q.debug(`[Auto] Refreshing tools cache due to list_changed notification`);let e=await this.client.listTools();this.toolsCache=e.tools??[],Q.debug(`[Auto] Refreshed tools cache: ${this.toolsCache.length} tools`)}catch(e){Q.warn(`[Auto] Failed to refresh tools cache:`,e)}}async onResourcesListChanged(){Q.debug(`[Auto] Resources list changed - clients should re-fetch if needed`)}async onPromptsListChanged(){Q.debug(`[Auto] Prompts list changed - clients should re-fetch if needed`)}async setRoots(e){this.rootsCache=[...e],this.client&&(Q.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()=>(Q.debug(`Server requested roots list, returning ${this.rootsCache.length} root(s)`),{roots:this.rootsCache}))}setupSamplingHandler(){if(!this.client){Q.debug(`setupSamplingHandler: No client available`);return}let e=this.opts.onSampling;if(!e){Q.debug(`setupSamplingHandler: No sampling callback provided`);return}Q.debug(`setupSamplingHandler: Setting up sampling request handler`),this.client.setRequestHandler(`sampling/createMessage`,async t=>(Q.debug(`Server requested sampling, forwarding to callback`),await e(t.params))),Q.debug(`setupSamplingHandler: Sampling handler registered successfully`)}setupElicitationHandler(){if(!this.client){Q.debug(`setupElicitationHandler: No client available`);return}let e=this.opts.onElicitation;if(!e){Q.debug(`setupElicitationHandler: No elicitation callback provided`);return}Q.debug(`setupElicitationHandler: Setting up elicitation request handler`),this.client.setRequestHandler(`elicitation/create`,async t=>(Q.debug(`Server requested elicitation, forwarding to callback`),await e(t.params))),Q.debug(`setupElicitationHandler: Elicitation handler registered successfully`)}async disconnect(){if(!this.connected){Q.debug(`Not connected to MCP implementation`);return}Q.debug(`Disconnecting from MCP implementation`),await this.cleanupResources(),this.connected=!1,Q.debug(`Disconnected from MCP implementation`)}get isClientConnected(){return this.client!=null}async initialize(e=this.opts.defaultRequestOptions??{}){if(!this.client)throw Error(`MCP client is not connected`);Q.debug(`Caching server capabilities & tools`);let t=this.client.getServerCapabilities();this.capabilitiesCache=t||null;let n=this.client.getServerVersion();this.serverInfoCache=n?{name:n.name,version:n.version,title:n.title,description:n.description,websiteUrl:n.websiteUrl,icons:n.icons}:null;try{let t=await this.client.listTools(void 0,e);this.toolsCache=t.tools??[],Q.debug(`Fetched ${this.toolsCache.length} tools from server`)}catch(e){let t=e;t.code===-32601?Q.debug(`Server does not implement tools/list, assuming no tools`):Q.debug(`Failed to list tools, assuming empty:`,t.message),this.toolsCache=[]}return Q.debug(`Server capabilities:`,t),Q.debug(`Server info:`,n),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,n){if(!this.client)throw Error(`MCP client is not connected`);let r=n?{...n}:void 0;r?.resetTimeoutOnProgress&&!r.onprogress&&(r.onprogress=()=>{},Q.debug(`[BaseConnector] Added onprogress callback for tool '${e}' to enable progressToken`)),Q.debug(`Calling tool '${e}' with args`,t);let i=r?.onprogress;i&&this.activeProgressHandlers.add(i);try{let n=await this.client.callTool({name:e,arguments:t},r);return Q.debug(`Tool '${e}' returned`,n),n}finally{i&&this.activeProgressHandlers.delete(i)}}async listTools(e){if(!this.client)throw Error(`MCP client is not connected`);Q.debug(`[listTools] Fetching fresh tools from server...`);let t=await this.client.listTools(void 0,e),n=t.tools?[...t.tools]:[];return Q.debug(`[listTools] Returned ${n.length} tools:`,n.map(e=>e.name)),n}async listResources(e,t){if(!this.client)throw Error(`MCP client is not connected`);return Q.debug(`Listing resources`,e?`with cursor: ${e}`:``),await this.client.listResources({cursor:e},t)}async listAllResources(e){if(!this.client)throw Error(`MCP client is not connected`);if(!this.capabilitiesCache?.resources)return Q.debug(`Server does not advertise resources capability, skipping`),{resources:[]};try{Q.debug(`Listing all resources (with auto-pagination)`);let t=[],n;do{let r=await this.client.listResources({cursor:n},e);t.push(...r.resources||[]),n=r.nextCursor}while(n);return{resources:t}}catch(e){if(e.code===-32601)return Q.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 Q.debug(`Listing resource templates`),await this.client.listResourceTemplates(void 0,e)}async complete(e,t){if(!this.client)throw Error(`MCP client is not connected`);Q.debug(`[complete] Requesting completions for:`,e.ref);let n=await this.client.complete(e,t);return Q.debug(`[complete] Received ${n.completion.values.length} suggestions`),n}async readResource(e,t){if(!this.client)throw Error(`MCP client is not connected`);return Q.debug(`Reading resource ${e}`),await this.client.readResource({uri:e},t)}async subscribeToResource(e,t){if(!this.client)throw Error(`MCP client is not connected`);return Q.debug(`Subscribing to resource: ${e}`),await this.client.subscribeResource({uri:e},t)}async unsubscribeFromResource(e,t){if(!this.client)throw Error(`MCP client is not connected`);return Q.debug(`Unsubscribing from resource: ${e}`),await this.client.unsubscribeResource({uri:e},t)}async listPrompts(){if(!this.client)throw Error(`MCP client is not connected`);if(!this.capabilitiesCache?.prompts)return Q.debug(`Server does not advertise prompts capability, skipping`),{prompts:[]};try{return Q.debug(`Listing prompts`),await this.client.listPrompts()}catch(e){if(e.code===-32601)return Q.debug(`Server advertised prompts but method not found`),{prompts:[]};throw e}}async getPrompt(e,t){if(!this.client)throw Error(`MCP client is not connected`);return Q.debug(`Getting prompt ${e}`),await this.client.getPrompt({name:e,arguments:t})}async request(e,t=null,n){if(!this.client)throw Error(`MCP client is not connected`);return Q.debug(`Sending raw request '${e}' with params`,t),await this.client.request({method:e,params:t??{}},Qw,n)}async cleanupResources(){let e=[];if(this.client)try{typeof this.client.close==`function`&&await this.client.close()}catch(t){let n=`Error closing client: ${t}`;Q.warn(n),e.push(n)}finally{this.client=null}if(this.connectionManager)try{await this.connectionManager.stop()}catch(t){let n=`Error stopping connection manager: ${t}`;Q.warn(n),e.push(n)}finally{this.connectionManager=null}this.toolsCache=null,e.length&&Q.warn(`Resource cleanup finished with ${e.length} issue(s)`)}};function eT(e,t=0){if(!e||t>5)return!1;if(e instanceof xS||e instanceof Z_&&e.status===401)return!0;if(e instanceof Error){if(e.cause&&eT(e.cause,t+1))return!0;let n=e instanceof X_?e.data:void 0;if(n?.cause&&eT(n.cause,t+1))return!0}return!1}function tT(e,t,n,r){let i=new URL(e),a=t.replace(/\/$/,``);return async(e,t)=>{let o=new Request(e,t),s=new URL(o.url);if(!(s.origin===i.origin&&s.pathname===i.pathname))return n(o);let c=new Headers(o.headers);c.set(`X-Target-URL`,o.url),r&&c.set(`X-Server-Id`,r);let l=o.method===`GET`||o.method===`HEAD`?void 0:await o.clone().arrayBuffer();return n(new Request(a,{method:o.method,headers:c,body:l,signal:o.signal,redirect:`manual`}))}}var nT=class extends $w{baseUrl;headers;timeout;customFetch;clientInfo;protocolNegotiation;gatewayUrl;serverId;reconnectionOptions;transportType=null;streamableTransport=null;constructor(e,t={}){super(t);let n=e.replace(/\/$/,``);this.baseUrl=n,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;let r=t.fetch??globalThis.fetch.bind(globalThis);this.customFetch=this.gatewayUrl?tT(n,this.gatewayUrl,r,this.serverId):t.fetch,this.clientInfo=t.clientInfo??{name:`http-connector`,version:`1.0.0`},this.protocolNegotiation=t.protocolNegotiation??`auto`,this.reconnectionOptions=t.reconnectionOptions}buildClientOptions(){return{...this.opts.clientOptions||{},jsonSchemaValidator:this.opts.clientOptions?.jsonSchemaValidator??new Zw,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 Z_?e:e instanceof Error&&e.cause instanceof Z_?e.cause:null}classifyStreamableHttpFailure(e){let t=`Unknown error`,n=!1,r,i=this.unwrapStreamableError(e);if(i){let e=i.status;return n=e===401,r=e,e===400&&i.message.includes(`Missing session ID`)?(t=`Server requires session ID (FastMCP compatibility)`,Q.warn(`\u26A0\uFE0F ${t}`)):e===404||e===405?(t=`Server returned ${e} - server likely doesn't support streamable HTTP`,Q.debug(t)):(t=`Server returned ${e}: ${i.message}`,Q.debug(t)),{fallbackReason:t,is401Error:n,httpStatusCode:r}}if(e instanceof Error){let r=e.toString(),i=e.message||``;n=eT(e)||r.includes(`401`)||i.includes(`Unauthorized`),r.includes(`Missing session ID`)||r.includes(`Bad Request: Missing session ID`)||i.includes(`FastMCP session ID error`)?(t=`Server requires session ID (FastMCP compatibility)`,Q.warn(`\u26A0\uFE0F ${t}`)):r.includes(`405 Method Not Allowed`)||r.includes(`404 Not Found`)?(t=`Server doesn't support streamable HTTP (405/404)`,Q.debug(t)):(t=`Streamable HTTP failed: ${e.message}`,Q.debug(t))}return{fallbackReason:t,is401Error:n,httpStatusCode:r}}async connect(){if(this.connected){Q.debug(`Already connected to MCP implementation`);return}let e=this.baseUrl;Q.debug(`Connecting to MCP implementation via HTTP: ${e}`);try{await this.connectWithStreamableHttp(e),Q.debug(`✅ Successfully connected via streamable HTTP`)}catch(e){Q.debug(`Streamable HTTP connect failed`,e);let{fallbackReason:t,is401Error:n,httpStatusCode:r}=this.classifyStreamableHttpFailure(e);if(await this.cleanupResources(),n){Q.info(`Authentication required`);let e=Error(`Authentication required`);throw e.code=401,e}let i=Error(`Could not connect via streamable HTTP: ${t}`);throw r!==void 0&&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,n]=e.body.tee();return(async()=>{let e=n.getReader(),t=new TextDecoder,r=``;try{for(;;){let{done:n,value:i}=await e.read();if(n)break;r+=t.decode(i,{stream:!0});let a=r.split(/\r?\n\r?\n/);r=a.pop()??``;for(let e of a)for(let t of e.split(/\r?\n/))if(t.startsWith(`data:`))try{let e=JSON.parse(t.slice(5).trim());e.method===`notifications/progress`&&this.forwardRoundProgress(e.params)}catch{}}}catch(e){e instanceof DOMException&&e.name===`AbortError`||Q.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{Q.debug(`[HttpConnector] Connecting with Streamable HTTP`,{baseUrl:e,originalUrl:this.baseUrl,gatewayUrl:this.gatewayUrl||`none`,authProviderUrl:this.opts.authProvider&&`serverUrl`in this.opts.authProvider&&typeof this.opts.authProvider.serverUrl==`string`?this.opts.authProvider.serverUrl:`none`,headers:this.headers});let t,n=new Promise(e=>{t=e}),r=this.customFetch??globalThis.fetch.bind(globalThis),i=new GC(new URL(e),{authProvider:this.opts.authProvider,fetch:async(e,n)=>{let i=await r(e,n),a=n?.method??(e instanceof Request?e.method:`GET`),o=new Headers(e instanceof Request?e.headers:void 0);return new Headers(n?.headers).forEach((e,t)=>{o.set(t,e)}),a.toUpperCase()===`GET`&&i.ok&&i.headers.get(`content-type`)?.includes(`text/event-stream`)&&t?.(),o.get(`mcp-method`)===`subscriptions/listen`?i:this.observeSseProgress(i)},requestInit:{headers:this.headers},reconnectionOptions:{maxReconnectionDelay:3e4,initialReconnectionDelay:1e3,reconnectionDelayGrowFactor:1.5,maxRetries:2,...this.reconnectionOptions}}),a=i;if(this.opts.wrapTransport){let e=this.baseUrl;a=this.opts.wrapTransport(a,e)}let o=this.buildClientOptions();Q.debug(`Creating Client with capabilities:`,JSON.stringify(o.capabilities,null,2)),this.client=new BC(this.clientInfo,o),this.setupRootsHandler(),this.setupSamplingHandler(),this.setupElicitationHandler(),Q.debug(`Roots/sampling/elicitation handlers registered before connect`);try{let e;if(await Promise.race([this.client.connect(a),new Promise((t,n)=>{e=setTimeout(()=>n(Error(`MCP connection timed out after ${this.timeout}ms`)),this.timeout)})]).finally(()=>{e!==void 0&&clearTimeout(e)}),(this.client.getProtocolEra?.()??`legacy`)===`legacy`&&i.sessionId){let e,t=await Promise.race([n.then(()=>!0),new Promise(t=>e=setTimeout(()=>t(!1),Math.min(this.timeout,5e3)))]);e&&clearTimeout(e),t||Q.warn(`Legacy server push stream did not attach before connect completed`)}let t=i.sessionId;t&&Q.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 n=Error(`Session ID error: ${t}. The SDK should automatically extract session ID from initialize response.`);throw n.cause=e,n}}throw e}this.streamableTransport=i,this.connectionManager={stop:async()=>{if(this.streamableTransport)try{await this.streamableTransport.close()}catch(e){Q.warn(`Error closing Streamable HTTP transport: ${e}`)}finally{this.streamableTransport=null}}},this.connected=!0,this.transportType=`streamable-http`,this.setupNotificationHandler(),Q.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&&this.protocolEra!==`modern`){let e;try{await Promise.race([this.streamableTransport.terminateSession().then(()=>!0),new Promise(t=>e=setTimeout(()=>t(!1),Math.min(this.timeout,5e3)))])||Q.debug(`Timed out terminating legacy HTTP session; closing transport`)}catch(e){Q.debug(`Error terminating Streamable HTTP session: ${e}`)}finally{e&&clearTimeout(e)}}await super.cleanupResources()}};function rT(e,t){return{onSampling:e?.onSampling??t?.onSampling,onElicitation:e?.onElicitation??t?.onElicitation,onNotification:e?.onNotification??t?.onNotification}}function iT(e){if(!(`url`in e)||typeof e.url!=`string`||e.authProvider||e.authToken||e.oauth===!1)return!1;let t=e.headers;if(t){for(let e of Object.keys(t))if(e.toLowerCase()===`authorization`)return!1}return!0}function aT(){return{name:`mcp-use`,title:`mcp-use`,version:aw(),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`}}function oT(e){let t=aT();if(!e||typeof e!=`object`)return t;let n=e;return!n.name||!n.version?t:{...t,...n}}var sT=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){e===`notification`&&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 protocolEra(){return this.connector.protocolEra}get negotiatedProtocolVersion(){return this.connector.negotiatedProtocolVersion}get info(){let e=this.protocolEra,t=this.negotiatedProtocolVersion,n=this.serverInfo;if(!e||!t||!n)throw Error(`MCP connection is not initialized`);let r=this.serverCapabilities,i=r.extensions&&typeof r.extensions==`object`&&!Array.isArray(r.extensions)?r.extensions:{};return{protocolEra:e,protocolVersion:t,server:n,capabilities:r,instructions:this.connector.instructions,extensions:i}}supports(e){return e in this.serverCapabilities}async callTool(e,t={},n){return this.connector.callTool(e,t,n)}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){return this.connector.getPrompt(e,t)}async request(e,t=null,n){return this.connector.request(e,t,n)}};function cT(e){return!!e&&typeof e==`object`&&`redirectUrl`in e&&`clientMetadata`in e}var lT=class{config={};sessions={};activeSessions=[];constructor(e){e&&(this.config=e)}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,YC(e,t)}async removeServer(e){this.config.mcpServers?.[e]&&(await this.closeSession(e),delete this.config.mcpServers[e],XC(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 n=this.config.mcpServers??{};if(Object.keys(n).length===0&&Q.warn(`No MCP servers defined in config`),!n[e])throw Error(`Server '${e}' not found in config`);let r={...n[e]},i;if(iT(r)){let e=r.oauth===!1?void 0:r.oauth??{};i=await this.createDefaultOAuthProvider(r.url,e),r={...r,authProvider:i}}else `authProvider`in r&&r.authProvider&&cT(r.authProvider)&&(i=r.authProvider);let a=async()=>{let e=new sT(await Promise.resolve(this.createConnectorFromConfig(r)));return t&&await e.initialize(),e},o;try{o=await a()}catch(n){let s=r;if(!t||!i||!(`url`in s)||!Uw(n)||i.preventAutoAuth)throw n;Q.info(`[MCPClient] Unauthorized connecting to '${e}'; completing OAuth\u2026`),await Ww(i,s.url),o=await a()}return this.sessions[e]=o,this.activeSessions.includes(e)||this.activeSessions.push(e),o}async connect(e){return this.createSession(e)}async createAllSessions(e=!0){let t=this.config.mcpServers??{};Object.keys(t).length===0&&Q.warn(`No MCP servers defined in config`);for(let n of Object.keys(t))await this.createSession(n,e);return this.sessions}async connectAll(){return this.createAllSessions()}getSession(e){return this.sessions[e]||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){Q.warn(`No session exists for server ${e}, nothing to close`);return}try{Q.debug(`Closing session for server ${e}`),await t.disconnect()}catch(t){Q.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 n of e)try{Q.debug(`Closing session for server ${n}`),await this.closeSession(n)}catch(e){let r=`Failed to close session for server '${n}': ${e}`;Q.error(r),t.push(r)}t.length?Q.error(`Encountered ${t.length} errors while closing sessions`):Q.debug(`All sessions closed successfully`)}async close(){await this.closeAllSessions()}};function uT(e){let t=Object.keys(e.mcpServers??{});kw.getInstance().trackMCPClientInit({codeMode:!1,sandbox:!1,allCallbacks:!1,verify:!1,servers:t,numServers:t.length,isBrowser:!0}).catch(e=>Q.debug(`Failed to track BrowserMCPClient init: ${e}`))}var dT=class e extends lT{static getPackageVersion(){return aw()}constructor(e){super(e),uT(this.config)}static fromDict(t){return new e(t)}async createDefaultOAuthProvider(e,t={}){return Lw(e,t)}createConnectorFromConfig(e){let{url:t,headers:n,fetch:r,authToken:i,authProvider:a,wrapTransport:o,clientOptions:s,protocolNegotiation:c,timeout:l,gatewayUrl:u,serverId:d,reconnectionOptions:f}=e;if(!t)throw Error(`Server URL is required`);let p=this.config,m=rT(e,p),h=oT(e.clientInfo??this.config.clientInfo),g={headers:n,fetch:r??globalThis.fetch.bind(globalThis),authToken:i,authProvider:a,wrapTransport:o,clientOptions:s,onSampling:m.onSampling,onElicitation:m.onElicitation,onNotification:m.onNotification,protocolNegotiation:c,timeout:l,clientInfo:h,gatewayUrl:u,serverId:d,reconnectionOptions:f};return Q.debug(`[BrowserMCPClient] Connector options prepared (clientOptions: ${s?`provided`:`none`})`),new nT(t,g)}},fT=`mcp_inspector_telemetry_disabled`,pT=`mcp_inspector_telemetry_user_id`,mT=`MCP_USE_ANONYMIZED_TELEMETRY`,hT=`mcp_use_user_id`;function gT(){return typeof localStorage<`u`&&typeof localStorage.getItem==`function`&&typeof localStorage.setItem==`function`}function _T(){if(gT())try{if(localStorage.getItem(fT)===`true`&&localStorage.getItem(mT)!==`false`&&localStorage.setItem(mT,`false`),!localStorage.getItem(hT)){let e=localStorage.getItem(pT);e&&localStorage.setItem(hT,e)}}catch{}}function vT(){_T(),Aw(`inspector`),kw.getInstance().setProductVersion(Lo())}function yT(){if(typeof window>`u`)return`standalone`;let e=window.__MCP_INSPECTOR_MODE__;return e===`standalone`||e===`embedded`||e===`cloud`?e:`standalone`}async function bT(e){await kw.getInstance().capture({name:e.name,properties:{...e.properties,package:`inspector`,mode:yT()}})}async function xT(e){await bT(new xo(e))}var ST=`io.modelcontextprotocol/related-task`,CT=`io.modelcontextprotocol/subscriptionId`,wT=lm(()=>J([V(),H(),U(),Tp(),Y(V(),wT),G(wT)])),TT=Y(V(),wT),ET=J([V(),H().int()]),DT=V(),OT=K({ttl:H().optional()}),kT=K({taskId:V()}),AT=q({progressToken:ET.optional(),[ST]:kT.optional()}),jT=K({_meta:AT.optional()}),MT=jT.extend({task:OT.optional()}),NT=K({method:V(),params:jT.loose().optional()}),PT=K({_meta:AT.optional()}),FT=K({method:V(),params:PT.loose().optional()}),IT=q({_meta:AT.optional()}),LT=J([V(),H().int()]),RT=K({jsonrpc:X(`2.0`),id:LT,...NT.shape}).strict(),zT=K({jsonrpc:X(`2.0`),...FT.shape}).strict(),BT=K({jsonrpc:X(`2.0`),id:LT,result:IT}).strict(),VT=K({jsonrpc:X(`2.0`),id:LT.optional(),error:K({code:H().int(),message:V(),data:W().optional()})}).strict(),HT=J([RT,zT,BT,VT]);J([BT,VT]);var UT=IT.strict(),WT=PT.extend({requestId:LT.optional(),reason:V().optional()}),GT=FT.extend({method:X(`notifications/cancelled`),params:WT}),KT=K({icons:G(K({src:V(),mimeType:V().optional(),sizes:G(V()).optional(),theme:Bp([`light`,`dark`]).optional()})).optional()}),qT=K({name:V(),title:V().optional()}),JT=qT.extend({...qT.shape,...KT.shape,version:V(),websiteUrl:V().optional(),description:V().optional()}),YT=pm(e=>e&&typeof e==`object`&&!Array.isArray(e)&&Object.keys(e).length===0?{form:{}}:e,Lp(K({form:Lp(K({applyDefaults:U().optional()}),TT).optional(),url:TT.optional()}),TT.optional())),XT=q({list:TT.optional(),cancel:TT.optional(),requests:q({sampling:q({createMessage:TT.optional()}).optional(),elicitation:q({create:TT.optional()}).optional()}).optional()}),ZT=q({list:TT.optional(),cancel:TT.optional(),requests:q({tools:q({call:TT.optional()}).optional()}).optional()}),QT=K({experimental:Y(V(),TT).optional(),sampling:K({context:TT.optional(),tools:TT.optional()}).optional(),elicitation:YT.optional(),roots:K({listChanged:U().optional()}).optional(),tasks:XT.optional(),extensions:Y(V(),TT).optional()}),$T=jT.extend({protocolVersion:V(),capabilities:QT,clientInfo:JT}),eE=NT.extend({method:X(`initialize`),params:$T}),tE=K({experimental:Y(V(),TT).optional(),logging:TT.optional(),completions:TT.optional(),prompts:K({listChanged:U().optional()}).optional(),resources:K({subscribe:U().optional(),listChanged:U().optional()}).optional(),tools:K({listChanged:U().optional()}).optional(),tasks:ZT.optional(),extensions:Y(V(),TT).optional()}),nE=IT.extend({protocolVersion:V(),capabilities:tE,serverInfo:JT,instructions:V().optional()}),rE=FT.extend({method:X(`notifications/initialized`),params:PT.optional()}),iE=NT.extend({method:X(`server/discover`),params:jT.optional()}),aE=IT.extend({supportedVersions:G(V()),capabilities:tE,serverInfo:JT,instructions:V().optional()}),oE=NT.extend({method:X(`ping`),params:jT.optional()}),sE=K({progress:H(),total:Z(H()),message:Z(V())}),cE=K({...PT.shape,...sE.shape,progressToken:ET}),lE=FT.extend({method:X(`notifications/progress`),params:cE}),uE=jT.extend({cursor:DT.optional()}),dE=NT.extend({params:uE.optional()}),fE=IT.extend({nextCursor:DT.optional()}),pE=K({uri:V(),mimeType:Z(V()),_meta:Y(V(),W()).optional()}),mE=pE.extend({text:V()}),hE=V().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:`Invalid Base64 string`}),gE=pE.extend({blob:hE}),_E=Bp([`user`,`assistant`]),vE=K({audience:G(_E).optional(),priority:H().min(0).max(1).optional(),lastModified:Tf({offset:!0}).optional()}),yE=K({...qT.shape,...KT.shape,uri:V(),description:Z(V()),mimeType:Z(V()),size:Z(H()),annotations:vE.optional(),_meta:Z(q({}))}),bE=K({...qT.shape,...KT.shape,uriTemplate:V(),description:Z(V()),mimeType:Z(V()),annotations:vE.optional(),_meta:Z(q({}))}),xE=dE.extend({method:X(`resources/list`)}),SE=fE.extend({resources:G(yE)}),CE=dE.extend({method:X(`resources/templates/list`)}),wE=fE.extend({resourceTemplates:G(bE)}),TE=jT.extend({uri:V()}),EE=TE,DE=NT.extend({method:X(`resources/read`),params:EE}),OE=IT.extend({contents:G(J([mE,gE]))}),kE=FT.extend({method:X(`notifications/resources/list_changed`),params:PT.optional()}),AE=TE,jE=NT.extend({method:X(`resources/subscribe`),params:AE}),ME=TE,NE=NT.extend({method:X(`resources/unsubscribe`),params:ME}),PE=K({toolsListChanged:U().optional(),promptsListChanged:U().optional(),resourcesListChanged:U().optional(),resourceSubscriptions:G(V()).optional()}),FE=jT.extend({notifications:PE}),IE=NT.extend({method:X(`subscriptions/listen`),params:FE}),LE=PT.extend({notifications:PE}),RE=FT.extend({method:X(`notifications/subscriptions/acknowledged`),params:LE}),zE=q({[CT]:LT}),BE=IT.extend({_meta:zE}),VE=PT.extend({uri:V()}),HE=FT.extend({method:X(`notifications/resources/updated`),params:VE}),UE=K({name:V(),description:Z(V()),required:Z(U())}),WE=K({...qT.shape,...KT.shape,description:Z(V()),arguments:Z(G(UE)),_meta:Z(q({}))}),GE=dE.extend({method:X(`prompts/list`)}),KE=fE.extend({prompts:G(WE)}),qE=jT.extend({name:V(),arguments:Y(V(),V()).optional()}),JE=NT.extend({method:X(`prompts/get`),params:qE}),YE=K({type:X(`text`),text:V(),annotations:vE.optional(),_meta:Y(V(),W()).optional()}),XE=K({type:X(`image`),data:hE,mimeType:V(),annotations:vE.optional(),_meta:Y(V(),W()).optional()}),ZE=K({type:X(`audio`),data:hE,mimeType:V(),annotations:vE.optional(),_meta:Y(V(),W()).optional()}),QE=K({type:X(`tool_use`),name:V(),id:V(),input:Y(V(),W()),_meta:Y(V(),W()).optional()}),$E=K({type:X(`resource`),resource:J([mE,gE]),annotations:vE.optional(),_meta:Y(V(),W()).optional()}),eD=yE.extend({type:X(`resource_link`)}),tD=J([YE,XE,ZE,eD,$E]),nD=K({role:_E,content:tD}),rD=IT.extend({description:V().optional(),messages:G(nD)}),iD=FT.extend({method:X(`notifications/prompts/list_changed`),params:PT.optional()}),aD=K({title:V().optional(),readOnlyHint:U().optional(),destructiveHint:U().optional(),idempotentHint:U().optional(),openWorldHint:U().optional()}),oD=K({taskSupport:Bp([`required`,`optional`,`forbidden`]).optional()}),sD=K({...qT.shape,...KT.shape,description:V().optional(),inputSchema:K({type:X(`object`),properties:Y(V(),wT).optional(),required:G(V()).optional()}).catchall(W()),outputSchema:q({$schema:V().optional()}).optional(),annotations:aD.optional(),execution:oD.optional(),_meta:Y(V(),W()).optional()}),cD=dE.extend({method:X(`tools/list`)}),lD=fE.extend({tools:G(sD)}),uD=IT.extend({content:G(tD).default([]),structuredContent:W().optional(),isError:U().optional()});uD.or(IT.extend({toolResult:W()}));var dD=MT.extend({name:V(),arguments:Y(V(),W()).optional()}),fD=NT.extend({method:X(`tools/call`),params:dD}),pD=FT.extend({method:X(`notifications/tools/list_changed`),params:PT.optional()});K({autoRefresh:U().default(!0),debounceMs:H().int().nonnegative().default(300)});var mD=Bp([`debug`,`info`,`notice`,`warning`,`error`,`critical`,`alert`,`emergency`]),hD=jT.extend({level:mD}),gD=NT.extend({method:X(`logging/setLevel`),params:hD}),_D=PT.extend({level:mD,logger:V().optional(),data:W()}),vD=FT.extend({method:X(`notifications/message`),params:_D}),yD=K({hints:G(K({name:V().optional()})).optional(),costPriority:H().min(0).max(1).optional(),speedPriority:H().min(0).max(1).optional(),intelligencePriority:H().min(0).max(1).optional()}),bD=K({mode:Bp([`auto`,`required`,`none`]).optional()}),xD=K({type:X(`tool_result`),toolUseId:V().describe(`The unique identifier for the corresponding tool call.`),content:G(tD),structuredContent:W().optional(),isError:U().optional(),_meta:Y(V(),W()).optional()}),SD=Fp(`type`,[YE,XE,ZE]),CD=Fp(`type`,[YE,XE,ZE,QE,xD]),wD=K({role:_E,content:J([CD,G(CD)]),_meta:Y(V(),W()).optional()}),TD=MT.extend({messages:G(wD),modelPreferences:yD.optional(),systemPrompt:V().optional(),includeContext:Bp([`none`,`thisServer`,`allServers`]).optional(),temperature:H().optional(),maxTokens:H().int(),stopSequences:G(V()).optional(),metadata:TT.optional(),tools:G(sD).optional(),toolChoice:bD.optional()}),ED=NT.extend({method:X(`sampling/createMessage`),params:TD}),DD=IT.extend({model:V(),stopReason:Z(Bp([`endTurn`,`stopSequence`,`maxTokens`]).or(V())),role:_E,content:SD}),OD=IT.extend({model:V(),stopReason:Z(Bp([`endTurn`,`stopSequence`,`maxTokens`,`toolUse`]).or(V())),role:_E,content:J([CD,G(CD)])}),kD=K({type:X(`boolean`),title:V().optional(),description:V().optional(),default:U().optional()}),AD=K({type:X(`string`),title:V().optional(),description:V().optional(),minLength:H().optional(),maxLength:H().optional(),format:Bp([`email`,`uri`,`date`,`date-time`]).optional(),default:V().optional()}),jD=K({type:Bp([`number`,`integer`]),title:V().optional(),description:V().optional(),minimum:H().optional(),maximum:H().optional(),default:H().optional()}),MD=K({type:X(`string`),title:V().optional(),description:V().optional(),enum:G(V()),default:V().optional()}),ND=K({type:X(`string`),title:V().optional(),description:V().optional(),oneOf:G(K({const:V(),title:V()})),default:V().optional()}),PD=J([J([K({type:X(`string`),title:V().optional(),description:V().optional(),enum:G(V()),enumNames:G(V()).optional(),default:V().optional()}),J([MD,ND]),J([K({type:X(`array`),title:V().optional(),description:V().optional(),minItems:H().optional(),maxItems:H().optional(),items:K({type:X(`string`),enum:G(V())}),default:G(V()).optional()}),K({type:X(`array`),title:V().optional(),description:V().optional(),minItems:H().optional(),maxItems:H().optional(),items:K({anyOf:G(K({const:V(),title:V()}))}),default:G(V()).optional()})])]),kD,AD,jD]),FD=J([MT.extend({mode:X(`form`).optional(),message:V(),requestedSchema:K({type:X(`object`),properties:Y(V(),PD),required:G(V()).optional()}).catchall(W())}),MT.extend({mode:X(`url`),message:V(),elicitationId:V(),url:V().url()})]),ID=NT.extend({method:X(`elicitation/create`),params:FD}),LD=PT.extend({elicitationId:V()}),RD=FT.extend({method:X(`notifications/elicitation/complete`),params:LD}),zD=IT.extend({action:Bp([`accept`,`decline`,`cancel`]),content:pm(e=>e===null?void 0:e,Y(V(),J([V(),H(),U(),G(V())])).optional())}),BD=K({type:X(`ref/resource`),uri:V()}),VD=K({type:X(`ref/prompt`),name:V()}),HD=jT.extend({ref:J([VD,BD]),argument:K({name:V(),value:V()}),context:K({arguments:Y(V(),V()).optional()}).optional()}),UD=NT.extend({method:X(`completion/complete`),params:HD}),WD=IT.extend({completion:q({values:G(V()).max(100),total:Z(H().int()),hasMore:Z(U())})}),GD=K({uri:V().startsWith(`file://`),name:V().optional(),_meta:Y(V(),W()).optional()}),KD=NT.extend({method:X(`roots/list`),params:jT.optional()}),qD=IT.extend({roots:G(GD)}),JD=FT.extend({method:X(`notifications/roots/list_changed`),params:PT.optional()});q({ttl:H().optional(),pollInterval:H().optional()});var YD=Bp([`working`,`input_required`,`completed`,`failed`,`cancelled`]),XD=K({taskId:V(),status:YD,ttl:J([H(),Tp()]),createdAt:V(),lastUpdatedAt:V(),pollInterval:Z(H()),statusMessage:Z(V())});IT.extend({task:XD});var ZD=PT.merge(XD);FT.extend({method:X(`notifications/tasks/status`),params:ZD}),NT.extend({method:X(`tasks/get`),params:jT.extend({taskId:V()})}),IT.merge(XD),NT.extend({method:X(`tasks/result`),params:jT.extend({taskId:V()})}),IT.loose(),dE.extend({method:X(`tasks/list`)}),fE.extend({tasks:G(XD)}),NT.extend({method:X(`tasks/cancel`),params:jT.extend({taskId:V()})}),IT.merge(XD),J([oE,eE,iE,UD,gD,JE,GE,xE,CE,DE,jE,NE,IE,fD,cD]),J([GT,lE,rE,JD]),J([UT,DD,OD,zD,qD]),J([oE,ED,ID,KD]),J([GT,lE,vD,HE,kE,pD,iD,RE,RD]),J([UT,nE,aE,WD,rD,KE,SE,wE,OE,uD,lD,BE]);var QD=np().superRefine((e,t)=>{if(!URL.canParse(e))return t.addIssue({code:mm.custom,message:`URL must be parseable`,fatal:!0}),Yo}).refine(e=>{let t=new URL(e);return t.protocol!==`javascript:`&&t.protocol!==`data:`&&t.protocol!==`vbscript:`},{message:`URL cannot use javascript:, data:, or vbscript: scheme`});q({resource:V().url(),authorization_servers:G(QD).optional(),jwks_uri:V().url().optional(),scopes_supported:G(V()).optional(),bearer_methods_supported:G(V()).optional(),resource_signing_alg_values_supported:G(V()).optional(),resource_name:V().optional(),resource_documentation:V().optional(),resource_policy_uri:V().url().optional(),resource_tos_uri:V().url().optional(),tls_client_certificate_bound_access_tokens:U().optional(),authorization_details_types_supported:G(V()).optional(),dpop_signing_alg_values_supported:G(V()).optional(),dpop_bound_access_tokens_required:U().optional()});var $D=q({issuer:V(),authorization_endpoint:QD,token_endpoint:QD,registration_endpoint:QD.optional(),scopes_supported:G(V()).optional(),response_types_supported:G(V()),response_modes_supported:G(V()).optional(),grant_types_supported:G(V()).optional(),token_endpoint_auth_methods_supported:G(V()).optional(),token_endpoint_auth_signing_alg_values_supported:G(V()).optional(),service_documentation:QD.optional(),revocation_endpoint:QD.optional(),revocation_endpoint_auth_methods_supported:G(V()).optional(),revocation_endpoint_auth_signing_alg_values_supported:G(V()).optional(),introspection_endpoint:V().optional(),introspection_endpoint_auth_methods_supported:G(V()).optional(),introspection_endpoint_auth_signing_alg_values_supported:G(V()).optional(),code_challenge_methods_supported:G(V()).optional(),client_id_metadata_document_supported:U().optional(),authorization_response_iss_parameter_supported:U().optional().catch(void 0)});K({...q({issuer:V(),authorization_endpoint:QD,token_endpoint:QD,userinfo_endpoint:QD.optional(),jwks_uri:QD,registration_endpoint:QD.optional(),scopes_supported:G(V()).optional(),response_types_supported:G(V()),response_modes_supported:G(V()).optional(),grant_types_supported:G(V()).optional(),acr_values_supported:G(V()).optional(),subject_types_supported:G(V()),id_token_signing_alg_values_supported:G(V()),id_token_encryption_alg_values_supported:G(V()).optional(),id_token_encryption_enc_values_supported:G(V()).optional(),userinfo_signing_alg_values_supported:G(V()).optional(),userinfo_encryption_alg_values_supported:G(V()).optional(),userinfo_encryption_enc_values_supported:G(V()).optional(),request_object_signing_alg_values_supported:G(V()).optional(),request_object_encryption_alg_values_supported:G(V()).optional(),request_object_encryption_enc_values_supported:G(V()).optional(),token_endpoint_auth_methods_supported:G(V()).optional(),token_endpoint_auth_signing_alg_values_supported:G(V()).optional(),display_values_supported:G(V()).optional(),claim_types_supported:G(V()).optional(),claims_supported:G(V()).optional(),service_documentation:V().optional(),claims_locales_supported:G(V()).optional(),ui_locales_supported:G(V()).optional(),claims_parameter_supported:U().optional(),request_parameter_supported:U().optional(),request_uri_parameter_supported:U().optional(),require_request_uri_registration:U().optional(),op_policy_uri:QD.optional(),op_tos_uri:QD.optional(),client_id_metadata_document_supported:U().optional(),authorization_response_iss_parameter_supported:U().optional().catch(void 0)}).shape,...$D.pick({code_challenge_methods_supported:!0}).shape}),K({access_token:V(),id_token:V().optional(),token_type:V(),expires_in:gm().optional(),scope:V().optional(),refresh_token:V().optional()}).strip(),K({issued_token_type:X(`urn:ietf:params:oauth:token-type:id-jag`),access_token:V(),token_type:V().optional(),expires_in:H().optional(),scope:V().optional()}).strip(),K({error:V(),error_description:V().optional(),error_uri:V().optional()});var eO=QD.optional().or(X(``).transform(()=>void 0)),tO=K({redirect_uris:G(QD),token_endpoint_auth_method:V().optional(),grant_types:G(V()).optional(),response_types:G(V()).optional(),application_type:V().optional(),client_name:V().optional(),client_uri:QD.optional(),logo_uri:eO,scope:V().optional(),contacts:G(V()).optional(),tos_uri:eO,policy_uri:V().optional(),jwks_uri:QD.optional(),jwks:Dp().optional(),software_id:V().optional(),software_version:V().optional(),software_statement:V().optional()}).strip(),nO=K({client_id:V(),client_secret:V().optional(),client_id_issued_at:H().optional(),client_secret_expires_at:H().optional()}).strip();tO.merge(nO),K({error:V(),error_description:V().optional()}).strip(),K({token:V(),token_type_hint:V().optional()}).strip(),(t=>typeof e<`u`?e:typeof Proxy<`u`?new Proxy(t,{get:(t,n)=>(typeof e<`u`?e:t)[n]}):t)(function(t){if(typeof e<`u`)return e.apply(this,arguments);throw Error(`Dynamic require of "`+t+`" is not supported`)});var rO=class{_eventSlots=new Map;setHandler(e,t){let n=this._ensureEventSlot(e);n.onHandler&&t&&console.warn(`[MCP Apps] on${String(e)} handler replaced. Use addEventListener("${String(e)}", …) to add multiple listeners without replacing.`),n.onHandler=t}getHandler(e){return this._eventSlots.get(e)?.onHandler}addEventListener(e,t){this._ensureEventSlot(e).listeners.push(t)}removeEventListener(e,t){let n=this._eventSlots.get(e);if(!n)return;let r=n.listeners.indexOf(t);r!==-1&&n.listeners.splice(r,1)}dispatch(e,t){let n=this._eventSlots.get(e);if(n){n.onHandler?.(t);for(let e of[...n.listeners])e(t)}}_ensureEventSlot(e){let t=this._eventSlots.get(e);return t||(t={listeners:[]},this._eventSlots.set(e,t)),t}},iO=`2026-01-26`,aO=J([X(`light`),X(`dark`)]).describe(`Color theme preference for the host environment.`),oO=J([X(`inline`),X(`fullscreen`),X(`pip`)]).describe(`Display mode for UI presentation.`),sO=Y(J([X(`--color-background-primary`),X(`--color-background-secondary`),X(`--color-background-tertiary`),X(`--color-background-inverse`),X(`--color-background-ghost`),X(`--color-background-info`),X(`--color-background-danger`),X(`--color-background-success`),X(`--color-background-warning`),X(`--color-background-disabled`),X(`--color-text-primary`),X(`--color-text-secondary`),X(`--color-text-tertiary`),X(`--color-text-inverse`),X(`--color-text-ghost`),X(`--color-text-info`),X(`--color-text-danger`),X(`--color-text-success`),X(`--color-text-warning`),X(`--color-text-disabled`),X(`--color-border-primary`),X(`--color-border-secondary`),X(`--color-border-tertiary`),X(`--color-border-inverse`),X(`--color-border-ghost`),X(`--color-border-info`),X(`--color-border-danger`),X(`--color-border-success`),X(`--color-border-warning`),X(`--color-border-disabled`),X(`--color-ring-primary`),X(`--color-ring-secondary`),X(`--color-ring-inverse`),X(`--color-ring-info`),X(`--color-ring-danger`),X(`--color-ring-success`),X(`--color-ring-warning`),X(`--font-sans`),X(`--font-mono`),X(`--font-weight-normal`),X(`--font-weight-medium`),X(`--font-weight-semibold`),X(`--font-weight-bold`),X(`--font-text-xs-size`),X(`--font-text-sm-size`),X(`--font-text-md-size`),X(`--font-text-lg-size`),X(`--font-heading-xs-size`),X(`--font-heading-sm-size`),X(`--font-heading-md-size`),X(`--font-heading-lg-size`),X(`--font-heading-xl-size`),X(`--font-heading-2xl-size`),X(`--font-heading-3xl-size`),X(`--font-text-xs-line-height`),X(`--font-text-sm-line-height`),X(`--font-text-md-line-height`),X(`--font-text-lg-line-height`),X(`--font-heading-xs-line-height`),X(`--font-heading-sm-line-height`),X(`--font-heading-md-line-height`),X(`--font-heading-lg-line-height`),X(`--font-heading-xl-line-height`),X(`--font-heading-2xl-line-height`),X(`--font-heading-3xl-line-height`),X(`--border-radius-xs`),X(`--border-radius-sm`),X(`--border-radius-md`),X(`--border-radius-lg`),X(`--border-radius-xl`),X(`--border-radius-full`),X(`--border-width-regular`),X(`--shadow-hairline`),X(`--shadow-sm`),X(`--shadow-md`),X(`--shadow-lg`)]).describe(`CSS variable keys available to MCP apps for theming.`).describe(`Style variables for theming MCP apps.
|
|
158
158
|
|
|
159
159
|
Individual style keys are optional - hosts may provide any subset of these values.
|
|
160
160
|
Values are strings containing CSS values (colors, sizes, font stacks, etc.).
|
|
@@ -172,10 +172,10 @@ Individual style keys are optional - hosts may provide any subset of these value
|
|
|
172
172
|
Values are strings containing CSS values (colors, sizes, font stacks, etc.).
|
|
173
173
|
|
|
174
174
|
Note: This type uses \`Record<K, string | undefined>\` rather than \`Partial<Record<K, string>>\`
|
|
175
|
-
for compatibility with Zod schema generation. Both are functionally equivalent for validation.`),
|
|
175
|
+
for compatibility with Zod schema generation. Both are functionally equivalent for validation.`),cO=K({method:X(`ui/open-link`),params:K({url:V().describe(`URL to open in the host's browser`)})}),lO=K({isError:U().optional().describe(`True if the host failed to open the URL (e.g., due to security policy).`)}).passthrough(),uO=K({isError:U().optional().describe(`True if the download failed (e.g., user cancelled or host denied).`)}).passthrough(),dO=K({isError:U().optional().describe(`True if the host rejected or failed to deliver the message.`)}).passthrough(),fO=K({method:X(`ui/notifications/sandbox-proxy-ready`),params:K({})}),pO=K({connectDomains:G(V()).optional().describe(`Origins for network requests (fetch/XHR/WebSocket).
|
|
176
176
|
|
|
177
177
|
- Maps to CSP \`connect-src\` directive
|
|
178
|
-
- Empty or omitted → no network connections (secure default)`),resourceDomains:G(V()).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:G(V()).optional().describe("Origins for nested iframes.\n\n- Maps to CSP `frame-src` directive\n- Empty or omitted → no nested iframes allowed (`frame-src 'none'`)"),baseUriDomains:G(V()).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'`)")}),
|
|
178
|
+
- Empty or omitted → no network connections (secure default)`),resourceDomains:G(V()).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:G(V()).optional().describe("Origins for nested iframes.\n\n- Maps to CSP `frame-src` directive\n- Empty or omitted → no nested iframes allowed (`frame-src 'none'`)"),baseUriDomains:G(V()).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'`)")}),mO=K({camera:K({}).optional().describe(`Request camera access.
|
|
179
179
|
|
|
180
180
|
Maps to Permission Policy \`camera\` feature.`),microphone:K({}).optional().describe(`Request microphone access.
|
|
181
181
|
|
|
@@ -183,7 +183,7 @@ Maps to Permission Policy \`microphone\` feature.`),geolocation:K({}).optional()
|
|
|
183
183
|
|
|
184
184
|
Maps to Permission Policy \`geolocation\` feature.`),clipboardWrite:K({}).optional().describe(`Request clipboard write access.
|
|
185
185
|
|
|
186
|
-
Maps to Permission Policy \`clipboard-write\` feature.`)}),
|
|
186
|
+
Maps to Permission Policy \`clipboard-write\` feature.`)}),hO=K({method:X(`ui/notifications/size-changed`),params:K({width:H().optional().describe(`New width in pixels.`),height:H().optional().describe(`New height in pixels.`)})});K({method:X(`ui/notifications/tool-input`),params:K({arguments:Y(V(),W().describe(`Complete tool call arguments as key-value pairs.`)).optional().describe(`Complete tool call arguments as key-value pairs.`)})}),K({method:X(`ui/notifications/tool-input-partial`),params:K({arguments:Y(V(),W().describe(`Partial tool call arguments (incomplete, may change).`)).optional().describe(`Partial tool call arguments (incomplete, may change).`)})}),K({method:X(`ui/notifications/tool-cancelled`),params:K({reason:V().optional().describe(`Optional reason for the cancellation (e.g., "user action", "timeout").`)})});var gO=K({fonts:V().optional()}),_O=K({variables:sO.optional().describe(`CSS variables for theming the app.`),css:gO.optional().describe(`CSS blocks that apps can inject.`)});K({method:X(`ui/resource-teardown`),params:K({})});var vO=Y(V(),W()),yO=K({text:K({}).optional().describe(`Host supports text content blocks.`),image:K({}).optional().describe(`Host supports image content blocks.`),audio:K({}).optional().describe(`Host supports audio content blocks.`),resource:K({}).optional().describe(`Host supports resource content blocks.`),resourceLink:K({}).optional().describe(`Host supports resource link content blocks.`),structuredContent:K({}).optional().describe(`Host supports structured content.`)}),bO=K({method:X(`ui/notifications/request-teardown`),params:K({}).optional()}),xO=K({experimental:K({}).optional().describe(`Experimental features (structure TBD).`),openLinks:K({}).optional().describe(`Host supports opening external URLs.`),downloadFile:K({}).optional().describe(`Host supports file downloads via ui/download-file.`),serverTools:K({listChanged:U().optional().describe(`Host supports tools/list_changed notifications.`)}).optional().describe(`Host can proxy tool calls to the MCP server.`),serverResources:K({listChanged:U().optional().describe(`Host supports resources/list_changed notifications.`)}).optional().describe(`Host can proxy resource reads to the MCP server.`),logging:K({}).optional().describe(`Host accepts log messages.`),sandbox:K({permissions:mO.optional().describe(`Permissions granted by the host (camera, microphone, geolocation).`),csp:pO.optional().describe(`CSP domains approved by the host.`)}).optional().describe(`Sandbox configuration applied by the host.`),updateModelContext:yO.optional().describe(`Host accepts context updates (ui/update-model-context) to be included in the model's context for future turns.`),message:yO.optional().describe(`Host supports receiving content messages (ui/message) from the view.`),sampling:K({tools:K({}).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.")}),SO=K({experimental:K({}).optional().describe(`Experimental features (structure TBD).`),tools:K({listChanged:U().optional().describe(`App supports tools/list_changed notifications.`)}).optional().describe(`App exposes MCP-style tools that the host can call.`),availableDisplayModes:G(oO).optional().describe(`Display modes the app supports.`)}),CO=K({method:X(`ui/notifications/initialized`),params:K({}).optional()});K({csp:pO.optional().describe(`Content Security Policy configuration for UI resources.`),permissions:mO.optional().describe(`Sandbox permissions requested by the UI resource.`),domain:V().optional().describe(`Dedicated origin for view sandbox.
|
|
187
187
|
|
|
188
188
|
Useful when views need stable, dedicated origins for OAuth callbacks, CORS policies, or API key allowlists.
|
|
189
189
|
|
|
@@ -197,10 +197,10 @@ Boolean requesting whether a visible border and background is provided by the ho
|
|
|
197
197
|
|
|
198
198
|
- \`true\`: request visible border + background
|
|
199
199
|
- \`false\`: request no visible border + background
|
|
200
|
-
- omitted: host decides border`)});var
|
|
200
|
+
- omitted: host decides border`)});var wO=K({method:X(`ui/request-display-mode`),params:K({mode:oO.describe(`The display mode being requested.`)})}),TO=K({mode:oO.describe(`The display mode that was actually set. May differ from requested if not supported.`)}).passthrough(),EO=J([X(`model`),X(`app`)]).describe(`Tool visibility scope - who can access the tool.`);K({resourceUri:V().optional(),visibility:G(EO).optional().describe(`Who can access this tool. Default: ["model", "app"]
|
|
201
201
|
- "model": Tool visible to and callable by the agent
|
|
202
|
-
- "app": Tool callable by the app from this server only`),csp:Ap().optional(),permissions:Ap().optional()}),K({mimeTypes:G(V()).optional().describe('Array of supported MIME types for UI resources.\nMust include `"text/html;profile=mcp-app"` for MCP Apps support.')});var
|
|
203
|
-
container holding the app. Specify either width or maxWidth, and either height or maxHeight.`),locale:V().optional().describe(`User's language and region preference in BCP 47 format.`),timeZone:V().optional().describe(`User's timezone in IANA format.`),userAgent:V().optional().describe(`Host application identifier.`),platform:J([X(`web`),X(`desktop`),X(`mobile`)]).optional().describe(`Platform type for responsive design decisions.`),deviceCapabilities:K({touch:U().optional().describe(`Whether the device supports touch input.`),hover:U().optional().describe(`Whether the device supports hover interactions.`)}).optional().describe(`Device input capabilities.`),safeAreaInsets:K({top:H().describe(`Top safe area inset in pixels.`),right:H().describe(`Right safe area inset in pixels.`),bottom:H().describe(`Bottom safe area inset in pixels.`),left:H().describe(`Left safe area inset in pixels.`)}).optional().describe(`Mobile safe area boundaries in pixels.`)}).passthrough();K({method:X(`ui/notifications/host-context-changed`),params:UO.describe(`Partial context update containing only changed fields.`)});var WO=K({method:X(`ui/update-model-context`),params:K({content:G(hD).optional().describe(`Context content blocks (text, image, etc.).`),structuredContent:Y(V(),W().describe(`Structured content for machine-readable context data.`)).optional().describe(`Structured content for machine-readable context data.`)})}),GO=K({method:X(`ui/initialize`),params:K({appInfo:cE.describe(`App identification (name and version).`),appCapabilities:IO.describe(`Features and capabilities this app provides.`),protocolVersion:V().describe(`Protocol version this app supports.`)})}),KO=K({protocolVersion:V().describe(`Negotiated protocol version string (e.g., "2025-11-21").`),hostInfo:cE.describe(`Host application identification and version.`),hostCapabilities:FO.describe(`Features and capabilities provided by the host.`),hostContext:UO.describe(`Rich context about the host environment.`)}).passthrough(),qO=class{eventTarget;eventSource;messageListener;constructor(e=window.parent,t){this.eventTarget=e,this.eventSource=t,this.messageListener=e=>{if(t&&e.source!==this.eventSource){console.debug(`Ignoring message from unknown source`,e);return}let n=nE.safeParse(e.data);n.success?(console.debug(`Parsed message`,n.data),this.onmessage?.(n.data)):e.data?.jsonrpc===`2.0`?(console.error(`Failed to parse message`,n.error.message,e),this.onerror?.(Error(`Invalid JSON-RPC message received: `+n.error.message))):console.debug(`Ignoring non-JSON-RPC message`,n.error.message,e)}}async start(){window.addEventListener(`message`,this.messageListener)}async send(e,t){e.method!==`ui/notifications/tool-input-partial`&&console.debug(`Sending message`,e),this.eventTarget.postMessage(e,`*`)}async close(){window.removeEventListener(`message`,this.messageListener),this.onclose?.()}onclose;onerror;onmessage;sessionId;setProtocolVersion},JO=`text/html;profile=mcp-app`;function YO(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(`; `)}var XO=[vO],ZO=class extends Jb{_client;_hostInfo;_hostCapabilities;_appCapabilities;_hostContext={};_appInfo;_initializedReceived=!1;_registeredEvents=new Set;_events=new _O;_wrapHandler(e,t){let n=super._wrapHandler(e,t);return e===`ui/initialize`||e===`ping`?n:async(t,r)=>(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.`),n(t,r))}eventSchemas={sizechange:kO,sandboxready:EO,initialized:LO,requestteardown:PO,loggingmessage:MD};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 n=t=>{e===`initialized`&&(this._initializedReceived=!0),this._events.dispatch(e,t)};e===`loggingmessage`?this.setNotificationHandler(`notifications/message`,e=>{n(e.params)}):this.setNotificationHandler(t.shape.method.value,{params:t.shape.params},e=>n(e)),this._registeredEvents.add(e)}warnIfRequestHandlerReplaced(e,t,n){t&&n&&console.warn(`[MCP Apps] ${e} handler replaced. Previous handler will no longer be called.`)}constructor(e,t,n,r){super(r),this._client=e,this._hostInfo=t,this._hostCapabilities=n,this._ensureEventSlot(`initialized`),this._hostContext=r?.hostContext||{},this.setRequestHandler(`ui/initialize`,{params:GO.shape.params,result:KO},e=>this._onAppsInitialize(e)),this.setRequestHandler(`ping`,(e,t)=>(this.onping?.(e.params,t),{})),this.setRequestHandler(`ui/request-display-mode`,{params:RO.shape.params,result:zO},()=>({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.setRequestHandler(`ui/message`,{params:HO.shape.params,result:TO},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.setRequestHandler(`ui/open-link`,{params:SO.shape.params,result:CO},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.setRequestHandler(`ui/download-file`,{params:VO.shape.params,result:wO},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.setRequestHandler(`ui/request-display-mode`,{params:RO.shape.params,result:zO},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.setRequestHandler(`ui/update-model-context`,{params:WO.shape.params,result:rE},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.setRequestHandler(`tools/call`,async(e,t)=>{if(!this._oncalltool)throw Error(`No oncalltool handler set`);return this._oncalltool(e.params,t)})}set oncreatesamplingmessage(e){this.setRequestHandler(`sampling/createMessage`,async(t,n)=>e(t.params,n))}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.setRequestHandler(`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.setRequestHandler(`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.setRequestHandler(`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.setRequestHandler(`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 this._appInfo!==void 0&&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:XO.includes(t)?t:vO,hostCapabilities:this.getCapabilities(),hostInfo:this._hostInfo,hostContext:this._hostContext}}setHostContext(e){let t={},n=!1;for(let r of Object.keys(e)){let i=this._hostContext[r],a=e[r];QO(i,a)||(t[r]=a,n=!0)}n&&(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})}teardownResource(e,t){return this.request({method:`ui/resource-teardown`,params:e},MO,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)}};function QO(e,t){return JSON.stringify(e)===JSON.stringify(t)}var $O=Object.defineProperty,ek=Object.getOwnPropertyNames,tk=(e,t)=>function(){return e&&(t=(0,e[ek(e)[0]])(e=0)),t},nk=(e,t)=>{for(var n in t)$O(e,n,{get:t[n],enumerable:!0})};function rk(){let e;try{e=typeof process<`u`?{}.MCP_USE_LOG_LEVEL??{}.DEBUG:void 0}catch{}let t=e?.trim().toLowerCase();return t===`2`?`debug`:t&&ik.includes(t)?t:`info`}var ik,ak,ok,sk,$,ck=tk({"src/utils/logging.ts"(){ik=[`silent`,`error`,`warn`,`info`,`http`,`verbose`,`debug`,`silly`],ak={silent:``,error:`❌`,warn:`⚠️`,info:`ℹ️`,http:`🌐`,verbose:`📝`,debug:`🔍`,silly:`🤪`},ok=class{constructor(e=`mcp-use`,t=`info`,n=`minimal`){this.name=e,this.level=t,this.format=n}write(e,t,n){if(this.level===`silent`||ik.indexOf(e)>ik.indexOf(this.level))return;let r=n.map(e=>{if(typeof e==`string`)return e;try{return JSON.stringify(e)}catch{return String(e)}}).join(` `),i=r?`${t} ${r}`:t,a=new Date().toLocaleTimeString(`en-US`,{hour12:!1}),o=this.format===`minimal`?e:e.toUpperCase(),s=this.format===`emoji`?` ${ak[e]}`:``,c=`${a} [${this.name}]${s} ${o}: ${i}`;(e===`error`?console.error:e===`warn`?console.warn:e===`info`?console.info:e===`debug`?console.debug:console.log)(c)}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}},sk=class{static instances={};static currentFormat=`minimal`;static currentLevel;static get(e=`mcp-use`){return this.instances[e]??=new ok(e,this.currentLevel??rk(),this.currentFormat)}static configure({level:e=rk(),format:t=`minimal`}={}){this.currentLevel=e,this.currentFormat=t;for(let n of Object.values(this.instances))n.level=e,n.format=t}static setDebug(e){let t=e===2||e===!0?`debug`:`info`;this.currentLevel=t;for(let e of Object.values(this.instances))e.level=t;try{typeof process<`u`&&({}.MCP_USE_LOG_LEVEL=t)}catch{}}static setFormat(e){this.configure({format:e})}},$=sk.get()}}),lk={};nk(lk,{clearRpcLogs:()=>pk,getAllRpcLogs:()=>dk,getRpcLogs:()=>uk,subscribeToRpcLogs:()=>fk,wrapTransportForLogging:()=>mk});function uk(e){return _k.getLogsForServer(e)}function dk(){return _k.getAllLogs()}function fk(e){return _k.subscribe(e)}function pk(e){_k.clear(e)}function mk(e,t){class n{constructor(e){this.inner=e,this.inner.onmessage=(e,n)=>{_k.publish({serverId:t,direction:`receive`,timestamp:new Date().toISOString(),message:e}),this.onmessage?.(e,n)},this.inner.onclose=()=>{this.onclose?.()},this.inner.onerror=e=>{this.onerror?.(e)}}onclose;onerror;onmessage;async start(){typeof this.inner.start==`function`&&await this.inner.start()}async send(e,n){_k.publish({serverId:t,direction:`send`,timestamp:new Date().toISOString(),message:e}),await this.inner.send(e,n)}async close(){await this.inner.close()}get sessionId(){return this.inner.sessionId}setProtocolVersion(e){typeof this.inner.setProtocolVersion==`function`&&this.inner.setProtocolVersion(e)}}return new n(e)}var hk,gk,_k,vk=tk({"src/react/rpc-logger.ts"(){ck(),hk=sk.get(`RpcLogger`),gk=class{logs=[];listeners=new Set;maxLogs=1e3;publish(e){hk.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)),hk.debug(`[RPC Logger] Total logs:`,this.logs.length,`Listeners:`,this.listeners.size),this.listeners.forEach(t=>{try{t(e)}catch(e){hk.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=[]}},_k=new gk}}),yk=`mcp_auth_callback`,bk=`mcp_auth_callback`;function xk(e){try{return typeof localStorage<`u`&&!!localStorage.getItem(e)}catch{return!1}}function Sk({popup:e,state:t,tokensKey:n,timeoutMs:r=5*6e4,closePollMs:i=1e3,closeGraceMs:a=2e4,expectedOrigin:o=typeof window<`u`?window.location.origin:``}){return new Promise(s=>{let c=!1,l=null,u=null,d=null,f=null,p=()=>{if(l&&=(clearInterval(l),null),u&&=(clearTimeout(u),null),d&&=(clearTimeout(d),null),typeof window<`u`&&(window.removeEventListener(`message`,g),window.removeEventListener(`storage`,v)),f){try{f.removeEventListener(`message`,_),f.close()}catch{}f=null}},m=e=>{c||(c=!0,p(),s(e))},h=e=>{!e||e.type!==bk||e.state&&t&&e.state!==t||(e.success?m({kind:`success`}):m({kind:`error`,error:e.error??`Authentication failed in callback.`}))},g=e=>{o&&e.origin!==o||h(e.data)},_=e=>{h(e.data)},v=e=>{e.key===n&&e.newValue&&m({kind:`success`})};if(typeof window<`u`&&(window.addEventListener(`message`,g),window.addEventListener(`storage`,v)),typeof BroadcastChannel<`u`)try{f=new BroadcastChannel(yk),f.addEventListener(`message`,_)}catch{f=null}e&&(l=setInterval(()=>{if(c)return;let t=!1;try{t=e.closed}catch{t=!1}if(t){if(l&&=(clearInterval(l),null),xk(n)){m({kind:`success`});return}d=setTimeout(()=>{m(xk(n)?{kind:`success`}:{kind:`cancelled`})},a)}},i)),u=setTimeout(()=>{m(xk(n)?{kind:`success`}:{kind:`timeout`})},r)})}ck();var Ck=`http://json-schema.org/draft-04/schema`,wk=new Set([`http://json-schema.org/draft-07/schema`,`https://json-schema.org/draft-07/schema`]),Tk=new Set([`https://json-schema.org/draft/2019-09/schema`,`http://json-schema.org/draft/2019-09/schema`]),Ek=new Set([`https://json-schema.org/draft/2020-12/schema`,`http://json-schema.org/draft/2020-12/schema`]);function Dk(e){if(!(`$schema`in e)||typeof e.$schema!=`string`)return`2020-12`;let t=e.$schema.replace(/#$/,``);if(t===Ck)return`4`;if(wk.has(t))return`7`;if(Tk.has(t))return`2019-09`;if(Ek.has(t))return`2020-12`}var Ok=class{getValidator(e){let t=Dk(e);return(t===void 0?new Jx:new Jx({draft:t})).getValidator(e)}};ck();var kk;function Ak(e){kk?.(e)}var jk={"~standard":{version:1,vendor:`mcp-use`,validate:e=>({value:e})}},Mk=class{client=null;connectionManager=null;toolsCache=null;capabilitiesCache=null;serverInfoCache=null;connected=!1;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){let t=this.constructor.name;Ak({connectorType:t,...e})}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){$.error(`Error in notification handler:`,e)}}async handleListChanged(e,t,n){if(t){$.warn(`[Auto] ${e} refresh failed:`,t);return}e===`notifications/tools/list_changed`&&n&&(this.toolsCache=[...n]),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();break;default:break}await this.forwardNotification(e)};let e=this.client._notificationHandlers;for(let t of[`notifications/progress`,`notifications/cancelled`]){let n=e.get(t);n&&e.set(t,async e=>{await n(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&&typeof e==`object`&&e.method===`notifications/progress`&&this.forwardRoundProgress(e.params),await t?.(e)}}forwardRoundProgress(e){if(this.activeProgressHandlers.size===1){let[t]=this.activeProgressHandlers;t?.(e)}}async refreshToolsCache(){if(this.client)try{$.debug(`[Auto] Refreshing tools cache due to list_changed notification`);let e=await this.client.listTools();this.toolsCache=e.tools??[],$.debug(`[Auto] Refreshed tools cache: ${this.toolsCache.length} tools`)}catch(e){$.warn(`[Auto] Failed to refresh tools cache:`,e)}}async onResourcesListChanged(){$.debug(`[Auto] Resources list changed - clients should re-fetch if needed`)}async onPromptsListChanged(){$.debug(`[Auto] Prompts list changed - clients should re-fetch if needed`)}async setRoots(e){this.rootsCache=[...e],this.client&&($.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()=>($.debug(`Server requested roots list, returning ${this.rootsCache.length} root(s)`),{roots:this.rootsCache}))}setupSamplingHandler(){if(!this.client){$.debug(`setupSamplingHandler: No client available`);return}let e=this.opts.onSampling;if(!e){$.debug(`setupSamplingHandler: No sampling callback provided`);return}$.debug(`setupSamplingHandler: Setting up sampling request handler`),this.client.setRequestHandler(`sampling/createMessage`,async t=>($.debug(`Server requested sampling, forwarding to callback`),await e(t.params))),$.debug(`setupSamplingHandler: Sampling handler registered successfully`)}setupElicitationHandler(){if(!this.client){$.debug(`setupElicitationHandler: No client available`);return}let e=this.opts.onElicitation;if(!e){$.debug(`setupElicitationHandler: No elicitation callback provided`);return}$.debug(`setupElicitationHandler: Setting up elicitation request handler`),this.client.setRequestHandler(`elicitation/create`,async t=>($.debug(`Server requested elicitation, forwarding to callback`),await e(t.params))),$.debug(`setupElicitationHandler: Elicitation handler registered successfully`)}async disconnect(){if(!this.connected){$.debug(`Not connected to MCP implementation`);return}$.debug(`Disconnecting from MCP implementation`),await this.cleanupResources(),this.connected=!1,$.debug(`Disconnected from MCP implementation`)}get isClientConnected(){return this.client!=null}async initialize(e=this.opts.defaultRequestOptions??{}){if(!this.client)throw Error(`MCP client is not connected`);$.debug(`Caching server capabilities & tools`);let t=this.client.getServerCapabilities();this.capabilitiesCache=t||null;let n=this.client.getServerVersion();this.serverInfoCache=n?{name:n.name,version:n.version,title:n.title,description:n.description,websiteUrl:n.websiteUrl,icons:n.icons}:null;try{let t=await this.client.listTools(void 0,e);this.toolsCache=t.tools??[],$.debug(`Fetched ${this.toolsCache.length} tools from server`)}catch(e){let t=e;t.code===-32601?$.debug(`Server does not implement tools/list, assuming no tools`):$.debug(`Failed to list tools, assuming empty:`,t.message),this.toolsCache=[]}return $.debug(`Server capabilities:`,t),$.debug(`Server info:`,n),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,n){if(!this.client)throw Error(`MCP client is not connected`);let r=n?{...n}:void 0;r?.resetTimeoutOnProgress&&!r.onprogress&&(r.onprogress=()=>{},$.debug(`[BaseConnector] Added onprogress callback for tool '${e}' to enable progressToken`)),$.debug(`Calling tool '${e}' with args`,t);let i=r?.onprogress;i&&this.activeProgressHandlers.add(i);try{let n=await this.client.callTool({name:e,arguments:t},r);return $.debug(`Tool '${e}' returned`,n),n}finally{i&&this.activeProgressHandlers.delete(i)}}async listTools(e){if(!this.client)throw Error(`MCP client is not connected`);$.debug(`[listTools] Fetching fresh tools from server...`);let t=await this.client.listTools(void 0,e),n=t.tools?[...t.tools]:[];return $.debug(`[listTools] Returned ${n.length} tools:`,n.map(e=>e.name)),n}async listResources(e,t){if(!this.client)throw Error(`MCP client is not connected`);return $.debug(`Listing resources`,e?`with cursor: ${e}`:``),await this.client.listResources({cursor:e},t)}async listAllResources(e){if(!this.client)throw Error(`MCP client is not connected`);if(!this.capabilitiesCache?.resources)return $.debug(`Server does not advertise resources capability, skipping`),{resources:[]};try{$.debug(`Listing all resources (with auto-pagination)`);let t=[],n;do{let r=await this.client.listResources({cursor:n},e);t.push(...r.resources||[]),n=r.nextCursor}while(n);return{resources:t}}catch(e){if(e.code===-32601)return $.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 $.debug(`Listing resource templates`),await this.client.listResourceTemplates(void 0,e)}async complete(e,t){if(!this.client)throw Error(`MCP client is not connected`);$.debug(`[complete] Requesting completions for:`,e.ref);let n=await this.client.complete(e,t);return $.debug(`[complete] Received ${n.completion.values.length} suggestions`),n}async readResource(e,t){if(!this.client)throw Error(`MCP client is not connected`);return $.debug(`Reading resource ${e}`),await this.client.readResource({uri:e},t)}async subscribeToResource(e,t){if(!this.client)throw Error(`MCP client is not connected`);return $.debug(`Subscribing to resource: ${e}`),await this.client.subscribeResource({uri:e},t)}async unsubscribeFromResource(e,t){if(!this.client)throw Error(`MCP client is not connected`);return $.debug(`Unsubscribing from resource: ${e}`),await this.client.unsubscribeResource({uri:e},t)}async listPrompts(){if(!this.client)throw Error(`MCP client is not connected`);if(!this.capabilitiesCache?.prompts)return $.debug(`Server does not advertise prompts capability, skipping`),{prompts:[]};try{return $.debug(`Listing prompts`),await this.client.listPrompts()}catch(e){if(e.code===-32601)return $.debug(`Server advertised prompts but method not found`),{prompts:[]};throw e}}async getPrompt(e,t){if(!this.client)throw Error(`MCP client is not connected`);return $.debug(`Getting prompt ${e}`),await this.client.getPrompt({name:e,arguments:t})}async request(e,t=null,n){if(!this.client)throw Error(`MCP client is not connected`);return $.debug(`Sending raw request '${e}' with params`,t),await this.client.request({method:e,params:t??{}},jk,n)}async cleanupResources(){let e=[];if(this.client)try{typeof this.client.close==`function`&&await this.client.close()}catch(t){let n=`Error closing client: ${t}`;$.warn(n),e.push(n)}finally{this.client=null}if(this.connectionManager)try{await this.connectionManager.stop()}catch(t){let n=`Error stopping connection manager: ${t}`;$.warn(n),e.push(n)}finally{this.connectionManager=null}this.toolsCache=null,e.length&&$.warn(`Resource cleanup finished with ${e.length} issue(s)`)}};function Nk(e,t=0){if(!e||t>5)return!1;if(e instanceof xS||e instanceof Z_&&e.status===401)return!0;if(e instanceof Error){if(e.cause&&Nk(e.cause,t+1))return!0;let n=e instanceof X_?e.data:void 0;if(n?.cause&&Nk(n.cause,t+1))return!0}return!1}function Pk(e,t,n,r){let i=new URL(e),a=t.replace(/\/$/,``);return async(e,t)=>{let o=new Request(e,t),s=new URL(o.url);if(!(s.origin===i.origin&&s.pathname===i.pathname))return n(o);let c=new Headers(o.headers);c.set(`X-Target-URL`,o.url),r&&c.set(`X-Server-Id`,r);let l=o.method===`GET`||o.method===`HEAD`?void 0:await o.clone().arrayBuffer();return n(new Request(a,{method:o.method,headers:c,body:l,signal:o.signal,redirect:`manual`}))}}var Fk=class extends Mk{baseUrl;headers;timeout;customFetch;clientInfo;protocolNegotiation;gatewayUrl;serverId;reconnectionOptions;transportType=null;streamableTransport=null;constructor(e,t={}){super(t);let n=e.replace(/\/$/,``);this.baseUrl=n,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;let r=t.fetch??globalThis.fetch.bind(globalThis);this.customFetch=this.gatewayUrl?Pk(n,this.gatewayUrl,r,this.serverId):t.fetch,this.clientInfo=t.clientInfo??{name:`http-connector`,version:`1.0.0`},this.protocolNegotiation=t.protocolNegotiation??`auto`,this.reconnectionOptions=t.reconnectionOptions}buildClientOptions(){return{...this.opts.clientOptions||{},jsonSchemaValidator:this.opts.clientOptions?.jsonSchemaValidator??new Ok,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 Z_?e:e instanceof Error&&e.cause instanceof Z_?e.cause:null}classifyStreamableHttpFailure(e){let t=`Unknown error`,n=!1,r,i=this.unwrapStreamableError(e);if(i){let e=i.status;return n=e===401,r=e,e===400&&i.message.includes(`Missing session ID`)?(t=`Server requires session ID (FastMCP compatibility)`,$.warn(`\u26A0\uFE0F ${t}`)):e===404||e===405?(t=`Server returned ${e} - server likely doesn't support streamable HTTP`,$.debug(t)):(t=`Server returned ${e}: ${i.message}`,$.debug(t)),{fallbackReason:t,is401Error:n,httpStatusCode:r}}if(e instanceof Error){let r=e.toString(),i=e.message||``;n=Nk(e)||r.includes(`401`)||i.includes(`Unauthorized`),r.includes(`Missing session ID`)||r.includes(`Bad Request: Missing session ID`)||i.includes(`FastMCP session ID error`)?(t=`Server requires session ID (FastMCP compatibility)`,$.warn(`\u26A0\uFE0F ${t}`)):r.includes(`405 Method Not Allowed`)||r.includes(`404 Not Found`)?(t=`Server doesn't support streamable HTTP (405/404)`,$.debug(t)):(t=`Streamable HTTP failed: ${e.message}`,$.debug(t))}return{fallbackReason:t,is401Error:n,httpStatusCode:r}}async connect(){if(this.connected){$.debug(`Already connected to MCP implementation`);return}let e=this.baseUrl;$.debug(`Connecting to MCP implementation via HTTP: ${e}`);try{await this.connectWithStreamableHttp(e),$.debug(`✅ Successfully connected via streamable HTTP`)}catch(e){$.debug(`Streamable HTTP connect failed`,e);let{fallbackReason:t,is401Error:n,httpStatusCode:r}=this.classifyStreamableHttpFailure(e);if(await this.cleanupResources(),n){$.info(`Authentication required`);let e=Error(`Authentication required`);throw e.code=401,e}let i=Error(`Could not connect via streamable HTTP: ${t}`);throw r!==void 0&&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,n]=e.body.tee();return(async()=>{let e=n.getReader(),t=new TextDecoder,r=``;try{for(;;){let{done:n,value:i}=await e.read();if(n)break;r+=t.decode(i,{stream:!0});let a=r.split(/\r?\n\r?\n/);r=a.pop()??``;for(let e of a)for(let t of e.split(/\r?\n/))if(t.startsWith(`data:`))try{let e=JSON.parse(t.slice(5).trim());e.method===`notifications/progress`&&this.forwardRoundProgress(e.params)}catch{}}}catch(e){e instanceof DOMException&&e.name===`AbortError`||$.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{$.debug(`[HttpConnector] Connecting with Streamable HTTP`,{baseUrl:e,originalUrl:this.baseUrl,gatewayUrl:this.gatewayUrl||`none`,authProviderUrl:this.opts.authProvider&&`serverUrl`in this.opts.authProvider&&typeof this.opts.authProvider.serverUrl==`string`?this.opts.authProvider.serverUrl:`none`,headers:this.headers});let t,n=new Promise(e=>{t=e}),r=this.customFetch??globalThis.fetch.bind(globalThis),i=new GC(new URL(e),{authProvider:this.opts.authProvider,fetch:async(e,n)=>{let i=await r(e,n),a=n?.method??(e instanceof Request?e.method:`GET`),o=new Headers(e instanceof Request?e.headers:void 0);return new Headers(n?.headers).forEach((e,t)=>{o.set(t,e)}),a.toUpperCase()===`GET`&&i.ok&&i.headers.get(`content-type`)?.includes(`text/event-stream`)&&t?.(),o.get(`mcp-method`)===`subscriptions/listen`?i:this.observeSseProgress(i)},requestInit:{headers:this.headers},reconnectionOptions:{maxReconnectionDelay:3e4,initialReconnectionDelay:1e3,reconnectionDelayGrowFactor:1.5,maxRetries:2,...this.reconnectionOptions}}),a=i;if(this.opts.wrapTransport){let e=this.baseUrl;a=this.opts.wrapTransport(a,e)}let o=this.buildClientOptions();$.debug(`Creating Client with capabilities:`,JSON.stringify(o.capabilities,null,2)),this.client=new BC(this.clientInfo,o),this.setupRootsHandler(),this.setupSamplingHandler(),this.setupElicitationHandler(),$.debug(`Roots/sampling/elicitation handlers registered before connect`);try{let e;if(await Promise.race([this.client.connect(a),new Promise((t,n)=>{e=setTimeout(()=>n(Error(`MCP connection timed out after ${this.timeout}ms`)),this.timeout)})]).finally(()=>{e!==void 0&&clearTimeout(e)}),(this.client.getProtocolEra?.()??`legacy`)===`legacy`&&i.sessionId){let e,t=await Promise.race([n.then(()=>!0),new Promise(t=>e=setTimeout(()=>t(!1),Math.min(this.timeout,5e3)))]);e&&clearTimeout(e),t||$.warn(`Legacy server push stream did not attach before connect completed`)}let t=i.sessionId;t&&$.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 n=Error(`Session ID error: ${t}. The SDK should automatically extract session ID from initialize response.`);throw n.cause=e,n}}throw e}this.streamableTransport=i,this.connectionManager={stop:async()=>{if(this.streamableTransport)try{await this.streamableTransport.close()}catch(e){$.warn(`Error closing Streamable HTTP transport: ${e}`)}finally{this.streamableTransport=null}}},this.connected=!0,this.transportType=`streamable-http`,this.setupNotificationHandler(),$.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&&this.protocolEra!==`modern`){let e;try{await Promise.race([this.streamableTransport.terminateSession().then(()=>!0),new Promise(t=>e=setTimeout(()=>t(!1),Math.min(this.timeout,5e3)))])||$.debug(`Timed out terminating legacy HTTP session; closing transport`)}catch(e){$.debug(`Error terminating Streamable HTTP session: ${e}`)}finally{e&&clearTimeout(e)}}await super.cleanupResources()}},Ik=`2.0.0-beta.4`;function Lk(){return Ik}function Rk(e,t){return{onSampling:e?.onSampling??t?.onSampling,onElicitation:e?.onElicitation??t?.onElicitation,onNotification:e?.onNotification??t?.onNotification}}function zk(e){if(!(`url`in e)||typeof e.url!=`string`||e.authProvider||e.authToken||e.oauth===!1)return!1;let t=e.headers;if(t){for(let e of Object.keys(t))if(e.toLowerCase()===`authorization`)return!1}return!0}function Bk(){return{name:`mcp-use`,title:`mcp-use`,version:Lk(),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`}}function Vk(e){let t=Bk();if(!e||typeof e!=`object`)return t;let n=e;return!n.name||!n.version?t:{...t,...n}}function Hk(e){let t=e?.capabilities;if(!t||t.views!==!0)return e;let{views:n,...r}=t,i=r.extensions&&typeof r.extensions==`object`&&!Array.isArray(r.extensions)?{...r.extensions}:{};return{...e,capabilities:{...r,extensions:{...i,"io.modelcontextprotocol/ui":{mimeTypes:[`text/html;profile=mcp-app`]}}}}}function Uk(e){let t=()=>{throw Error(`Invalid url to pass to open(): ${e}`)},n;try{n=new URL(e)}catch{t()}return n.protocol!==`https:`&&n.protocol!==`http:`&&t(),n.hostname!==encodeURIComponent(n.hostname)&&t(),n.username&&=encodeURIComponent(n.username),n.password&&=encodeURIComponent(n.password),n.pathname=n.pathname.slice(0,1)+encodeURIComponent(n.pathname.slice(1)).replace(/%2f/gi,`/`),n.search=n.search.slice(0,1)+Array.from(n.searchParams.entries()).map(Wk).join(`&`),n.hash=n.hash.slice(0,1)+encodeURIComponent(n.hash.slice(1)),n.href}function Wk([e,t]){return`${encodeURIComponent(e)}${t.length>0?`=${encodeURIComponent(t)}`:``}`}var Gk=class{get(e){return localStorage.getItem(e)}set(e,t){localStorage.setItem(e,t)}remove(e){localStorage.removeItem(e)}keys(){let e=[];for(let t=0;t<localStorage.length;t++){let n=localStorage.key(t);n&&e.push(n)}return e}},Kk=class e{serverUrl;storageKeyPrefix;serverUrlHash;clientName;clientUri;logoUri;callbackUrl;clientMetadataUrl;scope;store;allowClientSecret;constructor(t,n,r){US(n.clientMetadataUrl),this.serverUrl=t,this.storageKeyPrefix=n.storageKeyPrefix||`mcp:auth`,this.serverUrlHash=e.hashString(t),this.clientName=n.clientName||`mcp-use`,this.clientUri=n.clientUri||(typeof window<`u`?window.location.origin:`https://mcp-use.com`),this.logoUri=n.logoUri||`https://mcp-use.com/logo.png`,this.callbackUrl=Uk(n.callbackUrl||(typeof window<`u`?new URL(`/oauth/callback`,window.location.origin).toString():`/oauth/callback`)),this.clientMetadataUrl=n.clientMetadataUrl,this.scope=n.scope,this.store=r,this.allowClientSecret=n.allowClientSecret??!0}getKey(e){return`${this.storageKeyPrefix}_${this.serverUrlHash}_${e}`}static hashString(e){let t=0;for(let n=0;n<e.length;n++){let r=e.charCodeAt(n);t=(t<<5)-t+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 n=this.credentialKey(e,t),r=await this.store.get(n);if(!r&&t){let r=this.credentialKey(e),i=await this.store.get(r);if(i)try{let e=JSON.parse(i);if(!e.issuer||e.issuer===t.issuer){let i={...e,issuer:t.issuer},a=JSON.stringify(i);return await this.store.set(n,a),await this.store.set(r,a),{key:n,value:i}}}catch{await this.store.remove(r)}return}if(r)try{return{key:n,value:JSON.parse(r)}}catch(t){console.warn(`[${this.storageKeyPrefix}] Failed to parse ${e.replace(`_`,` `)}:`,t),await this.store.remove(n);return}}async tokens(e){return(await this.readCredential(`tokens`,e))?.value}async saveTokens(e,t){let n=JSON.stringify(e);await this.store.set(this.credentialKey(`tokens`,t),n),t&&await this.store.set(this.credentialKey(`tokens`),n),await this.store.remove(this.getKey(`code_verifier`)),await this.store.remove(this.getKey(`last_auth_url`))}async clientInformation(e){let t=await this.readCredential(`client_info`,e);if(!t)return;let{key:n,value:r}=t;try{if(!this.allowClientSecret&&r.client_secret){await this.store.remove(n),e&&await this.store.remove(this.credentialKey(`client_info`)),console.warn(`[${this.storageKeyPrefix}] Removed OAuth client information containing a browser client_secret.`);return}let t=Array.isArray(r.redirect_uris)?r.redirect_uris:[];if(!(t.length===0||t.includes(this.redirectUrl))){console.info(`[${this.storageKeyPrefix}] Invalidating cached OAuth client info due to redirect URI mismatch.`),await this.store.remove(n),await this.store.remove(this.credentialKey(`tokens`,e)),await this.store.remove(this.getKey(`last_auth_url`));return}return r}catch{await this.store.remove(n);return}}async saveClientInformation(e,t){let n=e;if(!this.allowClientSecret&&n.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(e);await this.store.set(this.credentialKey(`client_info`,t),r),t&&await this.store.set(this.credentialKey(`client_info`),r)}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}async invalidateCredentials(e){let t=async e=>{let t=`${this.getKey(e)}_`;for(let n of await this.store.keys())(n===this.getKey(e)||n.startsWith(t))&&await this.store.remove(n)};switch(e){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(`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`));break;default:break}}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 n=globalThis.crypto.randomUUID(),r=`${this.storageKeyPrefix}:state_${n}`,i={serverUrlHash:this.serverUrlHash,expiry:Date.now()+1e3*60*10,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`,n);let a=Uk(e.toString());return await this.store.set(r,JSON.stringify(i)),await this.store.set(this.getKey(`last_auth_url`),a),a}async getTokenEndpoint(){return(await this.discoveryState())?.authorizationServerMetadata?.token_endpoint??null}};async function qk(e){return typeof e==`string`?e:e instanceof URLSearchParams||e instanceof FormData?Object.fromEntries(e.entries()):e instanceof Blob?await e.text():e}var Jk=class{serverUrl;staticClientInfo;session;preventAutoAuth;useRedirectFlow;oauthProxyUrl;connectionUrl;proxyOAuthRequests;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.session=new Kk(e,{...t,allowClientSecret:!1},new Gk),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)}reanchorWellKnownUrl(e){if(!this.connectionUrl)return e;try{let t=new URL(e),n=new URL(this.connectionUrl);if(t.origin!==n.origin||!t.pathname.startsWith(`/.well-known/`))return e;let r=new URL(this.serverUrl),[i,...a]=t.pathname.slice(13).split(`/`);if(!i)return e;let o=a.length?`/${a.join(`/`)}`:``,s=n.pathname.replace(/\/+$/,``),c=r.pathname.replace(/\/+$/,``),l=o&&o===s?c:o;return`${r.origin}/.well-known/${i}${l}${t.search}`}catch{return e}}getProxyFetch(e){if(!this.proxyOAuthRequests||!this.oauthProxyUrl)return e;let t=e??globalThis.fetch.bind(globalThis),n=this.oauthProxyUrl,r=new Set,i=!1;return async(e,a)=>{let o=typeof e==`string`?e:e instanceof URL?e.toString():e.url,s=this.reanchorWellKnownUrl(o),c;try{c=new URL(s).pathname}catch{return await t(e,a)}let l=c.includes(`/.well-known/`);if(!i){i=!0;let e=(await this.discoveryState())?.authorizationServerMetadata;for(let t of[`registration_endpoint`,`token_endpoint`,`revocation_endpoint`,`introspection_endpoint`])typeof e?.[t]==`string`&&r.add(e[t])}let u=r.has(s)||/\/(?:register|registration|token|revoke|revocation|introspect|introspection)\/?$/.test(c);if(!l&&!u)return await t(e,a);try{let r=new URL(s),i=new URL(n);if(r.origin===i.origin&&(r.pathname.startsWith(i.pathname)||s.includes(`/inspector/api/oauth`)))return await t(e,a)}catch{}let d=l?`${n}/metadata?serverUrl=${encodeURIComponent(this.serverUrl)}&url=${encodeURIComponent(s)}`:`${n}/proxy`;if(l){let e=await t(d,{...a,method:`GET`});try{let t=await e.clone().json();for(let e of[`registration_endpoint`,`token_endpoint`,`revocation_endpoint`,`introspection_endpoint`])typeof t[e]==`string`&&r.add(t[e])}catch{}return e}let f=a?.body?await qk(a.body):void 0,p=await(await t(d,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({serverUrl:this.serverUrl,url:s,method:a?.method||`POST`,headers:a?.headers?Object.fromEntries(new Headers(a.headers)):{},body:f})})).json();return new Response(JSON.stringify(p.body),{status:p.status,statusText:p.statusText,headers:new Headers(p.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.session.saveTokens(e,t)}async clientInformation(e){return this.staticClientInfo?this.staticClientInfo:this.session.clientInformation(e)}async saveClientInformation(e,t){if(!this.staticClientInfo)return this.session.saveClientInformation(e,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)}discoveryState(){return this.session.discoveryState()}getTokenEndpoint(){return this.session.getTokenEndpoint()}async getClientCredentials(){let e=await this.clientInformation();return e?.client_id?{client_id:e.client_id}:null}async prepareAuthorizationUrl(e){return 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:typeof window<`u`?window.location.href:void 0})}async redirectToAuthorization(e){let t=await this.prepareAuthorizationUrl(e);if(this.preventAutoAuth){console.info(`[${this.storageKeyPrefix}] Auto-auth prevented. Authorization URL stored for manual trigger.`);return}if(this.useRedirectFlow){console.info(`[${this.storageKeyPrefix}] Redirecting to authorization URL (full-page redirect).`),window.location.href=t;return}let n=`width=600,height=700,resizable=yes,scrollbars=yes,status=yes`;try{let e=window.open(t,`mcp_auth_${this.serverUrlHash}`,n);this.onPopupWindow&&this.onPopupWindow(t,n,e),!e||e.closed||e.closed===void 0?console.warn(`[${this.storageKeyPrefix}] Popup likely blocked by browser. Manual navigation might be required using the stored URL.`):(e.focus(),console.info(`[${this.storageKeyPrefix}] Redirecting to authorization URL in popup.`))}catch(e){console.error(`[${this.storageKeyPrefix}] Error opening popup window:`,e)}}getLastAttemptedAuthUrl(){let e=localStorage.getItem(this.getKey(`last_auth_url`));return e?Uk(e):null}clearStorage(){let e=`${this.storageKeyPrefix}_${this.serverUrlHash}_`,t=`${this.storageKeyPrefix}:state_`,n=[],r=0;for(let r=0;r<localStorage.length;r++){let i=localStorage.key(r);if(i){if(i.startsWith(e))n.push(i);else if(i.startsWith(t))try{let e=localStorage.getItem(i);e&&JSON.parse(e).serverUrlHash===this.serverUrlHash&&n.push(i)}catch(e){console.warn(`[${this.storageKeyPrefix}] Error parsing state key ${i} during clearStorage:`,e)}}}return[...new Set(n)].forEach(e=>{localStorage.removeItem(e),r++}),r}};async function Yk(e,t={}){return new Jk(e,t)}ck(),ck();var Xk=class{},Zk=class extends Xk{constructor(e){super(),this.data=e}get name(){return`mcp_agent_execution`}get properties(){return{execution_method:this.data.executionMethod,query:this.data.query,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,server_identifiers:this.data.serverIdentifiers,total_tools_available:this.data.totalToolsAvailable,tools_available_names:this.data.toolsAvailableNames,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,tools_used_names:this.data.toolsUsedNames??null,response:this.data.response??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}}},Qk=class extends Xk{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}}},$k=class extends Xk{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}}},eA=class extends Xk{constructor(e){super(),this.data=e}get name(){return`client_add_server`}get properties(){let{serverName:e,serverConfig:t}=this.data,n=t.url;return{server_name:e,server_url_domain:n?this._extractHostname(n):null,transport:t.transport??null,has_auth:!!(t.authToken||t.authProvider)}}_extractHostname(e){try{return new URL(e).hostname}catch{return null}}},tA=class extends Xk{constructor(e){super(),this.data=e}get name(){return`client_remove_server`}get properties(){return{server_name:this.data.serverName}}};async function nA(e,t){try{await fetch(e,t)}catch{}}var rA=`https://eu.i.posthog.com`,iA=`phc_lyTtbYwvkdSbrcMQNPiKiiRWrrM1seyKIMjycSvItEI`,aA=`https://mcpuse.gateway.scarf.sh/events-ts`,oA=`https://mcpuse.gateway.scarf.sh/simple/`,sA=1800,cA=new Set([`query`,`response`,`messages`]);function lA(e){if(e==null)return``;if(typeof e==`string`)return e;if(typeof e==`number`||typeof e==`boolean`)return String(e);try{return JSON.stringify(e)}catch{return String(e)}}function uA(e,t=oA){let n=new URLSearchParams;for(let[t,r]of Object.entries(e)){let e=lA(r);cA.has(t)&&e.length>120&&(e=`${e.slice(0,117)}...`),e!==``&&n.set(t,e)}let r=`${t}${t.includes(`?`)?`&`:`?`}${n.toString()}`;if(r.length<=sA)return r;let i=[...n.keys()].sort((e,t)=>(n.get(t)?.length??0)-(n.get(e)?.length??0));for(let e of i){if(r.length<=sA)break;e===`event`||e===`user_id`||(n.delete(e),r=`${t}${t.includes(`?`)?`&`:`?`}${n.toString()}`)}return r.slice(0,sA)}function dA(e,t){return nA(t,{method:`POST`,headers:{"Content-Type":`application/json`},keepalive:!0,body:JSON.stringify(e)})}function fA(e,t){try{let n=uA(e,t),r=new Image;r.referrerPolicy=`no-referrer-when-downgrade`,r.src=n}catch{}return Promise.resolve()}function pA(e){let t=e.host??rA,n=e.apiKey??iA;return nA(`${t}/i/v0/e/`,{method:`POST`,headers:{"Content-Type":`application/json`},keepalive:!0,body:JSON.stringify({api_key:n,event:e.event,distinct_id:e.distinctId,properties:e.properties,timestamp:new Date().toISOString()})})}function mA(e,t=aA){return typeof window<`u`?fA(e,t===aA?oA:t):dA(e,t)}function hA(){return globalThis.crypto.randomUUID()}function gA(){let e=new Uint8Array(8);return globalThis.crypto.getRandomValues(e),Array.from(e,e=>e.toString(16).padStart(2,`0`)).join(``)}function _A(e,t){let n=e=>e.split(`-`)[0].split(`.`).map(e=>parseInt(e,10)||0),r=n(e),i=n(t),a=Math.max(r.length,i.length);for(let e=0;e<a;e++){let t=r[e]??0,n=i[e]??0;if(t!==n)return t>n}return!1}var vA=`mcp_use_user_id`,yA=`phc_lyTtbYwvkdSbrcMQNPiKiiRWrrM1seyKIMjycSvItEI`,bA=`https://eu.i.posthog.com`,xA=null;function SA(){return typeof localStorage<`u`&&typeof localStorage.getItem==`function`&&typeof localStorage.setItem==`function`&&typeof localStorage.removeItem==`function`}function CA(){if(!SA())return null;try{localStorage.setItem(`__mcp_use_test__`,`1`),localStorage.removeItem(`__mcp_use_test__`)}catch{return null}return{getUserId(){try{return localStorage.getItem(vA)}catch{return null}},setUserId(e){try{localStorage.setItem(vA,e)}catch{}},getDownloadedVersion:()=>null,setDownloadedVersion:()=>void 0}}function wA(){try{return globalThis.Bun===void 0?globalThis.Deno===void 0?typeof navigator<`u`&&navigator.userAgent?.includes(`Cloudflare-Workers`)?`cloudflare-workers`:globalThis.EdgeRuntime===void 0?typeof window<`u`&&typeof document<`u`?`browser`:typeof process<`u`&&process.versions?.node!==void 0?`node`:`unknown`:`edge`:`deno`:`bun`}catch{return`unknown`}}function TA(){if(typeof process<`u`&&{}.MCP_USE_TELEMETRY_SOURCE)return{}.MCP_USE_TELEMETRY_SOURCE;try{if(SA())return localStorage.getItem(`MCP_USE_TELEMETRY_SOURCE`)??void 0}catch{}}function EA(){if(typeof window<`u`&&window.__MCP_USE_ANONYMIZED_TELEMETRY__===!1||typeof process<`u`&&{}.MCP_USE_ANONYMIZED_TELEMETRY?.toLowerCase()===`false`)return!0;try{if(SA()&&localStorage.getItem(`MCP_USE_ANONYMIZED_TELEMETRY`)===`false`)return!0}catch{}return!1}function DA(){try{return`session-${hA()}`}catch{return`session-${Date.now()}-${gA()}`}}var OA=class e{static instance=null;UNKNOWN_USER_ID=`UNKNOWN_USER_ID`;_currUserId=null;_telemetryEnabled=!1;_pending=new Set;_scarfEnabled=!1;_runtimeEnvironment;_storageCapability;_storage;_fsBacked;_source;_productVersion;constructor(){this._runtimeEnvironment=wA(),this._fsBacked=xA!==null,this._storage=xA??CA()??null,this._storageCapability=this._storage?`persistent`:`session-only`,this._source=TA()||this._runtimeEnvironment;let e=EA(),t=this._runtimeEnvironment!==`unknown`;e?(this._telemetryEnabled=!1,$.debug(`Telemetry disabled via opt-out`)):t?($.debug(`Anonymized telemetry enabled. Set MCP_USE_ANONYMIZED_TELEMETRY=false to disable.`),this._telemetryEnabled=!0,this._scarfEnabled=!0,this._fsBacked&&setTimeout(()=>{this.trackPackageDownload({triggered_by:`initialization`}).catch(e=>$.debug(`Failed to track package download: ${e}`))},0)):(this._telemetryEnabled=!1,$.debug(`Telemetry disabled - unknown environment: ${this._runtimeEnvironment}`))}get runtimeEnvironment(){return this._runtimeEnvironment}get storageCapability(){return this._storageCapability}static getInstance(){return e.instance||=new e,e.instance}setSource(e){this._source=e;try{SA()&&localStorage.setItem(`MCP_USE_TELEMETRY_SOURCE`,e)}catch{}$.debug(`Telemetry source set to: ${e}`)}getSource(){return this._source}setProductVersion(e){this._productVersion=e}get isEnabled(){return this._telemetryEnabled||this._scarfEnabled}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=hA();return this._storage.setUserId(t),this._currUserId=t,t}this._currUserId=DA()}catch{this._currUserId=this.UNKNOWN_USER_ID}return this._currUserId}async capture(e){if(!this._telemetryEnabled&&!this._scarfEnabled)return;let t=this.userId,n={...e.properties,mcp_use_version:this._productVersion??Lk(),language:`typescript`,source:this._source,runtime:this._runtimeEnvironment};if(this._telemetryEnabled){let r=pA({host:bA,apiKey:yA,event:e.name,distinctId:t,properties:n});this._pending.add(r),r.finally(()=>this._pending.delete(r))}if(this._scarfEnabled){let r=mA({...n,user_id:t,event:e.name});this._pending.add(r),r.finally(()=>this._pending.delete(r))}}async trackPackageDownload(e){if(!this._scarfEnabled||!this._fsBacked||!this._storage)return;let t=Lk(),n=this._storage.getDownloadedVersion(),r=!1,i=!1;n?_A(t,n)&&(i=!0,this._storage.setDownloadedVersion(t)):(i=!0,r=!0,this._storage.setDownloadedVersion(t)),i&&await mA({...e||{},mcp_use_version:t,user_id:this.userId,event:`package_download`,first_download:r,language:`typescript`,source:this._source,runtime:this._runtimeEnvironment})}async trackAgentExecution(e){this.isEnabled&&await this.capture(new Zk(e))}async trackMCPClientInit(e){this.isEnabled&&await this.capture(new Qk(e))}async trackConnectorInit(e){this.isEnabled&&await this.capture(new $k(e))}async trackClientAddServer(e,t){this.isEnabled&&await this.capture(new eA({serverName:e,serverConfig:t}))}async trackClientRemoveServer(e){this.isEnabled&&await this.capture(new tA({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&&pA({host:bA,apiKey:yA,event:`$identify`,distinctId:e,properties:{$set:t??{}}})}reset(){this._currUserId=null}flush(){Promise.allSettled([...this._pending])}async shutdown(){try{await Promise.allSettled([...this._pending]),$.debug(`Telemetry fetch captures flushed`)}catch(e){$.debug(`Error flushing telemetry captures: ${e}`)}}},kA=5*6e4;function AA(e,t=0){if(!e||t>5)return!1;if(e instanceof xS)return!0;if(e instanceof Error){if(e.code===401||e.name===`UnauthorizedError`)return!0;let n=e.message??``;if(n.includes(`401`)||n.includes(`Unauthorized`)||e.cause&&AA(e.cause,t+1))return!0;let r=e.data;if(r?.cause&&AA(r.cause,t+1))return!0}return!1}async function jA(e,t,n={}){let r=e,i=n.timeoutMs??kA,a=n.fetchFn??r.getProxyFetch?.()??void 0;if(!r.hasPendingFlow){let n=await BS(e,{serverUrl:t,fetchFn:a});if(n===`AUTHORIZED`)return;if(n!==`REDIRECT`)throw Error(`Unexpected OAuth auth() result: ${n}`)}if(typeof r.getAuthorizationCode==`function`){await BS(e,{serverUrl:t,authorizationCode:await r.getAuthorizationCode(),fetchFn:a});return}await MA(r,i)}async function MA(e,t){if(typeof window>`u`)throw Error(`OAuth redirect requires a browser environment or a provider with getAuthorizationCode()`);if(e.useRedirectFlow)return;let n=e.getKey?.(`tokens`);if(!n)throw Error(`Browser OAuth provider must expose getKey() for token storage`);let r=null,i=e.getLastAttemptedAuthUrl?.();if(i)try{r=new URL(i).searchParams.get(`state`)}catch{}let a=await Sk({popup:null,state:r,tokensKey:n,timeoutMs:t});switch(a.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(a.error);default:throw Error(`Unexpected OAuth popup result`)}}ck();var NA=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){e===`notification`&&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 protocolEra(){return this.connector.protocolEra}get negotiatedProtocolVersion(){return this.connector.negotiatedProtocolVersion}get info(){let e=this.protocolEra,t=this.negotiatedProtocolVersion,n=this.serverInfo;if(!e||!t||!n)throw Error(`MCP connection is not initialized`);let r=this.serverCapabilities,i=r.extensions&&typeof r.extensions==`object`&&!Array.isArray(r.extensions)?r.extensions:{};return{protocolEra:e,protocolVersion:t,server:n,capabilities:r,instructions:this.connector.instructions,extensions:i}}supports(e){return e in this.serverCapabilities}async callTool(e,t={},n){return this.connector.callTool(e,t,n)}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){return this.connector.getPrompt(e,t)}async request(e,t=null,n){return this.connector.request(e,t,n)}},PA;function FA(e,t){PA?.addServer(e,t)}function IA(e){PA?.removeServer(e)}function LA(e){return!!e&&typeof e==`object`&&`redirectUrl`in e&&`clientMetadata`in e}var RA=class{config={};sessions={};activeSessions=[];constructor(e){e&&(this.config=e)}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,FA(e,t)}async removeServer(e){this.config.mcpServers?.[e]&&(await this.closeSession(e),delete this.config.mcpServers[e],IA(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 n=this.config.mcpServers??{};if(Object.keys(n).length===0&&$.warn(`No MCP servers defined in config`),!n[e])throw Error(`Server '${e}' not found in config`);let r={...n[e]},i;if(zk(r)){let e=r.oauth===!1?void 0:r.oauth??{};i=await this.createDefaultOAuthProvider(r.url,e),r={...r,authProvider:i}}else `authProvider`in r&&r.authProvider&&LA(r.authProvider)&&(i=r.authProvider);let a=async()=>{let e=new NA(await Promise.resolve(this.createConnectorFromConfig(r)));return t&&await e.initialize(),e},o;try{o=await a()}catch(n){let s=r;if(!t||!i||!(`url`in s)||!AA(n)||i.preventAutoAuth)throw n;$.info(`[MCPClient] Unauthorized connecting to '${e}'; completing OAuth\u2026`),await jA(i,s.url),o=await a()}return this.sessions[e]=o,this.activeSessions.includes(e)||this.activeSessions.push(e),o}async connect(e){return this.createSession(e)}async createAllSessions(e=!0){let t=this.config.mcpServers??{};Object.keys(t).length===0&&$.warn(`No MCP servers defined in config`);for(let n of Object.keys(t))await this.createSession(n,e);return this.sessions}async connectAll(){return this.createAllSessions()}getSession(e){return this.sessions[e]||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){$.warn(`No session exists for server ${e}, nothing to close`);return}try{$.debug(`Closing session for server ${e}`),await t.disconnect()}catch(t){$.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 n of e)try{$.debug(`Closing session for server ${n}`),await this.closeSession(n)}catch(e){let r=`Failed to close session for server '${n}': ${e}`;$.error(r),t.push(r)}t.length?$.error(`Encountered ${t.length} errors while closing sessions`):$.debug(`All sessions closed successfully`)}async close(){await this.closeAllSessions()}};function zA(e){let t=Object.keys(e.mcpServers??{});OA.getInstance().trackMCPClientInit({codeMode:!1,sandbox:!1,allCallbacks:!1,verify:!1,servers:t,numServers:t.length,isBrowser:!0}).catch(e=>$.debug(`Failed to track BrowserMCPClient init: ${e}`))}var BA=class e extends RA{static getPackageVersion(){return Lk()}constructor(e){super(e),zA(this.config)}static fromDict(t){return new e(t)}async createDefaultOAuthProvider(e,t={}){return Yk(e,t)}createConnectorFromConfig(e){let{url:t,headers:n,fetch:r,authToken:i,authProvider:a,wrapTransport:o,clientOptions:s,protocolNegotiation:c,timeout:l,gatewayUrl:u,serverId:d,reconnectionOptions:f}=e;if(!t)throw Error(`Server URL is required`);let p=this.config,m=Rk(e,p),h=Vk(e.clientInfo??this.config.clientInfo),g={headers:n,fetch:r??globalThis.fetch.bind(globalThis),authToken:i,authProvider:a,wrapTransport:o,clientOptions:s,onSampling:m.onSampling,onElicitation:m.onElicitation,onNotification:m.onNotification,protocolNegotiation:c,timeout:l,clientInfo:h,gatewayUrl:u,serverId:d,reconnectionOptions:f};return $.debug(`[BrowserMCPClient] Connector options prepared (clientOptions: ${s?`provided`:`none`})`),new Fk(t,g)}};ck();var VA=`https://favicon.tools.mcp-use.com`,HA=/^\d{1,3}(\.\d{1,3}){3}$/;function UA(e){try{let t=e.includes(`://`)?e:`https://${e}`;return new URL(t).hostname}catch{return null}}function WA(e){let t=e.toLowerCase();if(t===`localhost`||t.endsWith(`.localhost`)||t===`host.docker.internal`||t===`0.0.0.0`)return!0;if(!HA.test(t))return!1;if(t===`127.0.0.1`||t.startsWith(`127.`)||t.startsWith(`10.`)||t.startsWith(`192.168.`))return!0;let n=/^172\.(\d+)\./.exec(t);if(n){let e=Number.parseInt(n[1],10);if(e>=16&&e<=31)return!0}return!1}function GA(e){let t=e.split(`.`);return Array.from({length:t.length-1},(e,n)=>t.slice(n).join(`.`))}function KA(e){return new Promise((t,n)=>{let r=new FileReader;r.onloadend=()=>t(r.result),r.onerror=n,r.readAsDataURL(e)})}async function qA(e){try{let t=UA(e);if(!t||WA(t))return null;for(let e of GA(t))try{let t=await fetch(`${VA}/${e}?response=json`,{signal:AbortSignal.timeout(2e3)});if(!t.ok)continue;let n=await t.json();if(n.source==="default")continue;let r=n.url.replace(/^http:\/\//,`https://`),i=await fetch(r,{signal:AbortSignal.timeout(2e3)});if(!i.ok)continue;return await KA(await i.blob())}catch{continue}return null}catch(e){return console.warn(`[favicon] Error detecting favicon:`,e),null}}var JA=`inspector-server`;function YA(e,t){if(!e)throw Error(t)}async function XA(e){try{let t=e.serverInfo.icons?.[0]?.src;if(t){e.addLog(`info`,`Server provided icon:`,t);let n=await(await fetch(t)).blob(),r=await new Promise((e,t)=>{let r=new FileReader;r.onloadend=()=>e(r.result),r.onerror=t,r.readAsDataURL(n)});return e.isMounted()&&(e.setServerInfo(e=>e?{...e,icon:r}:void 0),e.addLog(`debug`,`Server icon converted to base64`)),r}if(e.url){let t=await qA(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 ZA(e,t){return t?`state=${e}`:`client disconnected (state=${e})`}function QA(e){return{name:e.name,version:e.version,uri:e.websiteUrl,logo_uri:e.icons?.[0]?.src}}function $A(e){let t=(e instanceof Error?e.message:String(e)).toLowerCase();return t.includes(`oauth discovery failed`)||t.includes(`oauth-authorization-server`)||t.includes(`not valid json`)||t.includes(`404`)&&(t.includes(`openid-configuration`)||t.includes(`oauth-protected-resources`)||t.includes(`oauth-authorization-url`)||t.includes(`register`))||t.includes(`invalid oauth error response`)&&t.includes(`not found`)}function ej(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}}function tj(e){let t=ej(e.gatewayUrl,e.oauthProxyUrl);return{provider:new Jk(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 nj(e){let t=null,n=Date.now(),r=!1,i=e.healthCheckIntervalMs??1e4,a=e.healthCheckTimeoutMs??3e4;return t=setInterval(async()=>{if(!r){if(!e.isMountedRef.current||e.stateRef.current!==`ready`){t&&=(clearInterval(t),null);return}try{let i=e.gatewayUrl||e.url;if(!i)return;let a=e.getAuthHeaders?await e.getAuthHeaders():{},o=await fetch(i,{method:`HEAD`,headers:{...e.allHeaders,...a},signal:AbortSignal.timeout(5e3)});if(o.status===405||o.status===404){r=!0,n=Date.now(),t&&=(clearInterval(t),null);return}if(o.ok||o.status<500)n=Date.now();else throw Error(`Server returned ${o.status}`)}catch{let r=Date.now()-n;r>a&&(e.addLog(`warn`,`Connection appears to be broken (no response for ${Math.round(r/1e3)}s), attempting to reconnect...`),t&&=(clearInterval(t),null),e.autoReconnectRef.current&&e.isMountedRef.current&&(e.setState(`discovering`),e.addLog(`info`,`Auto-reconnecting to MCP server...`),setTimeout(()=>{e.isMountedRef.current&&e.stateRef.current===`discovering`&&e.connect()},typeof e.autoReconnectRef.current==`number`?e.autoReconnectRef.current:e.defaultReconnectDelay)))}}},i),()=>{t&&=(clearInterval(t),null)}}function rj(e,t){let n=e.connectionRef.current;if(e.stateRef.current!==`ready`||!e.hasClient()||!n)throw Error(`MCP client is not ready (${ZA(e.stateRef.current,e.hasClient())}). Cannot ${t}.`);return n}function ij(e){let t=(0,z.useCallback)(async(t,n,r)=>{let i=rj(e,`call tool "${t}"`);e.addLog(`info`,`Calling tool: ${t}`,n);let a=Date.now();try{let o=await i.callTool(t,n||{},r);return e.addLog(`info`,`Tool "${t}" call successful:`,o),OA.getInstance().trackUseMcpToolCall({toolName:t,success:!0,executionTimeMs:Date.now()-a}).catch(()=>{}),o}catch(n){throw e.addLog(`error`,`Tool "${t}" call failed:`,n),OA.getInstance().trackUseMcpToolCall({toolName:t,success:!1,errorType:n instanceof Error?n.name:`UnknownError`,executionTimeMs:Date.now()-a}).catch(()=>{}),n}},[e.addLog]),n=(0,z.useCallback)(async()=>{let t=rj(e,`list resources`);e.addLog(`info`,`Listing resources`);let n=await t.listAllResources();e.setResources(n.resources||[])},[e.addLog]),r=(0,z.useCallback)(async t=>{let n=rj(e,`read resource`);e.addLog(`info`,`Reading resource: ${t}`);try{let e=await n.readResource(t);return OA.getInstance().trackUseMcpResourceRead({resourceUri:t,success:!0}).catch(()=>{}),e}catch(e){throw OA.getInstance().trackUseMcpResourceRead({resourceUri:t,success:!1,errorType:e instanceof Error?e.name:`UnknownError`}).catch(()=>{}),e}},[e.addLog]),i=(0,z.useCallback)(async()=>{let t=rj(e,`list prompts`);e.addLog(`info`,`Listing prompts`);let n=await t.listPrompts();e.setPrompts(n.prompts||[])},[e.addLog]),a=(0,z.useCallback)(async()=>{if(!(e.stateRef.current!==`ready`||!e.connectionRef.current))try{e.setTools(await e.connectionRef.current.listTools()||[])}catch(t){e.addLog(`error`,`Failed to refresh tools:`,t)}},[e.addLog]),o=(0,z.useCallback)(async()=>{if(!(e.stateRef.current!==`ready`||!e.connectionRef.current))try{let t=await e.connectionRef.current.listAllResources();e.setResources(t.resources||[])}catch(t){e.addLog(`warn`,`Failed to refresh resources:`,t)}},[e.addLog]),s=(0,z.useCallback)(async()=>{if(!(e.stateRef.current!==`ready`||!e.connectionRef.current))try{let t=await e.connectionRef.current.listPrompts();e.setPrompts(t.prompts||[])}catch(t){e.addLog(`warn`,`Failed to refresh prompts:`,t)}},[e.addLog]),c=(0,z.useCallback)(async()=>{let t=await rj(e,`refresh resource templates`).listResourceTemplates();e.isMounted()&&e.setResourceTemplates(t.resourceTemplates||[])},[e.addLog]);return{callTool:t,listResources:n,readResource:r,listPrompts:i,refreshTools:a,refreshResources:o,refreshPrompts:s,refreshResourceTemplates:c,refreshAll:(0,z.useCallback)(()=>Promise.all([a(),o(),c(),s()]).then(()=>void 0),[a,o,c,s]),getPrompt:(0,z.useCallback)(async(t,n)=>rj(e,`get prompt`).getPrompt(t,n||{}),[e.addLog]),complete:(0,z.useCallback)(async t=>rj(e,`request completion`).complete(t),[e.addLog])}}var aj=3e3,oj=5e3;function sj(e){let{url:t,enabled:n=!0,callbackUrl:r=typeof window<`u`?Uk(new URL(`/oauth/callback`,window.location.origin).toString()):`/oauth/callback`,storageKeyPrefix:i=`mcp:auth`,authProvider:a,headers:o,proxyConfig:s,oauthProxyUrl:c,autoProxyFallback:l=!1,logLevel:u=`silent`,autoRetry:d=!1,autoReconnect:f=!0,reconnectionOptions:p,preventAutoAuth:m=!0,useRedirectFlow:h=!1,onPopupWindow:g,timeout:_=3e4,wrapTransport:v,serverId:y,fetch:b,clientOptions:x,protocolNegotiation:S,onNotification:C,onSampling:w,onElicitation:T,oauth:E}=e,ee=`http`,D=E?.clientId?.trim()||void 0,te=E?.clientMetadataUrl?.trim()||void 0,ne=E?.scope?.trim()||void 0,re=(0,z.useMemo)(()=>D?{client_id:D}:void 0,[D]),O=(0,z.useMemo)(()=>{let e=`useMcp:${t||`no-url`}`,n=sk.get(e);return u&&(n.level=u),n},[t,u]),ie=o??{},k=(0,z.useMemo)(()=>Hk(x),[x]),A=w,j=T,ae=(0,z.useMemo)(()=>({name:`mcp-use`,title:`mcp-use`,version:Lk(),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`}),[]),oe=(0,z.useMemo)(()=>e.clientInfo?{...ae,...e.clientInfo}:ae,[e.clientInfo,ae]),se=(0,z.useMemo)(()=>QA(oe),[oe]),ce=(0,z.useMemo)(()=>{if(!l)return{enabled:!1,proxyAddress:void 0};if(typeof l==`boolean`){let e=s?.proxyAddress;return{enabled:l&&!!e,proxyAddress:e}}let e=l.proxyAddress??s?.proxyAddress;return{enabled:l.enabled!==!1&&!!e,proxyAddress:e}},[l,s]),M=(0,z.useMemo)(()=>f===!1?{enabled:!1,initialDelay:0,healthCheckInterval:!1,healthCheckTimeout:3e4}:f===!0?{enabled:!0,initialDelay:aj,healthCheckInterval:1e4,healthCheckTimeout:3e4}:typeof f==`number`?{enabled:!0,initialDelay:f,healthCheckInterval:1e4,healthCheckTimeout:3e4}:{enabled:f.enabled!==!1,initialDelay:f.initialDelay??aj,healthCheckInterval:f.healthCheckInterval??1e4,healthCheckTimeout:f.healthCheckTimeout??3e4},[f]),[N,le]=(0,z.useState)(void 0);(0,z.useEffect)(()=>{le(void 0)},[t,s]);let ue=(0,z.useMemo)(()=>{if(!N?.proxyAddress)return s;let e=s?.headers??{};return{...N,headers:{...e,...N.headers??{}}}},[N,s]),de=ue?.proxyAddress,fe=ue?.headers??{},pe=(0,z.useMemo)(()=>t||``,[t]),me=(0,z.useMemo)(()=>({...fe,...ie}),[fe,ie]),[he,ge]=(0,z.useState)(`discovering`),[_e,ve]=(0,z.useState)([]),[ye,be]=(0,z.useState)([]),[xe,P]=(0,z.useState)([]),[Se,Ce]=(0,z.useState)([]),[we,Te]=(0,z.useState)(e._initialServerInfo?.name?e._initialServerInfo:void 0),[Ee,De]=(0,z.useState)(),[Oe,ke]=(0,z.useState)(void 0),[Ae,je]=(0,z.useState)(void 0),[Me,Ne]=(0,z.useState)(),[Pe,Fe]=(0,z.useState)({}),[Ie,Le]=(0,z.useState)(void 0),[Re,ze]=(0,z.useState)([]),[Be,Ve]=(0,z.useState)(void 0),[He,Ue]=(0,z.useState)(void 0),We=(0,z.useRef)(null),Ge=(0,z.useRef)(null),Ke=(0,z.useRef)(a??null),qe=(0,z.useRef)(null),Je=(0,z.useRef)(!1),Ye=(0,z.useRef)(!0),Xe=(0,z.useRef)(0),Ze=(0,z.useRef)(0),Qe=(0,z.useRef)(null),$e=(0,z.useRef)(!1),et=(0,z.useRef)(!1),tt=(0,z.useRef)(he),nt=(0,z.useRef)(f),rt=(0,z.useRef)(null),it=(0,z.useRef)(null),at=(0,z.useRef)(null),ot=(0,z.useRef)(A),st=(0,z.useRef)(j),ct=(0,z.useRef)(A!==void 0),lt=(0,z.useRef)(j!==void 0),ut=(0,z.useRef)(C);A!==void 0&&(ot.current=A),j!==void 0&&(st.current=j),ct.current=A!==void 0,lt.current=j!==void 0,ut.current=C;let dt=(0,z.useCallback)(async e=>ot.current(e),[]),ft=(0,z.useCallback)(async e=>st.current(e),[]),pt=(0,z.useCallback)(e=>{ut.current?.(e)},[]);(0,z.useEffect)(()=>{tt.current=he,nt.current=f},[he,f]),(0,z.useEffect)(()=>{Ke.current=a??null},[a]);let F=(0,z.useCallback)((e,t,...n)=>{let r=n.length>0?`${t} ${n.map(e=>JSON.stringify(e)).join(` `)}`:t,i=`[useMcp] ${r}`;switch(e){case`error`:O.error(i);break;case`warn`:O.warn(i);break;case`info`:O.info(i);break;case`debug`:O.debug(i);break;default:O.info(i)}Ye.current&&ze(t=>[...t.slice(-100),{level:e,message:r,timestamp:Date.now()}])},[O]),mt=ij({stateRef:tt,connectionRef:Ge,hasClient:()=>We.current!==null,isMounted:()=>Ye.current,setTools:ve,setResources:be,setResourceTemplates:P,setPrompts:Ce,addLog:F}),ht=(0,z.useCallback)(async(e=!1)=>{e||F(`info`,`Disconnecting...`),Je.current=!1,Qe.current&&clearTimeout(Qe.current),Qe.current=null;let t=Ze.current,n=We.current;if(n)try{let e=JA,t=n===We.current?Ge.current:null;t&&t._healthCheckCleanup&&(t._healthCheckCleanup(),t._healthCheckCleanup=null),t&&await n.closeSession(e)}catch(t){e||F(`warn`,`Error closing connection:`,t)}let r=Ze.current!==t;We.current===n&&!r&&(We.current=null,Ge.current=null),Ye.current&&!e&&!r&&(ge(`discovering`),ve([]),be([]),P([]),Ce([]),Le(void 0),Ve(void 0),Ue(void 0),Te(void 0),De(void 0),ke(void 0),je(void 0),Ne(void 0),Fe({}))},[F]),gt=(0,z.useCallback)((e,n)=>{F(`error`,e,n??``);let r=n&&`code`in n?n.code:void 0,i=ce.enabled&&!ue?.proxyAddress,o=e.includes(`CORS`)||e.includes(`blocked by CORS policy`)||e.includes(`Failed to fetch`),s=r===400;if(i&&(o||s||typeof r==`number`&&r>=404&&r<500)&&!(r===401||r===403))return F(`info`,`Direct connection failed with ${o?`CORS error`:s?`HTTP 400 (Bad Request)`:`HTTP 4xx error`}. Trying with proxy...`),We.current=null,a||(Ke.current=null),F(`debug`,`Cleared client and auth provider for proxy fallback`),le({proxyAddress:ce.proxyAddress}),Ye.current&&ge(`discovering`),setTimeout(()=>{Ye.current&&it.current?.()},1e3),!0;if(Ye.current){F(`info`,`Setting state to FAILED:`,e),ge(`failed`),Le(e);let t=Ke.current?.getLastAttemptedAuthUrl?.();t&&(Ve(t),F(`info`,`Manual authentication URL may be available.`,t))}return Je.current=!1,t&&OA.getInstance().trackUseMcpConnection({url:t,transportType:ee,success:!1,errorType:n?.name||`UnknownError`,hasOAuth:!!Ke.current,hasSampling:ct.current,hasElicitation:lt.current}).catch(()=>{}),!1},[F,t,ee,ce,ue,a]),_t=(0,z.useCallback)(async()=>{if(!n||!t){F(`debug`,n?`No server URL provided, skipping connection.`:`Connection disabled via enabled flag.`);return}if(Je.current){F(`debug`,`Connection attempt already in progress.`);return}if(!Ye.current){F(`debug`,`Connect called after unmount, aborting.`);return}if(Je.current=!0,Ze.current+=1,Xe.current+=1,Le(void 0),Ve(void 0),rt.current=null,ge(`discovering`),ve([]),be([]),P([]),Ce([]),Te(void 0),De(void 0),ke(void 0),je(void 0),Ne(void 0),Fe({}),F(`info`,`Connecting attempt #${Xe.current} to ${t}...`),!Ke.current){let{provider:e,oauthProxyUrl:t}=tj({effectiveOAuthUrl:pe,storageKeyPrefix:i,oauthClientConfig:se,callbackUrl:r,preventAutoAuth:m,useRedirectFlow:h,gatewayUrl:de,oauthProxyUrl:c,onPopupWindow:g,proxyOAuthRequests:!0,staticClientInfo:re,clientMetadataUrl:te,scope:ne});Ke.current=e,t&&F(`debug`,`OAuth BFF enabled: ${t}`),F(`debug`,`BrowserOAuthClientProvider initialized with URL: ${pe}, proxy: ${t?`enabled`:`disabled`}, gateway: ${de?`enabled`:`disabled`}`)}We.current?F(`debug`,`BrowserMCPClient already exists, reusing.`):(We.current=new BA,F(`debug`,`BrowserMCPClient initialized in connect.`));let e=async n=>{if(!Ye.current)return F(`debug`,`Connection attempt aborted - component unmounted`),`failed`;F(`info`,`Attempting connection with transport: ${n}`),F(`debug`,`Client ref status at start of tryConnectWithTransport: ${We.current?`initialized`:`NULL`}`);try{let e=JA,r={url:t,timeout:_,clientInfo:oe,...(()=>{let e=Ke.current?.getProxyFetch?.(b)??b;return e?{fetch:e}:{}})(),...k&&{clientOptions:k},...S!==void 0&&{protocolNegotiation:S},...p?{reconnectionOptions:p}:f===!1?{reconnectionOptions:{maxRetries:0}}:{}};if(de&&(r.gatewayUrl=de,F(`debug`,`Using proxy gateway: ${de} for target: ${t}`)),me&&Object.keys(me).length>0&&(r.headers=me),!We.current){if(!Ye.current)return F(`debug`,`Connection aborted - component unmounted, client cleaned up`),`failed`;let e=Error(`Client not initialized - this is a bug in the connection flow`);throw F(`error`,`Client ref is null in tryConnectWithTransport but component is still mounted`),e}We.current.addServer(e,{...r,authProvider:Ke.current,onSampling:ct.current?dt:void 0,onElicitation:lt.current?ft:void 0,onNotification:e=>{F(`debug`,`Notification received:`,e.method,e),pt(e),e.method===`notifications/tools/list_changed`?(F(`info`,`Tools list changed, auto-refreshing...`),mt.refreshTools().catch(e=>F(`warn`,`Auto-refresh tools failed:`,e))):e.method===`notifications/resources/list_changed`?(F(`info`,`Resources list changed, auto-refreshing...`),mt.refreshResources().catch(e=>F(`warn`,`Auto-refresh resources failed:`,e))):e.method===`notifications/prompts/list_changed`&&(F(`info`,`Prompts list changed, auto-refreshing...`),mt.refreshPrompts().catch(e=>F(`warn`,`Auto-refresh prompts failed:`,e)))},wrapTransport:v?n=>(F(`debug`,`Applying transport wrapper for server:`,e,`url:`,t),v(n,y??t)):void 0});let i=await We.current.connect(e);if(Ge.current=i,!Ye.current)return F(`debug`,`Connection aborted after connection creation - component unmounted`),`failed`;F(`info`,`✅ Successfully connected to MCP server`),F(`info`,`Server info:`,i.info.server),F(`info`,`Server capabilities:`,i.info.capabilities),M.enabled&&M.healthCheckInterval!==!1&&(i._healthCheckCleanup=nj({gatewayUrl:de,url:t,allHeaders:me,getAuthHeaders:async()=>{try{let e=await Ke.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:Ye,stateRef:tt,autoReconnectRef:nt,setState:ge,addLog:F,connect:_t,defaultReconnectDelay:M.initialDelay,healthCheckIntervalMs:M.healthCheckInterval,healthCheckTimeoutMs:M.healthCheckTimeout})),OA.getInstance().trackUseMcpConnection({url:t,transportType:n,success:!0,hasOAuth:!!Ke.current,hasSampling:ct.current,hasElicitation:lt.current}).catch(()=>{}),ve(i.tools||[]);let[a,o,s]=await Promise.all([i.listAllResources(),i.listPrompts(),i.supports(`resources`)?i.listResourceTemplates():Promise.resolve({resourceTemplates:[]})]);if(!Ye.current)return F(`debug`,`Connection aborted after discovery - component unmounted`),`failed`;be(a.resources||[]),Ce(o.prompts||[]),P(s.resourceTemplates||[]);let{server:c,capabilities:l,protocolEra:u,protocolVersion:d,instructions:m,extensions:h}=i.info;if(Ye.current&&(ke(u),je(d),Ne(m),Fe(h)),c){if(F(`debug`,`Server info:`,c),!Ye.current)return F(`debug`,`Skipping state update - component unmounted`),`failed`;Te(c),qe.current=XA({serverInfo:c,url:t,isMounted:()=>Ye.current,setServerInfo:Te,addLog:F})}if(l){if(F(`debug`,`Server capabilities:`,l),!Ye.current)return F(`debug`,`Skipping state update - component unmounted`),`failed`;De(l)}if(Ke.current){let e=await Ke.current.tokens?.();if(!Ye.current)return F(`debug`,`Connection aborted after token fetch for auth tokens - component unmounted`),`failed`;if(e?.access_token){let t=e.expires_in?Date.now()+e.expires_in*1e3:void 0,n=null,r=null;try{n=await Ke.current.getTokenEndpoint?.()??null}catch{n=null}try{r=await Ke.current.getClientCredentials?.()??null}catch{r=null}if(!Ye.current)return F(`debug`,`Skipping state update - component unmounted`),`failed`;Ue({access_token:e.access_token,token_type:e.token_type||`Bearer`,expires_at:t,refresh_token:e.refresh_token,scope:e.scope,...n?{token_endpoint:n}:{},...r?.client_id?{client_id:r.client_id}:{},...r?.client_secret?{client_secret:r.client_secret}:{}})}}return rt.current=n,ge(`ready`),`success`}catch(r){let i=r,a=i?.message||String(r),o=Ke.current?.getLastAttemptedAuthUrl?.();if(o&&Ke.current&&m)return F(`info`,`OAuth already discovered (stored auth URL present); awaiting manual authentication.`),Ye.current&&(ge(`pending_auth`),Ve(o)),Je.current=!1,`auth_redirect`;let s=$A(r),c=AA(r);if(s&&ie&&Object.keys(ie).length>0)return gt(`Authentication failed (HTTP 401). Server does not support OAuth. Check your Authorization header value is correct.`),`failed`;if(s&&(!ie||Object.keys(ie).length===0))return gt(`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(c){if(s)return gt(`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(Ke.current)if(F(`info`,`Authentication required. OAuth provider available.`),m){if(F(`info`,`Waiting for user to initiate authentication flow...`),Ye.current){ge(`pending_auth`);let e=Ke.current?.getLastAttemptedAuthUrl?.();e&&(Ve(e),F(`info`,`Retrieved stored auth URL for manual authentication`))}return Je.current=!1,`auth_redirect`}else{F(`info`,`Triggering automatic OAuth authentication flow...`);try{if(await BS(Ke.current,{serverUrl:t,fetchFn:Ke.current.getProxyFetch?.()})===`REDIRECT`){let e=await Ke.current.getAuthorizationCode?.();if(!e)throw Error(`Authorization code not captured by headless provider`);await BS(Ke.current,{serverUrl:t,authorizationCode:e,fetchFn:Ke.current.getProxyFetch?.()})}return F(`info`,`OAuth flow completed, reconnecting...`),await e(n)}catch(e){return gt(`Automatic OAuth authentication failed: ${e instanceof Error?e.message:String(e)}`,e instanceof Error?e:Error(String(e))),`failed`}}return ie&&Object.keys(ie).length>0?(gt(`Authentication failed: Server returned 401 Unauthorized. Check your Authorization header value is correct.`),`failed`):(gt(`Authentication required: Server returned 401 Unauthorized. Add an Authorization header in the Custom Headers section (e.g., Authorization: Bearer YOUR_API_KEY).`),`failed`)}return gt(a,i instanceof Error?i:Error(String(i)))?`auth_redirect`:`failed`}},a=`failed`;F(`debug`,`Connecting via streamable HTTP`),a=await e(`http`),(a===`success`||a===`failed`||a===`auth_redirect`)&&(Je.current=!1),F(`debug`,`Connection sequence finished with status: ${a}`)},[F,gt,ht,t,i,r,se.name,se.version,se.uri,se.logo_uri,re,te,ne,ie,ee,m,h,g,n,_,oe,k,S,de,c,me,pe,dt,ft,pt]);(0,z.useEffect)(()=>{it.current=_t,at.current=gt},[_t,gt]);let vt=(0,z.useCallback)(()=>{tt.current===`failed`?(F(`info`,`Retry requested...`),it.current?.()):F(`warn`,`Retry called but state is not 'failed' (state: ${tt.current}). Ignoring.`)},[F]),yt=(0,z.useCallback)(async()=>{F(`info`,`Manual authentication requested...`);let e=tt.current;if(e===`failed`)F(`info`,`Attempting to reconnect and authenticate via retry...`),vt();else if(e===`pending_auth`){F(`info`,`Proceeding with authentication from pending state...`);try{if(YA(Ke.current,`Auth Provider not available for manual auth`),YA(t,`Server URL is required for authentication`),a){F(`info`,`Using provided authProvider for manual authentication`);let e=new URL(t),n=e.origin+e.pathname.replace(/\/+$/,``);await BS(Ke.current,{serverUrl:n,fetchFn:Ke.current.getProxyFetch?.()}),it.current?.();return}F(`info`,`Cleared ${Ke.current.clearStorage?.()??0} OAuth storage item(s) for fresh authentication`),ge(`authenticating`);let e=null,n=null,{provider:o,oauthProxyUrl:s}=tj({effectiveOAuthUrl:pe,storageKeyPrefix:i,oauthClientConfig:se,callbackUrl:r,preventAutoAuth:!1,useRedirectFlow:h,gatewayUrl:de,oauthProxyUrl:c,onPopupWindow:(t,r,i)=>{e=i;try{n=new URL(t).searchParams.get(`state`)}catch{}g?.(t,r,i)},proxyOAuthRequests:!0,staticClientInfo:re,clientMetadataUrl:te,scope:ne});s&&F(`info`,`Scoped OAuth proxy fetch enabled for manual auth`),Ke.current=o,F(`info`,`Triggering fresh OAuth authorization...`);let l=new URL(t),u=l.origin+l.pathname.replace(/\/+$/,``);try{await BS(o,{serverUrl:u,fetchFn:o.getProxyFetch?.()}),F(`info`,`OAuth flow completed (tokens obtained)`)}catch(e){F(`info`,`OAuth flow initiated (popup/redirect):`,e instanceof Error?e.message:`Redirecting...`)}let d=o.getLastAttemptedAuthUrl?.();if(d&&(Ve(d),F(`info`,`Updated auth URL for fallback:`,d),!n))try{n=new URL(d).searchParams.get(`state`)}catch{}if(h)return;let f=o.getKey?.(`tokens`);if(!f){F(`warn`,`Could not derive tokens storage key; relying on callback listener.`);return}et.current=!0;let p;try{p=await Sk({popup:e,state:n,tokensKey:f})}finally{et.current=!1}if(!Ye.current)return;switch(p.kind){case`success`:F(`info`,`Authentication succeeded; reconnecting to MCP server...`),Je.current=!1,it.current?.();break;case`cancelled`:F(`warn`,`Authentication popup was closed before completing. Returning to pending_auth.`),ge(`pending_auth`);break;case`timeout`:F(`warn`,`Authentication timed out waiting for the popup. Returning to pending_auth.`),ge(`pending_auth`);break;case`error`:gt(`Authentication failed: ${p.error}`);break;default:break}}catch(e){if(!Ye.current)return;ge(`pending_auth`),F(`error`,`Manual authentication failed: ${e instanceof Error?e.message:String(e)}`)}}else if(e===`authenticating`){F(`warn`,`Already attempting authentication. Check for blocked popups or wait for timeout.`);let e=Ke.current?.getLastAttemptedAuthUrl?.();e&&!Be&&(Ve(e),F(`info`,`Manual authentication URL retrieved:`,e))}else F(`info`,`Client not in a state requiring manual authentication trigger (state: ${e}). If needed, try disconnecting and reconnecting.`)},[F,vt,gt,Be,t,h,g,i,se.name,se.uri,se.logo_uri,re,te,ne,r,oe,a]),bt=(0,z.useCallback)(()=>{Ke.current?.clearStorage?(F(`info`,`Cleared ${Ke.current.clearStorage()} item(s) from localStorage for ${t}.`),Ve(void 0),ht()):F(`warn`,`Auth provider not initialized, cannot clear storage.`)},[t,F,ht]);(0,z.useEffect)(()=>{if(typeof window>`u`)return;let e=(e,t)=>{if(et.current){F(`debug`,`Ignoring auth callback via ${t}; manual popup flow owns this result.`);return}let n=Ke.current?.serverUrlHash;if(e?.serverUrlHash&&n&&e.serverUrlHash!==n){F(`debug`,`Ignoring auth callback via ${t} for a different server.`);return}if(F(`info`,`Received auth callback via ${t}.`,e),Qe.current&&clearTimeout(Qe.current),Qe.current=null,e?.success)F(`info`,`Authentication successful via popup. Reconnecting client...`),Je.current&&F(`debug`,`Connection attempt already in progress, resetting flag to allow reconnection.`),Je.current=!1,setTimeout(()=>{Ye.current&&(F(`debug`,`Initiating reconnection after successful auth callback.`),it.current?.())},100);else{if(tt.current!==`authenticating`&&tt.current!==`pending_auth`){F(`debug`,`Ignoring stale auth failure callback (state=${tt.current}).`);return}at.current?.(`Authentication failed in callback: ${e?.error||`Unknown reason.`}`)}},t=t=>{t.origin===window.location.origin&&t.data?.type===bk&&e(t.data,`postMessage`)};window.addEventListener(`message`,t),F(`debug`,`Auth callback message listener added.`);let n=null,r=t=>{t.data?.type===bk&&e(t.data,`BroadcastChannel`)};if(typeof BroadcastChannel<`u`)try{n=new BroadcastChannel(yk),n.addEventListener(`message`,r),F(`debug`,`Auth callback BroadcastChannel listener added.`)}catch(e){F(`warn`,`Failed to open auth callback BroadcastChannel; lost-opener popups will not reach this client.`,e),n=null}return()=>{if(window.removeEventListener(`message`,t),F(`debug`,`Auth callback message listener removed.`),n){try{n.removeEventListener(`message`,r),n.close()}catch{}F(`debug`,`Auth callback BroadcastChannel listener removed.`)}Qe.current&&clearTimeout(Qe.current)}},[F]),(0,z.useEffect)(()=>{if(Ye.current=!0,!n||!t)return F(`debug`,n?`No server URL provided, skipping connection.`:`Connection disabled via enabled flag.`),ge(`discovering`),()=>{Ye.current=!1};if(F(`debug`,`useMcp mounted, initiating connection.`),Xe.current=0,a)Ke.current=a,F(`debug`,`Using externally provided authProvider`);else if(!Ke.current||Ke.current.serverUrl!==pe){let{provider:e,oauthProxyUrl:t}=tj({effectiveOAuthUrl:pe,storageKeyPrefix:i,oauthClientConfig:se,callbackUrl:r,preventAutoAuth:m,useRedirectFlow:h,gatewayUrl:de,oauthProxyUrl:c,onPopupWindow:g,proxyOAuthRequests:!0,staticClientInfo:re,clientMetadataUrl:te,scope:ne});Ke.current=e,t&&F(`debug`,`OAuth proxy URL in effect: ${t}`),F(`debug`,`BrowserOAuthClientProvider initialized/updated with URL: ${pe}, proxy: ${t?`enabled`:`disabled`}, gateway: ${de?`enabled`:`disabled`}`)}return _t(),()=>{Ye.current=!1,F(`debug`,`useMcp unmounting, disconnecting.`),ht(!0)}},[t,n,i,r,se.name,se.version,se.uri,se.logo_uri,re,te,ne,h,oe,pe,s,a]);let xt=(0,z.useRef)(vt),St=(0,z.useRef)(F);(0,z.useEffect)(()=>{xt.current=vt,St.current=F},[vt,F]),(0,z.useEffect)(()=>{let e=null;if(he===`failed`&&d&&Xe.current>0){if(!$e.current){$e.current=!0;let t=typeof d==`number`?d:oj;St.current(`info`,`Connection failed, auto-retrying in ${t}ms...`),e=setTimeout(()=>{$e.current=!1,Ye.current&&tt.current===`failed`&&xt.current()},t)}}else he!==`failed`&&($e.current=!1);return()=>{e&&(clearTimeout(e),$e.current=!1)}},[he,d]);let Ct=(0,z.useCallback)(async()=>tt.current===`ready`?we?.icon?we.icon:qe.current?(F(`debug`,`Waiting for icon to finish loading...`),await qe.current):(F(`debug`,`No icon available and no loading in progress`),null):(F(`warn`,`Cannot ensure icon loaded - not connected`),null),[we,F]);return{state:he,name:we?.name||t||``,tools:_e,resources:ye,resourceTemplates:xe,prompts:Se,serverInfo:we,capabilities:Ee,protocolEra:Oe,protocolVersion:Ae,instructions:Me,extensions:Pe,error:Ie,log:Re,authUrl:Be,authTokens:He,client:We.current,...mt,retry:vt,disconnect:ht,authenticate:yt,clearStorage:bt,ensureIconLoaded:Ct}}var cj=null;function lj(){return typeof window<`u`&&window.name.startsWith(`mcp_auth_`)}function uj(e,t,n){return{type:bk,success:e,...e?{}:{error:t??`Unknown error`},...n.state?{state:n.state}:{},...n.serverUrlHash?{serverUrlHash:n.serverUrlHash}:{}}}function dj(e){if(typeof BroadcastChannel>`u`)return;let t;try{t=new BroadcastChannel(yk),t.postMessage(e)}catch(e){console.warn(`[mcp-callback] Failed to broadcast callback result:`,e)}finally{t&&setTimeout(()=>{try{t?.close()}catch{}},0)}}function fj(e,t,n,r){if(typeof document>`u`)return;document.body.innerHTML=``;let i=document.createElement(`div`);i.style.fontFamily=`sans-serif`,i.style.padding=`20px`;let a=document.createElement(`h1`);a.textContent=e,i.appendChild(a);let o=document.createElement(`p`);o.textContent=t,n&&(o.style.color=`red`,o.style.backgroundColor=`#ffebeb`,o.style.border=`1px solid red`,o.style.padding=`10px`,o.style.borderRadius=`4px`),i.appendChild(o);let s=document.createElement(`a`);if(s.href=`#`,s.textContent=`Close this window`,s.onclick=e=>(e.preventDefault(),window.close(),!1),i.appendChild(s),r){let e=document.createTextNode(` or `),t=document.createElement(`a`);t.href=r,t.textContent=`return to the app`,i.append(e,t)}document.body.appendChild(i)}function pj(e){let t=`mcp:auth:state_${e}`,n=localStorage.getItem(t)?t:null;if(!n){let t=`:state_${e}`;for(let e=0;e<localStorage.length;e++){let r=localStorage.key(e);if(r?.endsWith(t)){n=r;break}}}let r=n?localStorage.getItem(n):null;if(!n||!r)throw Error(`Invalid or expired OAuth state "${e}".`);let i;try{i=JSON.parse(r)}catch{throw localStorage.removeItem(n),Error(`Failed to parse stored OAuth state.`)}return{key:n,value:i}}function mj(e,t){let n=new URL(e);n.searchParams.set(`auth_error`,`oauth_callback_failed`),n.searchParams.set(`auth_error_description`,t),window.location.href=n.toString()}function hj(e,t,n,r){let i=uj(e,t,r),a=n?.returnUrl,o=n?.flowType===`popup`||lj();if(n?.flowType===`redirect`&&a){e?window.location.href=a:mj(a,t??`Authentication failed.`);return}if(window.opener&&!window.opener.closed){window.opener.postMessage(i,window.location.origin),window.close();return}if(o){dj(i),fj(e?`Authentication Successful!`:`Authentication Error`,e?`You're authenticated. You can close this window and return to the app.`:t??`Authentication failed.`,!e,a);try{window.close()}catch{}return}if(a){e?window.location.href=a:mj(a,t??`Authentication failed.`);return}if(!e){fj(`Authentication Error`,t??`Authentication failed.`,!0);return}window.location.href=`/`}function gj(){return cj||=_j(),cj}async function _j(){let e=new URLSearchParams(window.location.search),t=e.get(`state`),n=null,r=null,i=null;try{if(!t)throw Error(`OAuth callback is missing the state parameter.`);let a=pj(t);if(n=a.key,r=a.value,!r.expiry||r.expiry<Date.now())throw localStorage.removeItem(n),Error(`OAuth state has expired. Please start authentication again.`);if(!r.providerOptions)throw Error(`Stored OAuth state is missing provider options.`);let{serverUrl:o,...s}=r.providerOptions;i=new Jk(o,s),await new GC(new URL(o),{authProvider:i,fetch:i.getProxyFetch()}).finishAuth(e),localStorage.removeItem(n),hj(!0,void 0,r,{state:t,serverUrlHash:r.serverUrlHash})}catch(e){let a=e instanceof Error?e.message:String(e);console.error(`[mcp-callback] OAuth callback failed:`,e),n&&localStorage.removeItem(n),i&&localStorage.removeItem(i.getKey(`last_auth_url`)),hj(!1,a,r,{state:t,serverUrlHash:r?.serverUrlHash})}}ck();var vj=[`url`,`displayName`,`enabled`,`proxyConfig`,`oauthProxyUrl`,`connectionMode`,`autoProxyFallback`,`callbackUrl`,`storageKeyPrefix`,`headers`,`logLevel`,`autoRetry`,`autoReconnect`,`reconnectionOptions`,`popupFeatures`,`preventAutoAuth`,`useRedirectFlow`,`clientOptions`,`protocolNegotiation`,`timeout`,`clientInfo`,`oauth`];function yj(e){let t={};for(let n of vj){let r=e[n];r!==void 0&&(t[n]=r)}return t}function bj(e){return yj(e)}var xj=500,Sj=5*6e4;function Cj(e){let[t,n]=(0,z.useState)([]),[r,i]=(0,z.useState)([]),[a,o]=(0,z.useState)([]),s=(0,z.useRef)(0),c=(0,z.useRef)(0),l=(0,z.useRef)(new Map),u=(0,z.useRef)(new Map),d=(0,z.useCallback)(e=>{for(let t of l.current.values())clearTimeout(t.timeout),t.reject(Error(e));l.current.clear();for(let t of u.current.values())clearTimeout(t.timeout),t.reject(Error(e));u.current.clear(),i([]),o([])},[]);(0,z.useEffect)(()=>()=>d(`MCP server connection was removed`),[d]);let f=(0,z.useCallback)(t=>{let r={id:globalThis.crypto?.randomUUID?.()??`${Date.now()}-${Math.random()}`,method:t.method,params:t.params,timestamp:Date.now(),read:!1};n(e=>[r,...e].slice(0,xj)),e.onNotificationReceived?.(r)},[e.onNotificationReceived]),p=(0,z.useCallback)((e,t)=>{let n=l.current.get(e);n&&(clearTimeout(n.timeout),l.current.delete(e),i(t=>t.filter(t=>t.id!==e)),n.resolve(t))},[]),m=(0,z.useCallback)((e,t)=>{let n=l.current.get(e);n&&(clearTimeout(n.timeout),l.current.delete(e),i(t=>t.filter(t=>t.id!==e)),n.reject(Error(t??`User rejected sampling request`)))},[]),h=(0,z.useCallback)(t=>new Promise((n,r)=>{let a=`sampling-${s.current++}`,o={id:a,request:{method:`sampling/createMessage`,params:t},timestamp:Date.now(),serverName:e.serverName},c=setTimeout(()=>m(a,`Sampling request timed out`),Sj);l.current.set(a,{resolve:n,reject:r,timeout:c}),i(e=>[...e,o]),e.onSamplingRequest?.(o),e.onGlobalSamplingRequest?.(o,e.serverId,e.serverName,p,m)}),[p,e,m]),g=(0,z.useCallback)((e,t)=>{let n=u.current.get(e);n&&(clearTimeout(n.timeout),u.current.delete(e),o(t=>t.filter(t=>t.id!==e)),n.resolve(t))},[]),_=(0,z.useCallback)((e,t)=>{let n=u.current.get(e);n&&(clearTimeout(n.timeout),u.current.delete(e),o(t=>t.filter(t=>t.id!==e)),n.reject(Error(t??`User rejected elicitation request`)))},[]),v=(0,z.useCallback)(t=>new Promise((n,r)=>{let i=`elicitation-${c.current++}`,a={id:i,request:t,timestamp:Date.now(),serverName:e.serverName},s=setTimeout(()=>_(i,`Elicitation request timed out`),Sj);u.current.set(i,{resolve:n,reject:r,timeout:s}),o(e=>[...e,a]),e.onElicitationRequest?.(a),e.onGlobalElicitationRequest?.(a,e.serverId,e.serverName,g,_)}),[g,e,_]),y=(0,z.useCallback)(e=>{n(t=>t.map(t=>t.id===e?{...t,read:!0}:t))},[]),b=(0,z.useCallback)(()=>n(e=>e.map(e=>({...e,read:!0}))),[]),x=(0,z.useCallback)(()=>n([]),[]);return{notifications:t,pendingSamplingRequests:r,pendingElicitationRequests:a,unreadNotificationCount:t.filter(e=>!e.read).length,markNotificationRead:y,markAllNotificationsRead:b,clearNotifications:x,approveSampling:p,rejectSampling:m,approveElicitation:g,rejectElicitation:_,onNotification:f,onSampling:h,onElicitation:v,rejectAll:d}}var wj=sk.get(`McpClientProvider`),Tj=(0,z.createContext)(null);function Ej(e,t){return JSON.stringify(e)===JSON.stringify(t)}function Dj(e,t){return e.id===t.id&&Ej(yj(e),yj(t))&&e.name===t.name&&e.state===t.state&&e.error===t.error&&e.authUrl===t.authUrl&&Ej(e.authTokens,t.authTokens)&&e.protocolEra===t.protocolEra&&e.protocolVersion===t.protocolVersion&&Ej(e.serverInfo,t.serverInfo)&&Ej(e.capabilities,t.capabilities)&&e.instructions===t.instructions&&Ej(e.extensions,t.extensions)&&Ej(e.tools,t.tools)&&Ej(e.resources,t.resources)&&Ej(e.resourceTemplates,t.resourceTemplates)&&Ej(e.prompts,t.prompts)&&Ej(e.notifications,t.notifications)&&e.unreadNotificationCount===t.unreadNotificationCount&&Ej(e.pendingSamplingRequests,t.pendingSamplingRequests)&&Ej(e.pendingElicitationRequests,t.pendingElicitationRequests)&&e.client===t.client}function Oj({id:e,options:t,defaultCallbackUrl:n,defaultOAuthProxyUrl:r,defaultProxyConfig:i,defaultAutoProxyFallback:a,clientInfo:o,cachedMetadata:s,onUpdate:c,onUpdateConfig:l,onUpdateDisplayName:u,onReconnect:d,rpcWrapTransport:f,onGlobalSamplingRequest:p,onGlobalElicitationRequest:m}){let{displayName:h,onSamplingRequest:g,onElicitationRequest:_,onNotificationReceived:v,wrapTransport:y}=t,b=(0,z.useMemo)(()=>{let{displayName:c,onSamplingRequest:l,onElicitationRequest:u,onNotificationReceived:d,wrapTransport:f,...p}=t;return{...p,callbackUrl:p.callbackUrl||n,oauthProxyUrl:p.oauthProxyUrl||r,proxyConfig:p.proxyConfig||i,autoProxyFallback:p.autoProxyFallback===void 0?a:p.autoProxyFallback,clientInfo:p.clientInfo?o?{...o,...p.clientInfo}:p.clientInfo:o,_initialServerInfo:s,serverId:e}},[t,n,r,i,a,o,s]),x=(0,z.useMemo)(()=>{if(!(!f&&!y))return t=>{let n=t;return f&&(n=f(n,e)),y&&(n=y(n,e)),n}},[f,y,e]),S=Cj({serverId:e,serverName:h||e,onNotificationReceived:v,onSamplingRequest:g,onElicitationRequest:_,onGlobalSamplingRequest:p,onGlobalElicitationRequest:m}),C=sj({...b,onNotification:S.onNotification,onSampling:S.onSampling,onElicitation:S.onElicitation,wrapTransport:x});(0,z.useEffect)(()=>{C.state!==`ready`&&S.rejectAll(`MCP server connection is no longer active`)},[C.state,S.rejectAll]);let w=(0,z.useCallback)(t=>l(e,t),[e,l]),T=(0,z.useCallback)(n=>{let r=t.proxyConfig?.proxyAddress?.trim();return t.connectionMode===`proxy`&&r?l(e,{proxyConfig:{...t.proxyConfig,proxyAddress:r,...n?{headers:n}:{}},headers:void 0}):l(e,{headers:n})},[e,t.connectionMode,t.proxyConfig,l]),E=(0,z.useCallback)(t=>u(e,t),[e,u]),ee=(0,z.useCallback)(()=>d(e),[e,d]),D=(0,z.useRef)(c),te=(0,z.useRef)(null);return(0,z.useEffect)(()=>{D.current=c},[c]),(0,z.useEffect)(()=>{let n={...bj(t),...C,id:e,displayName:h||t.displayName||e,notifications:S.notifications,unreadNotificationCount:S.unreadNotificationCount,markNotificationRead:S.markNotificationRead,markAllNotificationsRead:S.markAllNotificationsRead,clearNotifications:S.clearNotifications,pendingSamplingRequests:S.pendingSamplingRequests,approveSampling:S.approveSampling,rejectSampling:S.rejectSampling,pendingElicitationRequests:S.pendingElicitationRequests,approveElicitation:S.approveElicitation,rejectElicitation:S.rejectElicitation,updateConfig:w,setHeaders:T,setDisplayName:E,reconnect:ee},r=te.current;!r||!Dj(r,n)?(te.current=n,D.current(n)):wj.debug(`[McpServerWrapper ${e}] No meaningful changes detected, skipping onUpdate`)},[e,h,t,t.url,C.state,C.error,C.authUrl,C.tools,C.resources,C.resourceTemplates,C.prompts,C.serverInfo,C.capabilities,C.protocolEra,C.protocolVersion,C.instructions,C.extensions,C.authTokens,S,w,T,E,ee]),null}function kj({children:e,mcpServers:t,defaultCallbackUrl:n,defaultOAuthProxyUrl:r,defaultProxyConfig:i,defaultAutoProxyFallback:a=!1,defaultServerConfig:o,clientInfo:s,storageProvider:c,enableRpcLogging:l=!1,onServerAdded:u,onServerRemoved:d,onServerStateChange:f,onSamplingRequest:p,onElicitationRequest:m}){let[h,g]=(0,z.useState)([]),[_,v]=(0,z.useState)([]),[y,b]=(0,z.useState)({}),[x,S]=(0,z.useState)(!1),C=(0,z.useRef)(!1),w=(0,z.useRef)([]);(0,z.useEffect)(()=>{w.current=_},[_]);let T=(0,z.useRef)({}),[E,ee]=(0,z.useState)(void 0),[D,te]=(0,z.useState)(!1);(0,z.useEffect)(()=>{if(!l||typeof window>`u`){ee(void 0),te(!0);return}Promise.resolve().then(()=>(vk(),lk)).then(e=>{wj.debug(`[McpClientProvider] RPC logger loaded`),ee(()=>e.wrapTransportForLogging),te(!0)}).catch(e=>{wj.error(`[McpClientProvider] Failed to load RPC logger:`,e),ee(void 0),te(!0)})},[l]),(0,z.useEffect)(()=>{if(!D){wj.debug(`[McpClientProvider] Waiting for RPC logging to be ready before loading servers`);return}C.current||(C.current=!0,(async()=>{if(wj.debug(`[McpClientProvider] Loading servers, storageProvider:`,!!c,`mcpServers:`,t),!c){if(t){let e=Object.entries(t).map(([e,t])=>({id:e,options:t}));wj.debug(`[McpClientProvider] Loaded from mcpServers prop:`,e.length),g(e)}S(!0);return}try{let e=await Promise.resolve(c.getServers());if(wj.debug(`[McpClientProvider] Loaded from storage:`,Object.keys(e).length),c.getServerMetadata)try{let t=Object.keys(e).map(async e=>[e,await Promise.resolve(c.getServerMetadata(e))]),n=await Promise.all(t);T.current=Object.fromEntries(n.filter(e=>e[1]!==void 0)),wj.debug(`[McpClientProvider] Loaded cached metadata for`,Object.keys(T.current).length,`servers`)}catch(e){wj.warn(`[McpClientProvider] Failed to load cached metadata:`,e)}let n={...e,...t},r=Object.entries(n).map(([e,t])=>({id:e,options:t}));wj.debug(`[McpClientProvider] Total servers after merge:`,r.length),g(r),S(!0)}catch(e){wj.error(`[McpClientProvider] Failed to load from storage:`,e),t&&g(Object.entries(t).map(([e,t])=>({id:e,options:t}))),S(!0)}})())},[c,t,D]),(0,z.useEffect)(()=>{!c||!x||(async()=>{try{let e=h.reduce((e,t)=>(e[t.id]=bj(t.options),e),{});await Promise.resolve(c.setServers(e))}catch(e){wj.error(`[McpClientProvider] Failed to save to storage:`,e)}})()},[h,c,x]);let ne=(0,z.useCallback)(e=>{wj.debug(`[McpClientProvider] handleServerUpdate called for server ${e.id}`,{toolCount:e.tools.length,state:e.state});let t=[];v(n=>{let r=n.findIndex(t=>t.id===e.id);if(r===-1)return wj.debug(`[McpClientProvider] Adding new server ${e.id} to state`),t.push(()=>u?.(e.id,e)),[...n,e];let i=n[r],a=i.state!==e.state,o=i.serverInfo!==e.serverInfo;if(wj.debug(`[McpClientProvider] Comparing server ${e.id}:`,{toolsChanged:i.tools!==e.tools,currentToolCount:i.tools.length,updatedToolCount:e.tools.length,stateChanged:a}),Dj(i,e))return wj.debug(`[McpClientProvider] No changes detected for server ${e.id}, skipping update`),n;if(wj.debug(`[McpClientProvider] Updating server ${e.id} in state`),a&&t.push(()=>f?.(e.id,e.state)),o&&e.serverInfo&&c?.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};T.current[e.id]=t,Promise.resolve(c.setServerMetadata(e.id,t)).catch(e=>{wj.error(`[McpClientProvider] Failed to save server metadata:`,e)})}let s=[...n];return s[r]=e,s}),t.length>0&&queueMicrotask(()=>{t.forEach(e=>e())})},[u,f,c]),re=(0,z.useCallback)((e,t)=>{g(n=>n.find(t=>t.id===e)?n:(wj.debug(`[McpClientProvider] Adding new server to configs:`,e),[...n,{id:e,options:t}]))},[]),O=(0,z.useCallback)(async(e,t)=>{let n=w.current.find(t=>t.id===e);if(v(t=>t.filter(t=>t.id!==e)),g(t=>t.filter(t=>t.id!==e)),b(t=>{let{[e]:n,...r}=t;return r}),n?.disconnect&&await n.disconnect(),t?.clearCredentials&&n?.clearStorage&&await n.clearStorage(),l){let{clearRpcLogs:t}=await Promise.resolve().then(()=>(vk(),lk));t(e)}d?.(e)},[l,d]),ie=(0,z.useCallback)(async(e,t)=>{let n=h.find(t=>t.id===e);if(!n){wj.warn(`[McpClientProvider] Cannot update server "${e}" - not found`);return}let r={...n.options,...t};Ej(yj(n.options),yj(r))||(await w.current.find(t=>t.id===e)?.disconnect(),v(t=>t.filter(t=>t.id!==e)),g(t=>t.map(t=>t.id===e?{id:e,options:r}:t)),b(t=>({...t,[e]:(t[e]??0)+1})))},[h]),k=(0,z.useCallback)(async e=>{if(!h.find(t=>t.id===e)){wj.warn(`[McpClientProvider] Cannot reconnect server "${e}" - not found`);return}await w.current.find(t=>t.id===e)?.disconnect(),v(t=>t.filter(t=>t.id!==e)),b(t=>({...t,[e]:(t[e]??0)+1}))},[h]),A=(0,z.useCallback)(async(e,t)=>new Promise(n=>{let r=h.find(t=>t.id===e);if(!r){wj.warn(`[McpClientProvider] Cannot update server metadata for "${e}" - not found`),n();return}let i={...r.options,displayName:t.name};v(n=>n.map(n=>n.id===e?{...n,displayName:t.name}:n)),g(t=>{let r=t.map(t=>t.id===e?{id:e,options:i}:t);return setTimeout(()=>n(),0),r})}),[h]),j=(0,z.useCallback)(e=>_.find(t=>t.id===e),[_]),ae=(0,z.useMemo)(()=>({servers:_,addServer:re,removeServer:O,updateServerMetadata:A,updateServer:ie,getServer:j,storageLoaded:x}),[_,re,O,A,ie,j,x]),{capabilities:oe,...se}=s||{},ce=(0,z.useMemo)(()=>Object.keys(se).length?se:void 0,[s]),M=(0,z.useMemo)(()=>h.map(e=>{let t=o?{...o,...e.options}:e.options;return oe&&(t={...t,clientOptions:{...t.clientOptions,capabilities:{...oe,...t.clientOptions?.capabilities}}}),{id:e.id,options:t}}),[h,oe,o]),N=typeof window<`u`&&/\/oauth\/callback\/?$/.test(window.location.pathname);return z.createElement(Tj.Provider,{value:ae},e,!N&&M.map(e=>z.createElement(Oj,{key:`${e.id}-v${y[e.id]??0}`,id:e.id,options:e.options,defaultCallbackUrl:n,defaultOAuthProxyUrl:r,defaultProxyConfig:i,defaultAutoProxyFallback:a,clientInfo:ce,cachedMetadata:T.current[e.id],onUpdate:ne,onUpdateConfig:ie,onUpdateDisplayName:(e,t)=>A(e,{name:t}),onReconnect:k,rpcWrapTransport:E,onGlobalSamplingRequest:p,onGlobalElicitationRequest:m})))}function Aj(){let e=(0,z.useContext)(Tj);if(!e)throw Error(`useMcpClient must be used within a McpClientProvider`);return e}var jj=class{constructor(e=`mcp-client-servers`){this.storageKey=e,this.metadataKey=`${e}-metadata`}metadataKey;getServers(){try{let e=localStorage.getItem(this.storageKey);return e?JSON.parse(e):{}}catch(e){return console.error(`[LocalStorageProvider] Failed to load servers:`,e),{}}}setServers(e){try{localStorage.setItem(this.storageKey,JSON.stringify(e))}catch(e){console.error(`[LocalStorageProvider] Failed to save servers:`,e)}}setServer(e,t){let n=this.getServers();n[e]=t,this.setServers(n)}removeServer(e){let t=this.getServers();delete t[e],this.setServers(t),this.removeServerMetadata(e)}clear(){try{localStorage.removeItem(this.storageKey),localStorage.removeItem(this.metadataKey)}catch(e){console.error(`[LocalStorageProvider] Failed to clear:`,e)}}getAllMetadata(){try{let e=localStorage.getItem(this.metadataKey);return e?JSON.parse(e):{}}catch(e){return console.error(`[LocalStorageProvider] Failed to load metadata:`,e),{}}}setAllMetadata(e){try{localStorage.setItem(this.metadataKey,JSON.stringify(e))}catch(e){console.error(`[LocalStorageProvider] Failed to save metadata:`,e)}}getServerMetadata(e){return this.getAllMetadata()[e]}setServerMetadata(e,t){let n=this.getAllMetadata();n[e]={...t,cachedAt:Date.now()},this.setAllMetadata(n)}removeServerMetadata(e){let t=this.getAllMetadata();delete t[e],this.setAllMetadata(t)}};vk();function Mj(e){let t={};if(!e)return t;for(let[n,r]of Object.entries(e))if(typeof r==`string`&&(r.trim().startsWith(`[`)||r.trim().startsWith(`{`)))try{t[n]=JSON.parse(r)}catch{t[n]=r}else t[n]=r;return t}var Nj=`<script>
|
|
202
|
+
- "app": Tool callable by the app from this server only`),csp:Ap().optional(),permissions:Ap().optional()}),K({mimeTypes:G(V()).optional().describe('Array of supported MIME types for UI resources.\nMust include `"text/html;profile=mcp-app"` for MCP Apps support.')});var DO=K({method:X(`ui/download-file`),params:K({contents:G(J([$E,eD])).describe(`Resource contents to download — embedded (inline data) or linked (host fetches). Uses standard MCP resource types.`)})}),OO=K({method:X(`ui/message`),params:K({role:X(`user`).describe(`Message role, currently only "user" is supported.`),content:G(tD).describe(`Message content blocks (text, image, etc.).`)})});K({method:X(`ui/notifications/sandbox-resource-ready`),params:K({html:V().describe(`HTML content to load into the inner iframe.`),sandbox:V().optional().describe(`Optional override for the inner iframe's sandbox attribute.`),csp:pO.optional().describe(`CSP configuration from resource metadata.`),permissions:mO.optional().describe(`Sandbox permissions from resource metadata.`)})}),K({method:X(`ui/notifications/tool-result`),params:uD.describe(`Standard MCP tool execution result.`)});var kO=K({toolInfo:K({id:LT.optional().describe(`JSON-RPC id of the tools/call request.`),tool:sD.describe(`Tool definition including name, inputSchema, etc.`)}).optional().describe(`Metadata of the tool call that instantiated this App.`),theme:aO.optional().describe(`Current color theme preference.`),styles:_O.optional().describe(`Style configuration for theming the app.`),displayMode:oO.optional().describe(`How the UI is currently displayed.`),availableDisplayModes:G(oO).optional().describe(`Display modes the host supports.`),containerDimensions:J([K({height:H().describe(`Fixed container height in pixels.`)}),K({maxHeight:J([H(),Cp()]).optional().describe(`Maximum container height in pixels.`)})]).and(J([K({width:H().describe(`Fixed container width in pixels.`)}),K({maxWidth:J([H(),Cp()]).optional().describe(`Maximum container width in pixels.`)})])).optional().describe(`Container dimensions. Represents the dimensions of the iframe or other
|
|
203
|
+
container holding the app. Specify either width or maxWidth, and either height or maxHeight.`),locale:V().optional().describe(`User's language and region preference in BCP 47 format.`),timeZone:V().optional().describe(`User's timezone in IANA format.`),userAgent:V().optional().describe(`Host application identifier.`),platform:J([X(`web`),X(`desktop`),X(`mobile`)]).optional().describe(`Platform type for responsive design decisions.`),deviceCapabilities:K({touch:U().optional().describe(`Whether the device supports touch input.`),hover:U().optional().describe(`Whether the device supports hover interactions.`)}).optional().describe(`Device input capabilities.`),safeAreaInsets:K({top:H().describe(`Top safe area inset in pixels.`),right:H().describe(`Right safe area inset in pixels.`),bottom:H().describe(`Bottom safe area inset in pixels.`),left:H().describe(`Left safe area inset in pixels.`)}).optional().describe(`Mobile safe area boundaries in pixels.`)}).passthrough();K({method:X(`ui/notifications/host-context-changed`),params:kO.describe(`Partial context update containing only changed fields.`)});var AO=K({method:X(`ui/update-model-context`),params:K({content:G(tD).optional().describe(`Context content blocks (text, image, etc.).`),structuredContent:Y(V(),W().describe(`Structured content for machine-readable context data.`)).optional().describe(`Structured content for machine-readable context data.`)})}),jO=K({method:X(`ui/initialize`),params:K({appInfo:JT.describe(`App identification (name and version).`),appCapabilities:SO.describe(`Features and capabilities this app provides.`),protocolVersion:V().describe(`Protocol version this app supports.`)})}),MO=K({protocolVersion:V().describe(`Negotiated protocol version string (e.g., "2025-11-21").`),hostInfo:JT.describe(`Host application identification and version.`),hostCapabilities:xO.describe(`Features and capabilities provided by the host.`),hostContext:kO.describe(`Rich context about the host environment.`)}).passthrough(),NO=class{eventTarget;eventSource;messageListener;constructor(e=window.parent,t){this.eventTarget=e,this.eventSource=t,this.messageListener=e=>{if(t&&e.source!==this.eventSource){console.debug(`Ignoring message from unknown source`,e);return}let n=HT.safeParse(e.data);n.success?(console.debug(`Parsed message`,n.data),this.onmessage?.(n.data)):e.data?.jsonrpc===`2.0`?(console.error(`Failed to parse message`,n.error.message,e),this.onerror?.(Error(`Invalid JSON-RPC message received: `+n.error.message))):console.debug(`Ignoring non-JSON-RPC message`,n.error.message,e)}}async start(){window.addEventListener(`message`,this.messageListener)}async send(e,t){e.method!==`ui/notifications/tool-input-partial`&&console.debug(`Sending message`,e),this.eventTarget.postMessage(e,`*`)}async close(){window.removeEventListener(`message`,this.messageListener),this.onclose?.()}onclose;onerror;onmessage;sessionId;setProtocolVersion},PO=`text/html;profile=mcp-app`;function FO(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(`; `)}var IO=[iO],LO=class extends Jb{_client;_hostInfo;_hostCapabilities;_appCapabilities;_hostContext={};_appInfo;_initializedReceived=!1;_registeredEvents=new Set;_events=new rO;_wrapHandler(e,t){let n=super._wrapHandler(e,t);return e===`ui/initialize`||e===`ping`?n:async(t,r)=>(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.`),n(t,r))}eventSchemas={sizechange:hO,sandboxready:fO,initialized:CO,requestteardown:bO,loggingmessage:vD};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 n=t=>{e===`initialized`&&(this._initializedReceived=!0),this._events.dispatch(e,t)};e===`loggingmessage`?this.setNotificationHandler(`notifications/message`,e=>{n(e.params)}):this.setNotificationHandler(t.shape.method.value,{params:t.shape.params},e=>n(e)),this._registeredEvents.add(e)}warnIfRequestHandlerReplaced(e,t,n){t&&n&&console.warn(`[MCP Apps] ${e} handler replaced. Previous handler will no longer be called.`)}constructor(e,t,n,r){super(r),this._client=e,this._hostInfo=t,this._hostCapabilities=n,this._ensureEventSlot(`initialized`),this._hostContext=r?.hostContext||{},this.setRequestHandler(`ui/initialize`,{params:jO.shape.params,result:MO},e=>this._onAppsInitialize(e)),this.setRequestHandler(`ping`,(e,t)=>(this.onping?.(e.params,t),{})),this.setRequestHandler(`ui/request-display-mode`,{params:wO.shape.params,result:TO},()=>({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.setRequestHandler(`ui/message`,{params:OO.shape.params,result:dO},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.setRequestHandler(`ui/open-link`,{params:cO.shape.params,result:lO},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.setRequestHandler(`ui/download-file`,{params:DO.shape.params,result:uO},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.setRequestHandler(`ui/request-display-mode`,{params:wO.shape.params,result:TO},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.setRequestHandler(`ui/update-model-context`,{params:AO.shape.params,result:UT},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.setRequestHandler(`tools/call`,async(e,t)=>{if(!this._oncalltool)throw Error(`No oncalltool handler set`);return this._oncalltool(e.params,t)})}set oncreatesamplingmessage(e){this.setRequestHandler(`sampling/createMessage`,async(t,n)=>e(t.params,n))}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.setRequestHandler(`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.setRequestHandler(`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.setRequestHandler(`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.setRequestHandler(`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 this._appInfo!==void 0&&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:IO.includes(t)?t:iO,hostCapabilities:this.getCapabilities(),hostInfo:this._hostInfo,hostContext:this._hostContext}}setHostContext(e){let t={},n=!1;for(let r of Object.keys(e)){let i=this._hostContext[r],a=e[r];RO(i,a)||(t[r]=a,n=!0)}n&&(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})}teardownResource(e,t){return this.request({method:`ui/resource-teardown`,params:e},vO,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)}};function RO(e,t){return JSON.stringify(e)===JSON.stringify(t)}var zO=Object.defineProperty,BO=Object.getOwnPropertyNames,VO=(e,t)=>function(){return e&&(t=(0,e[BO(e)[0]])(e=0)),t},HO=(e,t)=>{for(var n in t)zO(e,n,{get:t[n],enumerable:!0})};function UO(){let e;try{e=typeof process<`u`?{}.MCP_USE_LOG_LEVEL??{}.DEBUG:void 0}catch{}let t=e?.trim().toLowerCase();return t===`2`?`debug`:t&&WO.includes(t)?t:`info`}var WO,GO,KO,qO,$,JO=VO({"src/utils/logging.ts"(){WO=[`silent`,`error`,`warn`,`info`,`http`,`verbose`,`debug`,`silly`],GO={silent:``,error:`❌`,warn:`⚠️`,info:`ℹ️`,http:`🌐`,verbose:`📝`,debug:`🔍`,silly:`🤪`},KO=class{constructor(e=`mcp-use`,t=`info`,n=`minimal`){this.name=e,this.level=t,this.format=n}write(e,t,n){if(this.level===`silent`||WO.indexOf(e)>WO.indexOf(this.level))return;let r=n.map(e=>{if(typeof e==`string`)return e;try{return JSON.stringify(e)}catch{return String(e)}}).join(` `),i=r?`${t} ${r}`:t,a=new Date().toLocaleTimeString(`en-US`,{hour12:!1}),o=this.format===`minimal`?e:e.toUpperCase(),s=this.format===`emoji`?` ${GO[e]}`:``,c=`${a} [${this.name}]${s} ${o}: ${i}`;(e===`error`?console.error:e===`warn`?console.warn:e===`info`?console.info:e===`debug`?console.debug:console.log)(c)}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}},qO=class{static instances={};static currentFormat=`minimal`;static currentLevel;static get(e=`mcp-use`){return this.instances[e]??=new KO(e,this.currentLevel??UO(),this.currentFormat)}static configure({level:e=UO(),format:t=`minimal`}={}){this.currentLevel=e,this.currentFormat=t;for(let n of Object.values(this.instances))n.level=e,n.format=t}static setDebug(e){let t=e===2||e===!0?`debug`:`info`;this.currentLevel=t;for(let e of Object.values(this.instances))e.level=t;try{typeof process<`u`&&({}.MCP_USE_LOG_LEVEL=t)}catch{}}static setFormat(e){this.configure({format:e})}},$=qO.get()}}),YO={};HO(YO,{clearRpcLogs:()=>$O,getAllRpcLogs:()=>ZO,getRpcLogs:()=>XO,subscribeToRpcLogs:()=>QO,wrapTransportForLogging:()=>ek});function XO(e){return rk.getLogsForServer(e)}function ZO(){return rk.getAllLogs()}function QO(e){return rk.subscribe(e)}function $O(e){rk.clear(e)}function ek(e,t){class n{constructor(e){this.inner=e,this.inner.onmessage=(e,n)=>{rk.publish({serverId:t,direction:`receive`,timestamp:new Date().toISOString(),message:e}),this.onmessage?.(e,n)},this.inner.onclose=()=>{this.onclose?.()},this.inner.onerror=e=>{this.onerror?.(e)}}onclose;onerror;onmessage;async start(){typeof this.inner.start==`function`&&await this.inner.start()}async send(e,n){rk.publish({serverId:t,direction:`send`,timestamp:new Date().toISOString(),message:e}),await this.inner.send(e,n)}async close(){await this.inner.close()}get sessionId(){return this.inner.sessionId}setProtocolVersion(e){typeof this.inner.setProtocolVersion==`function`&&this.inner.setProtocolVersion(e)}}return new n(e)}var tk,nk,rk,ik=VO({"src/react/rpc-logger.ts"(){JO(),tk=qO.get(`RpcLogger`),nk=class{logs=[];listeners=new Set;maxLogs=1e3;publish(e){tk.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)),tk.debug(`[RPC Logger] Total logs:`,this.logs.length,`Listeners:`,this.listeners.size),this.listeners.forEach(t=>{try{t(e)}catch(e){tk.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=[]}},rk=new nk}}),ak=`mcp_auth_callback`,ok=`mcp_auth_callback`;function sk(e){try{return typeof localStorage<`u`&&!!localStorage.getItem(e)}catch{return!1}}function ck({popup:e,state:t,tokensKey:n,timeoutMs:r=5*6e4,closePollMs:i=1e3,closeGraceMs:a=2e4,expectedOrigin:o=typeof window<`u`?window.location.origin:``}){return new Promise(s=>{let c=!1,l=null,u=null,d=null,f=null,p=()=>{if(l&&=(clearInterval(l),null),u&&=(clearTimeout(u),null),d&&=(clearTimeout(d),null),typeof window<`u`&&(window.removeEventListener(`message`,g),window.removeEventListener(`storage`,v)),f){try{f.removeEventListener(`message`,_),f.close()}catch{}f=null}},m=e=>{c||(c=!0,p(),s(e))},h=e=>{!e||e.type!==ok||e.state&&t&&e.state!==t||(e.success?m({kind:`success`}):m({kind:`error`,error:e.error??`Authentication failed in callback.`}))},g=e=>{o&&e.origin!==o||h(e.data)},_=e=>{h(e.data)},v=e=>{e.key===n&&e.newValue&&m({kind:`success`})};if(typeof window<`u`&&(window.addEventListener(`message`,g),window.addEventListener(`storage`,v)),typeof BroadcastChannel<`u`)try{f=new BroadcastChannel(ak),f.addEventListener(`message`,_)}catch{f=null}e&&(l=setInterval(()=>{if(c)return;let t=!1;try{t=e.closed}catch{t=!1}if(t){if(l&&=(clearInterval(l),null),sk(n)){m({kind:`success`});return}d=setTimeout(()=>{m(sk(n)?{kind:`success`}:{kind:`cancelled`})},a)}},i)),u=setTimeout(()=>{m(sk(n)?{kind:`success`}:{kind:`timeout`})},r)})}JO();var lk=`http://json-schema.org/draft-04/schema`,uk=new Set([`http://json-schema.org/draft-07/schema`,`https://json-schema.org/draft-07/schema`]),dk=new Set([`https://json-schema.org/draft/2019-09/schema`,`http://json-schema.org/draft/2019-09/schema`]),fk=new Set([`https://json-schema.org/draft/2020-12/schema`,`http://json-schema.org/draft/2020-12/schema`]);function pk(e){if(!(`$schema`in e)||typeof e.$schema!=`string`)return`2020-12`;let t=e.$schema.replace(/#$/,``);if(t===lk)return`4`;if(uk.has(t))return`7`;if(dk.has(t))return`2019-09`;if(fk.has(t))return`2020-12`}var mk=class{getValidator(e){let t=pk(e);return(t===void 0?new Jx:new Jx({draft:t})).getValidator(e)}};JO();var hk;function gk(e){hk?.(e)}var _k={"~standard":{version:1,vendor:`mcp-use`,validate:e=>({value:e})}},vk=class{client=null;connectionManager=null;toolsCache=null;capabilitiesCache=null;serverInfoCache=null;connected=!1;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){let t=this.constructor.name;gk({connectorType:t,...e})}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){$.error(`Error in notification handler:`,e)}}async handleListChanged(e,t,n){if(t){$.warn(`[Auto] ${e} refresh failed:`,t);return}e===`notifications/tools/list_changed`&&n&&(this.toolsCache=[...n]),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();break;default:break}await this.forwardNotification(e)};let e=this.client._notificationHandlers;for(let t of[`notifications/progress`,`notifications/cancelled`]){let n=e.get(t);n&&e.set(t,async e=>{await n(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&&typeof e==`object`&&e.method===`notifications/progress`&&this.forwardRoundProgress(e.params),await t?.(e)}}forwardRoundProgress(e){if(this.activeProgressHandlers.size===1){let[t]=this.activeProgressHandlers;t?.(e)}}async refreshToolsCache(){if(this.client)try{$.debug(`[Auto] Refreshing tools cache due to list_changed notification`);let e=await this.client.listTools();this.toolsCache=e.tools??[],$.debug(`[Auto] Refreshed tools cache: ${this.toolsCache.length} tools`)}catch(e){$.warn(`[Auto] Failed to refresh tools cache:`,e)}}async onResourcesListChanged(){$.debug(`[Auto] Resources list changed - clients should re-fetch if needed`)}async onPromptsListChanged(){$.debug(`[Auto] Prompts list changed - clients should re-fetch if needed`)}async setRoots(e){this.rootsCache=[...e],this.client&&($.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()=>($.debug(`Server requested roots list, returning ${this.rootsCache.length} root(s)`),{roots:this.rootsCache}))}setupSamplingHandler(){if(!this.client){$.debug(`setupSamplingHandler: No client available`);return}let e=this.opts.onSampling;if(!e){$.debug(`setupSamplingHandler: No sampling callback provided`);return}$.debug(`setupSamplingHandler: Setting up sampling request handler`),this.client.setRequestHandler(`sampling/createMessage`,async t=>($.debug(`Server requested sampling, forwarding to callback`),await e(t.params))),$.debug(`setupSamplingHandler: Sampling handler registered successfully`)}setupElicitationHandler(){if(!this.client){$.debug(`setupElicitationHandler: No client available`);return}let e=this.opts.onElicitation;if(!e){$.debug(`setupElicitationHandler: No elicitation callback provided`);return}$.debug(`setupElicitationHandler: Setting up elicitation request handler`),this.client.setRequestHandler(`elicitation/create`,async t=>($.debug(`Server requested elicitation, forwarding to callback`),await e(t.params))),$.debug(`setupElicitationHandler: Elicitation handler registered successfully`)}async disconnect(){if(!this.connected){$.debug(`Not connected to MCP implementation`);return}$.debug(`Disconnecting from MCP implementation`),await this.cleanupResources(),this.connected=!1,$.debug(`Disconnected from MCP implementation`)}get isClientConnected(){return this.client!=null}async initialize(e=this.opts.defaultRequestOptions??{}){if(!this.client)throw Error(`MCP client is not connected`);$.debug(`Caching server capabilities & tools`);let t=this.client.getServerCapabilities();this.capabilitiesCache=t||null;let n=this.client.getServerVersion();this.serverInfoCache=n?{name:n.name,version:n.version,title:n.title,description:n.description,websiteUrl:n.websiteUrl,icons:n.icons}:null;try{let t=await this.client.listTools(void 0,e);this.toolsCache=t.tools??[],$.debug(`Fetched ${this.toolsCache.length} tools from server`)}catch(e){let t=e;t.code===-32601?$.debug(`Server does not implement tools/list, assuming no tools`):$.debug(`Failed to list tools, assuming empty:`,t.message),this.toolsCache=[]}return $.debug(`Server capabilities:`,t),$.debug(`Server info:`,n),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,n){if(!this.client)throw Error(`MCP client is not connected`);let r=n?{...n}:void 0;r?.resetTimeoutOnProgress&&!r.onprogress&&(r.onprogress=()=>{},$.debug(`[BaseConnector] Added onprogress callback for tool '${e}' to enable progressToken`)),$.debug(`Calling tool '${e}' with args`,t);let i=r?.onprogress;i&&this.activeProgressHandlers.add(i);try{let n=await this.client.callTool({name:e,arguments:t},r);return $.debug(`Tool '${e}' returned`,n),n}finally{i&&this.activeProgressHandlers.delete(i)}}async listTools(e){if(!this.client)throw Error(`MCP client is not connected`);$.debug(`[listTools] Fetching fresh tools from server...`);let t=await this.client.listTools(void 0,e),n=t.tools?[...t.tools]:[];return $.debug(`[listTools] Returned ${n.length} tools:`,n.map(e=>e.name)),n}async listResources(e,t){if(!this.client)throw Error(`MCP client is not connected`);return $.debug(`Listing resources`,e?`with cursor: ${e}`:``),await this.client.listResources({cursor:e},t)}async listAllResources(e){if(!this.client)throw Error(`MCP client is not connected`);if(!this.capabilitiesCache?.resources)return $.debug(`Server does not advertise resources capability, skipping`),{resources:[]};try{$.debug(`Listing all resources (with auto-pagination)`);let t=[],n;do{let r=await this.client.listResources({cursor:n},e);t.push(...r.resources||[]),n=r.nextCursor}while(n);return{resources:t}}catch(e){if(e.code===-32601)return $.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 $.debug(`Listing resource templates`),await this.client.listResourceTemplates(void 0,e)}async complete(e,t){if(!this.client)throw Error(`MCP client is not connected`);$.debug(`[complete] Requesting completions for:`,e.ref);let n=await this.client.complete(e,t);return $.debug(`[complete] Received ${n.completion.values.length} suggestions`),n}async readResource(e,t){if(!this.client)throw Error(`MCP client is not connected`);return $.debug(`Reading resource ${e}`),await this.client.readResource({uri:e},t)}async subscribeToResource(e,t){if(!this.client)throw Error(`MCP client is not connected`);return $.debug(`Subscribing to resource: ${e}`),await this.client.subscribeResource({uri:e},t)}async unsubscribeFromResource(e,t){if(!this.client)throw Error(`MCP client is not connected`);return $.debug(`Unsubscribing from resource: ${e}`),await this.client.unsubscribeResource({uri:e},t)}async listPrompts(){if(!this.client)throw Error(`MCP client is not connected`);if(!this.capabilitiesCache?.prompts)return $.debug(`Server does not advertise prompts capability, skipping`),{prompts:[]};try{return $.debug(`Listing prompts`),await this.client.listPrompts()}catch(e){if(e.code===-32601)return $.debug(`Server advertised prompts but method not found`),{prompts:[]};throw e}}async getPrompt(e,t){if(!this.client)throw Error(`MCP client is not connected`);return $.debug(`Getting prompt ${e}`),await this.client.getPrompt({name:e,arguments:t})}async request(e,t=null,n){if(!this.client)throw Error(`MCP client is not connected`);return $.debug(`Sending raw request '${e}' with params`,t),await this.client.request({method:e,params:t??{}},_k,n)}async cleanupResources(){let e=[];if(this.client)try{typeof this.client.close==`function`&&await this.client.close()}catch(t){let n=`Error closing client: ${t}`;$.warn(n),e.push(n)}finally{this.client=null}if(this.connectionManager)try{await this.connectionManager.stop()}catch(t){let n=`Error stopping connection manager: ${t}`;$.warn(n),e.push(n)}finally{this.connectionManager=null}this.toolsCache=null,e.length&&$.warn(`Resource cleanup finished with ${e.length} issue(s)`)}};function yk(e,t=0){if(!e||t>5)return!1;if(e instanceof xS||e instanceof Z_&&e.status===401)return!0;if(e instanceof Error){if(e.cause&&yk(e.cause,t+1))return!0;let n=e instanceof X_?e.data:void 0;if(n?.cause&&yk(n.cause,t+1))return!0}return!1}function bk(e,t,n,r){let i=new URL(e),a=t.replace(/\/$/,``);return async(e,t)=>{let o=new Request(e,t),s=new URL(o.url);if(!(s.origin===i.origin&&s.pathname===i.pathname))return n(o);let c=new Headers(o.headers);c.set(`X-Target-URL`,o.url),r&&c.set(`X-Server-Id`,r);let l=o.method===`GET`||o.method===`HEAD`?void 0:await o.clone().arrayBuffer();return n(new Request(a,{method:o.method,headers:c,body:l,signal:o.signal,redirect:`manual`}))}}var xk=class extends vk{baseUrl;headers;timeout;customFetch;clientInfo;protocolNegotiation;gatewayUrl;serverId;reconnectionOptions;transportType=null;streamableTransport=null;constructor(e,t={}){super(t);let n=e.replace(/\/$/,``);this.baseUrl=n,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;let r=t.fetch??globalThis.fetch.bind(globalThis);this.customFetch=this.gatewayUrl?bk(n,this.gatewayUrl,r,this.serverId):t.fetch,this.clientInfo=t.clientInfo??{name:`http-connector`,version:`1.0.0`},this.protocolNegotiation=t.protocolNegotiation??`auto`,this.reconnectionOptions=t.reconnectionOptions}buildClientOptions(){return{...this.opts.clientOptions||{},jsonSchemaValidator:this.opts.clientOptions?.jsonSchemaValidator??new mk,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 Z_?e:e instanceof Error&&e.cause instanceof Z_?e.cause:null}classifyStreamableHttpFailure(e){let t=`Unknown error`,n=!1,r,i=this.unwrapStreamableError(e);if(i){let e=i.status;return n=e===401,r=e,e===400&&i.message.includes(`Missing session ID`)?(t=`Server requires session ID (FastMCP compatibility)`,$.warn(`\u26A0\uFE0F ${t}`)):e===404||e===405?(t=`Server returned ${e} - server likely doesn't support streamable HTTP`,$.debug(t)):(t=`Server returned ${e}: ${i.message}`,$.debug(t)),{fallbackReason:t,is401Error:n,httpStatusCode:r}}if(e instanceof Error){let r=e.toString(),i=e.message||``;n=yk(e)||r.includes(`401`)||i.includes(`Unauthorized`),r.includes(`Missing session ID`)||r.includes(`Bad Request: Missing session ID`)||i.includes(`FastMCP session ID error`)?(t=`Server requires session ID (FastMCP compatibility)`,$.warn(`\u26A0\uFE0F ${t}`)):r.includes(`405 Method Not Allowed`)||r.includes(`404 Not Found`)?(t=`Server doesn't support streamable HTTP (405/404)`,$.debug(t)):(t=`Streamable HTTP failed: ${e.message}`,$.debug(t))}return{fallbackReason:t,is401Error:n,httpStatusCode:r}}async connect(){if(this.connected){$.debug(`Already connected to MCP implementation`);return}let e=this.baseUrl;$.debug(`Connecting to MCP implementation via HTTP: ${e}`);try{await this.connectWithStreamableHttp(e),$.debug(`✅ Successfully connected via streamable HTTP`)}catch(e){$.debug(`Streamable HTTP connect failed`,e);let{fallbackReason:t,is401Error:n,httpStatusCode:r}=this.classifyStreamableHttpFailure(e);if(await this.cleanupResources(),n){$.info(`Authentication required`);let e=Error(`Authentication required`);throw e.code=401,e}let i=Error(`Could not connect via streamable HTTP: ${t}`);throw r!==void 0&&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,n]=e.body.tee();return(async()=>{let e=n.getReader(),t=new TextDecoder,r=``;try{for(;;){let{done:n,value:i}=await e.read();if(n)break;r+=t.decode(i,{stream:!0});let a=r.split(/\r?\n\r?\n/);r=a.pop()??``;for(let e of a)for(let t of e.split(/\r?\n/))if(t.startsWith(`data:`))try{let e=JSON.parse(t.slice(5).trim());e.method===`notifications/progress`&&this.forwardRoundProgress(e.params)}catch{}}}catch(e){e instanceof DOMException&&e.name===`AbortError`||$.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{$.debug(`[HttpConnector] Connecting with Streamable HTTP`,{baseUrl:e,originalUrl:this.baseUrl,gatewayUrl:this.gatewayUrl||`none`,authProviderUrl:this.opts.authProvider&&`serverUrl`in this.opts.authProvider&&typeof this.opts.authProvider.serverUrl==`string`?this.opts.authProvider.serverUrl:`none`,headers:this.headers});let t,n=new Promise(e=>{t=e}),r=this.customFetch??globalThis.fetch.bind(globalThis),i=new GC(new URL(e),{authProvider:this.opts.authProvider,fetch:async(e,n)=>{let i=await r(e,n),a=n?.method??(e instanceof Request?e.method:`GET`),o=new Headers(e instanceof Request?e.headers:void 0);return new Headers(n?.headers).forEach((e,t)=>{o.set(t,e)}),a.toUpperCase()===`GET`&&i.ok&&i.headers.get(`content-type`)?.includes(`text/event-stream`)&&t?.(),o.get(`mcp-method`)===`subscriptions/listen`?i:this.observeSseProgress(i)},requestInit:{headers:this.headers},reconnectionOptions:{maxReconnectionDelay:3e4,initialReconnectionDelay:1e3,reconnectionDelayGrowFactor:1.5,maxRetries:2,...this.reconnectionOptions}}),a=i;if(this.opts.wrapTransport){let e=this.baseUrl;a=this.opts.wrapTransport(a,e)}let o=this.buildClientOptions();$.debug(`Creating Client with capabilities:`,JSON.stringify(o.capabilities,null,2)),this.client=new BC(this.clientInfo,o),this.setupRootsHandler(),this.setupSamplingHandler(),this.setupElicitationHandler(),$.debug(`Roots/sampling/elicitation handlers registered before connect`);try{let e;if(await Promise.race([this.client.connect(a),new Promise((t,n)=>{e=setTimeout(()=>n(Error(`MCP connection timed out after ${this.timeout}ms`)),this.timeout)})]).finally(()=>{e!==void 0&&clearTimeout(e)}),(this.client.getProtocolEra?.()??`legacy`)===`legacy`&&i.sessionId){let e,t=await Promise.race([n.then(()=>!0),new Promise(t=>e=setTimeout(()=>t(!1),Math.min(this.timeout,5e3)))]);e&&clearTimeout(e),t||$.warn(`Legacy server push stream did not attach before connect completed`)}let t=i.sessionId;t&&$.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 n=Error(`Session ID error: ${t}. The SDK should automatically extract session ID from initialize response.`);throw n.cause=e,n}}throw e}this.streamableTransport=i,this.connectionManager={stop:async()=>{if(this.streamableTransport)try{await this.streamableTransport.close()}catch(e){$.warn(`Error closing Streamable HTTP transport: ${e}`)}finally{this.streamableTransport=null}}},this.connected=!0,this.transportType=`streamable-http`,this.setupNotificationHandler(),$.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&&this.protocolEra!==`modern`){let e;try{await Promise.race([this.streamableTransport.terminateSession().then(()=>!0),new Promise(t=>e=setTimeout(()=>t(!1),Math.min(this.timeout,5e3)))])||$.debug(`Timed out terminating legacy HTTP session; closing transport`)}catch(e){$.debug(`Error terminating Streamable HTTP session: ${e}`)}finally{e&&clearTimeout(e)}}await super.cleanupResources()}},Sk=`2.0.0-beta.4`;function Ck(){return Sk}function wk(e,t){return{onSampling:e?.onSampling??t?.onSampling,onElicitation:e?.onElicitation??t?.onElicitation,onNotification:e?.onNotification??t?.onNotification}}function Tk(e){if(!(`url`in e)||typeof e.url!=`string`||e.authProvider||e.authToken||e.oauth===!1)return!1;let t=e.headers;if(t){for(let e of Object.keys(t))if(e.toLowerCase()===`authorization`)return!1}return!0}function Ek(){return{name:`mcp-use`,title:`mcp-use`,version:Ck(),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`}}function Dk(e){let t=Ek();if(!e||typeof e!=`object`)return t;let n=e;return!n.name||!n.version?t:{...t,...n}}function Ok(e){let t=e?.capabilities;if(!t||t.views!==!0)return e;let{views:n,...r}=t,i=r.extensions&&typeof r.extensions==`object`&&!Array.isArray(r.extensions)?{...r.extensions}:{};return{...e,capabilities:{...r,extensions:{...i,"io.modelcontextprotocol/ui":{mimeTypes:[`text/html;profile=mcp-app`]}}}}}function kk(e){let t=()=>{throw Error(`Invalid url to pass to open(): ${e}`)},n;try{n=new URL(e)}catch{t()}return n.protocol!==`https:`&&n.protocol!==`http:`&&t(),n.hostname!==encodeURIComponent(n.hostname)&&t(),n.username&&=encodeURIComponent(n.username),n.password&&=encodeURIComponent(n.password),n.pathname=n.pathname.slice(0,1)+encodeURIComponent(n.pathname.slice(1)).replace(/%2f/gi,`/`),n.search=n.search.slice(0,1)+Array.from(n.searchParams.entries()).map(Ak).join(`&`),n.hash=n.hash.slice(0,1)+encodeURIComponent(n.hash.slice(1)),n.href}function Ak([e,t]){return`${encodeURIComponent(e)}${t.length>0?`=${encodeURIComponent(t)}`:``}`}var jk=class{get(e){return localStorage.getItem(e)}set(e,t){localStorage.setItem(e,t)}remove(e){localStorage.removeItem(e)}keys(){let e=[];for(let t=0;t<localStorage.length;t++){let n=localStorage.key(t);n&&e.push(n)}return e}},Mk=class e{serverUrl;storageKeyPrefix;serverUrlHash;clientName;clientUri;logoUri;callbackUrl;clientMetadataUrl;scope;store;allowClientSecret;constructor(t,n,r){US(n.clientMetadataUrl),this.serverUrl=t,this.storageKeyPrefix=n.storageKeyPrefix||`mcp:auth`,this.serverUrlHash=e.hashString(t),this.clientName=n.clientName||`mcp-use`,this.clientUri=n.clientUri||(typeof window<`u`?window.location.origin:`https://mcp-use.com`),this.logoUri=n.logoUri||`https://mcp-use.com/logo.png`,this.callbackUrl=kk(n.callbackUrl||(typeof window<`u`?new URL(`/oauth/callback`,window.location.origin).toString():`/oauth/callback`)),this.clientMetadataUrl=n.clientMetadataUrl,this.scope=n.scope,this.store=r,this.allowClientSecret=n.allowClientSecret??!0}getKey(e){return`${this.storageKeyPrefix}_${this.serverUrlHash}_${e}`}static hashString(e){let t=0;for(let n=0;n<e.length;n++){let r=e.charCodeAt(n);t=(t<<5)-t+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 n=this.credentialKey(e,t),r=await this.store.get(n);if(!r&&t){let r=this.credentialKey(e),i=await this.store.get(r);if(i)try{let e=JSON.parse(i);if(!e.issuer||e.issuer===t.issuer){let i={...e,issuer:t.issuer},a=JSON.stringify(i);return await this.store.set(n,a),await this.store.set(r,a),{key:n,value:i}}}catch{await this.store.remove(r)}return}if(r)try{return{key:n,value:JSON.parse(r)}}catch(t){console.warn(`[${this.storageKeyPrefix}] Failed to parse ${e.replace(`_`,` `)}:`,t),await this.store.remove(n);return}}async tokens(e){return(await this.readCredential(`tokens`,e))?.value}async saveTokens(e,t){let n=JSON.stringify(e);await this.store.set(this.credentialKey(`tokens`,t),n),t&&await this.store.set(this.credentialKey(`tokens`),n),await this.store.remove(this.getKey(`code_verifier`)),await this.store.remove(this.getKey(`last_auth_url`))}async clientInformation(e){let t=await this.readCredential(`client_info`,e);if(!t)return;let{key:n,value:r}=t;try{if(!this.allowClientSecret&&r.client_secret){await this.store.remove(n),e&&await this.store.remove(this.credentialKey(`client_info`)),console.warn(`[${this.storageKeyPrefix}] Removed OAuth client information containing a browser client_secret.`);return}let t=Array.isArray(r.redirect_uris)?r.redirect_uris:[];if(!(t.length===0||t.includes(this.redirectUrl))){console.info(`[${this.storageKeyPrefix}] Invalidating cached OAuth client info due to redirect URI mismatch.`),await this.store.remove(n),await this.store.remove(this.credentialKey(`tokens`,e)),await this.store.remove(this.getKey(`last_auth_url`));return}return r}catch{await this.store.remove(n);return}}async saveClientInformation(e,t){let n=e;if(!this.allowClientSecret&&n.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(e);await this.store.set(this.credentialKey(`client_info`,t),r),t&&await this.store.set(this.credentialKey(`client_info`),r)}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}async invalidateCredentials(e){let t=async e=>{let t=`${this.getKey(e)}_`;for(let n of await this.store.keys())(n===this.getKey(e)||n.startsWith(t))&&await this.store.remove(n)};switch(e){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(`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`));break;default:break}}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 n=globalThis.crypto.randomUUID(),r=`${this.storageKeyPrefix}:state_${n}`,i={serverUrlHash:this.serverUrlHash,expiry:Date.now()+1e3*60*10,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`,n);let a=kk(e.toString());return await this.store.set(r,JSON.stringify(i)),await this.store.set(this.getKey(`last_auth_url`),a),a}async getTokenEndpoint(){return(await this.discoveryState())?.authorizationServerMetadata?.token_endpoint??null}};async function Nk(e){return typeof e==`string`?e:e instanceof URLSearchParams||e instanceof FormData?Object.fromEntries(e.entries()):e instanceof Blob?await e.text():e}var Pk=class{serverUrl;staticClientInfo;session;preventAutoAuth;useRedirectFlow;oauthProxyUrl;connectionUrl;proxyOAuthRequests;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.session=new Mk(e,{...t,allowClientSecret:!1},new jk),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)}reanchorWellKnownUrl(e){if(!this.connectionUrl)return e;try{let t=new URL(e),n=new URL(this.connectionUrl);if(t.origin!==n.origin||!t.pathname.startsWith(`/.well-known/`))return e;let r=new URL(this.serverUrl),[i,...a]=t.pathname.slice(13).split(`/`);if(!i)return e;let o=a.length?`/${a.join(`/`)}`:``,s=n.pathname.replace(/\/+$/,``),c=r.pathname.replace(/\/+$/,``),l=o&&o===s?c:o;return`${r.origin}/.well-known/${i}${l}${t.search}`}catch{return e}}getProxyFetch(e){if(!this.proxyOAuthRequests||!this.oauthProxyUrl)return e;let t=e??globalThis.fetch.bind(globalThis),n=this.oauthProxyUrl,r=new Set,i=!1;return async(e,a)=>{let o=typeof e==`string`?e:e instanceof URL?e.toString():e.url,s=this.reanchorWellKnownUrl(o),c;try{c=new URL(s).pathname}catch{return await t(e,a)}let l=c.includes(`/.well-known/`);if(!i){i=!0;let e=(await this.discoveryState())?.authorizationServerMetadata;for(let t of[`registration_endpoint`,`token_endpoint`,`revocation_endpoint`,`introspection_endpoint`])typeof e?.[t]==`string`&&r.add(e[t])}let u=r.has(s)||/\/(?:register|registration|token|revoke|revocation|introspect|introspection)\/?$/.test(c);if(!l&&!u)return await t(e,a);try{let r=new URL(s),i=new URL(n);if(r.origin===i.origin&&(r.pathname.startsWith(i.pathname)||s.includes(`/inspector/api/oauth`)))return await t(e,a)}catch{}let d=l?`${n}/metadata?serverUrl=${encodeURIComponent(this.serverUrl)}&url=${encodeURIComponent(s)}`:`${n}/proxy`;if(l){let e=await t(d,{...a,method:`GET`});try{let t=await e.clone().json();for(let e of[`registration_endpoint`,`token_endpoint`,`revocation_endpoint`,`introspection_endpoint`])typeof t[e]==`string`&&r.add(t[e])}catch{}return e}let f=a?.body?await Nk(a.body):void 0,p=await(await t(d,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({serverUrl:this.serverUrl,url:s,method:a?.method||`POST`,headers:a?.headers?Object.fromEntries(new Headers(a.headers)):{},body:f})})).json();return new Response(JSON.stringify(p.body),{status:p.status,statusText:p.statusText,headers:new Headers(p.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.session.saveTokens(e,t)}async clientInformation(e){return this.staticClientInfo?this.staticClientInfo:this.session.clientInformation(e)}async saveClientInformation(e,t){if(!this.staticClientInfo)return this.session.saveClientInformation(e,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)}discoveryState(){return this.session.discoveryState()}getTokenEndpoint(){return this.session.getTokenEndpoint()}async getClientCredentials(){let e=await this.clientInformation();return e?.client_id?{client_id:e.client_id}:null}async prepareAuthorizationUrl(e){return 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:typeof window<`u`?window.location.href:void 0})}async redirectToAuthorization(e){let t=await this.prepareAuthorizationUrl(e);if(this.preventAutoAuth){console.info(`[${this.storageKeyPrefix}] Auto-auth prevented. Authorization URL stored for manual trigger.`);return}if(this.useRedirectFlow){console.info(`[${this.storageKeyPrefix}] Redirecting to authorization URL (full-page redirect).`),window.location.href=t;return}let n=`width=600,height=700,resizable=yes,scrollbars=yes,status=yes`;try{let e=window.open(t,`mcp_auth_${this.serverUrlHash}`,n);this.onPopupWindow&&this.onPopupWindow(t,n,e),!e||e.closed||e.closed===void 0?console.warn(`[${this.storageKeyPrefix}] Popup likely blocked by browser. Manual navigation might be required using the stored URL.`):(e.focus(),console.info(`[${this.storageKeyPrefix}] Redirecting to authorization URL in popup.`))}catch(e){console.error(`[${this.storageKeyPrefix}] Error opening popup window:`,e)}}getLastAttemptedAuthUrl(){let e=localStorage.getItem(this.getKey(`last_auth_url`));return e?kk(e):null}clearStorage(){let e=`${this.storageKeyPrefix}_${this.serverUrlHash}_`,t=`${this.storageKeyPrefix}:state_`,n=[],r=0;for(let r=0;r<localStorage.length;r++){let i=localStorage.key(r);if(i){if(i.startsWith(e))n.push(i);else if(i.startsWith(t))try{let e=localStorage.getItem(i);e&&JSON.parse(e).serverUrlHash===this.serverUrlHash&&n.push(i)}catch(e){console.warn(`[${this.storageKeyPrefix}] Error parsing state key ${i} during clearStorage:`,e)}}}return[...new Set(n)].forEach(e=>{localStorage.removeItem(e),r++}),r}};async function Fk(e,t={}){return new Pk(e,t)}JO(),JO();var Ik=class{},Lk=class extends Ik{constructor(e){super(),this.data=e}get name(){return`mcp_agent_execution`}get properties(){return{execution_method:this.data.executionMethod,query:this.data.query,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,server_identifiers:this.data.serverIdentifiers,total_tools_available:this.data.totalToolsAvailable,tools_available_names:this.data.toolsAvailableNames,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,tools_used_names:this.data.toolsUsedNames??null,response:this.data.response??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}}},Rk=class extends Ik{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}}},zk=class extends Ik{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}}},Bk=class extends Ik{constructor(e){super(),this.data=e}get name(){return`client_add_server`}get properties(){let{serverName:e,serverConfig:t}=this.data,n=t.url;return{server_name:e,server_url_domain:n?this._extractHostname(n):null,transport:t.transport??null,has_auth:!!(t.authToken||t.authProvider)}}_extractHostname(e){try{return new URL(e).hostname}catch{return null}}},Vk=class extends Ik{constructor(e){super(),this.data=e}get name(){return`client_remove_server`}get properties(){return{server_name:this.data.serverName}}};async function Hk(e,t){try{await fetch(e,t)}catch{}}var Uk=`https://eu.i.posthog.com`,Wk=`phc_lyTtbYwvkdSbrcMQNPiKiiRWrrM1seyKIMjycSvItEI`;function Gk(e){let t=e.host??Uk,n=e.apiKey??Wk;return Hk(`${t}/i/v0/e/`,{method:`POST`,headers:{"Content-Type":`application/json`},keepalive:!0,body:JSON.stringify({api_key:n,event:e.event,distinct_id:e.distinctId,properties:e.properties,timestamp:new Date().toISOString()})})}function Kk(){return globalThis.crypto.randomUUID()}function qk(){let e=new Uint8Array(8);return globalThis.crypto.getRandomValues(e),Array.from(e,e=>e.toString(16).padStart(2,`0`)).join(``)}var Jk=`mcp_use_user_id`,Yk=`phc_lyTtbYwvkdSbrcMQNPiKiiRWrrM1seyKIMjycSvItEI`,Xk=`https://eu.i.posthog.com`,Zk=null;function Qk(){return typeof localStorage<`u`&&typeof localStorage.getItem==`function`&&typeof localStorage.setItem==`function`&&typeof localStorage.removeItem==`function`}function $k(){if(!Qk())return null;try{localStorage.setItem(`__mcp_use_test__`,`1`),localStorage.removeItem(`__mcp_use_test__`)}catch{return null}return{getUserId(){try{return localStorage.getItem(Jk)}catch{return null}},setUserId(e){try{localStorage.setItem(Jk,e)}catch{}}}}function eA(){try{return globalThis.Bun===void 0?globalThis.Deno===void 0?typeof navigator<`u`&&navigator.userAgent?.includes(`Cloudflare-Workers`)?`cloudflare-workers`:globalThis.EdgeRuntime===void 0?typeof window<`u`&&typeof document<`u`?`browser`:typeof process<`u`&&process.versions?.node!==void 0?`node`:`unknown`:`edge`:`deno`:`bun`}catch{return`unknown`}}function tA(){if(typeof process<`u`&&{}.MCP_USE_TELEMETRY_SOURCE)return{}.MCP_USE_TELEMETRY_SOURCE;try{if(Qk())return localStorage.getItem(`MCP_USE_TELEMETRY_SOURCE`)??void 0}catch{}}function nA(){if(typeof window<`u`&&window.__MCP_USE_ANONYMIZED_TELEMETRY__===!1||typeof process<`u`&&{}.MCP_USE_ANONYMIZED_TELEMETRY?.toLowerCase()===`false`)return!0;try{if(Qk()&&localStorage.getItem(`MCP_USE_ANONYMIZED_TELEMETRY`)===`false`)return!0}catch{}return!1}function rA(){try{return`session-${Kk()}`}catch{return`session-${Date.now()}-${qk()}`}}var iA=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=eA(),this._storage=Zk??$k()??null,this._storageCapability=this._storage?`persistent`:`session-only`,this._source=tA()||this._runtimeEnvironment;let e=nA(),t=this._runtimeEnvironment!==`unknown`;e?(this._telemetryEnabled=!1,$.debug(`Telemetry disabled via opt-out`)):t?($.debug(`Anonymized telemetry enabled. Set MCP_USE_ANONYMIZED_TELEMETRY=false to disable.`),this._telemetryEnabled=!0):(this._telemetryEnabled=!1,$.debug(`Telemetry disabled - unknown environment: ${this._runtimeEnvironment}`))}get runtimeEnvironment(){return this._runtimeEnvironment}get storageCapability(){return this._storageCapability}static getInstance(){return e.instance||=new e,e.instance}setSource(e){this._source=e;try{Qk()&&localStorage.setItem(`MCP_USE_TELEMETRY_SOURCE`,e)}catch{}$.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=Kk();return this._storage.setUserId(t),this._currUserId=t,t}this._currUserId=rA()}catch{this._currUserId=this.UNKNOWN_USER_ID}return this._currUserId}async capture(e){if(!this._telemetryEnabled)return;let t=this.userId,n={...e.properties,mcp_use_version:this._productVersion??Ck(),language:`typescript`,source:this._source,runtime:this._runtimeEnvironment},r=Gk({host:Xk,apiKey:Yk,event:e.name,distinctId:t,properties:n});this._pending.add(r),r.finally(()=>this._pending.delete(r))}async trackAgentExecution(e){this.isEnabled&&await this.capture(new Lk(e))}async trackMCPClientInit(e){this.isEnabled&&await this.capture(new Rk(e))}async trackConnectorInit(e){this.isEnabled&&await this.capture(new zk(e))}async trackClientAddServer(e,t){this.isEnabled&&await this.capture(new Bk({serverName:e,serverConfig:t}))}async trackClientRemoveServer(e){this.isEnabled&&await this.capture(new Vk({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&&Gk({host:Xk,apiKey:Yk,event:`$identify`,distinctId:e,properties:{$set:t??{}}})}reset(){this._currUserId=null}flush(){Promise.allSettled([...this._pending])}async shutdown(){try{await Promise.allSettled([...this._pending]),$.debug(`Telemetry fetch captures flushed`)}catch(e){$.debug(`Error flushing telemetry captures: ${e}`)}}},aA=5*6e4;function oA(e,t=0){if(!e||t>5)return!1;if(e instanceof xS)return!0;if(e instanceof Error){if(e.code===401||e.name===`UnauthorizedError`)return!0;let n=e.message??``;if(n.includes(`401`)||n.includes(`Unauthorized`)||e.cause&&oA(e.cause,t+1))return!0;let r=e.data;if(r?.cause&&oA(r.cause,t+1))return!0}return!1}async function sA(e,t,n={}){let r=e,i=n.timeoutMs??aA,a=n.fetchFn??r.getProxyFetch?.()??void 0;if(!r.hasPendingFlow){let n=await BS(e,{serverUrl:t,fetchFn:a});if(n===`AUTHORIZED`)return;if(n!==`REDIRECT`)throw Error(`Unexpected OAuth auth() result: ${n}`)}if(typeof r.getAuthorizationCode==`function`){await BS(e,{serverUrl:t,authorizationCode:await r.getAuthorizationCode(),fetchFn:a});return}await cA(r,i)}async function cA(e,t){if(typeof window>`u`)throw Error(`OAuth redirect requires a browser environment or a provider with getAuthorizationCode()`);if(e.useRedirectFlow)return;let n=e.getKey?.(`tokens`);if(!n)throw Error(`Browser OAuth provider must expose getKey() for token storage`);let r=null,i=e.getLastAttemptedAuthUrl?.();if(i)try{r=new URL(i).searchParams.get(`state`)}catch{}let a=await ck({popup:null,state:r,tokensKey:n,timeoutMs:t});switch(a.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(a.error);default:throw Error(`Unexpected OAuth popup result`)}}JO();var lA=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){e===`notification`&&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 protocolEra(){return this.connector.protocolEra}get negotiatedProtocolVersion(){return this.connector.negotiatedProtocolVersion}get info(){let e=this.protocolEra,t=this.negotiatedProtocolVersion,n=this.serverInfo;if(!e||!t||!n)throw Error(`MCP connection is not initialized`);let r=this.serverCapabilities,i=r.extensions&&typeof r.extensions==`object`&&!Array.isArray(r.extensions)?r.extensions:{};return{protocolEra:e,protocolVersion:t,server:n,capabilities:r,instructions:this.connector.instructions,extensions:i}}supports(e){return e in this.serverCapabilities}async callTool(e,t={},n){return this.connector.callTool(e,t,n)}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){return this.connector.getPrompt(e,t)}async request(e,t=null,n){return this.connector.request(e,t,n)}},uA;function dA(e,t){uA?.addServer(e,t)}function fA(e){uA?.removeServer(e)}function pA(e){return!!e&&typeof e==`object`&&`redirectUrl`in e&&`clientMetadata`in e}var mA=class{config={};sessions={};activeSessions=[];constructor(e){e&&(this.config=e)}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,dA(e,t)}async removeServer(e){this.config.mcpServers?.[e]&&(await this.closeSession(e),delete this.config.mcpServers[e],fA(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 n=this.config.mcpServers??{};if(Object.keys(n).length===0&&$.warn(`No MCP servers defined in config`),!n[e])throw Error(`Server '${e}' not found in config`);let r={...n[e]},i;if(Tk(r)){let e=r.oauth===!1?void 0:r.oauth??{};i=await this.createDefaultOAuthProvider(r.url,e),r={...r,authProvider:i}}else `authProvider`in r&&r.authProvider&&pA(r.authProvider)&&(i=r.authProvider);let a=async()=>{let e=new lA(await Promise.resolve(this.createConnectorFromConfig(r)));return t&&await e.initialize(),e},o;try{o=await a()}catch(n){let s=r;if(!t||!i||!(`url`in s)||!oA(n)||i.preventAutoAuth)throw n;$.info(`[MCPClient] Unauthorized connecting to '${e}'; completing OAuth\u2026`),await sA(i,s.url),o=await a()}return this.sessions[e]=o,this.activeSessions.includes(e)||this.activeSessions.push(e),o}async connect(e){return this.createSession(e)}async createAllSessions(e=!0){let t=this.config.mcpServers??{};Object.keys(t).length===0&&$.warn(`No MCP servers defined in config`);for(let n of Object.keys(t))await this.createSession(n,e);return this.sessions}async connectAll(){return this.createAllSessions()}getSession(e){return this.sessions[e]||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){$.warn(`No session exists for server ${e}, nothing to close`);return}try{$.debug(`Closing session for server ${e}`),await t.disconnect()}catch(t){$.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 n of e)try{$.debug(`Closing session for server ${n}`),await this.closeSession(n)}catch(e){let r=`Failed to close session for server '${n}': ${e}`;$.error(r),t.push(r)}t.length?$.error(`Encountered ${t.length} errors while closing sessions`):$.debug(`All sessions closed successfully`)}async close(){await this.closeAllSessions()}};function hA(e){let t=Object.keys(e.mcpServers??{});iA.getInstance().trackMCPClientInit({codeMode:!1,sandbox:!1,allCallbacks:!1,verify:!1,servers:t,numServers:t.length,isBrowser:!0}).catch(e=>$.debug(`Failed to track BrowserMCPClient init: ${e}`))}var gA=class e extends mA{static getPackageVersion(){return Ck()}constructor(e){super(e),hA(this.config)}static fromDict(t){return new e(t)}async createDefaultOAuthProvider(e,t={}){return Fk(e,t)}createConnectorFromConfig(e){let{url:t,headers:n,fetch:r,authToken:i,authProvider:a,wrapTransport:o,clientOptions:s,protocolNegotiation:c,timeout:l,gatewayUrl:u,serverId:d,reconnectionOptions:f}=e;if(!t)throw Error(`Server URL is required`);let p=this.config,m=wk(e,p),h=Dk(e.clientInfo??this.config.clientInfo),g={headers:n,fetch:r??globalThis.fetch.bind(globalThis),authToken:i,authProvider:a,wrapTransport:o,clientOptions:s,onSampling:m.onSampling,onElicitation:m.onElicitation,onNotification:m.onNotification,protocolNegotiation:c,timeout:l,clientInfo:h,gatewayUrl:u,serverId:d,reconnectionOptions:f};return $.debug(`[BrowserMCPClient] Connector options prepared (clientOptions: ${s?`provided`:`none`})`),new xk(t,g)}};JO();var _A=`https://favicon.tools.mcp-use.com`,vA=/^\d{1,3}(\.\d{1,3}){3}$/;function yA(e){try{let t=e.includes(`://`)?e:`https://${e}`;return new URL(t).hostname}catch{return null}}function bA(e){let t=e.toLowerCase();if(t===`localhost`||t.endsWith(`.localhost`)||t===`host.docker.internal`||t===`0.0.0.0`)return!0;if(!vA.test(t))return!1;if(t===`127.0.0.1`||t.startsWith(`127.`)||t.startsWith(`10.`)||t.startsWith(`192.168.`))return!0;let n=/^172\.(\d+)\./.exec(t);if(n){let e=Number.parseInt(n[1],10);if(e>=16&&e<=31)return!0}return!1}function xA(e){let t=e.split(`.`);return Array.from({length:t.length-1},(e,n)=>t.slice(n).join(`.`))}function SA(e){return new Promise((t,n)=>{let r=new FileReader;r.onloadend=()=>t(r.result),r.onerror=n,r.readAsDataURL(e)})}async function CA(e){try{let t=yA(e);if(!t||bA(t))return null;for(let e of xA(t))try{let t=await fetch(`${_A}/${e}?response=json`,{signal:AbortSignal.timeout(2e3)});if(!t.ok)continue;let n=await t.json();if(n.source==="default")continue;let r=n.url.replace(/^http:\/\//,`https://`),i=await fetch(r,{signal:AbortSignal.timeout(2e3)});if(!i.ok)continue;return await SA(await i.blob())}catch{continue}return null}catch(e){return console.warn(`[favicon] Error detecting favicon:`,e),null}}var wA=`inspector-server`;function TA(e,t){if(!e)throw Error(t)}async function EA(e){try{let t=e.serverInfo.icons?.[0]?.src;if(t){e.addLog(`info`,`Server provided icon:`,t);let n=await(await fetch(t)).blob(),r=await new Promise((e,t)=>{let r=new FileReader;r.onloadend=()=>e(r.result),r.onerror=t,r.readAsDataURL(n)});return e.isMounted()&&(e.setServerInfo(e=>e?{...e,icon:r}:void 0),e.addLog(`debug`,`Server icon converted to base64`)),r}if(e.url){let t=await CA(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 DA(e,t){return t?`state=${e}`:`client disconnected (state=${e})`}function OA(e){return{name:e.name,version:e.version,uri:e.websiteUrl,logo_uri:e.icons?.[0]?.src}}function kA(e){let t=(e instanceof Error?e.message:String(e)).toLowerCase();return t.includes(`oauth discovery failed`)||t.includes(`oauth-authorization-server`)||t.includes(`not valid json`)||t.includes(`404`)&&(t.includes(`openid-configuration`)||t.includes(`oauth-protected-resources`)||t.includes(`oauth-authorization-url`)||t.includes(`register`))||t.includes(`invalid oauth error response`)&&t.includes(`not found`)}function AA(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}}function jA(e){let t=AA(e.gatewayUrl,e.oauthProxyUrl);return{provider:new Pk(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 MA(e){let t=null,n=Date.now(),r=!1,i=e.healthCheckIntervalMs??1e4,a=e.healthCheckTimeoutMs??3e4;return t=setInterval(async()=>{if(!r){if(!e.isMountedRef.current||e.stateRef.current!==`ready`){t&&=(clearInterval(t),null);return}try{let i=e.gatewayUrl||e.url;if(!i)return;let a=e.getAuthHeaders?await e.getAuthHeaders():{},o=await fetch(i,{method:`HEAD`,headers:{...e.allHeaders,...a},signal:AbortSignal.timeout(5e3)});if(o.status===405||o.status===404){r=!0,n=Date.now(),t&&=(clearInterval(t),null);return}if(o.ok||o.status<500)n=Date.now();else throw Error(`Server returned ${o.status}`)}catch{let r=Date.now()-n;r>a&&(e.addLog(`warn`,`Connection appears to be broken (no response for ${Math.round(r/1e3)}s), attempting to reconnect...`),t&&=(clearInterval(t),null),e.autoReconnectRef.current&&e.isMountedRef.current&&(e.setState(`discovering`),e.addLog(`info`,`Auto-reconnecting to MCP server...`),setTimeout(()=>{e.isMountedRef.current&&e.stateRef.current===`discovering`&&e.connect()},typeof e.autoReconnectRef.current==`number`?e.autoReconnectRef.current:e.defaultReconnectDelay)))}}},i),()=>{t&&=(clearInterval(t),null)}}function NA(e,t){let n=e.connectionRef.current;if(e.stateRef.current!==`ready`||!e.hasClient()||!n)throw Error(`MCP client is not ready (${DA(e.stateRef.current,e.hasClient())}). Cannot ${t}.`);return n}function PA(e){let t=(0,z.useCallback)(async(t,n,r)=>{let i=NA(e,`call tool "${t}"`);e.addLog(`info`,`Calling tool: ${t}`,n);let a=Date.now();try{let o=await i.callTool(t,n||{},r);return e.addLog(`info`,`Tool "${t}" call successful:`,o),iA.getInstance().trackUseMcpToolCall({toolName:t,success:!0,executionTimeMs:Date.now()-a}).catch(()=>{}),o}catch(n){throw e.addLog(`error`,`Tool "${t}" call failed:`,n),iA.getInstance().trackUseMcpToolCall({toolName:t,success:!1,errorType:n instanceof Error?n.name:`UnknownError`,executionTimeMs:Date.now()-a}).catch(()=>{}),n}},[e.addLog]),n=(0,z.useCallback)(async()=>{let t=NA(e,`list resources`);e.addLog(`info`,`Listing resources`);let n=await t.listAllResources();e.setResources(n.resources||[])},[e.addLog]),r=(0,z.useCallback)(async t=>{let n=NA(e,`read resource`);e.addLog(`info`,`Reading resource: ${t}`);try{let e=await n.readResource(t);return iA.getInstance().trackUseMcpResourceRead({resourceUri:t,success:!0}).catch(()=>{}),e}catch(e){throw iA.getInstance().trackUseMcpResourceRead({resourceUri:t,success:!1,errorType:e instanceof Error?e.name:`UnknownError`}).catch(()=>{}),e}},[e.addLog]),i=(0,z.useCallback)(async()=>{let t=NA(e,`list prompts`);e.addLog(`info`,`Listing prompts`);let n=await t.listPrompts();e.setPrompts(n.prompts||[])},[e.addLog]),a=(0,z.useCallback)(async()=>{if(!(e.stateRef.current!==`ready`||!e.connectionRef.current))try{e.setTools(await e.connectionRef.current.listTools()||[])}catch(t){e.addLog(`error`,`Failed to refresh tools:`,t)}},[e.addLog]),o=(0,z.useCallback)(async()=>{if(!(e.stateRef.current!==`ready`||!e.connectionRef.current))try{let t=await e.connectionRef.current.listAllResources();e.setResources(t.resources||[])}catch(t){e.addLog(`warn`,`Failed to refresh resources:`,t)}},[e.addLog]),s=(0,z.useCallback)(async()=>{if(!(e.stateRef.current!==`ready`||!e.connectionRef.current))try{let t=await e.connectionRef.current.listPrompts();e.setPrompts(t.prompts||[])}catch(t){e.addLog(`warn`,`Failed to refresh prompts:`,t)}},[e.addLog]),c=(0,z.useCallback)(async()=>{let t=await NA(e,`refresh resource templates`).listResourceTemplates();e.isMounted()&&e.setResourceTemplates(t.resourceTemplates||[])},[e.addLog]);return{callTool:t,listResources:n,readResource:r,listPrompts:i,refreshTools:a,refreshResources:o,refreshPrompts:s,refreshResourceTemplates:c,refreshAll:(0,z.useCallback)(()=>Promise.all([a(),o(),c(),s()]).then(()=>void 0),[a,o,c,s]),getPrompt:(0,z.useCallback)(async(t,n)=>NA(e,`get prompt`).getPrompt(t,n||{}),[e.addLog]),complete:(0,z.useCallback)(async t=>NA(e,`request completion`).complete(t),[e.addLog])}}var FA=3e3,IA=5e3;function LA(e){let{url:t,enabled:n=!0,callbackUrl:r=typeof window<`u`?kk(new URL(`/oauth/callback`,window.location.origin).toString()):`/oauth/callback`,storageKeyPrefix:i=`mcp:auth`,authProvider:a,headers:o,proxyConfig:s,oauthProxyUrl:c,autoProxyFallback:l=!1,logLevel:u=`silent`,autoRetry:d=!1,autoReconnect:f=!0,reconnectionOptions:p,preventAutoAuth:m=!0,useRedirectFlow:h=!1,onPopupWindow:g,timeout:_=3e4,wrapTransport:v,serverId:y,fetch:b,clientOptions:x,protocolNegotiation:S,onNotification:C,onSampling:w,onElicitation:T,oauth:E}=e,ee=`http`,D=E?.clientId?.trim()||void 0,te=E?.clientMetadataUrl?.trim()||void 0,ne=E?.scope?.trim()||void 0,re=(0,z.useMemo)(()=>D?{client_id:D}:void 0,[D]),O=(0,z.useMemo)(()=>{let e=`useMcp:${t||`no-url`}`,n=qO.get(e);return u&&(n.level=u),n},[t,u]),ie=o??{},k=(0,z.useMemo)(()=>Ok(x),[x]),A=w,j=T,ae=(0,z.useMemo)(()=>({name:`mcp-use`,title:`mcp-use`,version:Ck(),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`}),[]),oe=(0,z.useMemo)(()=>e.clientInfo?{...ae,...e.clientInfo}:ae,[e.clientInfo,ae]),se=(0,z.useMemo)(()=>OA(oe),[oe]),ce=(0,z.useMemo)(()=>{if(!l)return{enabled:!1,proxyAddress:void 0};if(typeof l==`boolean`){let e=s?.proxyAddress;return{enabled:l&&!!e,proxyAddress:e}}let e=l.proxyAddress??s?.proxyAddress;return{enabled:l.enabled!==!1&&!!e,proxyAddress:e}},[l,s]),M=(0,z.useMemo)(()=>f===!1?{enabled:!1,initialDelay:0,healthCheckInterval:!1,healthCheckTimeout:3e4}:f===!0?{enabled:!0,initialDelay:FA,healthCheckInterval:1e4,healthCheckTimeout:3e4}:typeof f==`number`?{enabled:!0,initialDelay:f,healthCheckInterval:1e4,healthCheckTimeout:3e4}:{enabled:f.enabled!==!1,initialDelay:f.initialDelay??FA,healthCheckInterval:f.healthCheckInterval??1e4,healthCheckTimeout:f.healthCheckTimeout??3e4},[f]),[N,le]=(0,z.useState)(void 0);(0,z.useEffect)(()=>{le(void 0)},[t,s]);let ue=(0,z.useMemo)(()=>{if(!N?.proxyAddress)return s;let e=s?.headers??{};return{...N,headers:{...e,...N.headers??{}}}},[N,s]),de=ue?.proxyAddress,fe=ue?.headers??{},pe=(0,z.useMemo)(()=>t||``,[t]),me=(0,z.useMemo)(()=>({...fe,...ie}),[fe,ie]),[he,ge]=(0,z.useState)(`discovering`),[_e,ve]=(0,z.useState)([]),[ye,be]=(0,z.useState)([]),[xe,P]=(0,z.useState)([]),[Se,Ce]=(0,z.useState)([]),[we,Te]=(0,z.useState)(e._initialServerInfo?.name?e._initialServerInfo:void 0),[Ee,De]=(0,z.useState)(),[Oe,ke]=(0,z.useState)(void 0),[Ae,je]=(0,z.useState)(void 0),[Me,Ne]=(0,z.useState)(),[Pe,Fe]=(0,z.useState)({}),[Ie,Le]=(0,z.useState)(void 0),[Re,ze]=(0,z.useState)([]),[Be,Ve]=(0,z.useState)(void 0),[He,Ue]=(0,z.useState)(void 0),We=(0,z.useRef)(null),Ge=(0,z.useRef)(null),Ke=(0,z.useRef)(a??null),qe=(0,z.useRef)(null),Je=(0,z.useRef)(!1),Ye=(0,z.useRef)(!0),Xe=(0,z.useRef)(0),Ze=(0,z.useRef)(0),Qe=(0,z.useRef)(null),$e=(0,z.useRef)(!1),et=(0,z.useRef)(!1),tt=(0,z.useRef)(he),nt=(0,z.useRef)(f),rt=(0,z.useRef)(null),it=(0,z.useRef)(null),at=(0,z.useRef)(null),ot=(0,z.useRef)(A),st=(0,z.useRef)(j),ct=(0,z.useRef)(A!==void 0),lt=(0,z.useRef)(j!==void 0),ut=(0,z.useRef)(C);A!==void 0&&(ot.current=A),j!==void 0&&(st.current=j),ct.current=A!==void 0,lt.current=j!==void 0,ut.current=C;let dt=(0,z.useCallback)(async e=>ot.current(e),[]),ft=(0,z.useCallback)(async e=>st.current(e),[]),pt=(0,z.useCallback)(e=>{ut.current?.(e)},[]);(0,z.useEffect)(()=>{tt.current=he,nt.current=f},[he,f]),(0,z.useEffect)(()=>{Ke.current=a??null},[a]);let F=(0,z.useCallback)((e,t,...n)=>{let r=n.length>0?`${t} ${n.map(e=>JSON.stringify(e)).join(` `)}`:t,i=`[useMcp] ${r}`;switch(e){case`error`:O.error(i);break;case`warn`:O.warn(i);break;case`info`:O.info(i);break;case`debug`:O.debug(i);break;default:O.info(i)}Ye.current&&ze(t=>[...t.slice(-100),{level:e,message:r,timestamp:Date.now()}])},[O]),mt=PA({stateRef:tt,connectionRef:Ge,hasClient:()=>We.current!==null,isMounted:()=>Ye.current,setTools:ve,setResources:be,setResourceTemplates:P,setPrompts:Ce,addLog:F}),ht=(0,z.useCallback)(async(e=!1)=>{e||F(`info`,`Disconnecting...`),Je.current=!1,Qe.current&&clearTimeout(Qe.current),Qe.current=null;let t=Ze.current,n=We.current;if(n)try{let e=wA,t=n===We.current?Ge.current:null;t&&t._healthCheckCleanup&&(t._healthCheckCleanup(),t._healthCheckCleanup=null),t&&await n.closeSession(e)}catch(t){e||F(`warn`,`Error closing connection:`,t)}let r=Ze.current!==t;We.current===n&&!r&&(We.current=null,Ge.current=null),Ye.current&&!e&&!r&&(ge(`discovering`),ve([]),be([]),P([]),Ce([]),Le(void 0),Ve(void 0),Ue(void 0),Te(void 0),De(void 0),ke(void 0),je(void 0),Ne(void 0),Fe({}))},[F]),gt=(0,z.useCallback)((e,n)=>{F(`error`,e,n??``);let r=n&&`code`in n?n.code:void 0,i=ce.enabled&&!ue?.proxyAddress,o=e.includes(`CORS`)||e.includes(`blocked by CORS policy`)||e.includes(`Failed to fetch`),s=r===400;if(i&&(o||s||typeof r==`number`&&r>=404&&r<500)&&!(r===401||r===403))return F(`info`,`Direct connection failed with ${o?`CORS error`:s?`HTTP 400 (Bad Request)`:`HTTP 4xx error`}. Trying with proxy...`),We.current=null,a||(Ke.current=null),F(`debug`,`Cleared client and auth provider for proxy fallback`),le({proxyAddress:ce.proxyAddress}),Ye.current&&ge(`discovering`),setTimeout(()=>{Ye.current&&it.current?.()},1e3),!0;if(Ye.current){F(`info`,`Setting state to FAILED:`,e),ge(`failed`),Le(e);let t=Ke.current?.getLastAttemptedAuthUrl?.();t&&(Ve(t),F(`info`,`Manual authentication URL may be available.`,t))}return Je.current=!1,t&&iA.getInstance().trackUseMcpConnection({url:t,transportType:ee,success:!1,errorType:n?.name||`UnknownError`,hasOAuth:!!Ke.current,hasSampling:ct.current,hasElicitation:lt.current}).catch(()=>{}),!1},[F,t,ee,ce,ue,a]),_t=(0,z.useCallback)(async()=>{if(!n||!t){F(`debug`,n?`No server URL provided, skipping connection.`:`Connection disabled via enabled flag.`);return}if(Je.current){F(`debug`,`Connection attempt already in progress.`);return}if(!Ye.current){F(`debug`,`Connect called after unmount, aborting.`);return}if(Je.current=!0,Ze.current+=1,Xe.current+=1,Le(void 0),Ve(void 0),rt.current=null,ge(`discovering`),ve([]),be([]),P([]),Ce([]),Te(void 0),De(void 0),ke(void 0),je(void 0),Ne(void 0),Fe({}),F(`info`,`Connecting attempt #${Xe.current} to ${t}...`),!Ke.current){let{provider:e,oauthProxyUrl:t}=jA({effectiveOAuthUrl:pe,storageKeyPrefix:i,oauthClientConfig:se,callbackUrl:r,preventAutoAuth:m,useRedirectFlow:h,gatewayUrl:de,oauthProxyUrl:c,onPopupWindow:g,proxyOAuthRequests:!0,staticClientInfo:re,clientMetadataUrl:te,scope:ne});Ke.current=e,t&&F(`debug`,`OAuth BFF enabled: ${t}`),F(`debug`,`BrowserOAuthClientProvider initialized with URL: ${pe}, proxy: ${t?`enabled`:`disabled`}, gateway: ${de?`enabled`:`disabled`}`)}We.current?F(`debug`,`BrowserMCPClient already exists, reusing.`):(We.current=new gA,F(`debug`,`BrowserMCPClient initialized in connect.`));let e=async n=>{if(!Ye.current)return F(`debug`,`Connection attempt aborted - component unmounted`),`failed`;F(`info`,`Attempting connection with transport: ${n}`),F(`debug`,`Client ref status at start of tryConnectWithTransport: ${We.current?`initialized`:`NULL`}`);try{let e=wA,r={url:t,timeout:_,clientInfo:oe,...(()=>{let e=Ke.current?.getProxyFetch?.(b)??b;return e?{fetch:e}:{}})(),...k&&{clientOptions:k},...S!==void 0&&{protocolNegotiation:S},...p?{reconnectionOptions:p}:f===!1?{reconnectionOptions:{maxRetries:0}}:{}};if(de&&(r.gatewayUrl=de,F(`debug`,`Using proxy gateway: ${de} for target: ${t}`)),me&&Object.keys(me).length>0&&(r.headers=me),!We.current){if(!Ye.current)return F(`debug`,`Connection aborted - component unmounted, client cleaned up`),`failed`;let e=Error(`Client not initialized - this is a bug in the connection flow`);throw F(`error`,`Client ref is null in tryConnectWithTransport but component is still mounted`),e}We.current.addServer(e,{...r,authProvider:Ke.current,onSampling:ct.current?dt:void 0,onElicitation:lt.current?ft:void 0,onNotification:e=>{F(`debug`,`Notification received:`,e.method,e),pt(e),e.method===`notifications/tools/list_changed`?(F(`info`,`Tools list changed, auto-refreshing...`),mt.refreshTools().catch(e=>F(`warn`,`Auto-refresh tools failed:`,e))):e.method===`notifications/resources/list_changed`?(F(`info`,`Resources list changed, auto-refreshing...`),mt.refreshResources().catch(e=>F(`warn`,`Auto-refresh resources failed:`,e))):e.method===`notifications/prompts/list_changed`&&(F(`info`,`Prompts list changed, auto-refreshing...`),mt.refreshPrompts().catch(e=>F(`warn`,`Auto-refresh prompts failed:`,e)))},wrapTransport:v?n=>(F(`debug`,`Applying transport wrapper for server:`,e,`url:`,t),v(n,y??t)):void 0});let i=await We.current.connect(e);if(Ge.current=i,!Ye.current)return F(`debug`,`Connection aborted after connection creation - component unmounted`),`failed`;F(`info`,`✅ Successfully connected to MCP server`),F(`info`,`Server info:`,i.info.server),F(`info`,`Server capabilities:`,i.info.capabilities),M.enabled&&M.healthCheckInterval!==!1&&(i._healthCheckCleanup=MA({gatewayUrl:de,url:t,allHeaders:me,getAuthHeaders:async()=>{try{let e=await Ke.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:Ye,stateRef:tt,autoReconnectRef:nt,setState:ge,addLog:F,connect:_t,defaultReconnectDelay:M.initialDelay,healthCheckIntervalMs:M.healthCheckInterval,healthCheckTimeoutMs:M.healthCheckTimeout})),iA.getInstance().trackUseMcpConnection({url:t,transportType:n,success:!0,hasOAuth:!!Ke.current,hasSampling:ct.current,hasElicitation:lt.current}).catch(()=>{}),ve(i.tools||[]);let[a,o,s]=await Promise.all([i.listAllResources(),i.listPrompts(),i.supports(`resources`)?i.listResourceTemplates():Promise.resolve({resourceTemplates:[]})]);if(!Ye.current)return F(`debug`,`Connection aborted after discovery - component unmounted`),`failed`;be(a.resources||[]),Ce(o.prompts||[]),P(s.resourceTemplates||[]);let{server:c,capabilities:l,protocolEra:u,protocolVersion:d,instructions:m,extensions:h}=i.info;if(Ye.current&&(ke(u),je(d),Ne(m),Fe(h)),c){if(F(`debug`,`Server info:`,c),!Ye.current)return F(`debug`,`Skipping state update - component unmounted`),`failed`;Te(c),qe.current=EA({serverInfo:c,url:t,isMounted:()=>Ye.current,setServerInfo:Te,addLog:F})}if(l){if(F(`debug`,`Server capabilities:`,l),!Ye.current)return F(`debug`,`Skipping state update - component unmounted`),`failed`;De(l)}if(Ke.current){let e=await Ke.current.tokens?.();if(!Ye.current)return F(`debug`,`Connection aborted after token fetch for auth tokens - component unmounted`),`failed`;if(e?.access_token){let t=e.expires_in?Date.now()+e.expires_in*1e3:void 0,n=null,r=null;try{n=await Ke.current.getTokenEndpoint?.()??null}catch{n=null}try{r=await Ke.current.getClientCredentials?.()??null}catch{r=null}if(!Ye.current)return F(`debug`,`Skipping state update - component unmounted`),`failed`;Ue({access_token:e.access_token,token_type:e.token_type||`Bearer`,expires_at:t,refresh_token:e.refresh_token,scope:e.scope,...n?{token_endpoint:n}:{},...r?.client_id?{client_id:r.client_id}:{},...r?.client_secret?{client_secret:r.client_secret}:{}})}}return rt.current=n,ge(`ready`),`success`}catch(r){let i=r,a=i?.message||String(r),o=Ke.current?.getLastAttemptedAuthUrl?.();if(o&&Ke.current&&m)return F(`info`,`OAuth already discovered (stored auth URL present); awaiting manual authentication.`),Ye.current&&(ge(`pending_auth`),Ve(o)),Je.current=!1,`auth_redirect`;let s=kA(r),c=oA(r);if(s&&ie&&Object.keys(ie).length>0)return gt(`Authentication failed (HTTP 401). Server does not support OAuth. Check your Authorization header value is correct.`),`failed`;if(s&&(!ie||Object.keys(ie).length===0))return gt(`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(c){if(s)return gt(`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(Ke.current)if(F(`info`,`Authentication required. OAuth provider available.`),m){if(F(`info`,`Waiting for user to initiate authentication flow...`),Ye.current){ge(`pending_auth`);let e=Ke.current?.getLastAttemptedAuthUrl?.();e&&(Ve(e),F(`info`,`Retrieved stored auth URL for manual authentication`))}return Je.current=!1,`auth_redirect`}else{F(`info`,`Triggering automatic OAuth authentication flow...`);try{if(await BS(Ke.current,{serverUrl:t,fetchFn:Ke.current.getProxyFetch?.()})===`REDIRECT`){let e=await Ke.current.getAuthorizationCode?.();if(!e)throw Error(`Authorization code not captured by headless provider`);await BS(Ke.current,{serverUrl:t,authorizationCode:e,fetchFn:Ke.current.getProxyFetch?.()})}return F(`info`,`OAuth flow completed, reconnecting...`),await e(n)}catch(e){return gt(`Automatic OAuth authentication failed: ${e instanceof Error?e.message:String(e)}`,e instanceof Error?e:Error(String(e))),`failed`}}return ie&&Object.keys(ie).length>0?(gt(`Authentication failed: Server returned 401 Unauthorized. Check your Authorization header value is correct.`),`failed`):(gt(`Authentication required: Server returned 401 Unauthorized. Add an Authorization header in the Custom Headers section (e.g., Authorization: Bearer YOUR_API_KEY).`),`failed`)}return gt(a,i instanceof Error?i:Error(String(i)))?`auth_redirect`:`failed`}},a=`failed`;F(`debug`,`Connecting via streamable HTTP`),a=await e(`http`),(a===`success`||a===`failed`||a===`auth_redirect`)&&(Je.current=!1),F(`debug`,`Connection sequence finished with status: ${a}`)},[F,gt,ht,t,i,r,se.name,se.version,se.uri,se.logo_uri,re,te,ne,ie,ee,m,h,g,n,_,oe,k,S,de,c,me,pe,dt,ft,pt]);(0,z.useEffect)(()=>{it.current=_t,at.current=gt},[_t,gt]);let vt=(0,z.useCallback)(()=>{tt.current===`failed`?(F(`info`,`Retry requested...`),it.current?.()):F(`warn`,`Retry called but state is not 'failed' (state: ${tt.current}). Ignoring.`)},[F]),yt=(0,z.useCallback)(async()=>{F(`info`,`Manual authentication requested...`);let e=tt.current;if(e===`failed`)F(`info`,`Attempting to reconnect and authenticate via retry...`),vt();else if(e===`pending_auth`){F(`info`,`Proceeding with authentication from pending state...`);try{if(TA(Ke.current,`Auth Provider not available for manual auth`),TA(t,`Server URL is required for authentication`),a){F(`info`,`Using provided authProvider for manual authentication`);let e=new URL(t),n=e.origin+e.pathname.replace(/\/+$/,``);await BS(Ke.current,{serverUrl:n,fetchFn:Ke.current.getProxyFetch?.()}),it.current?.();return}F(`info`,`Cleared ${Ke.current.clearStorage?.()??0} OAuth storage item(s) for fresh authentication`),ge(`authenticating`);let e=null,n=null,{provider:o,oauthProxyUrl:s}=jA({effectiveOAuthUrl:pe,storageKeyPrefix:i,oauthClientConfig:se,callbackUrl:r,preventAutoAuth:!1,useRedirectFlow:h,gatewayUrl:de,oauthProxyUrl:c,onPopupWindow:(t,r,i)=>{e=i;try{n=new URL(t).searchParams.get(`state`)}catch{}g?.(t,r,i)},proxyOAuthRequests:!0,staticClientInfo:re,clientMetadataUrl:te,scope:ne});s&&F(`info`,`Scoped OAuth proxy fetch enabled for manual auth`),Ke.current=o,F(`info`,`Triggering fresh OAuth authorization...`);let l=new URL(t),u=l.origin+l.pathname.replace(/\/+$/,``);try{await BS(o,{serverUrl:u,fetchFn:o.getProxyFetch?.()}),F(`info`,`OAuth flow completed (tokens obtained)`)}catch(e){F(`info`,`OAuth flow initiated (popup/redirect):`,e instanceof Error?e.message:`Redirecting...`)}let d=o.getLastAttemptedAuthUrl?.();if(d&&(Ve(d),F(`info`,`Updated auth URL for fallback:`,d),!n))try{n=new URL(d).searchParams.get(`state`)}catch{}if(h)return;let f=o.getKey?.(`tokens`);if(!f){F(`warn`,`Could not derive tokens storage key; relying on callback listener.`);return}et.current=!0;let p;try{p=await ck({popup:e,state:n,tokensKey:f})}finally{et.current=!1}if(!Ye.current)return;switch(p.kind){case`success`:F(`info`,`Authentication succeeded; reconnecting to MCP server...`),Je.current=!1,it.current?.();break;case`cancelled`:F(`warn`,`Authentication popup was closed before completing. Returning to pending_auth.`),ge(`pending_auth`);break;case`timeout`:F(`warn`,`Authentication timed out waiting for the popup. Returning to pending_auth.`),ge(`pending_auth`);break;case`error`:gt(`Authentication failed: ${p.error}`);break;default:break}}catch(e){if(!Ye.current)return;ge(`pending_auth`),F(`error`,`Manual authentication failed: ${e instanceof Error?e.message:String(e)}`)}}else if(e===`authenticating`){F(`warn`,`Already attempting authentication. Check for blocked popups or wait for timeout.`);let e=Ke.current?.getLastAttemptedAuthUrl?.();e&&!Be&&(Ve(e),F(`info`,`Manual authentication URL retrieved:`,e))}else F(`info`,`Client not in a state requiring manual authentication trigger (state: ${e}). If needed, try disconnecting and reconnecting.`)},[F,vt,gt,Be,t,h,g,i,se.name,se.uri,se.logo_uri,re,te,ne,r,oe,a]),bt=(0,z.useCallback)(()=>{Ke.current?.clearStorage?(F(`info`,`Cleared ${Ke.current.clearStorage()} item(s) from localStorage for ${t}.`),Ve(void 0),ht()):F(`warn`,`Auth provider not initialized, cannot clear storage.`)},[t,F,ht]);(0,z.useEffect)(()=>{if(typeof window>`u`)return;let e=(e,t)=>{if(et.current){F(`debug`,`Ignoring auth callback via ${t}; manual popup flow owns this result.`);return}let n=Ke.current?.serverUrlHash;if(e?.serverUrlHash&&n&&e.serverUrlHash!==n){F(`debug`,`Ignoring auth callback via ${t} for a different server.`);return}if(F(`info`,`Received auth callback via ${t}.`,e),Qe.current&&clearTimeout(Qe.current),Qe.current=null,e?.success)F(`info`,`Authentication successful via popup. Reconnecting client...`),Je.current&&F(`debug`,`Connection attempt already in progress, resetting flag to allow reconnection.`),Je.current=!1,setTimeout(()=>{Ye.current&&(F(`debug`,`Initiating reconnection after successful auth callback.`),it.current?.())},100);else{if(tt.current!==`authenticating`&&tt.current!==`pending_auth`){F(`debug`,`Ignoring stale auth failure callback (state=${tt.current}).`);return}at.current?.(`Authentication failed in callback: ${e?.error||`Unknown reason.`}`)}},t=t=>{t.origin===window.location.origin&&t.data?.type===ok&&e(t.data,`postMessage`)};window.addEventListener(`message`,t),F(`debug`,`Auth callback message listener added.`);let n=null,r=t=>{t.data?.type===ok&&e(t.data,`BroadcastChannel`)};if(typeof BroadcastChannel<`u`)try{n=new BroadcastChannel(ak),n.addEventListener(`message`,r),F(`debug`,`Auth callback BroadcastChannel listener added.`)}catch(e){F(`warn`,`Failed to open auth callback BroadcastChannel; lost-opener popups will not reach this client.`,e),n=null}return()=>{if(window.removeEventListener(`message`,t),F(`debug`,`Auth callback message listener removed.`),n){try{n.removeEventListener(`message`,r),n.close()}catch{}F(`debug`,`Auth callback BroadcastChannel listener removed.`)}Qe.current&&clearTimeout(Qe.current)}},[F]),(0,z.useEffect)(()=>{if(Ye.current=!0,!n||!t)return F(`debug`,n?`No server URL provided, skipping connection.`:`Connection disabled via enabled flag.`),ge(`discovering`),()=>{Ye.current=!1};if(F(`debug`,`useMcp mounted, initiating connection.`),Xe.current=0,a)Ke.current=a,F(`debug`,`Using externally provided authProvider`);else if(!Ke.current||Ke.current.serverUrl!==pe){let{provider:e,oauthProxyUrl:t}=jA({effectiveOAuthUrl:pe,storageKeyPrefix:i,oauthClientConfig:se,callbackUrl:r,preventAutoAuth:m,useRedirectFlow:h,gatewayUrl:de,oauthProxyUrl:c,onPopupWindow:g,proxyOAuthRequests:!0,staticClientInfo:re,clientMetadataUrl:te,scope:ne});Ke.current=e,t&&F(`debug`,`OAuth proxy URL in effect: ${t}`),F(`debug`,`BrowserOAuthClientProvider initialized/updated with URL: ${pe}, proxy: ${t?`enabled`:`disabled`}, gateway: ${de?`enabled`:`disabled`}`)}return _t(),()=>{Ye.current=!1,F(`debug`,`useMcp unmounting, disconnecting.`),ht(!0)}},[t,n,i,r,se.name,se.version,se.uri,se.logo_uri,re,te,ne,h,oe,pe,s,a]);let xt=(0,z.useRef)(vt),St=(0,z.useRef)(F);(0,z.useEffect)(()=>{xt.current=vt,St.current=F},[vt,F]),(0,z.useEffect)(()=>{let e=null;if(he===`failed`&&d&&Xe.current>0){if(!$e.current){$e.current=!0;let t=typeof d==`number`?d:IA;St.current(`info`,`Connection failed, auto-retrying in ${t}ms...`),e=setTimeout(()=>{$e.current=!1,Ye.current&&tt.current===`failed`&&xt.current()},t)}}else he!==`failed`&&($e.current=!1);return()=>{e&&(clearTimeout(e),$e.current=!1)}},[he,d]);let Ct=(0,z.useCallback)(async()=>tt.current===`ready`?we?.icon?we.icon:qe.current?(F(`debug`,`Waiting for icon to finish loading...`),await qe.current):(F(`debug`,`No icon available and no loading in progress`),null):(F(`warn`,`Cannot ensure icon loaded - not connected`),null),[we,F]);return{state:he,name:we?.name||t||``,tools:_e,resources:ye,resourceTemplates:xe,prompts:Se,serverInfo:we,capabilities:Ee,protocolEra:Oe,protocolVersion:Ae,instructions:Me,extensions:Pe,error:Ie,log:Re,authUrl:Be,authTokens:He,client:We.current,...mt,retry:vt,disconnect:ht,authenticate:yt,clearStorage:bt,ensureIconLoaded:Ct}}var RA=null;function zA(){return typeof window<`u`&&window.name.startsWith(`mcp_auth_`)}function BA(e,t,n){return{type:ok,success:e,...e?{}:{error:t??`Unknown error`},...n.state?{state:n.state}:{},...n.serverUrlHash?{serverUrlHash:n.serverUrlHash}:{}}}function VA(e){if(typeof BroadcastChannel>`u`)return;let t;try{t=new BroadcastChannel(ak),t.postMessage(e)}catch(e){console.warn(`[mcp-callback] Failed to broadcast callback result:`,e)}finally{t&&setTimeout(()=>{try{t?.close()}catch{}},0)}}function HA(e,t,n,r){if(typeof document>`u`)return;document.body.innerHTML=``;let i=document.createElement(`div`);i.style.fontFamily=`sans-serif`,i.style.padding=`20px`;let a=document.createElement(`h1`);a.textContent=e,i.appendChild(a);let o=document.createElement(`p`);o.textContent=t,n&&(o.style.color=`red`,o.style.backgroundColor=`#ffebeb`,o.style.border=`1px solid red`,o.style.padding=`10px`,o.style.borderRadius=`4px`),i.appendChild(o);let s=document.createElement(`a`);if(s.href=`#`,s.textContent=`Close this window`,s.onclick=e=>(e.preventDefault(),window.close(),!1),i.appendChild(s),r){let e=document.createTextNode(` or `),t=document.createElement(`a`);t.href=r,t.textContent=`return to the app`,i.append(e,t)}document.body.appendChild(i)}function UA(e){let t=`mcp:auth:state_${e}`,n=localStorage.getItem(t)?t:null;if(!n){let t=`:state_${e}`;for(let e=0;e<localStorage.length;e++){let r=localStorage.key(e);if(r?.endsWith(t)){n=r;break}}}let r=n?localStorage.getItem(n):null;if(!n||!r)throw Error(`Invalid or expired OAuth state "${e}".`);let i;try{i=JSON.parse(r)}catch{throw localStorage.removeItem(n),Error(`Failed to parse stored OAuth state.`)}return{key:n,value:i}}function WA(e,t){let n=new URL(e);n.searchParams.set(`auth_error`,`oauth_callback_failed`),n.searchParams.set(`auth_error_description`,t),window.location.href=n.toString()}function GA(e,t,n,r){let i=BA(e,t,r),a=n?.returnUrl,o=n?.flowType===`popup`||zA();if(n?.flowType===`redirect`&&a){e?window.location.href=a:WA(a,t??`Authentication failed.`);return}if(window.opener&&!window.opener.closed){window.opener.postMessage(i,window.location.origin),window.close();return}if(o){VA(i),HA(e?`Authentication Successful!`:`Authentication Error`,e?`You're authenticated. You can close this window and return to the app.`:t??`Authentication failed.`,!e,a);try{window.close()}catch{}return}if(a){e?window.location.href=a:WA(a,t??`Authentication failed.`);return}if(!e){HA(`Authentication Error`,t??`Authentication failed.`,!0);return}window.location.href=`/`}function KA(){return RA||=qA(),RA}async function qA(){let e=new URLSearchParams(window.location.search),t=e.get(`state`),n=null,r=null,i=null;try{if(!t)throw Error(`OAuth callback is missing the state parameter.`);let a=UA(t);if(n=a.key,r=a.value,!r.expiry||r.expiry<Date.now())throw localStorage.removeItem(n),Error(`OAuth state has expired. Please start authentication again.`);if(!r.providerOptions)throw Error(`Stored OAuth state is missing provider options.`);let{serverUrl:o,...s}=r.providerOptions;i=new Pk(o,s),await new GC(new URL(o),{authProvider:i,fetch:i.getProxyFetch()}).finishAuth(e),localStorage.removeItem(n),GA(!0,void 0,r,{state:t,serverUrlHash:r.serverUrlHash})}catch(e){let a=e instanceof Error?e.message:String(e);console.error(`[mcp-callback] OAuth callback failed:`,e),n&&localStorage.removeItem(n),i&&localStorage.removeItem(i.getKey(`last_auth_url`)),GA(!1,a,r,{state:t,serverUrlHash:r?.serverUrlHash})}}JO();var JA=[`url`,`displayName`,`enabled`,`proxyConfig`,`oauthProxyUrl`,`connectionMode`,`autoProxyFallback`,`callbackUrl`,`storageKeyPrefix`,`headers`,`logLevel`,`autoRetry`,`autoReconnect`,`reconnectionOptions`,`popupFeatures`,`preventAutoAuth`,`useRedirectFlow`,`clientOptions`,`protocolNegotiation`,`timeout`,`clientInfo`,`oauth`];function YA(e){let t={};for(let n of JA){let r=e[n];r!==void 0&&(t[n]=r)}return t}function XA(e){return YA(e)}var ZA=500,QA=5*6e4;function $A(e){let[t,n]=(0,z.useState)([]),[r,i]=(0,z.useState)([]),[a,o]=(0,z.useState)([]),s=(0,z.useRef)(0),c=(0,z.useRef)(0),l=(0,z.useRef)(new Map),u=(0,z.useRef)(new Map),d=(0,z.useCallback)(e=>{for(let t of l.current.values())clearTimeout(t.timeout),t.reject(Error(e));l.current.clear();for(let t of u.current.values())clearTimeout(t.timeout),t.reject(Error(e));u.current.clear(),i([]),o([])},[]);(0,z.useEffect)(()=>()=>d(`MCP server connection was removed`),[d]);let f=(0,z.useCallback)(t=>{let r={id:globalThis.crypto?.randomUUID?.()??`${Date.now()}-${Math.random()}`,method:t.method,params:t.params,timestamp:Date.now(),read:!1};n(e=>[r,...e].slice(0,ZA)),e.onNotificationReceived?.(r)},[e.onNotificationReceived]),p=(0,z.useCallback)((e,t)=>{let n=l.current.get(e);n&&(clearTimeout(n.timeout),l.current.delete(e),i(t=>t.filter(t=>t.id!==e)),n.resolve(t))},[]),m=(0,z.useCallback)((e,t)=>{let n=l.current.get(e);n&&(clearTimeout(n.timeout),l.current.delete(e),i(t=>t.filter(t=>t.id!==e)),n.reject(Error(t??`User rejected sampling request`)))},[]),h=(0,z.useCallback)(t=>new Promise((n,r)=>{let a=`sampling-${s.current++}`,o={id:a,request:{method:`sampling/createMessage`,params:t},timestamp:Date.now(),serverName:e.serverName},c=setTimeout(()=>m(a,`Sampling request timed out`),QA);l.current.set(a,{resolve:n,reject:r,timeout:c}),i(e=>[...e,o]),e.onSamplingRequest?.(o),e.onGlobalSamplingRequest?.(o,e.serverId,e.serverName,p,m)}),[p,e,m]),g=(0,z.useCallback)((e,t)=>{let n=u.current.get(e);n&&(clearTimeout(n.timeout),u.current.delete(e),o(t=>t.filter(t=>t.id!==e)),n.resolve(t))},[]),_=(0,z.useCallback)((e,t)=>{let n=u.current.get(e);n&&(clearTimeout(n.timeout),u.current.delete(e),o(t=>t.filter(t=>t.id!==e)),n.reject(Error(t??`User rejected elicitation request`)))},[]),v=(0,z.useCallback)(t=>new Promise((n,r)=>{let i=`elicitation-${c.current++}`,a={id:i,request:t,timestamp:Date.now(),serverName:e.serverName},s=setTimeout(()=>_(i,`Elicitation request timed out`),QA);u.current.set(i,{resolve:n,reject:r,timeout:s}),o(e=>[...e,a]),e.onElicitationRequest?.(a),e.onGlobalElicitationRequest?.(a,e.serverId,e.serverName,g,_)}),[g,e,_]),y=(0,z.useCallback)(e=>{n(t=>t.map(t=>t.id===e?{...t,read:!0}:t))},[]),b=(0,z.useCallback)(()=>n(e=>e.map(e=>({...e,read:!0}))),[]),x=(0,z.useCallback)(()=>n([]),[]);return{notifications:t,pendingSamplingRequests:r,pendingElicitationRequests:a,unreadNotificationCount:t.filter(e=>!e.read).length,markNotificationRead:y,markAllNotificationsRead:b,clearNotifications:x,approveSampling:p,rejectSampling:m,approveElicitation:g,rejectElicitation:_,onNotification:f,onSampling:h,onElicitation:v,rejectAll:d}}var ej=qO.get(`McpClientProvider`),tj=(0,z.createContext)(null);function nj(e,t){return JSON.stringify(e)===JSON.stringify(t)}function rj(e,t){return e.id===t.id&&nj(YA(e),YA(t))&&e.name===t.name&&e.state===t.state&&e.error===t.error&&e.authUrl===t.authUrl&&nj(e.authTokens,t.authTokens)&&e.protocolEra===t.protocolEra&&e.protocolVersion===t.protocolVersion&&nj(e.serverInfo,t.serverInfo)&&nj(e.capabilities,t.capabilities)&&e.instructions===t.instructions&&nj(e.extensions,t.extensions)&&nj(e.tools,t.tools)&&nj(e.resources,t.resources)&&nj(e.resourceTemplates,t.resourceTemplates)&&nj(e.prompts,t.prompts)&&nj(e.notifications,t.notifications)&&e.unreadNotificationCount===t.unreadNotificationCount&&nj(e.pendingSamplingRequests,t.pendingSamplingRequests)&&nj(e.pendingElicitationRequests,t.pendingElicitationRequests)&&e.client===t.client}function ij({id:e,options:t,defaultCallbackUrl:n,defaultOAuthProxyUrl:r,defaultProxyConfig:i,defaultAutoProxyFallback:a,clientInfo:o,cachedMetadata:s,onUpdate:c,onUpdateConfig:l,onUpdateDisplayName:u,onReconnect:d,rpcWrapTransport:f,onGlobalSamplingRequest:p,onGlobalElicitationRequest:m}){let{displayName:h,onSamplingRequest:g,onElicitationRequest:_,onNotificationReceived:v,wrapTransport:y}=t,b=(0,z.useMemo)(()=>{let{displayName:c,onSamplingRequest:l,onElicitationRequest:u,onNotificationReceived:d,wrapTransport:f,...p}=t;return{...p,callbackUrl:p.callbackUrl||n,oauthProxyUrl:p.oauthProxyUrl||r,proxyConfig:p.proxyConfig||i,autoProxyFallback:p.autoProxyFallback===void 0?a:p.autoProxyFallback,clientInfo:p.clientInfo?o?{...o,...p.clientInfo}:p.clientInfo:o,_initialServerInfo:s,serverId:e}},[t,n,r,i,a,o,s]),x=(0,z.useMemo)(()=>{if(!(!f&&!y))return t=>{let n=t;return f&&(n=f(n,e)),y&&(n=y(n,e)),n}},[f,y,e]),S=$A({serverId:e,serverName:h||e,onNotificationReceived:v,onSamplingRequest:g,onElicitationRequest:_,onGlobalSamplingRequest:p,onGlobalElicitationRequest:m}),C=LA({...b,onNotification:S.onNotification,onSampling:S.onSampling,onElicitation:S.onElicitation,wrapTransport:x});(0,z.useEffect)(()=>{C.state!==`ready`&&S.rejectAll(`MCP server connection is no longer active`)},[C.state,S.rejectAll]);let w=(0,z.useCallback)(t=>l(e,t),[e,l]),T=(0,z.useCallback)(n=>{let r=t.proxyConfig?.proxyAddress?.trim();return t.connectionMode===`proxy`&&r?l(e,{proxyConfig:{...t.proxyConfig,proxyAddress:r,...n?{headers:n}:{}},headers:void 0}):l(e,{headers:n})},[e,t.connectionMode,t.proxyConfig,l]),E=(0,z.useCallback)(t=>u(e,t),[e,u]),ee=(0,z.useCallback)(()=>d(e),[e,d]),D=(0,z.useRef)(c),te=(0,z.useRef)(null);return(0,z.useEffect)(()=>{D.current=c},[c]),(0,z.useEffect)(()=>{let n={...XA(t),...C,id:e,displayName:h||t.displayName||e,notifications:S.notifications,unreadNotificationCount:S.unreadNotificationCount,markNotificationRead:S.markNotificationRead,markAllNotificationsRead:S.markAllNotificationsRead,clearNotifications:S.clearNotifications,pendingSamplingRequests:S.pendingSamplingRequests,approveSampling:S.approveSampling,rejectSampling:S.rejectSampling,pendingElicitationRequests:S.pendingElicitationRequests,approveElicitation:S.approveElicitation,rejectElicitation:S.rejectElicitation,updateConfig:w,setHeaders:T,setDisplayName:E,reconnect:ee},r=te.current;!r||!rj(r,n)?(te.current=n,D.current(n)):ej.debug(`[McpServerWrapper ${e}] No meaningful changes detected, skipping onUpdate`)},[e,h,t,t.url,C.state,C.error,C.authUrl,C.tools,C.resources,C.resourceTemplates,C.prompts,C.serverInfo,C.capabilities,C.protocolEra,C.protocolVersion,C.instructions,C.extensions,C.authTokens,S,w,T,E,ee]),null}function aj({children:e,mcpServers:t,defaultCallbackUrl:n,defaultOAuthProxyUrl:r,defaultProxyConfig:i,defaultAutoProxyFallback:a=!1,defaultServerConfig:o,clientInfo:s,storageProvider:c,enableRpcLogging:l=!1,onServerAdded:u,onServerRemoved:d,onServerStateChange:f,onSamplingRequest:p,onElicitationRequest:m}){let[h,g]=(0,z.useState)([]),[_,v]=(0,z.useState)([]),[y,b]=(0,z.useState)({}),[x,S]=(0,z.useState)(!1),C=(0,z.useRef)(!1),w=(0,z.useRef)([]);(0,z.useEffect)(()=>{w.current=_},[_]);let T=(0,z.useRef)({}),[E,ee]=(0,z.useState)(void 0),[D,te]=(0,z.useState)(!1);(0,z.useEffect)(()=>{if(!l||typeof window>`u`){ee(void 0),te(!0);return}Promise.resolve().then(()=>(ik(),YO)).then(e=>{ej.debug(`[McpClientProvider] RPC logger loaded`),ee(()=>e.wrapTransportForLogging),te(!0)}).catch(e=>{ej.error(`[McpClientProvider] Failed to load RPC logger:`,e),ee(void 0),te(!0)})},[l]),(0,z.useEffect)(()=>{if(!D){ej.debug(`[McpClientProvider] Waiting for RPC logging to be ready before loading servers`);return}C.current||(C.current=!0,(async()=>{if(ej.debug(`[McpClientProvider] Loading servers, storageProvider:`,!!c,`mcpServers:`,t),!c){if(t){let e=Object.entries(t).map(([e,t])=>({id:e,options:t}));ej.debug(`[McpClientProvider] Loaded from mcpServers prop:`,e.length),g(e)}S(!0);return}try{let e=await Promise.resolve(c.getServers());if(ej.debug(`[McpClientProvider] Loaded from storage:`,Object.keys(e).length),c.getServerMetadata)try{let t=Object.keys(e).map(async e=>[e,await Promise.resolve(c.getServerMetadata(e))]),n=await Promise.all(t);T.current=Object.fromEntries(n.filter(e=>e[1]!==void 0)),ej.debug(`[McpClientProvider] Loaded cached metadata for`,Object.keys(T.current).length,`servers`)}catch(e){ej.warn(`[McpClientProvider] Failed to load cached metadata:`,e)}let n={...e,...t},r=Object.entries(n).map(([e,t])=>({id:e,options:t}));ej.debug(`[McpClientProvider] Total servers after merge:`,r.length),g(r),S(!0)}catch(e){ej.error(`[McpClientProvider] Failed to load from storage:`,e),t&&g(Object.entries(t).map(([e,t])=>({id:e,options:t}))),S(!0)}})())},[c,t,D]),(0,z.useEffect)(()=>{!c||!x||(async()=>{try{let e=h.reduce((e,t)=>(e[t.id]=XA(t.options),e),{});await Promise.resolve(c.setServers(e))}catch(e){ej.error(`[McpClientProvider] Failed to save to storage:`,e)}})()},[h,c,x]);let ne=(0,z.useCallback)(e=>{ej.debug(`[McpClientProvider] handleServerUpdate called for server ${e.id}`,{toolCount:e.tools.length,state:e.state});let t=[];v(n=>{let r=n.findIndex(t=>t.id===e.id);if(r===-1)return ej.debug(`[McpClientProvider] Adding new server ${e.id} to state`),t.push(()=>u?.(e.id,e)),[...n,e];let i=n[r],a=i.state!==e.state,o=i.serverInfo!==e.serverInfo;if(ej.debug(`[McpClientProvider] Comparing server ${e.id}:`,{toolsChanged:i.tools!==e.tools,currentToolCount:i.tools.length,updatedToolCount:e.tools.length,stateChanged:a}),rj(i,e))return ej.debug(`[McpClientProvider] No changes detected for server ${e.id}, skipping update`),n;if(ej.debug(`[McpClientProvider] Updating server ${e.id} in state`),a&&t.push(()=>f?.(e.id,e.state)),o&&e.serverInfo&&c?.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};T.current[e.id]=t,Promise.resolve(c.setServerMetadata(e.id,t)).catch(e=>{ej.error(`[McpClientProvider] Failed to save server metadata:`,e)})}let s=[...n];return s[r]=e,s}),t.length>0&&queueMicrotask(()=>{t.forEach(e=>e())})},[u,f,c]),re=(0,z.useCallback)((e,t)=>{g(n=>n.find(t=>t.id===e)?n:(ej.debug(`[McpClientProvider] Adding new server to configs:`,e),[...n,{id:e,options:t}]))},[]),O=(0,z.useCallback)(async(e,t)=>{let n=w.current.find(t=>t.id===e);if(v(t=>t.filter(t=>t.id!==e)),g(t=>t.filter(t=>t.id!==e)),b(t=>{let{[e]:n,...r}=t;return r}),n?.disconnect&&await n.disconnect(),t?.clearCredentials&&n?.clearStorage&&await n.clearStorage(),l){let{clearRpcLogs:t}=await Promise.resolve().then(()=>(ik(),YO));t(e)}d?.(e)},[l,d]),ie=(0,z.useCallback)(async(e,t)=>{let n=h.find(t=>t.id===e);if(!n){ej.warn(`[McpClientProvider] Cannot update server "${e}" - not found`);return}let r={...n.options,...t};nj(YA(n.options),YA(r))||(await w.current.find(t=>t.id===e)?.disconnect(),v(t=>t.filter(t=>t.id!==e)),g(t=>t.map(t=>t.id===e?{id:e,options:r}:t)),b(t=>({...t,[e]:(t[e]??0)+1})))},[h]),k=(0,z.useCallback)(async e=>{if(!h.find(t=>t.id===e)){ej.warn(`[McpClientProvider] Cannot reconnect server "${e}" - not found`);return}await w.current.find(t=>t.id===e)?.disconnect(),v(t=>t.filter(t=>t.id!==e)),b(t=>({...t,[e]:(t[e]??0)+1}))},[h]),A=(0,z.useCallback)(async(e,t)=>new Promise(n=>{let r=h.find(t=>t.id===e);if(!r){ej.warn(`[McpClientProvider] Cannot update server metadata for "${e}" - not found`),n();return}let i={...r.options,displayName:t.name};v(n=>n.map(n=>n.id===e?{...n,displayName:t.name}:n)),g(t=>{let r=t.map(t=>t.id===e?{id:e,options:i}:t);return setTimeout(()=>n(),0),r})}),[h]),j=(0,z.useCallback)(e=>_.find(t=>t.id===e),[_]),ae=(0,z.useMemo)(()=>({servers:_,addServer:re,removeServer:O,updateServerMetadata:A,updateServer:ie,getServer:j,storageLoaded:x}),[_,re,O,A,ie,j,x]),{capabilities:oe,...se}=s||{},ce=(0,z.useMemo)(()=>Object.keys(se).length?se:void 0,[s]),M=(0,z.useMemo)(()=>h.map(e=>{let t=o?{...o,...e.options}:e.options;return oe&&(t={...t,clientOptions:{...t.clientOptions,capabilities:{...oe,...t.clientOptions?.capabilities}}}),{id:e.id,options:t}}),[h,oe,o]),N=typeof window<`u`&&/\/oauth\/callback\/?$/.test(window.location.pathname);return z.createElement(tj.Provider,{value:ae},e,!N&&M.map(e=>z.createElement(ij,{key:`${e.id}-v${y[e.id]??0}`,id:e.id,options:e.options,defaultCallbackUrl:n,defaultOAuthProxyUrl:r,defaultProxyConfig:i,defaultAutoProxyFallback:a,clientInfo:ce,cachedMetadata:T.current[e.id],onUpdate:ne,onUpdateConfig:ie,onUpdateDisplayName:(e,t)=>A(e,{name:t}),onReconnect:k,rpcWrapTransport:E,onGlobalSamplingRequest:p,onGlobalElicitationRequest:m})))}function oj(){let e=(0,z.useContext)(tj);if(!e)throw Error(`useMcpClient must be used within a McpClientProvider`);return e}var sj=class{constructor(e=`mcp-client-servers`){this.storageKey=e,this.metadataKey=`${e}-metadata`}metadataKey;getServers(){try{let e=localStorage.getItem(this.storageKey);return e?JSON.parse(e):{}}catch(e){return console.error(`[LocalStorageProvider] Failed to load servers:`,e),{}}}setServers(e){try{localStorage.setItem(this.storageKey,JSON.stringify(e))}catch(e){console.error(`[LocalStorageProvider] Failed to save servers:`,e)}}setServer(e,t){let n=this.getServers();n[e]=t,this.setServers(n)}removeServer(e){let t=this.getServers();delete t[e],this.setServers(t),this.removeServerMetadata(e)}clear(){try{localStorage.removeItem(this.storageKey),localStorage.removeItem(this.metadataKey)}catch(e){console.error(`[LocalStorageProvider] Failed to clear:`,e)}}getAllMetadata(){try{let e=localStorage.getItem(this.metadataKey);return e?JSON.parse(e):{}}catch(e){return console.error(`[LocalStorageProvider] Failed to load metadata:`,e),{}}}setAllMetadata(e){try{localStorage.setItem(this.metadataKey,JSON.stringify(e))}catch(e){console.error(`[LocalStorageProvider] Failed to save metadata:`,e)}}getServerMetadata(e){return this.getAllMetadata()[e]}setServerMetadata(e,t){let n=this.getAllMetadata();n[e]={...t,cachedAt:Date.now()},this.setAllMetadata(n)}removeServerMetadata(e){let t=this.getAllMetadata();delete t[e],this.setAllMetadata(t)}};ik();function cj(e){let t={};if(!e)return t;for(let[n,r]of Object.entries(e))if(typeof r==`string`&&(r.trim().startsWith(`[`)||r.trim().startsWith(`{`)))try{t[n]=JSON.parse(r)}catch{t[n]=r}else t[n]=r;return t}var lj=`<script>
|
|
204
204
|
(function () {
|
|
205
205
|
var files = new Map();
|
|
206
206
|
window.openai = window.openai || {};
|
|
@@ -217,7 +217,7 @@ container holding the app. Specify either width or maxWidth, and either height o
|
|
|
217
217
|
return { downloadUrl: URL.createObjectURL(file) };
|
|
218
218
|
};
|
|
219
219
|
})();
|
|
220
|
-
<\/script>`;function
|
|
220
|
+
<\/script>`;function uj(e){return e.includes(`<head>`)?e.replace(`<head>`,`<head>`+lj):e.includes(`<HEAD>`)?e.replace(`<HEAD>`,`<HEAD>`+lj):e.includes(`<html>`)?e.replace(`<html>`,`<html><head>`+lj+`</head>`):e.includes(`<HTML>`)?e.replace(`<HTML>`,`<HTML><head>`+lj+`</head>`):e.includes(`<!DOCTYPE`)||e.includes(`<!doctype`)?e.replace(/(<!DOCTYPE[^>]*>|<!doctype[^>]*>)/i,`$1<head>`+lj+`</head>`):lj+e}function dj(e){let{resourceResult:t,listingResource:n,cspMode:r,resourceUri:i}=e,a=(Array.isArray(t?.contents)?t.contents:[])[0],o=``,s;if(a&&(s=a.mimeType,typeof a.text==`string`?o=a.text:typeof a.blob==`string`&&(o=atob(a.blob))),!o)throw Error(`No HTML content in resource`);let c=n?._meta?.ui,l=a?._meta?.ui,u=c||l?{...c,...l}:void 0,d=u?.csp,f=u?.permissions,p=u?.prefersBorder??!1,m=s===PO,h=m?null:s?`Invalid MIME type "${s}" - SEP-1865 requires "${PO}"`:`Missing MIME type - SEP-1865 requires "${PO}"`;return h&&console.warn(`[ViewRenderer] MIME type validation:`,h,{resourceUri:i}),{html:o,declaredCsp:d,csp:r===`permissive`?void 0:d,permissions:f,prefersBorder:p,mimeType:s,mimeTypeValid:m,mimeTypeWarning:h}}function fj(e,t){let{cspMode:n,permissions:r,widgetCsp:i}=t;e.searchParams.set(`v`,JSON.stringify({cspMode:n,permissions:r,widgetCsp:i})),e.searchParams.set(`csp_mode`,n),r&&Object.keys(r).length>0&&e.searchParams.set(`permissions`,JSON.stringify(r)),i&&Object.keys(i).length>0&&e.searchParams.set(`widget_csp`,JSON.stringify(i))}function pj(e){let t=new URL(`https://sandbox.invalid/`);fj(t,e);let n=hj(t.search);return new URL(URL.createObjectURL(new Blob([n],{type:`text/html`})))}var mj=`<!doctype html>
|
|
221
221
|
<html>
|
|
222
222
|
<head>
|
|
223
223
|
<meta charset="utf-8" />
|
|
@@ -489,11 +489,11 @@ window.addEventListener('unhandledrejection', function(event) {
|
|
|
489
489
|
}, "*");
|
|
490
490
|
<\/script>
|
|
491
491
|
</body>
|
|
492
|
-
</html>`;function zj(e){let t=`<script>window.__SANDBOX_SEARCH__ = `+JSON.stringify(e).replace(/</g,`\\u003c`)+`;<\/script>`;return Rj.replace(`<body>`,`<body>`+t)}var Bj=`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`,Vj=[`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`].join(` `),Hj=`data-mcp-widget-fullscreen`,Uj=`data-mcp-widget-display-mode`;function Wj(e){(0,z.useEffect)(()=>{if(!(typeof document>`u`)){if(e===`pip`||e===`fullscreen`)return document.documentElement.setAttribute(Uj,e),e===`fullscreen`?document.documentElement.setAttribute(Hj,``):document.documentElement.removeAttribute(Hj),()=>{document.documentElement.removeAttribute(Uj),document.documentElement.removeAttribute(Hj)};document.documentElement.removeAttribute(Uj),document.documentElement.removeAttribute(Hj)}},[e])}function Gj({displayMode:e,setDisplayMode:t}){let n=e===`fullscreen`,r=e===`pip`;return Wj(e),{handleDisplayModeChange:(0,z.useCallback)(e=>t(e),[t]),fullscreenShellClassName:n?Bj:void 0,pipShellClassName:r?Vj:void 0,isFullscreen:n,isPip:r}}var Kj={PIP_MAX_WIDTH:700,DEFAULT_HEIGHT:400,FULLSCREEN_HEADER_HEIGHT:50};function qj(e){let t=e?.ui;return t&&typeof t==`object`&&`resourceUri`in t&&typeof t.resourceUri==`string`?t.resourceUri:null}function Jj(e){return qj(e)!==null}function Yj(e){return e===JO}var Xj={name:`mcp-use-client`,version:`2.0.0`},Zj=6e5,Qj=`ui/notifications/sandbox-proxy-ready`,$j={openLinks:{},serverTools:{},serverResources:{},logging:{},updateModelContext:{text:{}},message:{text:{}}};function eM(){return z.createElement(`svg`,{width:`14`,height:`14`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,"aria-hidden":!0},z.createElement(`path`,{d:`M18 6 6 18`}),z.createElement(`path`,{d:`m6 6 12 12`}))}function tM(e){return new Promise(t=>{let n=r=>{r.source===e.contentWindow&&r.data?.method===Qj&&(window.removeEventListener(`message`,n),t())};window.addEventListener(`message`,n)})}function nM(e){let t=e.oninitialized;return new Promise(n=>{e.oninitialized=(...r)=>{n(),e.oninitialized=t,t?.(...r)}})}function rM(e,t){let n=Mj(t);return Object.keys(n).length>0?{...typeof e==`object`&&e?e:{},structuredContent:n}:e??null}function iM({viewId:e,source:t,sandboxUrl:n,toolName:r=`view`,toolInput:i,toolOutput:a,partialToolInput:o,customProps:s,cancelled:c,hostInfo:l=Xj,hostContext:u,hostCapabilities:d,cspMode:f=`widget-declared`,displayMode:p,onDisplayModeChange:m,inlineMaxWidth:h=768,chromeless:g,onMessage:_,onModelContextUpdate:v,onLog:y,onReady:b,onLifecycleChange:x,onError:S,onCspViolation:C,onResourceResolved:w,wrapTransport:T,toolCallTimeout:E=Zj,mockOpenAiFileApis:ee=!1,onInlineHeightChange:D,fullscreenHeader:te,renderFullscreenClose:ne,className:re,testId:O=`mcp-app-frame`,invoking:ie,invoked:k}){let A=(0,z.useRef)(null),j=(0,z.useRef)(null),ae=(0,z.useRef)(null),oe=(0,z.useRef)(t.kind===`live`?t.connection:null),[se,ce]=(0,z.useState)(null),[M,N]=(0,z.useState)(null),[le,ue]=(0,z.useState)(null),[de,fe]=(0,z.useState)(0),[pe,me]=(0,z.useState)(!0),[he,ge]=(0,z.useState)(Kj.DEFAULT_HEIGHT),[_e,ve]=(0,z.useState)(`inline`),ye=p??_e,be=(0,z.useMemo)(()=>!u||u.displayMode===ye?u:{...u,displayMode:ye},[u,ye]),xe=(0,z.useRef)(be);xe.current=be;let P=(0,z.useRef)(_);P.current=_;let Se=(0,z.useRef)(i);Se.current=i;let Ce=(0,z.useRef)(o);Ce.current=o;let we=(0,z.useRef)(a);we.current=a;let Te=(0,z.useRef)(s);Te.current=s;let Ee=(0,z.useRef)(w);Ee.current=w;let De=(0,z.useRef)(v);De.current=v;let Oe=(0,z.useRef)(y);Oe.current=y;let ke=(0,z.useRef)(S);ke.current=S;let Ae=(0,z.useRef)(C);Ae.current=C;let je=(0,z.useRef)(b);je.current=b;let Me=(0,z.useRef)(x);Me.current=x;let Ne=(0,z.useRef)(D);Ne.current=D;let Pe=(0,z.useRef)(n);Pe.current=n;let Fe=(0,z.useRef)(f);Fe.current=f;let Ie=(0,z.useRef)(ee);Ie.current=ee;let Le=(0,z.useCallback)(e=>{let t=Pe.current;return t?typeof t==`function`?t(e):t:Lj({cspMode:Fe.current,permissions:e.permissions,widgetCsp:e.declaredCsp})},[]),{handleDisplayModeChange:Re,fullscreenShellClassName:ze,pipShellClassName:Be,isFullscreen:Ve,isPip:He}=Gj({containerRef:ae,displayMode:ye,setDisplayMode:(0,z.useCallback)(e=>{m?m(e):ve(e)},[m])}),Ue=(0,z.useRef)(Re);Ue.current=Re;let We=(0,z.useRef)(ye);We.current=ye;let Ge=t.kind===`live`?t.resourceUri:void 0,Ke=t.kind===`preloaded`?t.html:void 0;t.kind===`live`&&(oe.current=t.connection),(0,z.useEffect)(()=>{let e=!1;Me.current?.({status:`resolving`});let n=e=>{ce(e),Me.current?.({status:`sandbox-loading`});let t=Le(e);N(e=>e?.href===t.href?e:t),Ee.current?.(e)};if(t.kind===`preloaded`){n({html:t.html,declaredCsp:t.csp,csp:f===`permissive`?void 0:t.csp,permissions:t.permissions,prefersBorder:t.prefersBorder??!1,mimeType:`text/html;profile=mcp-app`,mimeTypeValid:!0,mimeTypeWarning:null});return}let{connection:r,resourceUri:i}=t;return oe.current=r,(async()=>{try{let t=await r.readResource(i);if(e)return;let a=r.resources?.find(e=>e.uri===i),o=Fj({resourceResult:t,listingResource:a,cspMode:f,resourceUri:i});if(!o.mimeTypeValid){let e=o.mimeTypeWarning||`Invalid MIME type - SEP-1865 requires "text/html;profile=mcp-app"`;ue(e),Me.current?.({status:`error`,error:e});return}n(o)}catch(t){if(e)return;ue(t instanceof Error?t.message:`Failed to prepare view`),Me.current?.({status:`error`,error:t instanceof Error?t.message:`Failed to prepare view`})}})(),()=>{e=!0}},[t.kind,Ge,Ke,f,Le]),(0,z.useEffect)(()=>{let e=M;return()=>{e?.protocol===`blob:`&&URL.revokeObjectURL(e.href)}},[M]);let qe=M?.protocol===`blob:`,Je=!M||qe?null:(()=>{try{return M.origin}catch{return null}})();(0,z.useEffect)(()=>{if(!Je&&!qe)return;let e=e=>{let t=A.current;if(t?.contentWindow&&e.source===t.contentWindow&&!(!qe&&e.origin!==Je&&Je!==`*`)){if(e.data?.type===`mcp-apps:csp-violation`){Ae.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()});return}e.data?.type===`iframe-console-log`&&Oe.current&&Oe.current({level:e.data.level??`log`,data:e.data.args})}};return window.addEventListener(`message`,e),()=>window.removeEventListener(`message`,e)},[Je,qe]),(0,z.useEffect)(()=>{if(!se||!M)return;let t=A.current;if(!t)return;let n=!1,r=null;return(async()=>{try{Me.current?.({status:`connecting`}),t.setAttribute(`sandbox`,`allow-scripts allow-same-origin allow-forms`);let i=YO(se.permissions);i&&t.setAttribute(`allow`,i);let a=tM(t);if(t.src=M.href,await a,n)return;r=new ZO(null,l,{...d??$j,sandbox:{csp:f===`permissive`?void 0:se.csp,permissions:se.permissions}},{hostContext:xe.current}),r.onmessage=async({content:e})=>(e.length>0&&P.current&&P.current(e),{}),r.onopenlink=async({url:e})=>(e&&window.open(e,`_blank`,`noopener,noreferrer`),{}),r.oncalltool=(async({name:e,arguments:t})=>{let n=oe.current;if(!n)throw Error(`Server connection not available`);try{return await n.callTool(e,t||{},{timeout:E,resetTimeoutOnProgress:!0})}catch(e){throw r?.sendToolCancelled({reason:e instanceof Error?e.message:String(e)}),e}}),r.onreadresource=(async({uri:e})=>{let t=oe.current;if(!t)throw Error(`Server connection not available`);return await t.readResource(e)}),r.onlistresources=(async()=>{let e=oe.current;if(!e)throw Error(`Server connection not available`);return{resources:[...e.resources??[]]}}),r.onrequestdisplaymode=async({mode:e})=>{let t=e??`inline`,n=(xe.current?.availableDisplayModes??[`inline`,`pip`,`fullscreen`]).includes(t)?t:We.current;return await Ue.current(n),{mode:n}},r.onupdatemodelcontext=async({content:e,structuredContent:t})=>(De.current?.({content:e,structuredContent:t}),{}),r.onloggingmessage=async({level:e,data:t})=>(Oe.current?.({level:e,data:t}),{}),r.onsizechange=async({height:e})=>{We.current===`inline`&&e!==void 0&&(ge(e),Ne.current?.(e))};let o=nM(r),s=new qO(t.contentWindow,t.contentWindow);if(T&&(s=T(s,e)),await r.connect(s),n||(await r.sendSandboxResourceReady({html:Ie.current?Pj(se.html):se.html,csp:se.csp,permissions:se.permissions}),await o,n))return;j.current=r,fe(e=>e+1),Me.current?.({status:`initialized`});let c=Ce.current;if(c)r.sendToolInputPartial({arguments:c});else{let e={...Se.current,...Mj(Te.current)};r.sendToolInput({arguments:e})}let u=rM(we.current,Te.current);u&&r.sendToolResult(u),Me.current?.({status:`ready`})}catch(e){if(!n){let t=e instanceof Error?e.message:`Failed to connect view`;ue(t),ke.current?.(t),Me.current?.({status:`error`,error:t})}}})(),()=>{n=!0;let e=r;j.current=null,e&&(Me.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(()=>{}),Me.current?.({status:`closed`})}})())}},[se,M,l,d,f,e,T,E,ee]),(0,z.useEffect)(()=>{let e=j.current;!e||de===0||!be||e.setHostContext(be)},[be,de]),(0,z.useEffect)(()=>{let e=j.current;!e||de===0||!o||e.sendToolInputPartial({arguments:o})},[de,o]),(0,z.useEffect)(()=>{let e=j.current;if(!e||de===0||o)return;let t={...i,...Mj(s)};e.sendToolInput({arguments:t})},[de,i,o,s]),(0,z.useEffect)(()=>{let e=j.current;if(!e||de===0)return;let t=rM(a,s);t&&e.sendToolResult(t)},[de,a,s]),(0,z.useEffect)(()=>{let e=j.current;!e||de===0||!c||e.sendToolCancelled({reason:`Cancelled by user`})},[c,de]);let Ye=(0,z.useRef)(!1);(0,z.useEffect)(()=>{Ye.current||de===0||(Ye.current=!0,je.current?.())},[de]),(0,z.useEffect)(()=>{if(de===0||!pe)return;let e=setTimeout(()=>me(!1),300);return()=>clearTimeout(e)},[de,pe]);let Xe=se!==null&&se.prefersBorder&&ye!==`fullscreen`;if(le)return z.createElement(`div`,{className:re},z.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`},z.createElement(`p`,{className:`text-sm text-red-600 dark:text-red-400`},`Failed to load view: `,le)));if(!se)return z.createElement(`div`,{className:re},z.createElement(`div`,{className:`flex items-center justify-center w-full h-[200px]`},z.createElement(`span`,{className:`text-sm text-muted-foreground`},`Loading view…`)));let Ze=ze??Be??`flex group flex-1 items-center justify-center`,Qe={height:Ve||He?`100%`:`${he}px`,width:`100%`,maxWidth:ye===`inline`?`${h}px`:`100%`,transition:Ve||He?void 0:`height 300ms ease-out`},$e=z.createElement(`div`,{ref:ae,className:Ve?`${Ze} flex flex-col`:Ze,style:He?{height:Kj.DEFAULT_HEIGHT,maxWidth:Kj.PIP_MAX_WIDTH,zIndex:100}:Ve?{zIndex:100}:void 0},Ve&&z.createElement(`header`,{className:`grid shrink-0 items-center border-b border-zinc-200 bg-background px-3 dark:border-zinc-700`,style:{height:Kj.FULLSCREEN_HEADER_HEIGHT,gridTemplateColumns:`auto 1fr auto`}},ne?ne({onClick:()=>void Re(`inline`),"data-testid":`debugger-exit-fullscreen-button`,"aria-label":`Exit fullscreen`}):z.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 Re(`inline`)},z.createElement(eM,null)),z.createElement(`div`,{className:`flex min-w-0 items-center justify-center gap-2 px-2`},te?.iconUrl?z.createElement(`img`,{src:te.iconUrl,alt:``,className:`size-6 shrink-0 rounded-md object-contain`}):null,z.createElement(`span`,{className:`truncate text-sm font-medium text-foreground`},te?.title??r)),z.createElement(`div`,{className:`size-8 shrink-0`,"aria-hidden":!0})),He&&(ne?z.createElement(`div`,{className:`absolute right-3 top-3`,style:{zIndex:110}},ne({onClick:()=>void Re(`inline`),"data-testid":`debugger-exit-pip-button`,"aria-label":`Exit picture-in-picture`})):z.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 Re(`inline`)},z.createElement(eM,null))),z.createElement(`div`,{className:Ve?`relative flex min-h-0 w-full flex-1 flex-col`:He?`relative w-full h-full min-h-0 flex flex-1 flex-col`:`relative w-full flex flex-1 justify-center items-center`},pe&&z.createElement(`div`,{className:`flex absolute inset-0 items-center justify-center z-10`},z.createElement(`span`,{className:`text-sm text-muted-foreground`},`Loading…`)),!He&&!Ve&&(ie||k)&&z.createElement(`div`,{className:`absolute -top-8 left-2 z-10 whitespace-nowrap pointer-events-none text-xs text-muted-foreground`},ie&&!a?ie:k),z.createElement(`div`,{"data-testid":O,"data-mcp-app-tool":r,className:ye===`fullscreen`?`w-full h-full overflow-hidden`:`w-full overflow-hidden`,style:Qe},z.createElement(`iframe`,{ref:A,title:`MCP App: ${r}`,className:Xe?`w-full h-full bg-transparent border border-border rounded-xl`:`w-full h-full bg-transparent border-0`}))));return z.createElement(`div`,{className:re},$e)}function aM(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.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)}var oM=(0,z.memo)(iM,aM);function sM(e){let t=document.createElement(`textarea`);t.value=e,t.style.cssText=`position:fixed;top:-9999px;left:-9999px;opacity:0`,document.body.appendChild(t),t.focus(),t.select();try{return document.execCommand(`copy`)}finally{document.body.removeChild(t)}}function cM(e){return sM(e)}async function lM(e){if(!sM(e)){if(navigator.clipboard?.writeText)return navigator.clipboard.writeText(e);throw Error(`copy failed`)}}function uM(e){let t=Date.now()-e,n=Math.floor(t/1e3),r=Math.floor(n/60),i=Math.floor(r/60),a=Math.floor(i/24);return n<60?`just now`:r<60?`${r}m ago`:i<24?`${i}h ago`:a<7?`${a}d ago`:new Date(e).toLocaleDateString()}function dM(e){if(e==null)return`/mcp`;let t=e.trim().replace(/\/{2,}/g,`/`).replace(/\/+$/,``);return t===``||t===`/`?``:(t.startsWith(`/`)||(t=`/${t}`),t)}function fM(){if(typeof window>`u`)return``;let e=window.location.pathname||``,t=e.indexOf(`/inspector`);return t<=0?``:dM(e.slice(0,t))}function pM(){if(typeof window>`u`)return``;let e=window.__MCP_BASE_PATH__;return e==null?fM():dM(e)}function mM(){return`${pM()}/inspector`}function hM(e){let t=e.replace(/^\/+/,``);return`${mM()}/api/${t}`}var gM=/^127\.(?:0|[1-9]\d?|1\d\d|2[0-4]\d|25[0-5])(?:\.(?:0|[1-9]\d?|1\d\d|2[0-4]\d|25[0-5])){2}$/;function _M(e){try{let t=new URL(e).hostname.toLowerCase().replace(/^\[|\]$/g,``);return t===`localhost`||t===`::1`||t===`0.0.0.0`||gM.test(t)}catch{return!1}}function vM(e){try{return new URL(e).hostname.endsWith(`.mcp-use.run`)}catch{return!1}}function yM(e){let t=e.name?.trim(),n=e.url?.trim();return t?t===n?``:t:``}function bM(e){return yM(e)||e.serverInfo?.title?.trim()||e.serverInfo?.name?.trim()||e.name?.trim()||e.url?.trim()||`Unknown server`}function xM(e){let t=e.serverInfo?.icons;return t&&t.length>0?t[0].src:e.serverInfo?.icon?e.serverInfo.icon:null}var SM=`2026-07-28`;function CM(e){switch(e){case`v1`:return`legacy`;case`v2`:return{pin:SM};default:return`auto`}}function wM(e){return e===`legacy`?`v1`:typeof e==`object`&&e?.pin?`v2`:`auto`}function TM(){if(typeof window>`u`)return``;let e=window.__MCP_PROXY_URL__;return e===null?``:`${window.location.origin}${e||hM(`proxy`)}`}function EM(e,t,n=!1){return e===`auto`||e===`direct`||e===`proxy`?e:t===`Via Proxy`?`proxy`:t===`Direct`?`auto`:n?`proxy`:`auto`}function DM(e){return!e||typeof e==`boolean`?``:e.proxyAddress?.trim()||``}var OM=[`requestTimeout`,`resetTimeoutOnProgress`,`maxTotalTimeout`];function kM(e){if(!e)return{};let t={};for(let n of OM){let r=e[n];r!==void 0&&(t[n]=r)}return t}function AM(e,t){try{let n=localStorage.getItem(`mcp-inspector-connections`),r=n?JSON.parse(n):{};r[e]={...r[e],...t},localStorage.setItem(`mcp-inspector-connections`,JSON.stringify(r))}catch{}}function jM(e,t,n){let r=e.trim(),i=t.trim(),a=n.trim();if(!(!r&&!a))return{...r?{clientId:r}:{},...r&&i?{clientSecret:i}:{},...a?{scope:a}:{}}}function MM(e){let t=e.headers||e.proxyConfig?.headers||e.proxyConfig?.customHeaders;return t&&Object.keys(t).length>0?t:void 0}function NM(e){let t=e.proxyConfig,n=e.headers||e.customHeaders,r=t?.headers||t?.customHeaders||void 0,i=n||r,a=t?{...t,...r?{headers:r}:{},customHeaders:void 0}:void 0,{customHeaders:o,connectionType:s,transportType:c,...l}=e;return{...l,...i&&!a?.proxyAddress?{headers:i}:{},...a?{proxyConfig:a}:{},connectionMode:EM(e.connectionMode,e.connectionType,!!a?.proxyAddress)}}function PM(e){let t=LM(e),n=e.proxyConfig?.proxyAddress?.trim()||DM(e.autoProxyFallback),r=EM(e.connectionMode,e.connectionType,!!n),i={url:e.url,displayName:e.name?.trim()||e.url,connectionMode:r,protocolNegotiation:e.protocolNegotiation??`auto`,...e.oauth?{oauth:e.oauth}:{}};return r===`proxy`&&n?i.proxyConfig={proxyAddress:n,...Object.keys(t).length>0?{headers:t}:{}}:Object.keys(t).length>0&&(i.headers=t),r===`auto`&&(i.autoProxyFallback=e.autoProxyFallback??(n?{enabled:!0,proxyAddress:n}:!1)),i}function FM(e,t){let n=t?NM(t):e,r=MM(e)||{},i=n.proxyConfig?.proxyAddress?.trim()||DM(n.autoProxyFallback);return{url:e.url||``,name:e.displayName||e.url||``,transportType:`http`,connectionMode:EM(n.connectionMode,void 0,!!i),connectionType:n.connectionMode===`proxy`?`Via Proxy`:`Direct`,proxyConfig:n.connectionMode===`proxy`&&i?{proxyAddress:i,...Object.keys(r).length>0?{headers:r}:{}}:void 0,headers:r,oauth:n.oauth,autoProxyFallback:n.autoProxyFallback,protocolNegotiation:n.protocolNegotiation??`auto`,...kM(t)}}function IM(e){try{let t=localStorage.getItem(`mcp-inspector-connections`);return t&&JSON.parse(t)[e]||null}catch{return null}}function LM(e){let t=e.proxyConfig?.headers||e.proxyConfig?.customHeaders||e.headers||e.customHeaders||{};return Object.fromEntries(Object.entries(t).filter(([e,t])=>e&&t).map(([e,t])=>[e,String(t)]).sort(([e],[t])=>e.localeCompare(t)))}function RM(e){let t=e.url?.trim()||``,n=e.proxyConfig?.proxyAddress?.trim()||DM(e.autoProxyFallback);return{url:t,name:e.name?.trim()||t,transportType:e.transportType||`http`,proxyAddress:n,connectionMode:EM(e.connectionMode,e.connectionType,!!n),headers:LM(e),oauthClientId:e.oauth?.clientId?.trim()||``,oauthClientSecret:e.oauth?.clientSecret?.trim()||``,oauthScope:e.oauth?.scope?.trim()||``,requestTimeout:`requestTimeout`in e?e.requestTimeout:void 0,resetTimeoutOnProgress:`resetTimeoutOnProgress`in e?e.resetTimeoutOnProgress:void 0,maxTotalTimeout:`maxTotalTimeout`in e?e.maxTotalTimeout:void 0,protocolMode:wM(e.protocolNegotiation)}}function zM(e,t){let n=RM(e),r=RM(t);return n.url===r.url&&n.transportType===r.transportType&&n.proxyAddress===r.proxyAddress&&n.connectionMode===r.connectionMode&&JSON.stringify(n.headers)===JSON.stringify(r.headers)&&n.oauthClientId===r.oauthClientId&&n.oauthClientSecret===r.oauthClientSecret&&n.oauthScope===r.oauthScope&&n.requestTimeout===r.requestTimeout&&n.resetTimeoutOnProgress===r.resetTimeoutOnProgress&&n.maxTotalTimeout===r.maxTotalTimeout&&n.protocolMode===r.protocolMode&&n.name!==r.name}var BM=class extends jj{setServers(e){let t=this.readRawStoredServers(),n=Object.fromEntries(Object.entries(e).map(([e,n])=>[e,{...kM(t[e]),...n,..._M(e)&&typeof n.url==`string`&&vM(n.url)?{url:e}:{}}]));super.setServers(n)}setServer(e,t){let n=this.getServers();n[e]={...kM(this.readRawStoredServers()[e]),...t},this.setServers(n)}readRawStoredServers(){try{let e=localStorage.getItem(`mcp-inspector-connections`);return e?JSON.parse(e):{}}catch{return{}}}},VM=`popstate`;function HM(e){return typeof e==`object`&&!!e&&`pathname`in e&&`search`in e&&`hash`in e&&`state`in e&&`key`in e}function UM(e={}){function t(e,t){let n=t.state?.masked,{pathname:r,search:i,hash:a}=n||e.location;return JM(``,{pathname:r,search:i,hash:a},t.state&&t.state.usr||null,t.state&&t.state.key||`default`,n?{pathname:e.location.pathname,search:e.location.search,hash:e.location.hash}:void 0)}function n(e,t){return typeof t==`string`?t:YM(t)}return ZM(t,n,null,e)}function WM(e,t){if(e===!1||e==null)throw Error(t)}function GM(e,t){if(!e){typeof console<`u`&&console.warn(t);try{throw Error(t)}catch{}}}function KM(){return Math.random().toString(36).substring(2,10)}function qM(e,t){return{usr:e.state,key:e.key,idx:t,masked:e.mask?{pathname:e.pathname,search:e.search,hash:e.hash}:void 0}}function JM(e,t,n=null,r,i){return{pathname:typeof e==`string`?e:e.pathname,search:``,hash:``,...typeof t==`string`?XM(t):t,state:n,key:t&&t.key||r||KM(),mask:i}}function YM({pathname:e=`/`,search:t=``,hash:n=``}){return t&&t!==`?`&&(e+=t.charAt(0)===`?`?t:`?`+t),n&&n!==`#`&&(e+=n.charAt(0)===`#`?n:`#`+n),e}function XM(e){let t={};if(e){let n=e.indexOf(`#`);n>=0&&(t.hash=e.substring(n),e=e.substring(0,n));let r=e.indexOf(`?`);r>=0&&(t.search=e.substring(r),e=e.substring(0,r)),e&&(t.pathname=e)}return t}function ZM(e,t,n,r={}){let{window:i=document.defaultView,v5Compat:a=!1}=r,o=i.history,s=`POP`,c=null,l=u();l??(l=0,o.replaceState({...o.state,idx:l},``));function u(){return(o.state||{idx:null}).idx}function d(){s=`POP`;let e=u(),t=e==null?null:e-l;l=e,c&&c({action:s,location:h.location,delta:t})}function f(e,t){s=`PUSH`;let r=HM(e)?e:JM(h.location,e,t);n&&n(r,e),l=u()+1;let d=qM(r,l),f=h.createHref(r.mask||r);try{o.pushState(d,``,f)}catch(e){if(e instanceof DOMException&&e.name===`DataCloneError`)throw e;i.location.assign(f)}a&&c&&c({action:s,location:h.location,delta:1})}function p(e,t){s=`REPLACE`;let r=HM(e)?e:JM(h.location,e,t);n&&n(r,e),l=u();let i=qM(r,l),d=h.createHref(r.mask||r);o.replaceState(i,``,d),a&&c&&c({action:s,location:h.location,delta:0})}function m(e){return QM(i,e)}let h={get action(){return s},get location(){return e(i,o)},listen(e){if(c)throw Error(`A history only accepts one active listener`);return i.addEventListener(VM,d),c=e,()=>{i.removeEventListener(VM,d),c=null}},createHref(e){return t(i,e)},createURL:m,encodeLocation(e){let t=m(e);return{pathname:t.pathname,search:t.search,hash:t.hash}},push:f,replace:p,go(e){return o.go(e)}};return h}function QM(e,t,n=!1){let r=`http://localhost`;e&&(r=e.location.origin===`null`?e.location.href:e.location.origin),WM(r,`No window.location.(origin|href) available to create URL`);let i=typeof t==`string`?t:YM(t);return i=i.replace(/ $/,`%20`),!n&&i.startsWith(`//`)&&(i=r+i),new URL(i,r)}function $M(e,t,n=`/`){return eN(e,t,n,!1)}function eN(e,t,n,r,i){let a=yN((typeof t==`string`?XM(t):t).pathname||`/`,n);if(a==null)return null;let o=i??nN(e),s=null,c=vN(a);for(let e=0;s==null&&e<o.length;++e)s=hN(o[e],c,r);return s}function tN(e,t){let{route:n,pathname:r,params:i}=e;return{id:n.id,pathname:r,params:i,data:t[n.id],loaderData:t[n.id],handle:n.handle}}function nN(e){let t=rN(e);return aN(t),t}function rN(e,t=[],n=[],r=``,i=!1){let a=(e,a,o=i,s)=>{let c={relativePath:s===void 0?e.path||``:s,caseSensitive:e.caseSensitive===!0,childrenIndex:a,route:e};if(c.relativePath.startsWith(`/`)){if(!c.relativePath.startsWith(r)&&o)return;WM(c.relativePath.startsWith(r),`Absolute route path "${c.relativePath}" nested under path "${r}" is not valid. An absolute child route path must start with the combined path of all its parent routes.`),c.relativePath=c.relativePath.slice(r.length)}let l=ON([r,c.relativePath]),u=n.concat(c);e.children&&e.children.length>0&&(WM(e.index!==!0,`Index routes must not have child routes. Please remove all child routes from route path "${l}".`),rN(e.children,t,u,l,o)),!(e.path==null&&!e.index)&&t.push({path:l,score:pN(l,e.index),routesMeta:u})};return e.forEach((e,t)=>{if(e.path===``||!e.path?.includes(`?`))a(e,t);else for(let n of iN(e.path))a(e,t,!0,n)}),t}function iN(e){let t=e.split(`/`);if(t.length===0)return[];let[n,...r]=t,i=n.endsWith(`?`),a=n.replace(/\?$/,``);if(r.length===0)return i?[a,``]:[a];let o=iN(r.join(`/`)),s=[];return s.push(...o.map(e=>e===``?a:[a,e].join(`/`))),i&&s.push(...o),s.map(t=>e.startsWith(`/`)&&t===``?`/`:t)}function aN(e){e.sort((e,t)=>e.score===t.score?mN(e.routesMeta.map(e=>e.childrenIndex),t.routesMeta.map(e=>e.childrenIndex)):t.score-e.score)}var oN=/^:[\w-]+$/,sN=3,cN=2,lN=1,uN=10,dN=-2,fN=e=>e===`*`;function pN(e,t){let n=e.split(`/`),r=n.length;return n.some(fN)&&(r+=dN),t&&(r+=cN),n.filter(e=>!fN(e)).reduce((e,t)=>e+(oN.test(t)?sN:t===``?lN:uN),r)}function mN(e,t){return e.length===t.length&&e.slice(0,-1).every((e,n)=>e===t[n])?e[e.length-1]-t[t.length-1]:0}function hN(e,t,n=!1){let{routesMeta:r}=e,i={},a=`/`,o=[];for(let e=0;e<r.length;++e){let s=r[e],c=e===r.length-1,l=a===`/`?t:t.slice(a.length)||`/`,u=gN({path:s.relativePath,caseSensitive:s.caseSensitive,end:c},l),d=s.route;if(!u&&c&&n&&!r[r.length-1].route.index&&(u=gN({path:s.relativePath,caseSensitive:s.caseSensitive,end:!1},l)),!u)return null;Object.assign(i,u.params),o.push({params:i,pathname:ON([a,u.pathname]),pathnameBase:AN(ON([a,u.pathnameBase])),route:d}),u.pathnameBase!==`/`&&(a=ON([a,u.pathnameBase]))}return o}function gN(e,t){typeof e==`string`&&(e={path:e,caseSensitive:!1,end:!0});let[n,r]=_N(e.path,e.caseSensitive,e.end),i=t.match(n);if(!i)return null;let a=i[0],o=a.replace(/(.)\/+$/,`$1`),s=i.slice(1);return{params:r.reduce((e,{paramName:t,isOptional:n},r)=>{if(t===`*`){let e=s[r]||``;o=a.slice(0,a.length-e.length).replace(/(.)\/+$/,`$1`)}let i=s[r];return n&&!i?e[t]=void 0:e[t]=(i||``).replace(/%2F/g,`/`),e},{}),pathname:a,pathnameBase:o,pattern:e}}function _N(e,t=!1,n=!0){GM(e===`*`||!e.endsWith(`*`)||e.endsWith(`/*`),`Route path "${e}" will be treated as if it were "${e.replace(/\*$/,`/*`)}" because the \`*\` character must always follow a \`/\` in the pattern. To get rid of this warning, please change the route path to "${e.replace(/\*$/,`/*`)}".`);let r=[],i=`^`+e.replace(/\/*\*?$/,``).replace(/^\/*/,`/`).replace(/[\\.*+^${}|()[\]]/g,`\\$&`).replace(/\/:([\w-]+)(\?)?/g,(e,t,n,i,a)=>{if(r.push({paramName:t,isOptional:n!=null}),n){let t=a.charAt(i+e.length);return t&&t!==`/`?`/([^\\/]*)`:`(?:/([^\\/]*))?`}return`/([^\\/]+)`}).replace(/\/([\w-]+)\?(\/|$)/g,`(/$1)?$2`);return e.endsWith(`*`)?(r.push({paramName:`*`}),i+=e===`*`||e===`/*`?`(.*)$`:`(?:\\/(.+)|\\/*)$`):n?i+=`\\/*$`:e!==``&&e!==`/`&&(i+=`(?:(?=\\/|$))`),[new RegExp(i,t?void 0:`i`),r]}function vN(e){try{return e.split(`/`).map(e=>decodeURIComponent(e).replace(/\//g,`%2F`)).join(`/`)}catch(t){return GM(!1,`The URL path "${e}" could not be decoded because it is a malformed URL segment. This is probably due to a bad percent encoding (${t}).`),e}}function yN(e,t){if(t===`/`)return e;if(!e.toLowerCase().startsWith(t.toLowerCase()))return null;let n=t.endsWith(`/`)?t.length-1:t.length,r=e.charAt(n);return r&&r!==`/`?null:e.slice(n)||`/`}var bN=/^(?:[a-z][a-z0-9+.-]*:|\/\/)/i;function xN(e,t=`/`){let{pathname:n,search:r=``,hash:i=``}=typeof e==`string`?XM(e):e,a;return n?(n=DN(n),a=n.startsWith(`/`)?SN(n.substring(1),`/`):SN(n,t)):a=t,{pathname:a,search:jN(r),hash:MN(i)}}function SN(e,t){let n=kN(t).split(`/`);return e.split(`/`).forEach(e=>{e===`..`?n.length>1&&n.pop():e!==`.`&&n.push(e)}),n.length>1?n.join(`/`):`/`}function CN(e,t,n,r){return`Cannot include a '${e}' character in a manually specified \`to.${t}\` field [${JSON.stringify(r)}]. Please separate it out to the \`to.${n}\` field. Alternatively you may provide the full path as a string in <Link to="..."> and the router will parse it for you.`}function wN(e){return e.filter((e,t)=>t===0||e.route.path&&e.route.path.length>0)}function TN(e){let t=wN(e);return t.map((e,n)=>n===t.length-1?e.pathname:e.pathnameBase)}function EN(e,t,n,r=!1){let i;typeof e==`string`?i=XM(e):(i={...e},WM(!i.pathname||!i.pathname.includes(`?`),CN(`?`,`pathname`,`search`,i)),WM(!i.pathname||!i.pathname.includes(`#`),CN(`#`,`pathname`,`hash`,i)),WM(!i.search||!i.search.includes(`#`),CN(`#`,`search`,`hash`,i)));let a=e===``||i.pathname===``,o=a?`/`:i.pathname,s;if(o==null)s=n;else{let e=t.length-1;if(!r&&o.startsWith(`..`)){let t=o.split(`/`);for(;t[0]===`..`;)t.shift(),--e;i.pathname=t.join(`/`)}s=e>=0?t[e]:`/`}let c=xN(i,s),l=o&&o!==`/`&&o.endsWith(`/`),u=(a||o===`.`)&&n.endsWith(`/`);return!c.pathname.endsWith(`/`)&&(l||u)&&(c.pathname+=`/`),c}var DN=e=>e.replace(/\/\/+/g,`/`),ON=e=>DN(e.join(`/`)),kN=e=>e.replace(/\/+$/,``),AN=e=>kN(e).replace(/^\/*/,`/`),jN=e=>!e||e===`?`?``:e.startsWith(`?`)?e:`?`+e,MN=e=>!e||e===`#`?``:e.startsWith(`#`)?e:`#`+e,NN=class{constructor(e,t,n,r=!1){this.status=e,this.statusText=t||``,this.internal=r,n instanceof Error?(this.data=n.toString(),this.error=n):this.data=n}};function PN(e){return e!=null&&typeof e.status==`number`&&typeof e.statusText==`string`&&typeof e.internal==`boolean`&&`data`in e}function FN(e){return ON(e.map(e=>e.route.path).filter(Boolean))||`/`}var IN=typeof window<`u`&&window.document!==void 0&&window.document.createElement!==void 0;function LN(e,t){let n=e;if(typeof n!=`string`||!bN.test(n))return{absoluteURL:void 0,isExternal:!1,to:n};let r=n,i=!1;if(IN)try{let e=new URL(window.location.href),r=n.startsWith(`//`)?new URL(e.protocol+n):new URL(n),a=yN(r.pathname,t);r.origin===e.origin&&a!=null?n=a+r.search+r.hash:i=!0}catch{GM(!1,`<Link to="${n}"> contains an invalid URL which will probably break when clicked - please update to a valid URL path.`)}return{absoluteURL:r,isExternal:i,to:n}}Object.getOwnPropertyNames(Object.prototype).sort().join(`\0`);var RN=[`POST`,`PUT`,`PATCH`,`DELETE`];new Set(RN);var zN=[`GET`,...RN];new Set(zN);var BN=z.createContext(null);BN.displayName=`DataRouter`;var VN=z.createContext(null);VN.displayName=`DataRouterState`;var HN=z.createContext(!1);function UN(){return z.useContext(HN)}var WN=z.createContext({isTransitioning:!1});WN.displayName=`ViewTransition`;var GN=z.createContext(new Map);GN.displayName=`Fetchers`;var KN=z.createContext(null);KN.displayName=`Await`;var qN=z.createContext(null);qN.displayName=`Navigation`;var JN=z.createContext(null);JN.displayName=`Location`;var YN=z.createContext({outlet:null,matches:[],isDataRoute:!1});YN.displayName=`Route`;var XN=z.createContext(null);XN.displayName=`RouteError`;var ZN=`REACT_ROUTER_ERROR`,QN=`REDIRECT`,$N=`ROUTE_ERROR_RESPONSE`;function eP(e){if(e.startsWith(`${ZN}:${QN}:{`))try{let t=JSON.parse(e.slice(28));if(typeof t==`object`&&t&&typeof t.status==`number`&&typeof t.statusText==`string`&&typeof t.location==`string`&&typeof t.reloadDocument==`boolean`&&typeof t.replace==`boolean`)return t}catch{}}function tP(e){if(e.startsWith(`${ZN}:${$N}:{`))try{let t=JSON.parse(e.slice(40));if(typeof t==`object`&&t&&typeof t.status==`number`&&typeof t.statusText==`string`)return new NN(t.status,t.statusText,t.data)}catch{}}function nP(e,{relative:t}={}){WM(rP(),`useHref() may be used only in the context of a <Router> component.`);let{basename:n,navigator:r}=z.useContext(qN),{hash:i,pathname:a,search:o}=uP(e,{relative:t}),s=a;return n!==`/`&&(s=a===`/`?n:ON([n,a])),r.createHref({pathname:s,search:o,hash:i})}function rP(){return z.useContext(JN)!=null}function iP(){return WM(rP(),`useLocation() may be used only in the context of a <Router> component.`),z.useContext(JN).location}var aP=`You should call navigate() in a React.useEffect(), not when your component is first rendered.`;function oP(e){z.useContext(qN).static||z.useLayoutEffect(e)}function sP(){let{isDataRoute:e}=z.useContext(YN);return e?kP():cP()}function cP(){WM(rP(),`useNavigate() may be used only in the context of a <Router> component.`);let e=z.useContext(BN),{basename:t,navigator:n}=z.useContext(qN),{matches:r}=z.useContext(YN),{pathname:i}=iP(),a=JSON.stringify(TN(r)),o=z.useRef(!1);return oP(()=>{o.current=!0}),z.useCallback((r,s={})=>{if(GM(o.current,aP),!o.current)return;if(typeof r==`number`){n.go(r);return}let c=EN(r,JSON.parse(a),i,s.relative===`path`);e==null&&t!==`/`&&(c.pathname=c.pathname===`/`?t:ON([t,c.pathname])),(s.replace?n.replace:n.push)(c,s.state,s)},[t,n,a,i,e])}z.createContext(null);function lP(){let{matches:e}=z.useContext(YN);return e[e.length-1]?.params??{}}function uP(e,{relative:t}={}){let{matches:n}=z.useContext(YN),{pathname:r}=iP(),i=JSON.stringify(TN(n));return z.useMemo(()=>EN(e,JSON.parse(i),r,t===`path`),[e,i,r,t])}function dP(e,t){return fP(e,t)}function fP(e,t,n){WM(rP(),`useRoutes() may be used only in the context of a <Router> component.`);let{navigator:r}=z.useContext(qN),{matches:i}=z.useContext(YN),a=i[i.length-1],o=a?a.params:{},s=a?a.pathname:`/`,c=a?a.pathnameBase:`/`,l=a&&a.route;{let e=l&&l.path||``;jP(s,!l||e.endsWith(`*`)||e.endsWith(`*?`),`You rendered descendant <Routes> (or called \`useRoutes()\`) at "${s}" (under <Route path="${e}">) but the parent route path has no trailing "*". This means if you navigate deeper, the parent won't match anymore and therefore the child routes will never render.
|
|
492
|
+
</html>`;function hj(e){let t=`<script>window.__SANDBOX_SEARCH__ = `+JSON.stringify(e).replace(/</g,`\\u003c`)+`;<\/script>`;return mj.replace(`<body>`,`<body>`+t)}var gj=`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`,_j=[`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`].join(` `),vj=`data-mcp-widget-fullscreen`,yj=`data-mcp-widget-display-mode`;function bj(e){(0,z.useEffect)(()=>{if(!(typeof document>`u`)){if(e===`pip`||e===`fullscreen`)return document.documentElement.setAttribute(yj,e),e===`fullscreen`?document.documentElement.setAttribute(vj,``):document.documentElement.removeAttribute(vj),()=>{document.documentElement.removeAttribute(yj),document.documentElement.removeAttribute(vj)};document.documentElement.removeAttribute(yj),document.documentElement.removeAttribute(vj)}},[e])}function xj({displayMode:e,setDisplayMode:t}){let n=e===`fullscreen`,r=e===`pip`;return bj(e),{handleDisplayModeChange:(0,z.useCallback)(e=>t(e),[t]),fullscreenShellClassName:n?gj:void 0,pipShellClassName:r?_j:void 0,isFullscreen:n,isPip:r}}var Sj={PIP_MAX_WIDTH:700,DEFAULT_HEIGHT:400,FULLSCREEN_HEADER_HEIGHT:50};function Cj(e){let t=e?.ui;return t&&typeof t==`object`&&`resourceUri`in t&&typeof t.resourceUri==`string`?t.resourceUri:null}function wj(e){return Cj(e)!==null}function Tj(e){return e===PO}var Ej={name:`mcp-use-client`,version:`2.0.0`},Dj=6e5,Oj=`ui/notifications/sandbox-proxy-ready`,kj={openLinks:{},serverTools:{},serverResources:{},logging:{},updateModelContext:{text:{}},message:{text:{}}};function Aj(){return z.createElement(`svg`,{width:`14`,height:`14`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,"aria-hidden":!0},z.createElement(`path`,{d:`M18 6 6 18`}),z.createElement(`path`,{d:`m6 6 12 12`}))}function jj(e){return new Promise(t=>{let n=r=>{r.source===e.contentWindow&&r.data?.method===Oj&&(window.removeEventListener(`message`,n),t())};window.addEventListener(`message`,n)})}function Mj(e){let t=e.oninitialized;return new Promise(n=>{e.oninitialized=(...r)=>{n(),e.oninitialized=t,t?.(...r)}})}function Nj(e,t){let n=cj(t);return Object.keys(n).length>0?{...typeof e==`object`&&e?e:{},structuredContent:n}:e??null}function Pj({viewId:e,source:t,sandboxUrl:n,toolName:r=`view`,toolInput:i,toolOutput:a,partialToolInput:o,customProps:s,cancelled:c,hostInfo:l=Ej,hostContext:u,hostCapabilities:d,cspMode:f=`widget-declared`,displayMode:p,onDisplayModeChange:m,inlineMaxWidth:h=768,chromeless:g,onMessage:_,onModelContextUpdate:v,onLog:y,onReady:b,onLifecycleChange:x,onError:S,onCspViolation:C,onResourceResolved:w,wrapTransport:T,toolCallTimeout:E=Dj,mockOpenAiFileApis:ee=!1,onInlineHeightChange:D,fullscreenHeader:te,renderFullscreenClose:ne,className:re,testId:O=`mcp-app-frame`,invoking:ie,invoked:k}){let A=(0,z.useRef)(null),j=(0,z.useRef)(null),ae=(0,z.useRef)(null),oe=(0,z.useRef)(t.kind===`live`?t.connection:null),[se,ce]=(0,z.useState)(null),[M,N]=(0,z.useState)(null),[le,ue]=(0,z.useState)(null),[de,fe]=(0,z.useState)(0),[pe,me]=(0,z.useState)(!0),[he,ge]=(0,z.useState)(Sj.DEFAULT_HEIGHT),[_e,ve]=(0,z.useState)(`inline`),ye=p??_e,be=(0,z.useMemo)(()=>!u||u.displayMode===ye?u:{...u,displayMode:ye},[u,ye]),xe=(0,z.useRef)(be);xe.current=be;let P=(0,z.useRef)(_);P.current=_;let Se=(0,z.useRef)(i);Se.current=i;let Ce=(0,z.useRef)(o);Ce.current=o;let we=(0,z.useRef)(a);we.current=a;let Te=(0,z.useRef)(s);Te.current=s;let Ee=(0,z.useRef)(w);Ee.current=w;let De=(0,z.useRef)(v);De.current=v;let Oe=(0,z.useRef)(y);Oe.current=y;let ke=(0,z.useRef)(S);ke.current=S;let Ae=(0,z.useRef)(C);Ae.current=C;let je=(0,z.useRef)(b);je.current=b;let Me=(0,z.useRef)(x);Me.current=x;let Ne=(0,z.useRef)(D);Ne.current=D;let Pe=(0,z.useRef)(n);Pe.current=n;let Fe=(0,z.useRef)(f);Fe.current=f;let Ie=(0,z.useRef)(ee);Ie.current=ee;let Le=(0,z.useCallback)(e=>{let t=Pe.current;return t?typeof t==`function`?t(e):t:pj({cspMode:Fe.current,permissions:e.permissions,widgetCsp:e.declaredCsp})},[]),{handleDisplayModeChange:Re,fullscreenShellClassName:ze,pipShellClassName:Be,isFullscreen:Ve,isPip:He}=xj({containerRef:ae,displayMode:ye,setDisplayMode:(0,z.useCallback)(e=>{m?m(e):ve(e)},[m])}),Ue=(0,z.useRef)(Re);Ue.current=Re;let We=(0,z.useRef)(ye);We.current=ye;let Ge=t.kind===`live`?t.resourceUri:void 0,Ke=t.kind===`preloaded`?t.html:void 0;t.kind===`live`&&(oe.current=t.connection),(0,z.useEffect)(()=>{let e=!1;Me.current?.({status:`resolving`});let n=e=>{ce(e),Me.current?.({status:`sandbox-loading`});let t=Le(e);N(e=>e?.href===t.href?e:t),Ee.current?.(e)};if(t.kind===`preloaded`){n({html:t.html,declaredCsp:t.csp,csp:f===`permissive`?void 0:t.csp,permissions:t.permissions,prefersBorder:t.prefersBorder??!1,mimeType:`text/html;profile=mcp-app`,mimeTypeValid:!0,mimeTypeWarning:null});return}let{connection:r,resourceUri:i}=t;return oe.current=r,(async()=>{try{let t=await r.readResource(i);if(e)return;let a=r.resources?.find(e=>e.uri===i),o=dj({resourceResult:t,listingResource:a,cspMode:f,resourceUri:i});if(!o.mimeTypeValid){let e=o.mimeTypeWarning||`Invalid MIME type - SEP-1865 requires "text/html;profile=mcp-app"`;ue(e),Me.current?.({status:`error`,error:e});return}n(o)}catch(t){if(e)return;ue(t instanceof Error?t.message:`Failed to prepare view`),Me.current?.({status:`error`,error:t instanceof Error?t.message:`Failed to prepare view`})}})(),()=>{e=!0}},[t.kind,Ge,Ke,f,Le]),(0,z.useEffect)(()=>{let e=M;return()=>{e?.protocol===`blob:`&&URL.revokeObjectURL(e.href)}},[M]);let qe=M?.protocol===`blob:`,Je=!M||qe?null:(()=>{try{return M.origin}catch{return null}})();(0,z.useEffect)(()=>{if(!Je&&!qe)return;let e=e=>{let t=A.current;if(t?.contentWindow&&e.source===t.contentWindow&&!(!qe&&e.origin!==Je&&Je!==`*`)){if(e.data?.type===`mcp-apps:csp-violation`){Ae.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()});return}e.data?.type===`iframe-console-log`&&Oe.current&&Oe.current({level:e.data.level??`log`,data:e.data.args})}};return window.addEventListener(`message`,e),()=>window.removeEventListener(`message`,e)},[Je,qe]),(0,z.useEffect)(()=>{if(!se||!M)return;let t=A.current;if(!t)return;let n=!1,r=null;return(async()=>{try{Me.current?.({status:`connecting`}),t.setAttribute(`sandbox`,`allow-scripts allow-same-origin allow-forms`);let i=FO(se.permissions);i&&t.setAttribute(`allow`,i);let a=jj(t);if(t.src=M.href,await a,n)return;r=new LO(null,l,{...d??kj,sandbox:{csp:f===`permissive`?void 0:se.csp,permissions:se.permissions}},{hostContext:xe.current}),r.onmessage=async({content:e})=>(e.length>0&&P.current&&P.current(e),{}),r.onopenlink=async({url:e})=>(e&&window.open(e,`_blank`,`noopener,noreferrer`),{}),r.oncalltool=(async({name:e,arguments:t})=>{let n=oe.current;if(!n)throw Error(`Server connection not available`);try{return await n.callTool(e,t||{},{timeout:E,resetTimeoutOnProgress:!0})}catch(e){throw r?.sendToolCancelled({reason:e instanceof Error?e.message:String(e)}),e}}),r.onreadresource=(async({uri:e})=>{let t=oe.current;if(!t)throw Error(`Server connection not available`);return await t.readResource(e)}),r.onlistresources=(async()=>{let e=oe.current;if(!e)throw Error(`Server connection not available`);return{resources:[...e.resources??[]]}}),r.onrequestdisplaymode=async({mode:e})=>{let t=e??`inline`,n=(xe.current?.availableDisplayModes??[`inline`,`pip`,`fullscreen`]).includes(t)?t:We.current;return await Ue.current(n),{mode:n}},r.onupdatemodelcontext=async({content:e,structuredContent:t})=>(De.current?.({content:e,structuredContent:t}),{}),r.onloggingmessage=async({level:e,data:t})=>(Oe.current?.({level:e,data:t}),{}),r.onsizechange=async({height:e})=>{We.current===`inline`&&e!==void 0&&(ge(e),Ne.current?.(e))};let o=Mj(r),s=new NO(t.contentWindow,t.contentWindow);if(T&&(s=T(s,e)),await r.connect(s),n||(await r.sendSandboxResourceReady({html:Ie.current?uj(se.html):se.html,csp:se.csp,permissions:se.permissions}),await o,n))return;j.current=r,fe(e=>e+1),Me.current?.({status:`initialized`});let c=Ce.current;if(c)r.sendToolInputPartial({arguments:c});else{let e={...Se.current,...cj(Te.current)};r.sendToolInput({arguments:e})}let u=Nj(we.current,Te.current);u&&r.sendToolResult(u),Me.current?.({status:`ready`})}catch(e){if(!n){let t=e instanceof Error?e.message:`Failed to connect view`;ue(t),ke.current?.(t),Me.current?.({status:`error`,error:t})}}})(),()=>{n=!0;let e=r;j.current=null,e&&(Me.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(()=>{}),Me.current?.({status:`closed`})}})())}},[se,M,l,d,f,e,T,E,ee]),(0,z.useEffect)(()=>{let e=j.current;!e||de===0||!be||e.setHostContext(be)},[be,de]),(0,z.useEffect)(()=>{let e=j.current;!e||de===0||!o||e.sendToolInputPartial({arguments:o})},[de,o]),(0,z.useEffect)(()=>{let e=j.current;if(!e||de===0||o)return;let t={...i,...cj(s)};e.sendToolInput({arguments:t})},[de,i,o,s]),(0,z.useEffect)(()=>{let e=j.current;if(!e||de===0)return;let t=Nj(a,s);t&&e.sendToolResult(t)},[de,a,s]),(0,z.useEffect)(()=>{let e=j.current;!e||de===0||!c||e.sendToolCancelled({reason:`Cancelled by user`})},[c,de]);let Ye=(0,z.useRef)(!1);(0,z.useEffect)(()=>{Ye.current||de===0||(Ye.current=!0,je.current?.())},[de]),(0,z.useEffect)(()=>{if(de===0||!pe)return;let e=setTimeout(()=>me(!1),300);return()=>clearTimeout(e)},[de,pe]);let Xe=se!==null&&se.prefersBorder&&ye!==`fullscreen`;if(le)return z.createElement(`div`,{className:re},z.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`},z.createElement(`p`,{className:`text-sm text-red-600 dark:text-red-400`},`Failed to load view: `,le)));if(!se)return z.createElement(`div`,{className:re},z.createElement(`div`,{className:`flex items-center justify-center w-full h-[200px]`},z.createElement(`span`,{className:`text-sm text-muted-foreground`},`Loading view…`)));let Ze=ze??Be??`flex group flex-1 items-center justify-center`,Qe={height:Ve||He?`100%`:`${he}px`,width:`100%`,maxWidth:ye===`inline`?`${h}px`:`100%`,transition:Ve||He?void 0:`height 300ms ease-out`},$e=z.createElement(`div`,{ref:ae,className:Ve?`${Ze} flex flex-col`:Ze,style:He?{height:Sj.DEFAULT_HEIGHT,maxWidth:Sj.PIP_MAX_WIDTH,zIndex:100}:Ve?{zIndex:100}:void 0},Ve&&z.createElement(`header`,{className:`grid shrink-0 items-center border-b border-zinc-200 bg-background px-3 dark:border-zinc-700`,style:{height:Sj.FULLSCREEN_HEADER_HEIGHT,gridTemplateColumns:`auto 1fr auto`}},ne?ne({onClick:()=>void Re(`inline`),"data-testid":`debugger-exit-fullscreen-button`,"aria-label":`Exit fullscreen`}):z.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 Re(`inline`)},z.createElement(Aj,null)),z.createElement(`div`,{className:`flex min-w-0 items-center justify-center gap-2 px-2`},te?.iconUrl?z.createElement(`img`,{src:te.iconUrl,alt:``,className:`size-6 shrink-0 rounded-md object-contain`}):null,z.createElement(`span`,{className:`truncate text-sm font-medium text-foreground`},te?.title??r)),z.createElement(`div`,{className:`size-8 shrink-0`,"aria-hidden":!0})),He&&(ne?z.createElement(`div`,{className:`absolute right-3 top-3`,style:{zIndex:110}},ne({onClick:()=>void Re(`inline`),"data-testid":`debugger-exit-pip-button`,"aria-label":`Exit picture-in-picture`})):z.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 Re(`inline`)},z.createElement(Aj,null))),z.createElement(`div`,{className:Ve?`relative flex min-h-0 w-full flex-1 flex-col`:He?`relative w-full h-full min-h-0 flex flex-1 flex-col`:`relative w-full flex flex-1 justify-center items-center`},pe&&z.createElement(`div`,{className:`flex absolute inset-0 items-center justify-center z-10`},z.createElement(`span`,{className:`text-sm text-muted-foreground`},`Loading…`)),!He&&!Ve&&(ie||k)&&z.createElement(`div`,{className:`absolute -top-8 left-2 z-10 whitespace-nowrap pointer-events-none text-xs text-muted-foreground`},ie&&!a?ie:k),z.createElement(`div`,{"data-testid":O,"data-mcp-app-tool":r,className:ye===`fullscreen`?`w-full h-full overflow-hidden`:`w-full overflow-hidden`,style:Qe},z.createElement(`iframe`,{ref:A,title:`MCP App: ${r}`,className:Xe?`w-full h-full bg-transparent border border-border rounded-xl`:`w-full h-full bg-transparent border-0`}))));return z.createElement(`div`,{className:re},$e)}function Fj(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.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)}var Ij=(0,z.memo)(Pj,Fj);function Lj(e){let t=document.createElement(`textarea`);t.value=e,t.style.cssText=`position:fixed;top:-9999px;left:-9999px;opacity:0`,document.body.appendChild(t),t.focus(),t.select();try{return document.execCommand(`copy`)}finally{document.body.removeChild(t)}}function Rj(e){return Lj(e)}async function zj(e){if(!Lj(e)){if(navigator.clipboard?.writeText)return navigator.clipboard.writeText(e);throw Error(`copy failed`)}}function Bj(e){let t=Date.now()-e,n=Math.floor(t/1e3),r=Math.floor(n/60),i=Math.floor(r/60),a=Math.floor(i/24);return n<60?`just now`:r<60?`${r}m ago`:i<24?`${i}h ago`:a<7?`${a}d ago`:new Date(e).toLocaleDateString()}function Vj(e){if(e==null)return`/mcp`;let t=e.trim().replace(/\/{2,}/g,`/`).replace(/\/+$/,``);return t===``||t===`/`?``:(t.startsWith(`/`)||(t=`/${t}`),t)}function Hj(){if(typeof window>`u`)return``;let e=window.location.pathname||``,t=e.indexOf(`/inspector`);return t<=0?``:Vj(e.slice(0,t))}function Uj(){if(typeof window>`u`)return``;let e=window.__MCP_BASE_PATH__;return e==null?Hj():Vj(e)}function Wj(){return`${Uj()}/inspector`}function Gj(e){let t=e.replace(/^\/+/,``);return`${Wj()}/api/${t}`}var Kj=/^127\.(?:0|[1-9]\d?|1\d\d|2[0-4]\d|25[0-5])(?:\.(?:0|[1-9]\d?|1\d\d|2[0-4]\d|25[0-5])){2}$/;function qj(e){try{let t=new URL(e).hostname.toLowerCase().replace(/^\[|\]$/g,``);return t===`localhost`||t===`::1`||t===`0.0.0.0`||Kj.test(t)}catch{return!1}}function Jj(e){try{return new URL(e).hostname.endsWith(`.mcp-use.run`)}catch{return!1}}function Yj(e){let t=e.name?.trim(),n=e.url?.trim();return t?t===n?``:t:``}function Xj(e){return Yj(e)||e.serverInfo?.title?.trim()||e.serverInfo?.name?.trim()||e.name?.trim()||e.url?.trim()||`Unknown server`}function Zj(e){let t=e.serverInfo?.icons;return t&&t.length>0?t[0].src:e.serverInfo?.icon?e.serverInfo.icon:null}var Qj=`2026-07-28`;function $j(e){switch(e){case`v1`:return`legacy`;case`v2`:return{pin:Qj};default:return`auto`}}function eM(e){return e===`legacy`?`v1`:typeof e==`object`&&e?.pin?`v2`:`auto`}function tM(){if(typeof window>`u`)return``;let e=window.__MCP_PROXY_URL__;return e===null?``:`${window.location.origin}${e||Gj(`proxy`)}`}function nM(e,t,n=!1){return e===`auto`||e===`direct`||e===`proxy`?e:t===`Via Proxy`?`proxy`:t===`Direct`?`auto`:n?`proxy`:`auto`}function rM(e){return!e||typeof e==`boolean`?``:e.proxyAddress?.trim()||``}var iM=[`requestTimeout`,`resetTimeoutOnProgress`,`maxTotalTimeout`];function aM(e){if(!e)return{};let t={};for(let n of iM){let r=e[n];r!==void 0&&(t[n]=r)}return t}function oM(e,t){try{let n=localStorage.getItem(`mcp-inspector-connections`),r=n?JSON.parse(n):{};r[e]={...r[e],...t},localStorage.setItem(`mcp-inspector-connections`,JSON.stringify(r))}catch{}}function sM(e,t,n){let r=e.trim(),i=t.trim(),a=n.trim();if(!(!r&&!a))return{...r?{clientId:r}:{},...r&&i?{clientSecret:i}:{},...a?{scope:a}:{}}}function cM(e){let t=e.headers||e.proxyConfig?.headers||e.proxyConfig?.customHeaders;return t&&Object.keys(t).length>0?t:void 0}function lM(e){let t=e.proxyConfig,n=e.headers||e.customHeaders,r=t?.headers||t?.customHeaders||void 0,i=n||r,a=t?{...t,...r?{headers:r}:{},customHeaders:void 0}:void 0,{customHeaders:o,connectionType:s,transportType:c,...l}=e;return{...l,...i&&!a?.proxyAddress?{headers:i}:{},...a?{proxyConfig:a}:{},connectionMode:nM(e.connectionMode,e.connectionType,!!a?.proxyAddress)}}function uM(e){let t=pM(e),n=e.proxyConfig?.proxyAddress?.trim()||rM(e.autoProxyFallback),r=nM(e.connectionMode,e.connectionType,!!n),i={url:e.url,displayName:e.name?.trim()||e.url,connectionMode:r,protocolNegotiation:e.protocolNegotiation??`auto`,...e.oauth?{oauth:e.oauth}:{}};return r===`proxy`&&n?i.proxyConfig={proxyAddress:n,...Object.keys(t).length>0?{headers:t}:{}}:Object.keys(t).length>0&&(i.headers=t),r===`auto`&&(i.autoProxyFallback=e.autoProxyFallback??(n?{enabled:!0,proxyAddress:n}:!1)),i}function dM(e,t){let n=t?lM(t):e,r=cM(e)||{},i=n.proxyConfig?.proxyAddress?.trim()||rM(n.autoProxyFallback);return{url:e.url||``,name:e.displayName||e.url||``,transportType:`http`,connectionMode:nM(n.connectionMode,void 0,!!i),connectionType:n.connectionMode===`proxy`?`Via Proxy`:`Direct`,proxyConfig:n.connectionMode===`proxy`&&i?{proxyAddress:i,...Object.keys(r).length>0?{headers:r}:{}}:void 0,headers:r,oauth:n.oauth,autoProxyFallback:n.autoProxyFallback,protocolNegotiation:n.protocolNegotiation??`auto`,...aM(t)}}function fM(e){try{let t=localStorage.getItem(`mcp-inspector-connections`);return t&&JSON.parse(t)[e]||null}catch{return null}}function pM(e){let t=e.proxyConfig?.headers||e.proxyConfig?.customHeaders||e.headers||e.customHeaders||{};return Object.fromEntries(Object.entries(t).filter(([e,t])=>e&&t).map(([e,t])=>[e,String(t)]).sort(([e],[t])=>e.localeCompare(t)))}function mM(e){let t=e.url?.trim()||``,n=e.proxyConfig?.proxyAddress?.trim()||rM(e.autoProxyFallback);return{url:t,name:e.name?.trim()||t,transportType:e.transportType||`http`,proxyAddress:n,connectionMode:nM(e.connectionMode,e.connectionType,!!n),headers:pM(e),oauthClientId:e.oauth?.clientId?.trim()||``,oauthClientSecret:e.oauth?.clientSecret?.trim()||``,oauthScope:e.oauth?.scope?.trim()||``,requestTimeout:`requestTimeout`in e?e.requestTimeout:void 0,resetTimeoutOnProgress:`resetTimeoutOnProgress`in e?e.resetTimeoutOnProgress:void 0,maxTotalTimeout:`maxTotalTimeout`in e?e.maxTotalTimeout:void 0,protocolMode:eM(e.protocolNegotiation)}}function hM(e,t){let n=mM(e),r=mM(t);return n.url===r.url&&n.transportType===r.transportType&&n.proxyAddress===r.proxyAddress&&n.connectionMode===r.connectionMode&&JSON.stringify(n.headers)===JSON.stringify(r.headers)&&n.oauthClientId===r.oauthClientId&&n.oauthClientSecret===r.oauthClientSecret&&n.oauthScope===r.oauthScope&&n.requestTimeout===r.requestTimeout&&n.resetTimeoutOnProgress===r.resetTimeoutOnProgress&&n.maxTotalTimeout===r.maxTotalTimeout&&n.protocolMode===r.protocolMode&&n.name!==r.name}var gM=class extends sj{setServers(e){let t=this.readRawStoredServers(),n=Object.fromEntries(Object.entries(e).map(([e,n])=>[e,{...aM(t[e]),...n,...qj(e)&&typeof n.url==`string`&&Jj(n.url)?{url:e}:{}}]));super.setServers(n)}setServer(e,t){let n=this.getServers();n[e]={...aM(this.readRawStoredServers()[e]),...t},this.setServers(n)}readRawStoredServers(){try{let e=localStorage.getItem(`mcp-inspector-connections`);return e?JSON.parse(e):{}}catch{return{}}}},_M=`popstate`;function vM(e){return typeof e==`object`&&!!e&&`pathname`in e&&`search`in e&&`hash`in e&&`state`in e&&`key`in e}function yM(e={}){function t(e,t){let n=t.state?.masked,{pathname:r,search:i,hash:a}=n||e.location;return wM(``,{pathname:r,search:i,hash:a},t.state&&t.state.usr||null,t.state&&t.state.key||`default`,n?{pathname:e.location.pathname,search:e.location.search,hash:e.location.hash}:void 0)}function n(e,t){return typeof t==`string`?t:TM(t)}return DM(t,n,null,e)}function bM(e,t){if(e===!1||e==null)throw Error(t)}function xM(e,t){if(!e){typeof console<`u`&&console.warn(t);try{throw Error(t)}catch{}}}function SM(){return Math.random().toString(36).substring(2,10)}function CM(e,t){return{usr:e.state,key:e.key,idx:t,masked:e.mask?{pathname:e.pathname,search:e.search,hash:e.hash}:void 0}}function wM(e,t,n=null,r,i){return{pathname:typeof e==`string`?e:e.pathname,search:``,hash:``,...typeof t==`string`?EM(t):t,state:n,key:t&&t.key||r||SM(),mask:i}}function TM({pathname:e=`/`,search:t=``,hash:n=``}){return t&&t!==`?`&&(e+=t.charAt(0)===`?`?t:`?`+t),n&&n!==`#`&&(e+=n.charAt(0)===`#`?n:`#`+n),e}function EM(e){let t={};if(e){let n=e.indexOf(`#`);n>=0&&(t.hash=e.substring(n),e=e.substring(0,n));let r=e.indexOf(`?`);r>=0&&(t.search=e.substring(r),e=e.substring(0,r)),e&&(t.pathname=e)}return t}function DM(e,t,n,r={}){let{window:i=document.defaultView,v5Compat:a=!1}=r,o=i.history,s=`POP`,c=null,l=u();l??(l=0,o.replaceState({...o.state,idx:l},``));function u(){return(o.state||{idx:null}).idx}function d(){s=`POP`;let e=u(),t=e==null?null:e-l;l=e,c&&c({action:s,location:h.location,delta:t})}function f(e,t){s=`PUSH`;let r=vM(e)?e:wM(h.location,e,t);n&&n(r,e),l=u()+1;let d=CM(r,l),f=h.createHref(r.mask||r);try{o.pushState(d,``,f)}catch(e){if(e instanceof DOMException&&e.name===`DataCloneError`)throw e;i.location.assign(f)}a&&c&&c({action:s,location:h.location,delta:1})}function p(e,t){s=`REPLACE`;let r=vM(e)?e:wM(h.location,e,t);n&&n(r,e),l=u();let i=CM(r,l),d=h.createHref(r.mask||r);o.replaceState(i,``,d),a&&c&&c({action:s,location:h.location,delta:0})}function m(e){return OM(i,e)}let h={get action(){return s},get location(){return e(i,o)},listen(e){if(c)throw Error(`A history only accepts one active listener`);return i.addEventListener(_M,d),c=e,()=>{i.removeEventListener(_M,d),c=null}},createHref(e){return t(i,e)},createURL:m,encodeLocation(e){let t=m(e);return{pathname:t.pathname,search:t.search,hash:t.hash}},push:f,replace:p,go(e){return o.go(e)}};return h}function OM(e,t,n=!1){let r=`http://localhost`;e&&(r=e.location.origin===`null`?e.location.href:e.location.origin),bM(r,`No window.location.(origin|href) available to create URL`);let i=typeof t==`string`?t:TM(t);return i=i.replace(/ $/,`%20`),!n&&i.startsWith(`//`)&&(i=r+i),new URL(i,r)}function kM(e,t,n=`/`){return AM(e,t,n,!1)}function AM(e,t,n,r,i){let a=YM((typeof t==`string`?EM(t):t).pathname||`/`,n);if(a==null)return null;let o=i??MM(e),s=null,c=JM(a);for(let e=0;s==null&&e<o.length;++e)s=GM(o[e],c,r);return s}function jM(e,t){let{route:n,pathname:r,params:i}=e;return{id:n.id,pathname:r,params:i,data:t[n.id],loaderData:t[n.id],handle:n.handle}}function MM(e){let t=NM(e);return FM(t),t}function NM(e,t=[],n=[],r=``,i=!1){let a=(e,a,o=i,s)=>{let c={relativePath:s===void 0?e.path||``:s,caseSensitive:e.caseSensitive===!0,childrenIndex:a,route:e};if(c.relativePath.startsWith(`/`)){if(!c.relativePath.startsWith(r)&&o)return;bM(c.relativePath.startsWith(r),`Absolute route path "${c.relativePath}" nested under path "${r}" is not valid. An absolute child route path must start with the combined path of all its parent routes.`),c.relativePath=c.relativePath.slice(r.length)}let l=iN([r,c.relativePath]),u=n.concat(c);e.children&&e.children.length>0&&(bM(e.index!==!0,`Index routes must not have child routes. Please remove all child routes from route path "${l}".`),NM(e.children,t,u,l,o)),!(e.path==null&&!e.index)&&t.push({path:l,score:UM(l,e.index),routesMeta:u})};return e.forEach((e,t)=>{if(e.path===``||!e.path?.includes(`?`))a(e,t);else for(let n of PM(e.path))a(e,t,!0,n)}),t}function PM(e){let t=e.split(`/`);if(t.length===0)return[];let[n,...r]=t,i=n.endsWith(`?`),a=n.replace(/\?$/,``);if(r.length===0)return i?[a,``]:[a];let o=PM(r.join(`/`)),s=[];return s.push(...o.map(e=>e===``?a:[a,e].join(`/`))),i&&s.push(...o),s.map(t=>e.startsWith(`/`)&&t===``?`/`:t)}function FM(e){e.sort((e,t)=>e.score===t.score?WM(e.routesMeta.map(e=>e.childrenIndex),t.routesMeta.map(e=>e.childrenIndex)):t.score-e.score)}var IM=/^:[\w-]+$/,LM=3,RM=2,zM=1,BM=10,VM=-2,HM=e=>e===`*`;function UM(e,t){let n=e.split(`/`),r=n.length;return n.some(HM)&&(r+=VM),t&&(r+=RM),n.filter(e=>!HM(e)).reduce((e,t)=>e+(IM.test(t)?LM:t===``?zM:BM),r)}function WM(e,t){return e.length===t.length&&e.slice(0,-1).every((e,n)=>e===t[n])?e[e.length-1]-t[t.length-1]:0}function GM(e,t,n=!1){let{routesMeta:r}=e,i={},a=`/`,o=[];for(let e=0;e<r.length;++e){let s=r[e],c=e===r.length-1,l=a===`/`?t:t.slice(a.length)||`/`,u=KM({path:s.relativePath,caseSensitive:s.caseSensitive,end:c},l),d=s.route;if(!u&&c&&n&&!r[r.length-1].route.index&&(u=KM({path:s.relativePath,caseSensitive:s.caseSensitive,end:!1},l)),!u)return null;Object.assign(i,u.params),o.push({params:i,pathname:iN([a,u.pathname]),pathnameBase:oN(iN([a,u.pathnameBase])),route:d}),u.pathnameBase!==`/`&&(a=iN([a,u.pathnameBase]))}return o}function KM(e,t){typeof e==`string`&&(e={path:e,caseSensitive:!1,end:!0});let[n,r]=qM(e.path,e.caseSensitive,e.end),i=t.match(n);if(!i)return null;let a=i[0],o=a.replace(/(.)\/+$/,`$1`),s=i.slice(1);return{params:r.reduce((e,{paramName:t,isOptional:n},r)=>{if(t===`*`){let e=s[r]||``;o=a.slice(0,a.length-e.length).replace(/(.)\/+$/,`$1`)}let i=s[r];return n&&!i?e[t]=void 0:e[t]=(i||``).replace(/%2F/g,`/`),e},{}),pathname:a,pathnameBase:o,pattern:e}}function qM(e,t=!1,n=!0){xM(e===`*`||!e.endsWith(`*`)||e.endsWith(`/*`),`Route path "${e}" will be treated as if it were "${e.replace(/\*$/,`/*`)}" because the \`*\` character must always follow a \`/\` in the pattern. To get rid of this warning, please change the route path to "${e.replace(/\*$/,`/*`)}".`);let r=[],i=`^`+e.replace(/\/*\*?$/,``).replace(/^\/*/,`/`).replace(/[\\.*+^${}|()[\]]/g,`\\$&`).replace(/\/:([\w-]+)(\?)?/g,(e,t,n,i,a)=>{if(r.push({paramName:t,isOptional:n!=null}),n){let t=a.charAt(i+e.length);return t&&t!==`/`?`/([^\\/]*)`:`(?:/([^\\/]*))?`}return`/([^\\/]+)`}).replace(/\/([\w-]+)\?(\/|$)/g,`(/$1)?$2`);return e.endsWith(`*`)?(r.push({paramName:`*`}),i+=e===`*`||e===`/*`?`(.*)$`:`(?:\\/(.+)|\\/*)$`):n?i+=`\\/*$`:e!==``&&e!==`/`&&(i+=`(?:(?=\\/|$))`),[new RegExp(i,t?void 0:`i`),r]}function JM(e){try{return e.split(`/`).map(e=>decodeURIComponent(e).replace(/\//g,`%2F`)).join(`/`)}catch(t){return xM(!1,`The URL path "${e}" could not be decoded because it is a malformed URL segment. This is probably due to a bad percent encoding (${t}).`),e}}function YM(e,t){if(t===`/`)return e;if(!e.toLowerCase().startsWith(t.toLowerCase()))return null;let n=t.endsWith(`/`)?t.length-1:t.length,r=e.charAt(n);return r&&r!==`/`?null:e.slice(n)||`/`}var XM=/^(?:[a-z][a-z0-9+.-]*:|\/\/)/i;function ZM(e,t=`/`){let{pathname:n,search:r=``,hash:i=``}=typeof e==`string`?EM(e):e,a;return n?(n=rN(n),a=n.startsWith(`/`)?QM(n.substring(1),`/`):QM(n,t)):a=t,{pathname:a,search:sN(r),hash:cN(i)}}function QM(e,t){let n=aN(t).split(`/`);return e.split(`/`).forEach(e=>{e===`..`?n.length>1&&n.pop():e!==`.`&&n.push(e)}),n.length>1?n.join(`/`):`/`}function $M(e,t,n,r){return`Cannot include a '${e}' character in a manually specified \`to.${t}\` field [${JSON.stringify(r)}]. Please separate it out to the \`to.${n}\` field. Alternatively you may provide the full path as a string in <Link to="..."> and the router will parse it for you.`}function eN(e){return e.filter((e,t)=>t===0||e.route.path&&e.route.path.length>0)}function tN(e){let t=eN(e);return t.map((e,n)=>n===t.length-1?e.pathname:e.pathnameBase)}function nN(e,t,n,r=!1){let i;typeof e==`string`?i=EM(e):(i={...e},bM(!i.pathname||!i.pathname.includes(`?`),$M(`?`,`pathname`,`search`,i)),bM(!i.pathname||!i.pathname.includes(`#`),$M(`#`,`pathname`,`hash`,i)),bM(!i.search||!i.search.includes(`#`),$M(`#`,`search`,`hash`,i)));let a=e===``||i.pathname===``,o=a?`/`:i.pathname,s;if(o==null)s=n;else{let e=t.length-1;if(!r&&o.startsWith(`..`)){let t=o.split(`/`);for(;t[0]===`..`;)t.shift(),--e;i.pathname=t.join(`/`)}s=e>=0?t[e]:`/`}let c=ZM(i,s),l=o&&o!==`/`&&o.endsWith(`/`),u=(a||o===`.`)&&n.endsWith(`/`);return!c.pathname.endsWith(`/`)&&(l||u)&&(c.pathname+=`/`),c}var rN=e=>e.replace(/\/\/+/g,`/`),iN=e=>rN(e.join(`/`)),aN=e=>e.replace(/\/+$/,``),oN=e=>aN(e).replace(/^\/*/,`/`),sN=e=>!e||e===`?`?``:e.startsWith(`?`)?e:`?`+e,cN=e=>!e||e===`#`?``:e.startsWith(`#`)?e:`#`+e,lN=class{constructor(e,t,n,r=!1){this.status=e,this.statusText=t||``,this.internal=r,n instanceof Error?(this.data=n.toString(),this.error=n):this.data=n}};function uN(e){return e!=null&&typeof e.status==`number`&&typeof e.statusText==`string`&&typeof e.internal==`boolean`&&`data`in e}function dN(e){return iN(e.map(e=>e.route.path).filter(Boolean))||`/`}var fN=typeof window<`u`&&window.document!==void 0&&window.document.createElement!==void 0;function pN(e,t){let n=e;if(typeof n!=`string`||!XM.test(n))return{absoluteURL:void 0,isExternal:!1,to:n};let r=n,i=!1;if(fN)try{let e=new URL(window.location.href),r=n.startsWith(`//`)?new URL(e.protocol+n):new URL(n),a=YM(r.pathname,t);r.origin===e.origin&&a!=null?n=a+r.search+r.hash:i=!0}catch{xM(!1,`<Link to="${n}"> contains an invalid URL which will probably break when clicked - please update to a valid URL path.`)}return{absoluteURL:r,isExternal:i,to:n}}Object.getOwnPropertyNames(Object.prototype).sort().join(`\0`);var mN=[`POST`,`PUT`,`PATCH`,`DELETE`];new Set(mN);var hN=[`GET`,...mN];new Set(hN);var gN=z.createContext(null);gN.displayName=`DataRouter`;var _N=z.createContext(null);_N.displayName=`DataRouterState`;var vN=z.createContext(!1);function yN(){return z.useContext(vN)}var bN=z.createContext({isTransitioning:!1});bN.displayName=`ViewTransition`;var xN=z.createContext(new Map);xN.displayName=`Fetchers`;var SN=z.createContext(null);SN.displayName=`Await`;var CN=z.createContext(null);CN.displayName=`Navigation`;var wN=z.createContext(null);wN.displayName=`Location`;var TN=z.createContext({outlet:null,matches:[],isDataRoute:!1});TN.displayName=`Route`;var EN=z.createContext(null);EN.displayName=`RouteError`;var DN=`REACT_ROUTER_ERROR`,ON=`REDIRECT`,kN=`ROUTE_ERROR_RESPONSE`;function AN(e){if(e.startsWith(`${DN}:${ON}:{`))try{let t=JSON.parse(e.slice(28));if(typeof t==`object`&&t&&typeof t.status==`number`&&typeof t.statusText==`string`&&typeof t.location==`string`&&typeof t.reloadDocument==`boolean`&&typeof t.replace==`boolean`)return t}catch{}}function jN(e){if(e.startsWith(`${DN}:${kN}:{`))try{let t=JSON.parse(e.slice(40));if(typeof t==`object`&&t&&typeof t.status==`number`&&typeof t.statusText==`string`)return new lN(t.status,t.statusText,t.data)}catch{}}function MN(e,{relative:t}={}){bM(NN(),`useHref() may be used only in the context of a <Router> component.`);let{basename:n,navigator:r}=z.useContext(CN),{hash:i,pathname:a,search:o}=BN(e,{relative:t}),s=a;return n!==`/`&&(s=a===`/`?n:iN([n,a])),r.createHref({pathname:s,search:o,hash:i})}function NN(){return z.useContext(wN)!=null}function PN(){return bM(NN(),`useLocation() may be used only in the context of a <Router> component.`),z.useContext(wN).location}var FN=`You should call navigate() in a React.useEffect(), not when your component is first rendered.`;function IN(e){z.useContext(CN).static||z.useLayoutEffect(e)}function LN(){let{isDataRoute:e}=z.useContext(TN);return e?aP():RN()}function RN(){bM(NN(),`useNavigate() may be used only in the context of a <Router> component.`);let e=z.useContext(gN),{basename:t,navigator:n}=z.useContext(CN),{matches:r}=z.useContext(TN),{pathname:i}=PN(),a=JSON.stringify(tN(r)),o=z.useRef(!1);return IN(()=>{o.current=!0}),z.useCallback((r,s={})=>{if(xM(o.current,FN),!o.current)return;if(typeof r==`number`){n.go(r);return}let c=nN(r,JSON.parse(a),i,s.relative===`path`);e==null&&t!==`/`&&(c.pathname=c.pathname===`/`?t:iN([t,c.pathname])),(s.replace?n.replace:n.push)(c,s.state,s)},[t,n,a,i,e])}z.createContext(null);function zN(){let{matches:e}=z.useContext(TN);return e[e.length-1]?.params??{}}function BN(e,{relative:t}={}){let{matches:n}=z.useContext(TN),{pathname:r}=PN(),i=JSON.stringify(tN(n));return z.useMemo(()=>nN(e,JSON.parse(i),r,t===`path`),[e,i,r,t])}function VN(e,t){return HN(e,t)}function HN(e,t,n){bM(NN(),`useRoutes() may be used only in the context of a <Router> component.`);let{navigator:r}=z.useContext(CN),{matches:i}=z.useContext(TN),a=i[i.length-1],o=a?a.params:{},s=a?a.pathname:`/`,c=a?a.pathnameBase:`/`,l=a&&a.route;{let e=l&&l.path||``;sP(s,!l||e.endsWith(`*`)||e.endsWith(`*?`),`You rendered descendant <Routes> (or called \`useRoutes()\`) at "${s}" (under <Route path="${e}">) but the parent route path has no trailing "*". This means if you navigate deeper, the parent won't match anymore and therefore the child routes will never render.
|
|
493
493
|
|
|
494
|
-
Please change the parent <Route path="${e}"> to <Route path="${e===`/`?`*`:`${e}/*`}">.`)}let u=iP(),d;if(t){let e=typeof t==`string`?XM(t):t;WM(c===`/`||e.pathname?.startsWith(c),`When overriding the location using \`<Routes location>\` or \`useRoutes(routes, location)\`, the location pathname must begin with the portion of the URL pathname that was matched by all parent routes. The current pathname base is "${c}" but pathname "${e.pathname}" was given in the \`location\` prop.`),d=e}else d=u;let f=d.pathname||`/`,p=f;if(c!==`/`){let e=c.replace(/^\//,``).split(`/`);p=`/`+f.replace(/^\//,``).split(`/`).slice(e.length).join(`/`)}let m=n&&n.state.matches.length?n.state.matches.map(e=>Object.assign(e,{route:n.manifest[e.route.id]||e.route})):$M(e,{pathname:p});GM(l||m!=null,`No routes matched location "${d.pathname}${d.search}${d.hash}" `),GM(m==null||m[m.length-1].route.element!==void 0||m[m.length-1].route.Component!==void 0||m[m.length-1].route.lazy!==void 0,`Matched leaf route at location "${d.pathname}${d.search}${d.hash}" does not have an element or Component. This means it will render an <Outlet /> with a null value by default resulting in an "empty" page.`);let h=yP(m&&m.map(e=>Object.assign({},e,{params:Object.assign({},o,e.params),pathname:ON([c,r.encodeLocation?r.encodeLocation(e.pathname.replace(/%/g,`%25`).replace(/\?/g,`%3F`).replace(/#/g,`%23`)).pathname:e.pathname]),pathnameBase:e.pathnameBase===`/`?c:ON([c,r.encodeLocation?r.encodeLocation(e.pathnameBase.replace(/%/g,`%25`).replace(/\?/g,`%3F`).replace(/#/g,`%23`)).pathname:e.pathnameBase])})),i,n);return t&&h?z.createElement(JN.Provider,{value:{location:{pathname:`/`,search:``,hash:``,state:null,key:`default`,mask:void 0,...d},navigationType:`POP`}},h):h}function pP(){let e=OP(),t=PN(e)?`${e.status} ${e.statusText}`:e instanceof Error?e.message:JSON.stringify(e),n=e instanceof Error?e.stack:null,r=`rgba(200,200,200, 0.5)`,i={padding:`0.5rem`,backgroundColor:r},a={padding:`2px 4px`,backgroundColor:r},o=null;return console.error(`Error handled by React Router default ErrorBoundary:`,e),o=z.createElement(z.Fragment,null,z.createElement(`p`,null,`💿 Hey developer 👋`),z.createElement(`p`,null,`You can provide a way better UX than this when your app throws errors by providing your own `,z.createElement(`code`,{style:a},`ErrorBoundary`),` or`,` `,z.createElement(`code`,{style:a},`errorElement`),` prop on your route.`)),z.createElement(z.Fragment,null,z.createElement(`h2`,null,`Unexpected Application Error!`),z.createElement(`h3`,{style:{fontStyle:`italic`}},t),n?z.createElement(`pre`,{style:i},n):null,o)}var mP=z.createElement(pP,null),hP=class extends z.Component{constructor(e){super(e),this.state={location:e.location,revalidation:e.revalidation,error:e.error}}static getDerivedStateFromError(e){return{error:e}}static getDerivedStateFromProps(e,t){return t.location!==e.location||t.revalidation!==`idle`&&e.revalidation===`idle`?{error:e.error,location:e.location,revalidation:e.revalidation}:{error:e.error===void 0?t.error:e.error,location:t.location,revalidation:e.revalidation||t.revalidation}}componentDidCatch(e,t){this.props.onError?this.props.onError(e,t):console.error(`React Router caught the following error during render`,e)}render(){let e=this.state.error;if(this.context&&typeof e==`object`&&e&&`digest`in e&&typeof e.digest==`string`){let t=tP(e.digest);t&&(e=t)}let t=e===void 0?this.props.children:z.createElement(YN.Provider,{value:this.props.routeContext},z.createElement(XN.Provider,{value:e,children:this.props.component}));return this.context?z.createElement(_P,{error:e},t):t}};hP.contextType=HN;var gP=new WeakMap;function _P({children:e,error:t}){let{basename:n}=z.useContext(qN);if(typeof t==`object`&&t&&`digest`in t&&typeof t.digest==`string`){let e=eP(t.digest);if(e){let r=gP.get(t);if(r)throw r;let i=LN(e.location,n);if(IN&&!gP.get(t))if(i.isExternal||e.reloadDocument)window.location.href=i.absoluteURL||i.to;else{let n=Promise.resolve().then(()=>window.__reactRouterDataRouter.navigate(i.to,{replace:e.replace}));throw gP.set(t,n),n}return z.createElement(`meta`,{httpEquiv:`refresh`,content:`0;url=${i.absoluteURL||i.to}`})}}return e}function vP({routeContext:e,match:t,children:n}){let r=z.useContext(BN);return r&&r.static&&r.staticContext&&(t.route.errorElement||t.route.ErrorBoundary)&&(r.staticContext._deepestRenderedBoundaryId=t.route.id),z.createElement(YN.Provider,{value:e},n)}function yP(e,t=[],n){let r=n?.state;if(e==null){if(!r)return null;if(r.errors)e=r.matches;else if(t.length===0&&!r.initialized&&r.matches.length>0)e=r.matches;else return null}let i=e,a=r?.errors;if(a!=null){let e=i.findIndex(e=>e.route.id&&a?.[e.route.id]!==void 0);WM(e>=0,`Could not find a matching route for errors on route IDs: ${Object.keys(a).join(`,`)}`),i=i.slice(0,Math.min(i.length,e+1))}let o=!1,s=-1;if(n&&r){o=r.renderFallback;for(let e=0;e<i.length;e++){let t=i[e];if((t.route.HydrateFallback||t.route.hydrateFallbackElement)&&(s=e),t.route.id){let{loaderData:e,errors:a}=r,c=t.route.loader&&!e.hasOwnProperty(t.route.id)&&(!a||a[t.route.id]===void 0);if(t.route.lazy||c){n.isStatic&&(o=!0),i=s>=0?i.slice(0,s+1):[i[0]];break}}}}let c=n?.onError,l=r&&c?(e,t)=>{c(e,{location:r.location,params:r.matches?.[0]?.params??{},pattern:FN(r.matches),errorInfo:t})}:void 0;return i.reduceRight((e,n,c)=>{let u,d=!1,f=null,p=null;r&&(u=a&&n.route.id?a[n.route.id]:void 0,f=n.route.errorElement||mP,o&&(s<0&&c===0?(jP(`route-fallback`,!1,"No `HydrateFallback` element provided to render during initial hydration"),d=!0,p=null):s===c&&(d=!0,p=n.route.hydrateFallbackElement||null)));let m=t.concat(i.slice(0,c+1)),h=()=>{let t;return t=u?f:d?p:n.route.Component?z.createElement(n.route.Component,null):n.route.element?n.route.element:e,z.createElement(vP,{match:n,routeContext:{outlet:e,matches:m,isDataRoute:r!=null},children:t})};return r&&(n.route.ErrorBoundary||n.route.errorElement||c===0)?z.createElement(hP,{location:r.location,revalidation:r.revalidation,component:f,error:u,children:h(),routeContext:{outlet:null,matches:m,isDataRoute:!0},onError:l}):h()},null)}function bP(e){return`${e} must be used within a data router. See https://reactrouter.com/en/main/routers/picking-a-router.`}function xP(e){let t=z.useContext(BN);return WM(t,bP(e)),t}function SP(e){let t=z.useContext(VN);return WM(t,bP(e)),t}function CP(e){let t=z.useContext(YN);return WM(t,bP(e)),t}function wP(e){let t=CP(e),n=t.matches[t.matches.length-1];return WM(n.route.id,`${e} can only be used on routes that contain a unique "id"`),n.route.id}function TP(){return wP(`useRouteId`)}function EP(){let e=SP(`useNavigation`);return z.useMemo(()=>{let{matches:t,historyAction:n,...r}=e.navigation;return r},[e.navigation])}function DP(){let{matches:e,loaderData:t}=SP(`useMatches`);return z.useMemo(()=>e.map(e=>tN(e,t)),[e,t])}function OP(){let e=z.useContext(XN),t=SP(`useRouteError`),n=wP(`useRouteError`);return e===void 0?t.errors?.[n]:e}function kP(){let{router:e}=xP(`useNavigate`),t=wP(`useNavigate`),n=z.useRef(!1);return oP(()=>{n.current=!0}),z.useCallback(async(r,i={})=>{GM(n.current,aP),n.current&&(typeof r==`number`?await e.navigate(r):await e.navigate(r,{fromRouteId:t,...i}))},[e,t])}var AP={};function jP(e,t,n){!t&&!AP[e]&&(AP[e]=!0,GM(!1,n))}z.memo(MP);function MP({routes:e,manifest:t,future:n,state:r,isStatic:i,onError:a}){return fP(e,void 0,{manifest:t,state:r,isStatic:i,onError:a,future:n})}function NP(e){WM(!1,`A <Route> is only ever to be used as the child of <Routes> element, never rendered directly. Please wrap your <Route> in a <Routes>.`)}function PP({basename:e=`/`,children:t=null,location:n,navigationType:r=`POP`,navigator:i,static:a=!1,useTransitions:o}){WM(!rP(),`You cannot render a <Router> inside another <Router>. You should never have more than one in your app.`);let s=e.replace(/^\/*/,`/`),c=z.useMemo(()=>({basename:s,navigator:i,static:a,useTransitions:o,future:{}}),[s,i,a,o]);typeof n==`string`&&(n=XM(n));let{pathname:l=`/`,search:u=``,hash:d=``,state:f=null,key:p=`default`,mask:m}=n,h=z.useMemo(()=>{let e=yN(l,s);return e==null?null:{location:{pathname:e,search:u,hash:d,state:f,key:p,mask:m},navigationType:r}},[s,l,u,d,f,p,r,m]);return GM(h!=null,`<Router basename="${s}"> is not able to match the URL "${l}${u}${d}" because it does not start with the basename, so the <Router> won't render anything.`),h==null?null:z.createElement(qN.Provider,{value:c},z.createElement(JN.Provider,{children:t,value:h}))}function FP({children:e,location:t}){return dP(IP(e),t)}z.Component;function IP(e,t=[]){let n=[];return z.Children.forEach(e,(e,r)=>{if(!z.isValidElement(e))return;let i=[...t,r];if(e.type===z.Fragment){n.push.apply(n,IP(e.props.children,i));return}WM(e.type===NP,`[${typeof e.type==`string`?e.type:e.type.name}] is not a <Route> component. All component children of <Routes> must be a <Route> or <React.Fragment>`),WM(!e.props.index||!e.props.children,`An index route cannot have child routes.`);let a={id:e.props.id||i.join(`-`),caseSensitive:e.props.caseSensitive,element:e.props.element,Component:e.props.Component,index:e.props.index,path:e.props.path,middleware:e.props.middleware,loader:e.props.loader,action:e.props.action,hydrateFallbackElement:e.props.hydrateFallbackElement,HydrateFallback:e.props.HydrateFallback,errorElement:e.props.errorElement,ErrorBoundary:e.props.ErrorBoundary,hasErrorBoundary:e.props.hasErrorBoundary===!0||e.props.ErrorBoundary!=null||e.props.errorElement!=null,shouldRevalidate:e.props.shouldRevalidate,handle:e.props.handle,lazy:e.props.lazy};e.props.children&&(a.children=IP(e.props.children,i)),n.push(a)}),n}var LP=`get`,RP=`application/x-www-form-urlencoded`;function zP(e){return typeof HTMLElement<`u`&&e instanceof HTMLElement}function BP(e){return zP(e)&&e.tagName.toLowerCase()===`button`}function VP(e){return zP(e)&&e.tagName.toLowerCase()===`form`}function HP(e){return zP(e)&&e.tagName.toLowerCase()===`input`}function UP(e){return!!(e.metaKey||e.altKey||e.ctrlKey||e.shiftKey)}function WP(e,t){return e.button===0&&(!t||t===`_self`)&&!UP(e)}function GP(e=``){return new URLSearchParams(typeof e==`string`||Array.isArray(e)||e instanceof URLSearchParams?e:Object.keys(e).reduce((t,n)=>{let r=e[n];return t.concat(Array.isArray(r)?r.map(e=>[n,e]):[[n,r]])},[]))}function KP(e,t){let n=GP(e);return t&&t.forEach((e,r)=>{n.has(r)||t.getAll(r).forEach(e=>{n.append(r,e)})}),n}var qP=null;function JP(){if(qP===null)try{new FormData(document.createElement(`form`),0),qP=!1}catch{qP=!0}return qP}var YP=new Set([`application/x-www-form-urlencoded`,`multipart/form-data`,`text/plain`]);function XP(e){return e!=null&&!YP.has(e)?(GM(!1,`"${e}" is not a valid \`encType\` for \`<Form>\`/\`<fetcher.Form>\` and will default to "${RP}"`),null):e}function ZP(e,t){let n,r,i,a,o;if(VP(e)){let o=e.getAttribute(`action`);r=o?yN(o,t):null,n=e.getAttribute(`method`)||LP,i=XP(e.getAttribute(`enctype`))||RP,a=new FormData(e)}else if(BP(e)||HP(e)&&(e.type===`submit`||e.type===`image`)){let o=e.form;if(o==null)throw Error(`Cannot submit a <button> or <input type="submit"> without a <form>`);let s=e.getAttribute(`formaction`)||o.getAttribute(`action`);if(r=s?yN(s,t):null,n=e.getAttribute(`formmethod`)||o.getAttribute(`method`)||LP,i=XP(e.getAttribute(`formenctype`))||XP(o.getAttribute(`enctype`))||RP,a=new FormData(o,e),!JP()){let{name:t,type:n,value:r}=e;if(n===`image`){let e=t?`${t}.`:``;a.append(`${e}x`,`0`),a.append(`${e}y`,`0`)}else t&&a.append(t,r)}}else if(zP(e))throw Error(`Cannot submit element that is not <form>, <button>, or <input type="submit|image">`);else n=LP,r=null,i=RP,o=e;return a&&i===`text/plain`&&(o=a,a=void 0),{action:r,method:n.toLowerCase(),encType:i,formData:a,body:o}}Object.getOwnPropertyNames(Object.prototype).sort().join(`\0`);var QP={"&":`\\u0026`,">":`\\u003e`,"<":`\\u003c`,"\u2028":`\\u2028`,"\u2029":`\\u2029`},$P=/[&><\u2028\u2029]/g;function eF(e){return e.replace($P,e=>QP[e])}function tF(e,t){if(e===!1||e==null)throw Error(t)}function nF(e,t,n,r){let i=typeof e==`string`?new URL(e,typeof window>`u`?`server://singlefetch/`:window.location.origin):e;return n?i.pathname.endsWith(`/`)?i.pathname=`${i.pathname}_.${r}`:i.pathname=`${i.pathname}.${r}`:i.pathname===`/`?i.pathname=`_root.${r}`:t&&yN(i.pathname,t)===`/`?i.pathname=`${kN(t)}/_root.${r}`:i.pathname=`${kN(i.pathname)}.${r}`,i}async function rF(e,t){if(e.id in t)return t[e.id];try{let n=await lS(()=>import(e.module),[]);return t[e.id]=n,n}catch(t){return console.error(`Error loading route module \`${e.module}\`, reloading page...`),console.error(t),window.__reactRouterContext&&window.__reactRouterContext.isSpaMode,window.location.reload(),new Promise(()=>{})}}function iF(e){return e!=null&&typeof e.page==`string`}function aF(e){return e==null?!1:e.href==null?e.rel===`preload`&&typeof e.imageSrcSet==`string`&&typeof e.imageSizes==`string`:typeof e.rel==`string`&&typeof e.href==`string`}async function oF(e,t,n){return dF((await Promise.all(e.map(async e=>{let r=t.routes[e.route.id];if(r){let e=await rF(r,n);return e.links?e.links():[]}return[]}))).flat(1).filter(aF).filter(e=>e.rel===`stylesheet`||e.rel===`preload`).map(e=>e.rel===`stylesheet`?{...e,rel:`prefetch`,as:`style`}:{...e,rel:`prefetch`}))}function sF(e,t,n,r,i,a){let o=(e,t)=>n[t]?e.route.id!==n[t].route.id:!0,s=(e,t)=>n[t].pathname!==e.pathname||n[t].route.path?.endsWith(`*`)&&n[t].params[`*`]!==e.params[`*`];return a===`assets`?t.filter((e,t)=>o(e,t)||s(e,t)):a===`data`?t.filter((t,a)=>{let c=r.routes[t.route.id];if(!c||!c.hasLoader)return!1;if(o(t,a)||s(t,a))return!0;if(t.route.shouldRevalidate){let r=t.route.shouldRevalidate({currentUrl:new URL(i.pathname+i.search+i.hash,window.origin),currentParams:n[0]?.params||{},nextUrl:new URL(e,window.origin),nextParams:t.params,defaultShouldRevalidate:!0});if(typeof r==`boolean`)return r}return!0}):[]}function cF(e,t,{includeHydrateFallback:n}={}){return lF(e.map(e=>{let r=t.routes[e.route.id];if(!r)return[];let i=[r.module];return r.clientActionModule&&(i=i.concat(r.clientActionModule)),r.clientLoaderModule&&(i=i.concat(r.clientLoaderModule)),n&&r.hydrateFallbackModule&&(i=i.concat(r.hydrateFallbackModule)),r.imports&&(i=i.concat(r.imports)),i}).flat(1))}function lF(e){return[...new Set(e)]}function uF(e){let t={},n=Object.keys(e).sort();for(let r of n)t[r]=e[r];return t}function dF(e,t){let n=new Set,r=new Set(t);return e.reduce((e,i)=>{if(t&&!iF(i)&&i.as===`script`&&i.href&&r.has(i.href))return e;let a=JSON.stringify(uF(i));return n.has(a)||(n.add(a),e.push({key:a,link:i})),e},[])}function fF(){let e=z.useContext(BN);return tF(e,`You must render this element inside a <DataRouterContext.Provider> element`),e}function pF(){let e=z.useContext(VN);return tF(e,`You must render this element inside a <DataRouterStateContext.Provider> element`),e}var mF=z.createContext(void 0);mF.displayName=`FrameworkContext`;function hF(){let e=z.useContext(mF);return tF(e,`You must render this element inside a <HydratedRouter> element`),e}function gF(e,t){let n=z.useContext(mF),[r,i]=z.useState(!1),[a,o]=z.useState(!1),{onFocus:s,onBlur:c,onMouseEnter:l,onMouseLeave:u,onTouchStart:d}=t,f=z.useRef(null);z.useEffect(()=>{if(e===`render`&&o(!0),e===`viewport`){let e=new IntersectionObserver(e=>{e.forEach(e=>{o(e.isIntersecting)})},{threshold:.5});return f.current&&e.observe(f.current),()=>{e.disconnect()}}},[e]),z.useEffect(()=>{if(r){let e=setTimeout(()=>{o(!0)},100);return()=>{clearTimeout(e)}}},[r]);let p=()=>{i(!0)},m=()=>{i(!1),o(!1)};return n?e===`intent`?[a,f,{onFocus:_F(s,p),onBlur:_F(c,m),onMouseEnter:_F(l,p),onMouseLeave:_F(u,m),onTouchStart:_F(d,p)}]:[a,f,{}]:[!1,f,{}]}function _F(e,t){return n=>{e&&e(n),n.defaultPrevented||t(n)}}function vF({page:e,...t}){let n=UN(),{router:r}=fF(),i=z.useMemo(()=>$M(r.routes,e,r.basename),[r.routes,e,r.basename]);return i?n?z.createElement(bF,{page:e,matches:i,...t}):z.createElement(xF,{page:e,matches:i,...t}):null}function yF(e){let{manifest:t,routeModules:n}=hF(),[r,i]=z.useState([]);return z.useEffect(()=>{let r=!1;return oF(e,t,n).then(e=>{r||i(e)}),()=>{r=!0}},[e,t,n]),r}function bF({page:e,matches:t,...n}){let r=iP(),{future:i}=hF(),{basename:a}=fF(),o=z.useMemo(()=>{if(e===r.pathname+r.search+r.hash)return[];let n=nF(e,a,i.v8_trailingSlashAwareDataRequests,`rsc`),o=!1,s=[];for(let e of t)typeof e.route.shouldRevalidate==`function`?o=!0:s.push(e.route.id);return o&&s.length>0&&n.searchParams.set(`_routes`,s.join(`,`)),[n.pathname+n.search]},[a,i.v8_trailingSlashAwareDataRequests,e,r,t]);return z.createElement(z.Fragment,null,o.map(e=>z.createElement(`link`,{key:e,rel:`prefetch`,as:`fetch`,href:e,...n})))}function xF({page:e,matches:t,...n}){let r=iP(),{future:i,manifest:a,routeModules:o}=hF(),{basename:s}=fF(),{loaderData:c,matches:l}=pF(),u=z.useMemo(()=>sF(e,t,l,a,r,`data`),[e,t,l,a,r]),d=z.useMemo(()=>sF(e,t,l,a,r,`assets`),[e,t,l,a,r]),f=z.useMemo(()=>{if(e===r.pathname+r.search+r.hash)return[];let n=new Set,l=!1;if(t.forEach(e=>{let t=a.routes[e.route.id];!t||!t.hasLoader||(!u.some(t=>t.route.id===e.route.id)&&e.route.id in c&&o[e.route.id]?.shouldRevalidate||t.hasClientLoader?l=!0:n.add(e.route.id))}),n.size===0)return[];let d=nF(e,s,i.v8_trailingSlashAwareDataRequests,`data`);return l&&n.size>0&&d.searchParams.set(`_routes`,t.filter(e=>n.has(e.route.id)).map(e=>e.route.id).join(`,`)),[d.pathname+d.search]},[s,i.v8_trailingSlashAwareDataRequests,c,r,a,u,t,e,o]),p=z.useMemo(()=>cF(d,a),[d,a]),m=yF(d);return z.createElement(z.Fragment,null,f.map(e=>z.createElement(`link`,{key:e,rel:`prefetch`,as:`fetch`,href:e,...n})),p.map(e=>z.createElement(`link`,{key:e,rel:`modulepreload`,href:e,...n})),m.map(({key:e,link:t})=>z.createElement(`link`,{key:e,nonce:n.nonce,...t,crossOrigin:t.crossOrigin??n.crossOrigin})))}function SF(...e){return t=>{e.forEach(e=>{typeof e==`function`?e(t):e!=null&&(e.current=t)})}}z.Component;var CF=typeof window<`u`&&window.document!==void 0&&window.document.createElement!==void 0;try{CF&&(window.__reactRouterVersion=`7.16.0`)}catch{}function wF({basename:e,children:t,useTransitions:n,window:r}){let i=z.useRef();i.current??=UM({window:r,v5Compat:!0});let a=i.current,[o,s]=z.useState({action:a.action,location:a.location}),c=z.useCallback(e=>{n===!1?s(e):z.startTransition(()=>s(e))},[n]);return z.useLayoutEffect(()=>a.listen(c),[a,c]),z.createElement(PP,{basename:e,children:t,location:o.location,navigationType:o.action,navigator:a,useTransitions:n})}function TF({basename:e,children:t,history:n,useTransitions:r}){let[i,a]=z.useState({action:n.action,location:n.location}),o=z.useCallback(e=>{r===!1?a(e):z.startTransition(()=>a(e))},[r]);return z.useLayoutEffect(()=>n.listen(o),[n,o]),z.createElement(PP,{basename:e,children:t,location:i.location,navigationType:i.action,navigator:n,useTransitions:r})}TF.displayName=`unstable_HistoryRouter`;var EF=/^(?:[a-z][a-z0-9+.-]*:|\/\/)/i,DF=z.forwardRef(function({onClick:e,discover:t=`render`,prefetch:n=`none`,relative:r,reloadDocument:i,replace:a,mask:o,state:s,target:c,to:l,preventScrollReset:u,viewTransition:d,defaultShouldRevalidate:f,...p},m){let{basename:h,navigator:g,useTransitions:_}=z.useContext(qN),v=typeof l==`string`&&EF.test(l),y=LN(l,h);l=y.to;let b=nP(l,{relative:r}),x=iP(),S=null;if(o){let e=EN(o,[],x.mask?x.mask.pathname:`/`,!0);h!==`/`&&(e.pathname=e.pathname===`/`?h:ON([h,e.pathname])),S=g.createHref(e)}let[C,w,T]=gF(n,p),E=PF(l,{replace:a,mask:o,state:s,target:c,preventScrollReset:u,relative:r,viewTransition:d,defaultShouldRevalidate:f,useTransitions:_});function ee(t){e&&e(t),t.defaultPrevented||E(t)}let D=!(y.isExternal||i),te=z.createElement(`a`,{...p,...T,href:(D?S:void 0)||y.absoluteURL||b,onClick:D?ee:e,ref:SF(m,w),target:c,"data-discover":!v&&t===`render`?`true`:void 0});return C&&!v?z.createElement(z.Fragment,null,te,z.createElement(vF,{page:b})):te});DF.displayName=`Link`;var OF=z.forwardRef(function({"aria-current":e=`page`,caseSensitive:t=!1,className:n=``,end:r=!1,style:i,to:a,viewTransition:o,children:s,...c},l){let u=uP(a,{relative:c.relative}),d=iP(),f=z.useContext(VN),{navigator:p,basename:m}=z.useContext(qN),h=f!=null&&GF(u)&&o===!0,g=p.encodeLocation?p.encodeLocation(u).pathname:u.pathname,_=d.pathname,v=f&&f.navigation&&f.navigation.location?f.navigation.location.pathname:null;t||(_=_.toLowerCase(),v=v?v.toLowerCase():null,g=g.toLowerCase()),v&&m&&(v=yN(v,m)||v);let y=g!==`/`&&g.endsWith(`/`)?g.length-1:g.length,b=_===g||!r&&_.startsWith(g)&&_.charAt(y)===`/`,x=v!=null&&(v===g||!r&&v.startsWith(g)&&v.charAt(g.length)===`/`),S={isActive:b,isPending:x,isTransitioning:h},C=b?e:void 0,w;w=typeof n==`function`?n(S):[n,b?`active`:null,x?`pending`:null,h?`transitioning`:null].filter(Boolean).join(` `);let T=typeof i==`function`?i(S):i;return z.createElement(DF,{...c,"aria-current":C,className:w,ref:l,style:T,to:a,viewTransition:o},typeof s==`function`?s(S):s)});OF.displayName=`NavLink`;var kF=z.forwardRef(({discover:e=`render`,fetcherKey:t,navigate:n,reloadDocument:r,replace:i,state:a,method:o=LP,action:s,onSubmit:c,relative:l,preventScrollReset:u,viewTransition:d,defaultShouldRevalidate:f,...p},m)=>{let{useTransitions:h}=z.useContext(qN),g=RF(),_=zF(s,{relative:l}),v=o.toLowerCase()===`get`?`get`:`post`,y=typeof s==`string`&&EF.test(s);return z.createElement(`form`,{ref:m,method:v,action:_,onSubmit:r?c:e=>{if(c&&c(e),e.defaultPrevented)return;e.preventDefault();let r=e.nativeEvent.submitter,s=r?.getAttribute(`formmethod`)||o,p=()=>g(r||e.currentTarget,{fetcherKey:t,method:s,navigate:n,replace:i,state:a,relative:l,preventScrollReset:u,viewTransition:d,defaultShouldRevalidate:f});h&&n!==!1?z.startTransition(()=>p()):p()},...p,"data-discover":!y&&e===`render`?`true`:void 0})});kF.displayName=`Form`;function AF({getKey:e,storageKey:t,...n}){let r=z.useContext(mF),{basename:i}=z.useContext(qN),a=iP(),o=DP();UF({getKey:e,storageKey:t});let s=z.useMemo(()=>{if(!r||!e)return null;let t=HF(a,o,i,e);return t===a.key?null:t},[]);if(!r||r.isSpaMode)return null;let c=((e,t)=>{if(!window.history.state||!window.history.state.key){let e=Math.random().toString(32).slice(2);window.history.replaceState({key:e},``)}try{let n=JSON.parse(sessionStorage.getItem(e)||`{}`)[t||window.history.state.key];typeof n==`number`&&window.scrollTo(0,n)}catch(t){console.error(t),sessionStorage.removeItem(e)}}).toString();return z.createElement(`script`,{...n,suppressHydrationWarning:!0,dangerouslySetInnerHTML:{__html:`(${c})(${eF(JSON.stringify(t||BF))}, ${eF(JSON.stringify(s))})`}})}AF.displayName=`ScrollRestoration`;function jF(e){return`${e} must be used within a data router. See https://reactrouter.com/en/main/routers/picking-a-router.`}function MF(e){let t=z.useContext(BN);return WM(t,jF(e)),t}function NF(e){let t=z.useContext(VN);return WM(t,jF(e)),t}function PF(e,{target:t,replace:n,mask:r,state:i,preventScrollReset:a,relative:o,viewTransition:s,defaultShouldRevalidate:c,useTransitions:l}={}){let u=sP(),d=iP(),f=uP(e,{relative:o});return z.useCallback(p=>{if(WP(p,t)){p.preventDefault();let t=n===void 0?YM(d)===YM(f):n,m=()=>u(e,{replace:t,mask:r,state:i,preventScrollReset:a,relative:o,viewTransition:s,defaultShouldRevalidate:c});l?z.startTransition(()=>m()):m()}},[d,u,f,n,r,i,t,e,a,o,s,c,l])}function FF(e){GM(typeof URLSearchParams<`u`,"You cannot use the `useSearchParams` hook in a browser that does not support the URLSearchParams API. If you need to support Internet Explorer 11, we recommend you load a polyfill such as https://github.com/ungap/url-search-params.");let t=z.useRef(GP(e)),n=z.useRef(!1),r=iP(),i=z.useMemo(()=>KP(r.search,n.current?null:t.current),[r.search]),a=sP();return[i,z.useCallback((e,t)=>{let r=GP(typeof e==`function`?e(new URLSearchParams(i)):e);n.current=!0,a(`?`+r,t)},[a,i])]}var IF=0,LF=()=>`__${String(++IF)}__`;function RF(){let{router:e}=MF(`useSubmit`),{basename:t}=z.useContext(qN),n=TP(),r=e.fetch,i=e.navigate;return z.useCallback(async(e,a={})=>{let{action:o,method:s,encType:c,formData:l,body:u}=ZP(e,t);a.navigate===!1?await r(a.fetcherKey||LF(),n,a.action||o,{defaultShouldRevalidate:a.defaultShouldRevalidate,preventScrollReset:a.preventScrollReset,formData:l,body:u,formMethod:a.method||s,formEncType:a.encType||c,flushSync:a.flushSync}):await i(a.action||o,{defaultShouldRevalidate:a.defaultShouldRevalidate,preventScrollReset:a.preventScrollReset,formData:l,body:u,formMethod:a.method||s,formEncType:a.encType||c,replace:a.replace,state:a.state,fromRouteId:n,flushSync:a.flushSync,viewTransition:a.viewTransition})},[r,i,t,n])}function zF(e,{relative:t}={}){let{basename:n}=z.useContext(qN),r=z.useContext(YN);WM(r,`useFormAction must be used inside a RouteContext`);let[i]=r.matches.slice(-1),a={...uP(e||`.`,{relative:t})},o=iP();if(e==null){a.search=o.search;let e=new URLSearchParams(a.search),t=e.getAll(`index`);if(t.some(e=>e===``)){e.delete(`index`),t.filter(e=>e).forEach(t=>e.append(`index`,t));let n=e.toString();a.search=n?`?${n}`:``}}return(!e||e===`.`)&&i.route.index&&(a.search=a.search?a.search.replace(/^\?/,`?index&`):`?index`),n!==`/`&&(a.pathname=a.pathname===`/`?n:ON([n,a.pathname])),YM(a)}var BF=`react-router-scroll-positions`,VF={};function HF(e,t,n,r){let i=null;return r&&(i=r(n===`/`?e:{...e,pathname:yN(e.pathname,n)||e.pathname},t)),i??=e.key,i}function UF({getKey:e,storageKey:t}={}){let{router:n}=MF(`useScrollRestoration`),{restoreScrollPosition:r,preventScrollReset:i}=NF(`useScrollRestoration`),{basename:a}=z.useContext(qN),o=iP(),s=DP(),c=EP();z.useEffect(()=>(window.history.scrollRestoration=`manual`,()=>{window.history.scrollRestoration=`auto`}),[]),WF(z.useCallback(()=>{if(c.state===`idle`){let t=HF(o,s,a,e);VF[t]=window.scrollY}try{sessionStorage.setItem(t||BF,JSON.stringify(VF))}catch(e){GM(!1,`Failed to save scroll positions in sessionStorage, <ScrollRestoration /> will not work properly (${e}).`)}window.history.scrollRestoration=`auto`},[c.state,e,a,o,s,t])),typeof document<`u`&&(z.useLayoutEffect(()=>{try{let e=sessionStorage.getItem(t||BF);e&&(VF=JSON.parse(e))}catch{}},[t]),z.useLayoutEffect(()=>{let t=n?.enableScrollRestoration(VF,()=>window.scrollY,e?(t,n)=>HF(t,n,a,e):void 0);return()=>t&&t()},[n,a,e]),z.useLayoutEffect(()=>{if(r!==!1){if(typeof r==`number`){window.scrollTo(0,r);return}try{if(o.hash){let e=document.getElementById(decodeURIComponent(o.hash.slice(1)));if(e){e.scrollIntoView();return}}}catch{GM(!1,`"${o.hash.slice(1)}" is not a decodable element ID. The view will not scroll to it.`)}i!==!0&&window.scrollTo(0,0)}},[o,r,i]))}function WF(e,t){let{capture:n}=t||{};z.useEffect(()=>{let t=n==null?void 0:{capture:n};return window.addEventListener(`pagehide`,e,t),()=>{window.removeEventListener(`pagehide`,e,t)}},[e,n])}function GF(e,{relative:t}={}){let n=z.useContext(WN);WM(n!=null,"`useViewTransitionState` must be used within `react-router-dom`'s `RouterProvider`. Did you accidentally import `RouterProvider` from `react-router`?");let{basename:r}=MF(`useViewTransitionState`),i=uP(e,{relative:t});if(!n.isTransitioning)return!1;let a=yN(n.currentLocation.pathname,r)||n.currentLocation.pathname,o=yN(n.nextLocation.pathname,r)||n.nextLocation.pathname;return gN(i.pathname,o)!=null||gN(i.pathname,a)!=null}function KF(e){if(!e||typeof document>`u`)return;let t=document.head||document.getElementsByTagName(`head`)[0],n=document.createElement(`style`);n.type=`text/css`,t.appendChild(n),n.styleSheet?n.styleSheet.cssText=e:n.appendChild(document.createTextNode(e))}var qF=e=>{switch(e){case`success`:return XF;case`info`:return QF;case`warning`:return ZF;case`error`:return $F;default:return null}},JF=Array(12).fill(0),YF=({visible:e,className:t})=>z.createElement(`div`,{className:[`sonner-loading-wrapper`,t].filter(Boolean).join(` `),"data-visible":e},z.createElement(`div`,{className:`sonner-spinner`},JF.map((e,t)=>z.createElement(`div`,{className:`sonner-loading-bar`,key:`spinner-bar-${t}`})))),XF=z.createElement(`svg`,{xmlns:`http://www.w3.org/2000/svg`,viewBox:`0 0 20 20`,fill:`currentColor`,height:`20`,width:`20`},z.createElement(`path`,{fillRule:`evenodd`,d:`M10 18a8 8 0 100-16 8 8 0 000 16zm3.857-9.809a.75.75 0 00-1.214-.882l-3.483 4.79-1.88-1.88a.75.75 0 10-1.06 1.061l2.5 2.5a.75.75 0 001.137-.089l4-5.5z`,clipRule:`evenodd`})),ZF=z.createElement(`svg`,{xmlns:`http://www.w3.org/2000/svg`,viewBox:`0 0 24 24`,fill:`currentColor`,height:`20`,width:`20`},z.createElement(`path`,{fillRule:`evenodd`,d:`M9.401 3.003c1.155-2 4.043-2 5.197 0l7.355 12.748c1.154 2-.29 4.5-2.599 4.5H4.645c-2.309 0-3.752-2.5-2.598-4.5L9.4 3.003zM12 8.25a.75.75 0 01.75.75v3.75a.75.75 0 01-1.5 0V9a.75.75 0 01.75-.75zm0 8.25a.75.75 0 100-1.5.75.75 0 000 1.5z`,clipRule:`evenodd`})),QF=z.createElement(`svg`,{xmlns:`http://www.w3.org/2000/svg`,viewBox:`0 0 20 20`,fill:`currentColor`,height:`20`,width:`20`},z.createElement(`path`,{fillRule:`evenodd`,d:`M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7-4a1 1 0 11-2 0 1 1 0 012 0zM9 9a.75.75 0 000 1.5h.253a.25.25 0 01.244.304l-.459 2.066A1.75 1.75 0 0010.747 15H11a.75.75 0 000-1.5h-.253a.25.25 0 01-.244-.304l.459-2.066A1.75 1.75 0 009.253 9H9z`,clipRule:`evenodd`})),$F=z.createElement(`svg`,{xmlns:`http://www.w3.org/2000/svg`,viewBox:`0 0 20 20`,fill:`currentColor`,height:`20`,width:`20`},z.createElement(`path`,{fillRule:`evenodd`,d:`M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-8-5a.75.75 0 01.75.75v4.5a.75.75 0 01-1.5 0v-4.5A.75.75 0 0110 5zm0 10a1 1 0 100-2 1 1 0 000 2z`,clipRule:`evenodd`})),eI=z.createElement(`svg`,{xmlns:`http://www.w3.org/2000/svg`,width:`12`,height:`12`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`1.5`,strokeLinecap:`round`,strokeLinejoin:`round`},z.createElement(`line`,{x1:`18`,y1:`6`,x2:`6`,y2:`18`}),z.createElement(`line`,{x1:`6`,y1:`6`,x2:`18`,y2:`18`})),tI=()=>{let[e,t]=z.useState(document.hidden);return z.useEffect(()=>{let e=()=>{t(document.hidden)};return document.addEventListener(`visibilitychange`,e),()=>window.removeEventListener(`visibilitychange`,e)},[]),e},nI=1,rI=new class{constructor(){this.subscribe=e=>(this.subscribers.push(e),()=>{let t=this.subscribers.indexOf(e);this.subscribers.splice(t,1)}),this.publish=e=>{this.subscribers.forEach(t=>t(e))},this.addToast=e=>{this.publish(e),this.toasts=[...this.toasts,e]},this.create=e=>{let{message:t,...n}=e,r=typeof e?.id==`number`||e.id?.length>0?e.id:nI++,i=this.toasts.find(e=>e.id===r),a=e.dismissible===void 0?!0:e.dismissible;return this.dismissedToasts.has(r)&&this.dismissedToasts.delete(r),i?this.toasts=this.toasts.map(n=>n.id===r?(this.publish({...n,...e,id:r,title:t}),{...n,...e,id:r,dismissible:a,title:t}):n):this.addToast({title:t,...n,dismissible:a,id:r}),r},this.dismiss=e=>(e?(this.dismissedToasts.add(e),requestAnimationFrame(()=>this.subscribers.forEach(t=>t({id:e,dismiss:!0})))):this.toasts.forEach(e=>{this.subscribers.forEach(t=>t({id:e.id,dismiss:!0}))}),e),this.message=(e,t)=>this.create({...t,message:e}),this.error=(e,t)=>this.create({...t,message:e,type:`error`}),this.success=(e,t)=>this.create({...t,type:`success`,message:e}),this.info=(e,t)=>this.create({...t,type:`info`,message:e}),this.warning=(e,t)=>this.create({...t,type:`warning`,message:e}),this.loading=(e,t)=>this.create({...t,type:`loading`,message:e}),this.promise=(e,t)=>{if(!t)return;let n;t.loading!==void 0&&(n=this.create({...t,promise:e,type:`loading`,message:t.loading,description:typeof t.description==`function`?void 0:t.description}));let r=Promise.resolve(e instanceof Function?e():e),i=n!==void 0,a,o=r.then(async e=>{if(a=[`resolve`,e],z.isValidElement(e))i=!1,this.create({id:n,type:`default`,message:e});else if(aI(e)&&!e.ok){i=!1;let r=typeof t.error==`function`?await t.error(`HTTP error! status: ${e.status}`):t.error,a=typeof t.description==`function`?await t.description(`HTTP error! status: ${e.status}`):t.description,o=typeof r==`object`&&!z.isValidElement(r)?r:{message:r};this.create({id:n,type:`error`,description:a,...o})}else if(e instanceof Error){i=!1;let r=typeof t.error==`function`?await t.error(e):t.error,a=typeof t.description==`function`?await t.description(e):t.description,o=typeof r==`object`&&!z.isValidElement(r)?r:{message:r};this.create({id:n,type:`error`,description:a,...o})}else if(t.success!==void 0){i=!1;let r=typeof t.success==`function`?await t.success(e):t.success,a=typeof t.description==`function`?await t.description(e):t.description,o=typeof r==`object`&&!z.isValidElement(r)?r:{message:r};this.create({id:n,type:`success`,description:a,...o})}}).catch(async e=>{if(a=[`reject`,e],t.error!==void 0){i=!1;let r=typeof t.error==`function`?await t.error(e):t.error,a=typeof t.description==`function`?await t.description(e):t.description,o=typeof r==`object`&&!z.isValidElement(r)?r:{message:r};this.create({id:n,type:`error`,description:a,...o})}}).finally(()=>{i&&(this.dismiss(n),n=void 0),t.finally==null||t.finally.call(t)}),s=()=>new Promise((e,t)=>o.then(()=>a[0]===`reject`?t(a[1]):e(a[1])).catch(t));return typeof n!=`string`&&typeof n!=`number`?{unwrap:s}:Object.assign(n,{unwrap:s})},this.custom=(e,t)=>{let n=t?.id||nI++;return this.create({jsx:e(n),id:n,...t}),n},this.getActiveToasts=()=>this.toasts.filter(e=>!this.dismissedToasts.has(e.id)),this.subscribers=[],this.toasts=[],this.dismissedToasts=new Set}},iI=(e,t)=>{let n=t?.id||nI++;return rI.addToast({title:e,...t,id:n}),n},aI=e=>e&&typeof e==`object`&&`ok`in e&&typeof e.ok==`boolean`&&`status`in e&&typeof e.status==`number`,oI=Object.assign(iI,{success:rI.success,info:rI.info,warning:rI.warning,error:rI.error,custom:rI.custom,message:rI.message,promise:rI.promise,dismiss:rI.dismiss,loading:rI.loading},{getHistory:()=>rI.toasts,getToasts:()=>rI.getActiveToasts()});KF(`[data-sonner-toaster][dir=ltr],html[dir=ltr]{--toast-icon-margin-start:-3px;--toast-icon-margin-end:4px;--toast-svg-margin-start:-1px;--toast-svg-margin-end:0px;--toast-button-margin-start:auto;--toast-button-margin-end:0;--toast-close-button-start:0;--toast-close-button-end:unset;--toast-close-button-transform:translate(-35%, -35%)}[data-sonner-toaster][dir=rtl],html[dir=rtl]{--toast-icon-margin-start:4px;--toast-icon-margin-end:-3px;--toast-svg-margin-start:0px;--toast-svg-margin-end:-1px;--toast-button-margin-start:0;--toast-button-margin-end:auto;--toast-close-button-start:unset;--toast-close-button-end:0;--toast-close-button-transform:translate(35%, -35%)}[data-sonner-toaster]{position:fixed;width:var(--width);font-family:ui-sans-serif,system-ui,-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Helvetica Neue,Arial,Noto Sans,sans-serif,Apple Color Emoji,Segoe UI Emoji,Segoe UI Symbol,Noto Color Emoji;--gray1:hsl(0, 0%, 99%);--gray2:hsl(0, 0%, 97.3%);--gray3:hsl(0, 0%, 95.1%);--gray4:hsl(0, 0%, 93%);--gray5:hsl(0, 0%, 90.9%);--gray6:hsl(0, 0%, 88.7%);--gray7:hsl(0, 0%, 85.8%);--gray8:hsl(0, 0%, 78%);--gray9:hsl(0, 0%, 56.1%);--gray10:hsl(0, 0%, 52.3%);--gray11:hsl(0, 0%, 43.5%);--gray12:hsl(0, 0%, 9%);--border-radius:8px;box-sizing:border-box;padding:0;margin:0;list-style:none;outline:0;z-index:999999999;transition:transform .4s ease}@media (hover:none) and (pointer:coarse){[data-sonner-toaster][data-lifted=true]{transform:none}}[data-sonner-toaster][data-x-position=right]{right:var(--offset-right)}[data-sonner-toaster][data-x-position=left]{left:var(--offset-left)}[data-sonner-toaster][data-x-position=center]{left:50%;transform:translateX(-50%)}[data-sonner-toaster][data-y-position=top]{top:var(--offset-top)}[data-sonner-toaster][data-y-position=bottom]{bottom:var(--offset-bottom)}[data-sonner-toast]{--y:translateY(100%);--lift-amount:calc(var(--lift) * var(--gap));z-index:var(--z-index);position:absolute;opacity:0;transform:var(--y);touch-action:none;transition:transform .4s,opacity .4s,height .4s,box-shadow .2s;box-sizing:border-box;outline:0;overflow-wrap:anywhere}[data-sonner-toast][data-styled=true]{padding:16px;background:var(--normal-bg);border:1px solid var(--normal-border);color:var(--normal-text);border-radius:var(--border-radius);box-shadow:0 4px 12px rgba(0,0,0,.1);width:var(--width);font-size:13px;display:flex;align-items:center;gap:6px}[data-sonner-toast]:focus-visible{box-shadow:0 4px 12px rgba(0,0,0,.1),0 0 0 2px rgba(0,0,0,.2)}[data-sonner-toast][data-y-position=top]{top:0;--y:translateY(-100%);--lift:1;--lift-amount:calc(1 * var(--gap))}[data-sonner-toast][data-y-position=bottom]{bottom:0;--y:translateY(100%);--lift:-1;--lift-amount:calc(var(--lift) * var(--gap))}[data-sonner-toast][data-styled=true] [data-description]{font-weight:400;line-height:1.4;color:#3f3f3f}[data-rich-colors=true][data-sonner-toast][data-styled=true] [data-description]{color:inherit}[data-sonner-toaster][data-sonner-theme=dark] [data-description]{color:#e8e8e8}[data-sonner-toast][data-styled=true] [data-title]{font-weight:500;line-height:1.5;color:inherit}[data-sonner-toast][data-styled=true] [data-icon]{display:flex;height:16px;width:16px;position:relative;justify-content:flex-start;align-items:center;flex-shrink:0;margin-left:var(--toast-icon-margin-start);margin-right:var(--toast-icon-margin-end)}[data-sonner-toast][data-promise=true] [data-icon]>svg{opacity:0;transform:scale(.8);transform-origin:center;animation:sonner-fade-in .3s ease forwards}[data-sonner-toast][data-styled=true] [data-icon]>*{flex-shrink:0}[data-sonner-toast][data-styled=true] [data-icon] svg{margin-left:var(--toast-svg-margin-start);margin-right:var(--toast-svg-margin-end)}[data-sonner-toast][data-styled=true] [data-content]{display:flex;flex-direction:column;gap:2px}[data-sonner-toast][data-styled=true] [data-button]{border-radius:4px;padding-left:8px;padding-right:8px;height:24px;font-size:12px;color:var(--normal-bg);background:var(--normal-text);margin-left:var(--toast-button-margin-start);margin-right:var(--toast-button-margin-end);border:none;font-weight:500;cursor:pointer;outline:0;display:flex;align-items:center;flex-shrink:0;transition:opacity .4s,box-shadow .2s}[data-sonner-toast][data-styled=true] [data-button]:focus-visible{box-shadow:0 0 0 2px rgba(0,0,0,.4)}[data-sonner-toast][data-styled=true] [data-button]:first-of-type{margin-left:var(--toast-button-margin-start);margin-right:var(--toast-button-margin-end)}[data-sonner-toast][data-styled=true] [data-cancel]{color:var(--normal-text);background:rgba(0,0,0,.08)}[data-sonner-toaster][data-sonner-theme=dark] [data-sonner-toast][data-styled=true] [data-cancel]{background:rgba(255,255,255,.3)}[data-sonner-toast][data-styled=true] [data-close-button]{position:absolute;left:var(--toast-close-button-start);right:var(--toast-close-button-end);top:0;height:20px;width:20px;display:flex;justify-content:center;align-items:center;padding:0;color:var(--gray12);background:var(--normal-bg);border:1px solid var(--gray4);transform:var(--toast-close-button-transform);border-radius:50%;cursor:pointer;z-index:1;transition:opacity .1s,background .2s,border-color .2s}[data-sonner-toast][data-styled=true] [data-close-button]:focus-visible{box-shadow:0 4px 12px rgba(0,0,0,.1),0 0 0 2px rgba(0,0,0,.2)}[data-sonner-toast][data-styled=true] [data-disabled=true]{cursor:not-allowed}[data-sonner-toast][data-styled=true]:hover [data-close-button]:hover{background:var(--gray2);border-color:var(--gray5)}[data-sonner-toast][data-swiping=true]::before{content:'';position:absolute;left:-100%;right:-100%;height:100%;z-index:-1}[data-sonner-toast][data-y-position=top][data-swiping=true]::before{bottom:50%;transform:scaleY(3) translateY(50%)}[data-sonner-toast][data-y-position=bottom][data-swiping=true]::before{top:50%;transform:scaleY(3) translateY(-50%)}[data-sonner-toast][data-swiping=false][data-removed=true]::before{content:'';position:absolute;inset:0;transform:scaleY(2)}[data-sonner-toast][data-expanded=true]::after{content:'';position:absolute;left:0;height:calc(var(--gap) + 1px);bottom:100%;width:100%}[data-sonner-toast][data-mounted=true]{--y:translateY(0);opacity:1}[data-sonner-toast][data-expanded=false][data-front=false]{--scale:var(--toasts-before) * 0.05 + 1;--y:translateY(calc(var(--lift-amount) * var(--toasts-before))) scale(calc(-1 * var(--scale)));height:var(--front-toast-height)}[data-sonner-toast]>*{transition:opacity .4s}[data-sonner-toast][data-x-position=right]{right:0}[data-sonner-toast][data-x-position=left]{left:0}[data-sonner-toast][data-expanded=false][data-front=false][data-styled=true]>*{opacity:0}[data-sonner-toast][data-visible=false]{opacity:0;pointer-events:none}[data-sonner-toast][data-mounted=true][data-expanded=true]{--y:translateY(calc(var(--lift) * var(--offset)));height:var(--initial-height)}[data-sonner-toast][data-removed=true][data-front=true][data-swipe-out=false]{--y:translateY(calc(var(--lift) * -100%));opacity:0}[data-sonner-toast][data-removed=true][data-front=false][data-swipe-out=false][data-expanded=true]{--y:translateY(calc(var(--lift) * var(--offset) + var(--lift) * -100%));opacity:0}[data-sonner-toast][data-removed=true][data-front=false][data-swipe-out=false][data-expanded=false]{--y:translateY(40%);opacity:0;transition:transform .5s,opacity .2s}[data-sonner-toast][data-removed=true][data-front=false]::before{height:calc(var(--initial-height) + 20%)}[data-sonner-toast][data-swiping=true]{transform:var(--y) translateY(var(--swipe-amount-y,0)) translateX(var(--swipe-amount-x,0));transition:none}[data-sonner-toast][data-swiped=true]{user-select:none}[data-sonner-toast][data-swipe-out=true][data-y-position=bottom],[data-sonner-toast][data-swipe-out=true][data-y-position=top]{animation-duration:.2s;animation-timing-function:ease-out;animation-fill-mode:forwards}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=left]{animation-name:swipe-out-left}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=right]{animation-name:swipe-out-right}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=up]{animation-name:swipe-out-up}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=down]{animation-name:swipe-out-down}@keyframes swipe-out-left{from{transform:var(--y) translateX(var(--swipe-amount-x));opacity:1}to{transform:var(--y) translateX(calc(var(--swipe-amount-x) - 100%));opacity:0}}@keyframes swipe-out-right{from{transform:var(--y) translateX(var(--swipe-amount-x));opacity:1}to{transform:var(--y) translateX(calc(var(--swipe-amount-x) + 100%));opacity:0}}@keyframes swipe-out-up{from{transform:var(--y) translateY(var(--swipe-amount-y));opacity:1}to{transform:var(--y) translateY(calc(var(--swipe-amount-y) - 100%));opacity:0}}@keyframes swipe-out-down{from{transform:var(--y) translateY(var(--swipe-amount-y));opacity:1}to{transform:var(--y) translateY(calc(var(--swipe-amount-y) + 100%));opacity:0}}@media (max-width:600px){[data-sonner-toaster]{position:fixed;right:var(--mobile-offset-right);left:var(--mobile-offset-left);width:100%}[data-sonner-toaster][dir=rtl]{left:calc(var(--mobile-offset-left) * -1)}[data-sonner-toaster] [data-sonner-toast]{left:0;right:0;width:calc(100% - var(--mobile-offset-left) * 2)}[data-sonner-toaster][data-x-position=left]{left:var(--mobile-offset-left)}[data-sonner-toaster][data-y-position=bottom]{bottom:var(--mobile-offset-bottom)}[data-sonner-toaster][data-y-position=top]{top:var(--mobile-offset-top)}[data-sonner-toaster][data-x-position=center]{left:var(--mobile-offset-left);right:var(--mobile-offset-right);transform:none}}[data-sonner-toaster][data-sonner-theme=light]{--normal-bg:#fff;--normal-border:var(--gray4);--normal-text:var(--gray12);--success-bg:hsl(143, 85%, 96%);--success-border:hsl(145, 92%, 87%);--success-text:hsl(140, 100%, 27%);--info-bg:hsl(208, 100%, 97%);--info-border:hsl(221, 91%, 93%);--info-text:hsl(210, 92%, 45%);--warning-bg:hsl(49, 100%, 97%);--warning-border:hsl(49, 91%, 84%);--warning-text:hsl(31, 92%, 45%);--error-bg:hsl(359, 100%, 97%);--error-border:hsl(359, 100%, 94%);--error-text:hsl(360, 100%, 45%)}[data-sonner-toaster][data-sonner-theme=light] [data-sonner-toast][data-invert=true]{--normal-bg:#000;--normal-border:hsl(0, 0%, 20%);--normal-text:var(--gray1)}[data-sonner-toaster][data-sonner-theme=dark] [data-sonner-toast][data-invert=true]{--normal-bg:#fff;--normal-border:var(--gray3);--normal-text:var(--gray12)}[data-sonner-toaster][data-sonner-theme=dark]{--normal-bg:#000;--normal-bg-hover:hsl(0, 0%, 12%);--normal-border:hsl(0, 0%, 20%);--normal-border-hover:hsl(0, 0%, 25%);--normal-text:var(--gray1);--success-bg:hsl(150, 100%, 6%);--success-border:hsl(147, 100%, 12%);--success-text:hsl(150, 86%, 65%);--info-bg:hsl(215, 100%, 6%);--info-border:hsl(223, 43%, 17%);--info-text:hsl(216, 87%, 65%);--warning-bg:hsl(64, 100%, 6%);--warning-border:hsl(60, 100%, 9%);--warning-text:hsl(46, 87%, 65%);--error-bg:hsl(358, 76%, 10%);--error-border:hsl(357, 89%, 16%);--error-text:hsl(358, 100%, 81%)}[data-sonner-toaster][data-sonner-theme=dark] [data-sonner-toast] [data-close-button]{background:var(--normal-bg);border-color:var(--normal-border);color:var(--normal-text)}[data-sonner-toaster][data-sonner-theme=dark] [data-sonner-toast] [data-close-button]:hover{background:var(--normal-bg-hover);border-color:var(--normal-border-hover)}[data-rich-colors=true][data-sonner-toast][data-type=success]{background:var(--success-bg);border-color:var(--success-border);color:var(--success-text)}[data-rich-colors=true][data-sonner-toast][data-type=success] [data-close-button]{background:var(--success-bg);border-color:var(--success-border);color:var(--success-text)}[data-rich-colors=true][data-sonner-toast][data-type=info]{background:var(--info-bg);border-color:var(--info-border);color:var(--info-text)}[data-rich-colors=true][data-sonner-toast][data-type=info] [data-close-button]{background:var(--info-bg);border-color:var(--info-border);color:var(--info-text)}[data-rich-colors=true][data-sonner-toast][data-type=warning]{background:var(--warning-bg);border-color:var(--warning-border);color:var(--warning-text)}[data-rich-colors=true][data-sonner-toast][data-type=warning] [data-close-button]{background:var(--warning-bg);border-color:var(--warning-border);color:var(--warning-text)}[data-rich-colors=true][data-sonner-toast][data-type=error]{background:var(--error-bg);border-color:var(--error-border);color:var(--error-text)}[data-rich-colors=true][data-sonner-toast][data-type=error] [data-close-button]{background:var(--error-bg);border-color:var(--error-border);color:var(--error-text)}.sonner-loading-wrapper{--size:16px;height:var(--size);width:var(--size);position:absolute;inset:0;z-index:10}.sonner-loading-wrapper[data-visible=false]{transform-origin:center;animation:sonner-fade-out .2s ease forwards}.sonner-spinner{position:relative;top:50%;left:50%;height:var(--size);width:var(--size)}.sonner-loading-bar{animation:sonner-spin 1.2s linear infinite;background:var(--gray11);border-radius:6px;height:8%;left:-10%;position:absolute;top:-3.9%;width:24%}.sonner-loading-bar:first-child{animation-delay:-1.2s;transform:rotate(.0001deg) translate(146%)}.sonner-loading-bar:nth-child(2){animation-delay:-1.1s;transform:rotate(30deg) translate(146%)}.sonner-loading-bar:nth-child(3){animation-delay:-1s;transform:rotate(60deg) translate(146%)}.sonner-loading-bar:nth-child(4){animation-delay:-.9s;transform:rotate(90deg) translate(146%)}.sonner-loading-bar:nth-child(5){animation-delay:-.8s;transform:rotate(120deg) translate(146%)}.sonner-loading-bar:nth-child(6){animation-delay:-.7s;transform:rotate(150deg) translate(146%)}.sonner-loading-bar:nth-child(7){animation-delay:-.6s;transform:rotate(180deg) translate(146%)}.sonner-loading-bar:nth-child(8){animation-delay:-.5s;transform:rotate(210deg) translate(146%)}.sonner-loading-bar:nth-child(9){animation-delay:-.4s;transform:rotate(240deg) translate(146%)}.sonner-loading-bar:nth-child(10){animation-delay:-.3s;transform:rotate(270deg) translate(146%)}.sonner-loading-bar:nth-child(11){animation-delay:-.2s;transform:rotate(300deg) translate(146%)}.sonner-loading-bar:nth-child(12){animation-delay:-.1s;transform:rotate(330deg) translate(146%)}@keyframes sonner-fade-in{0%{opacity:0;transform:scale(.8)}100%{opacity:1;transform:scale(1)}}@keyframes sonner-fade-out{0%{opacity:1;transform:scale(1)}100%{opacity:0;transform:scale(.8)}}@keyframes sonner-spin{0%{opacity:1}100%{opacity:.15}}@media (prefers-reduced-motion){.sonner-loading-bar,[data-sonner-toast],[data-sonner-toast]>*{transition:none!important;animation:none!important}}.sonner-loader{position:absolute;top:50%;left:50%;transform:translate(-50%,-50%);transform-origin:center;transition:opacity .2s,transform .2s}.sonner-loader[data-visible=false]{opacity:0;transform:scale(.8) translate(-50%,-50%)}`);function sI(e){return e.label!==void 0}var cI=3,lI=`24px`,uI=`16px`,dI=4e3,fI=356,pI=14,mI=45,hI=200;function gI(...e){return e.filter(Boolean).join(` `)}function _I(e){let[t,n]=e.split(`-`),r=[];return t&&r.push(t),n&&r.push(n),r}var vI=e=>{let{invert:t,toast:n,unstyled:r,interacting:i,setHeights:a,visibleToasts:o,heights:s,index:c,toasts:l,expanded:u,removeToast:d,defaultRichColors:f,closeButton:p,style:m,cancelButtonStyle:h,actionButtonStyle:g,className:_=``,descriptionClassName:v=``,duration:y,position:b,gap:x,expandByDefault:S,classNames:C,icons:w,closeButtonAriaLabel:T=`Close toast`}=e,[E,ee]=z.useState(null),[D,te]=z.useState(null),[ne,re]=z.useState(!1),[O,ie]=z.useState(!1),[k,A]=z.useState(!1),[j,ae]=z.useState(!1),[oe,se]=z.useState(!1),[ce,M]=z.useState(0),[N,le]=z.useState(0),ue=z.useRef(n.duration||y||dI),de=z.useRef(null),fe=z.useRef(null),pe=c===0,me=c+1<=o,he=n.type,ge=n.dismissible!==!1,_e=n.className||``,ve=n.descriptionClassName||``,ye=z.useMemo(()=>s.findIndex(e=>e.toastId===n.id)||0,[s,n.id]),be=z.useMemo(()=>n.closeButton??p,[n.closeButton,p]),xe=z.useMemo(()=>n.duration||y||dI,[n.duration,y]),P=z.useRef(0),Se=z.useRef(0),Ce=z.useRef(0),we=z.useRef(null),[Te,Ee]=b.split(`-`),De=z.useMemo(()=>s.reduce((e,t,n)=>n>=ye?e:e+t.height,0),[s,ye]),Oe=tI(),ke=n.invert||t,Ae=he===`loading`;Se.current=z.useMemo(()=>ye*x+De,[ye,De]),z.useEffect(()=>{ue.current=xe},[xe]),z.useEffect(()=>{re(!0)},[]),z.useEffect(()=>{let e=fe.current;if(e){let t=e.getBoundingClientRect().height;return le(t),a(e=>[{toastId:n.id,height:t,position:n.position},...e]),()=>a(e=>e.filter(e=>e.toastId!==n.id))}},[a,n.id]),z.useLayoutEffect(()=>{if(!ne)return;let e=fe.current,t=e.style.height;e.style.height=`auto`;let r=e.getBoundingClientRect().height;e.style.height=t,le(r),a(e=>e.find(e=>e.toastId===n.id)?e.map(e=>e.toastId===n.id?{...e,height:r}:e):[{toastId:n.id,height:r,position:n.position},...e])},[ne,n.title,n.description,a,n.id,n.jsx,n.action,n.cancel]);let je=z.useCallback(()=>{ie(!0),M(Se.current),a(e=>e.filter(e=>e.toastId!==n.id)),setTimeout(()=>{d(n)},hI)},[n,d,a,Se]);z.useEffect(()=>{if(n.promise&&he===`loading`||n.duration===1/0||n.type===`loading`)return;let e;return u||i||Oe?(()=>{if(Ce.current<P.current){let e=new Date().getTime()-P.current;ue.current-=e}Ce.current=new Date().getTime()})():ue.current!==1/0&&(P.current=new Date().getTime(),e=setTimeout(()=>{n.onAutoClose==null||n.onAutoClose.call(n,n),je()},ue.current)),()=>clearTimeout(e)},[u,i,n,he,Oe,je]),z.useEffect(()=>{n.delete&&(je(),n.onDismiss==null||n.onDismiss.call(n,n))},[je,n.delete]);function Me(){return w?.loading?z.createElement(`div`,{className:gI(C?.loader,n?.classNames?.loader,`sonner-loader`),"data-visible":he===`loading`},w.loading):z.createElement(YF,{className:gI(C?.loader,n?.classNames?.loader),visible:he===`loading`})}let Ne=n.icon||w?.[he]||qF(he);return z.createElement(`li`,{tabIndex:0,ref:fe,className:gI(_,_e,C?.toast,n?.classNames?.toast,C?.default,C?.[he],n?.classNames?.[he]),"data-sonner-toast":``,"data-rich-colors":n.richColors??f,"data-styled":!(n.jsx||n.unstyled||r),"data-mounted":ne,"data-promise":!!n.promise,"data-swiped":oe,"data-removed":O,"data-visible":me,"data-y-position":Te,"data-x-position":Ee,"data-index":c,"data-front":pe,"data-swiping":k,"data-dismissible":ge,"data-type":he,"data-invert":ke,"data-swipe-out":j,"data-swipe-direction":D,"data-expanded":!!(u||S&&ne),"data-testid":n.testId,style:{"--index":c,"--toasts-before":c,"--z-index":l.length-c,"--offset":`${O?ce:Se.current}px`,"--initial-height":S?`auto`:`${N}px`,...m,...n.style},onDragEnd:()=>{A(!1),ee(null),we.current=null},onPointerDown:e=>{e.button!==2&&(Ae||!ge||(de.current=new Date,M(Se.current),e.target.setPointerCapture(e.pointerId),e.target.tagName!==`BUTTON`&&(A(!0),we.current={x:e.clientX,y:e.clientY})))},onPointerUp:()=>{if(j||!ge)return;we.current=null;let e=Number(fe.current?.style.getPropertyValue(`--swipe-amount-x`).replace(`px`,``)||0),t=Number(fe.current?.style.getPropertyValue(`--swipe-amount-y`).replace(`px`,``)||0),r=new Date().getTime()-de.current?.getTime(),i=E===`x`?e:t,a=Math.abs(i)/r;if(Math.abs(i)>=mI||a>.11){M(Se.current),n.onDismiss==null||n.onDismiss.call(n,n),te(E===`x`?e>0?`right`:`left`:t>0?`down`:`up`),je(),ae(!0);return}else{var o,s;(o=fe.current)==null||o.style.setProperty(`--swipe-amount-x`,`0px`),(s=fe.current)==null||s.style.setProperty(`--swipe-amount-y`,`0px`)}se(!1),A(!1),ee(null)},onPointerMove:t=>{var n,r;if(!we.current||!ge||window.getSelection()?.toString().length>0)return;let i=t.clientY-we.current.y,a=t.clientX-we.current.x,o=e.swipeDirections??_I(b);!E&&(Math.abs(a)>1||Math.abs(i)>1)&&ee(Math.abs(a)>Math.abs(i)?`x`:`y`);let s={x:0,y:0},c=e=>1/(1.5+Math.abs(e)/20);if(E===`y`){if(o.includes(`top`)||o.includes(`bottom`))if(o.includes(`top`)&&i<0||o.includes(`bottom`)&&i>0)s.y=i;else{let e=i*c(i);s.y=Math.abs(e)<Math.abs(i)?e:i}}else if(E===`x`&&(o.includes(`left`)||o.includes(`right`)))if(o.includes(`left`)&&a<0||o.includes(`right`)&&a>0)s.x=a;else{let e=a*c(a);s.x=Math.abs(e)<Math.abs(a)?e:a}(Math.abs(s.x)>0||Math.abs(s.y)>0)&&se(!0),(n=fe.current)==null||n.style.setProperty(`--swipe-amount-x`,`${s.x}px`),(r=fe.current)==null||r.style.setProperty(`--swipe-amount-y`,`${s.y}px`)}},be&&!n.jsx&&he!==`loading`?z.createElement(`button`,{"aria-label":T,"data-disabled":Ae,"data-close-button":!0,onClick:Ae||!ge?()=>{}:()=>{je(),n.onDismiss==null||n.onDismiss.call(n,n)},className:gI(C?.closeButton,n?.classNames?.closeButton)},w?.close??eI):null,(he||n.icon||n.promise)&&n.icon!==null&&(w?.[he]!==null||n.icon)?z.createElement(`div`,{"data-icon":``,className:gI(C?.icon,n?.classNames?.icon)},n.promise||n.type===`loading`&&!n.icon?n.icon||Me():null,n.type===`loading`?null:Ne):null,z.createElement(`div`,{"data-content":``,className:gI(C?.content,n?.classNames?.content)},z.createElement(`div`,{"data-title":``,className:gI(C?.title,n?.classNames?.title)},n.jsx?n.jsx:typeof n.title==`function`?n.title():n.title),n.description?z.createElement(`div`,{"data-description":``,className:gI(v,ve,C?.description,n?.classNames?.description)},typeof n.description==`function`?n.description():n.description):null),z.isValidElement(n.cancel)?n.cancel:n.cancel&&sI(n.cancel)?z.createElement(`button`,{"data-button":!0,"data-cancel":!0,style:n.cancelButtonStyle||h,onClick:e=>{sI(n.cancel)&&ge&&(n.cancel.onClick==null||n.cancel.onClick.call(n.cancel,e),je())},className:gI(C?.cancelButton,n?.classNames?.cancelButton)},n.cancel.label):null,z.isValidElement(n.action)?n.action:n.action&&sI(n.action)?z.createElement(`button`,{"data-button":!0,"data-action":!0,style:n.actionButtonStyle||g,onClick:e=>{sI(n.action)&&(n.action.onClick==null||n.action.onClick.call(n.action,e),!e.defaultPrevented&&je())},className:gI(C?.actionButton,n?.classNames?.actionButton)},n.action.label):null)};function yI(){if(typeof window>`u`||typeof document>`u`)return`ltr`;let e=document.documentElement.getAttribute(`dir`);return e===`auto`||!e?window.getComputedStyle(document.documentElement).direction:e}function bI(e,t){let n={};return[e,t].forEach((e,t)=>{let r=t===1,i=r?`--mobile-offset`:`--offset`,a=r?uI:lI;function o(e){[`top`,`right`,`bottom`,`left`].forEach(t=>{n[`${i}-${t}`]=typeof e==`number`?`${e}px`:e})}typeof e==`number`||typeof e==`string`?o(e):typeof e==`object`?[`top`,`right`,`bottom`,`left`].forEach(t=>{e[t]===void 0?n[`${i}-${t}`]=a:n[`${i}-${t}`]=typeof e[t]==`number`?`${e[t]}px`:e[t]}):o(a)}),n}var xI=z.forwardRef(function(e,t){let{id:n,invert:r,position:i=`bottom-right`,hotkey:a=[`altKey`,`KeyT`],expand:o,closeButton:s,className:c,offset:l,mobileOffset:u,theme:d=`light`,richColors:f,duration:p,style:m,visibleToasts:h=cI,toastOptions:g,dir:_=yI(),gap:v=pI,icons:y,containerAriaLabel:b=`Notifications`}=e,[x,S]=z.useState([]),C=z.useMemo(()=>n?x.filter(e=>e.toasterId===n):x.filter(e=>!e.toasterId),[x,n]),w=z.useMemo(()=>Array.from(new Set([i].concat(C.filter(e=>e.position).map(e=>e.position)))),[C,i]),[T,E]=z.useState([]),[ee,D]=z.useState(!1),[te,ne]=z.useState(!1),[re,O]=z.useState(d===`system`?typeof window<`u`&&window.matchMedia&&window.matchMedia(`(prefers-color-scheme: dark)`).matches?`dark`:`light`:d),ie=z.useRef(null),k=a.join(`+`).replace(/Key/g,``).replace(/Digit/g,``),A=z.useRef(null),j=z.useRef(!1),ae=z.useCallback(e=>{S(t=>(t.find(t=>t.id===e.id)?.delete||rI.dismiss(e.id),t.filter(({id:t})=>t!==e.id)))},[]);return z.useEffect(()=>rI.subscribe(e=>{if(e.dismiss){requestAnimationFrame(()=>{S(t=>t.map(t=>t.id===e.id?{...t,delete:!0}:t))});return}setTimeout(()=>{br.flushSync(()=>{S(t=>{let n=t.findIndex(t=>t.id===e.id);return n===-1?[e,...t]:[...t.slice(0,n),{...t[n],...e},...t.slice(n+1)]})})})}),[x]),z.useEffect(()=>{if(d!==`system`){O(d);return}if(d===`system`&&(window.matchMedia&&window.matchMedia(`(prefers-color-scheme: dark)`).matches?O(`dark`):O(`light`)),typeof window>`u`)return;let e=window.matchMedia(`(prefers-color-scheme: dark)`);try{e.addEventListener(`change`,({matches:e})=>{O(e?`dark`:`light`)})}catch{e.addListener(({matches:e})=>{try{O(e?`dark`:`light`)}catch(e){console.error(e)}})}},[d]),z.useEffect(()=>{x.length<=1&&D(!1)},[x]),z.useEffect(()=>{let e=e=>{if(a.every(t=>e[t]||e.code===t)){var t;D(!0),(t=ie.current)==null||t.focus()}e.code===`Escape`&&(document.activeElement===ie.current||ie.current?.contains(document.activeElement))&&D(!1)};return document.addEventListener(`keydown`,e),()=>document.removeEventListener(`keydown`,e)},[a]),z.useEffect(()=>{if(ie.current)return()=>{A.current&&(A.current.focus({preventScroll:!0}),A.current=null,j.current=!1)}},[ie.current]),z.createElement(`section`,{ref:t,"aria-label":`${b} ${k}`,tabIndex:-1,"aria-live":`polite`,"aria-relevant":`additions text`,"aria-atomic":`false`,suppressHydrationWarning:!0},w.map((t,n)=>{let[i,a]=t.split(`-`);return C.length?z.createElement(`ol`,{key:t,dir:_===`auto`?yI():_,tabIndex:-1,ref:ie,className:c,"data-sonner-toaster":!0,"data-sonner-theme":re,"data-y-position":i,"data-x-position":a,style:{"--front-toast-height":`${T[0]?.height||0}px`,"--width":`${fI}px`,"--gap":`${v}px`,...m,...bI(l,u)},onBlur:e=>{j.current&&!e.currentTarget.contains(e.relatedTarget)&&(j.current=!1,A.current&&=(A.current.focus({preventScroll:!0}),null))},onFocus:e=>{e.target instanceof HTMLElement&&e.target.dataset.dismissible===`false`||j.current||(j.current=!0,A.current=e.relatedTarget)},onMouseEnter:()=>D(!0),onMouseMove:()=>D(!0),onMouseLeave:()=>{te||D(!1)},onDragEnd:()=>D(!1),onPointerDown:e=>{e.target instanceof HTMLElement&&e.target.dataset.dismissible===`false`||ne(!0)},onPointerUp:()=>ne(!1)},C.filter(e=>!e.position&&n===0||e.position===t).map((n,i)=>z.createElement(vI,{key:n.id,icons:y,index:i,toast:n,defaultRichColors:f,duration:g?.duration??p,className:g?.className,descriptionClassName:g?.descriptionClassName,invert:r,visibleToasts:h,closeButton:g?.closeButton??s,interacting:te,position:t,style:g?.style,unstyled:g?.unstyled,classNames:g?.classNames,cancelButtonStyle:g?.cancelButtonStyle,actionButtonStyle:g?.actionButtonStyle,closeButtonAriaLabel:g?.closeButtonAriaLabel,removeToast:ae,toasts:C.filter(e=>e.position==n.position),heights:T.filter(e=>e.position==n.position),setHeights:E,expandByDefault:o,gap:v,expanded:ee,swipeDirections:e.swipeDirections}))):null}))}),SI=`__mcpUseInspectorReconnect`;function CI(e){let t=e??(typeof window<`u`?window.location.search:``);if(typeof window<`u`){try{if(sessionStorage.getItem(`__mcpUseInspectorReconnect`))return!0}catch{}if(window.__MCP_USE_INSPECTOR__?.autoConnectUrl)return!0}return!!new URLSearchParams(t).get(`autoConnect`)}function wI(e,t){return e.url===t.url&&e.state!==`ready`&&((e.transportType??`http`)!==t.transportType||wM(e.protocolNegotiation)!==wM(t.protocolNegotiation))}function TI(e){if(!e||typeof e!=`string`)return console.warn(`[useAutoConnect] parseAutoConnectParam: invalid param`,e),null;let t=e.trim();if((t.startsWith(`{`)||t.startsWith(`[`))&&t.endsWith(`/`)&&(t=t.replace(/\/+$/,``)),t.startsWith(`http://`)||t.startsWith(`https://`))return console.log(`[useAutoConnect] parseAutoConnectParam: treating as plain URL:`,t),{url:t,name:`Auto-connected Server`,transportType:`http`,connectionType:`Direct`,connectionMode:`auto`};try{let e=JSON.parse(t);if(console.log(`[useAutoConnect] parseAutoConnectParam: parsed JSON:`,e),e&&typeof e==`object`&&!Array.isArray(e))if(e.url&&typeof e.url==`string`){let t=e.url.trim();if((t.startsWith(`{`)||t.startsWith(`[`))&&t.length>2)try{let e=JSON.parse(t);e&&typeof e==`object`&&e.url&&typeof e.url==`string`?(t=e.url.trim(),console.log(`[useAutoConnect] parseAutoConnectParam: extracted URL from nested JSON:`,t)):console.warn(`[useAutoConnect] parseAutoConnectParam: url field is JSON but doesn't contain a url:`,e)}catch(e){console.warn(`[useAutoConnect] parseAutoConnectParam: url field looks like JSON but failed to parse, using as-is:`,e)}return!t.startsWith(`http://`)&&!t.startsWith(`https://`)?(console.error(`[useAutoConnect] parseAutoConnectParam: extracted URL is not a valid HTTP(S) URL:`,t),null):(console.log(`[useAutoConnect] parseAutoConnectParam: extracted URL:`,t),{url:t,name:e.name||`Auto-connected Server`,transportType:e.transportType===`sse`?`sse`:`http`,connectionMode:EM(e.connectionMode,e.connectionType,!!e.proxyConfig?.proxyAddress),connectionType:e.connectionType===`Via Proxy`?`Via Proxy`:`Direct`,autoProxyFallback:e.autoProxyFallback,protocolNegotiation:CM(wM(e.protocolNegotiation)),customHeaders:e.customHeaders||{},requestTimeout:e.requestTimeout,resetTimeoutOnProgress:e.resetTimeoutOnProgress,maxTotalTimeout:e.maxTotalTimeout,auth:e.auth})}else return console.warn(`[useAutoConnect] parseAutoConnectParam: parsed object missing or invalid url field:`,e),null;else return typeof e==`string`&&(e.startsWith(`http://`)||e.startsWith(`https://`))?(console.log(`[useAutoConnect] parseAutoConnectParam: JSON parsed to URL string:`,e),{url:e,name:`Auto-connected Server`,transportType:`http`,connectionType:`Direct`,connectionMode:`auto`}):(console.warn(`[useAutoConnect] parseAutoConnectParam: parsed value is not a valid object:`,e),null)}catch(e){return console.error(`[useAutoConnect] parseAutoConnectParam: Failed to parse as JSON and not a valid URL:`,e,`Param:`,t),null}}function EI({connections:e,addServer:t,removeConnection:n,configLoaded:r,embedded:i=!1}){let a=sP(),[o,s]=(0,z.useState)(()=>CI()),[c,l]=(0,z.useState)(null),[u,d]=(0,z.useState)(!1),f=(0,z.useCallback)(e=>{let{url:n,name:r,transportType:a,connectionMode:o,protocolNegotiation:s,customHeaders:c,auth:l}=e;console.log(`[useAutoConnect] Config received:`,e),console.log(`[useAutoConnect] Custom headers before auth:`,c),console.log(`[useAutoConnect] Auth config:`,l);let u={...c};if(l?.access_token){let e=l.token_type||`bearer`;if(u.Authorization=`${e.charAt(0).toUpperCase()+e.slice(1)} ${l.access_token}`,console.log(`[useAutoConnect] Added Authorization header:`,u.Authorization),typeof window<`u`&&!i){let e=`mcp:auth:${n}`,t={access_token:l.access_token,token_type:l.token_type||`bearer`,expires_at:l.expires_at,refresh_token:l.refresh_token,scope:l.scope||``};try{localStorage.setItem(e,JSON.stringify(t)),console.log(`[useAutoConnect] Pre-stored OAuth tokens for ${n}`)}catch(e){console.error(`[useAutoConnect] Failed to store OAuth tokens:`,e)}}}console.log(`[useAutoConnect] Final custom headers:`,u);let d;try{let e=new URL(n).origin;window.location.origin!==e&&(d=TM())}catch{d=TM()}let f=o===`proxy`&&d?{proxyAddress:d,...Object.keys(u).length>0&&{headers:u}}:Object.keys(u).length>0?{headers:u}:void 0,p=o===`auto`?e.autoProxyFallback===void 0?d?{enabled:!0,proxyAddress:d}:!1:e.autoProxyFallback:!1;console.warn(`[useAutoConnect] Attempting connection (${o}):`,{url:n,transportType:a,proxyConfig:f,autoProxyFallback:p}),t(n,PM({url:n,name:r,transportType:a,connectionMode:o,protocolNegotiation:s??`auto`,connectionType:o===`proxy`?`Via Proxy`:`Direct`,proxyConfig:f,headers:u,autoProxyFallback:p}))},[t]),p=(0,z.useCallback)(t=>{let r=e.find(e=>e.url===t.url);if(r){if(wI(r,t)){console.warn(`[useAutoConnect] Existing connection transport differs from auto-connect config; replacing it`),n(r.id),l(t),s(!0),f(t);return}if(r.state===`ready`){console.warn(`[useAutoConnect] Connection already ready, navigating to server`);let e=new URLSearchParams(window.location.search),t=e.get(`tunnelUrl`),n=e.get(`tab`),i=e.get(`openTunnelPopover`),o=new URLSearchParams;o.set(`server`,r.id),t&&o.set(`tunnelUrl`,t),n&&o.set(`tab`,n),i&&o.set(`openTunnelPopover`,i),a(`/?${o.toString()}`)}else console.warn(`[useAutoConnect] Connection exists, waiting for ready state`),l(t),s(!0)}else l(t),s(!0),f(t)},[e,a,n,f]);return(0,z.useEffect)(()=>{if(u)return;let e=()=>{if(typeof sessionStorage>`u`)return!1;try{let e=sessionStorage.getItem(SI);if(!e)return!1;let t=JSON.parse(e);return sessionStorage.removeItem(SI),!t?.url||!t.transportType?!1:(p(t),!0)}catch{try{sessionStorage.removeItem(SI)}catch{}return!1}};if(i){if(e()){d(!0);return}let t=new URLSearchParams(window.location.search).get(`autoConnect`);if(t){try{t=decodeURIComponent(t)}catch{}console.log(`[useAutoConnect] Raw autoConnect param:`,t);let e=TI(t);console.log(`[useAutoConnect] Parsed config:`,e),e&&p(e),d(!0);return}d(!0);return}if(r!==!0)return;if(e()){d(!0);return}let t=new URLSearchParams(window.location.search).get(`autoConnect`);if(t)try{t=decodeURIComponent(t)}catch{}if(t){let e=TI(t);e&&p(e),d(!0);return}let n=window.__MCP_USE_INSPECTOR__?.autoConnectUrl;if(n){let e=TI(n);e&&p(e),d(!0);return}fetch(`${mM()}/config.json`).then(e=>e.json()).then(e=>{if(d(!0),e.autoConnectUrl){let t=TI(e.autoConnectUrl);t&&p(t)}}).catch(()=>d(!0))},[u,r,p,i]),(0,z.useEffect)(()=>{if(!c)return;let t=e.find(e=>e.url===c.url);if(t?.state===`ready`){console.warn(`[useAutoConnect] Connection succeeded, navigating to server`);let e=new URLSearchParams(window.location.search),n=e.get(`tunnelUrl`),r=e.get(`tab`),i=e.get(`openTunnelPopover`),o=new URLSearchParams;o.set(`server`,t.id),n&&o.set(`tunnelUrl`,n),r&&o.set(`tab`,r),i&&o.set(`openTunnelPopover`,i),a(`/?${o.toString()}`),setTimeout(()=>{l(null),s(!1)},100);return}if(t?.state===`pending_auth`||t?.state===`authenticating`){console.warn(`[useAutoConnect] Connection requires authentication, clearing loading overlay`),setTimeout(()=>{s(!1)},100);return}t?.state===`failed`&&(console.warn(`[useAutoConnect] Connection failed after all retries`),oI.error(`Cannot connect to server. Please check the URL and try again.`),queueMicrotask(()=>{s(!1),l(null)}))},[e,c,a]),(0,z.useEffect)(()=>{if(o&&e.length>0&&!c&&e.some(e=>e.state===`ready`||e.state===`failed`||e.state===`pending_auth`)){let e=setTimeout(()=>s(!1),500);return()=>clearTimeout(e)}},[o,e,c]),(0,z.useEffect)(()=>{if(!o)return;let e=setTimeout(()=>{o&&(console.warn(`[useAutoConnect] Auto-connect timeout - clearing loading state`),s(!1),l(null))},3e4);return()=>clearTimeout(e)},[o]),{isAutoConnecting:o,autoConnectUrl:c?.url||null}}function DI({className:e,...t}){return(0,R.jsx)(`div`,{"data-slot":`card`,className:L(`flex flex-col gap-6 rounded-xl border border-border bg-transparent py-6 text-card-foreground`,e),...t})}function OI({className:e,...t}){return(0,R.jsx)(`div`,{"data-slot":`card-header`,className:L(`@container/card-header grid auto-rows-min grid-rows-[auto_auto] items-start gap-1.5 px-6 has-data-[slot=card-action]:grid-cols-[1fr_auto]`,e),...t})}function kI({className:e,...t}){return(0,R.jsx)(`div`,{"data-slot":`card-title`,className:L(`font-semibold leading-none`,e),...t})}function AI({className:e,...t}){return(0,R.jsx)(`div`,{"data-slot":`card-description`,className:L(`text-sm text-muted-foreground`,e),...t})}function jI({className:e,...t}){return(0,R.jsx)(`div`,{"data-slot":`card-content`,className:L(`px-6`,e),...t})}var MI={"chevron-right":C,"chevron-down":Ir,pipette:Oi,x:Xi,copy:Wr,menu:_i,dot:Kr,monitor:bi,sun:Wi,moon:xi,"rectangle-horizontal":ji,circle:Br,"square-library":Bi,clock:Vr,star:Hi,settings:Ii,plus:Ai,"arrow-left":Or,"arrow-right":kr,"arrow-up":jr,search:v,loader:pi,users:Ji,lock:mi,mail:gi,bell:Mr,shield:Li,palette:Ci,lightbulb:ui,rocket:Mi,heart:ni,paintbrush:Si,brain:Nr,globe:ei,user:qi,image:ai,link:di,check:Fr,"rotate-ccw":Ni,play:ki,pause:Ei,home:ii,"message-circle":vi,inbox:oi,pencil:Di,"skip-forward":Ri,"corner-down-right":Gr},NI=(0,z.createContext)(null);function PI(e){return((0,z.useContext)(NI)??MI)[e]}var FI=z.createContext(!1),II=z.createContext(void 0);function LI(e){let t=z.useContext(II);if(e===!1&&t===void 0)throw Error(Vt(27));return t}var RI={...dt,...it},zI=z.forwardRef(function(e,t){let{render:n,className:r,style:i,forceRender:a=!1,...o}=e,{store:s}=LI(),c=s.useState(`open`),l=s.useState(`nested`),u=s.useState(`mounted`);return Ft(`div`,e,{state:{open:c,transitionStatus:s.useState(`transitionStatus`)},ref:[s.context.backdropRef,t],stateAttributesMapping:RI,props:[{role:`presentation`,hidden:!u,style:{userSelect:`none`,WebkitUserSelect:`none`}},o],enabled:a||!l})}),BI=z.forwardRef(function(e,t){let{render:n,className:r,style:i,disabled:a=!1,nativeButton:o=!0,...s}=e,{store:c}=LI(),l=c.useState(`open`),{getButtonProps:d,buttonRef:f}=Lt({disabled:a,native:o}),p={disabled:a};function m(e){l&&c.setOpen(!1,te(u,e.nativeEvent))}return Ft(`button`,e,{state:p,ref:[t,f],props:[{onClick:m},s,d]})}),VI=z.forwardRef(function(e,t){let{render:n,className:r,style:i,id:a,...o}=e,{store:s}=LI(),c=O(a);return s.useSyncedValueWithCleanup(`descriptionElementId`,c),Ft(`p`,e,{ref:t,props:[{id:c},o]})}),HI=function(e){return e.nestedDialogs=`--nested-dialogs`,e}({}),UI=function(e){return e[e.open=tt.open]=`open`,e[e.closed=tt.closed]=`closed`,e[e.startingStyle=tt.startingStyle]=`startingStyle`,e[e.endingStyle=tt.endingStyle]=`endingStyle`,e.nested=`data-nested`,e.nestedDialogOpen=`data-nested-dialog-open`,e}({}),WI=z.createContext(void 0);function GI(){let e=z.useContext(WI);if(e===void 0)throw Error(Vt(26));return e}var KI={...dt,...it,nestedDialogOpen(e){return e?{[UI.nestedDialogOpen]:``}:null}},qI=z.forwardRef(function(e,t){let{render:n,className:r,style:i,finalFocus:a,initialFocus:o,...s}=e,{store:c}=LI(),l=c.useState(`descriptionElementId`),u=c.useState(`disablePointerDismissal`),d=c.useState(`floatingRootContext`),f=c.useState(`popupProps`),p=c.useState(`modal`),m=c.useState(`mounted`),h=c.useState(`nested`),_=c.useState(`nestedOpenDialogCount`),v=c.useState(`open`),y=c.useState(`openMethod`),b=c.useState(`titleElementId`),x=c.useState(`transitionStatus`),S=c.useState(`role`),C=d.useState(`floatingId`),w=s.id??C;GI(),g({open:v,ref:c.context.popupRef,onComplete(){v&&c.context.onOpenChangeComplete?.(!0)}});let T=o===void 0?Xe(c.context.popupRef):o,E=_>0,ee=c.useStateSetter(`popupElement`),D=Ft(`div`,e,{state:{open:v,nested:h,transitionStatus:x,nestedDialogOpen:E},props:[f,{id:w,"aria-labelledby":b??void 0,"aria-describedby":l??void 0,role:S,...mt,hidden:!m,onKeyDown(e){Qt.has(e.key)&&e.stopPropagation()},style:{[HI.nestedDialogs]:_}},s],ref:[t,c.context.popupRef,ee],stateAttributesMapping:KI});return(0,R.jsx)(rn,{context:d,openInteractionType:y,disabled:!m,closeOnFocusOut:!u,initialFocus:T,returnFocus:a,modal:p!==!1,restoreFocus:`popup`,children:D})}),JI=z.forwardRef(function(e,t){let{keepMounted:n=!1,...r}=e,{store:i}=LI(),a=i.useState(`mounted`),o=i.useState(`modal`),s=i.useState(`open`);return a||n?(0,R.jsx)(WI.Provider,{value:n,children:(0,R.jsxs)(oe,{ref:t,...r,children:[a&&o===!0&&(0,R.jsx)(wn,{ref:i.context.internalBackdropRef,inert:sn(!s)}),e.children]})}):null});function YI(e){let{store:t,actionsRef:n}=e,r=t.useState(`open`);Be(t,r),Me(t);let{forceUnmount:i}=ot(r,t),a=z.useCallback(()=>{t.setOpen(!1,te(_e))},[t]);z.useImperativeHandle(n,()=>({unmount:i,close:a}),[i,a])}function XI({store:e,parentContext:t,isDrawer:n}){let r=e.useState(`open`),i=e.useState(`disablePointerDismissal`),a=e.useState(`modal`),o=e.useState(`popupElement`),s=e.useState(`floatingRootContext`),[c,l]=z.useState(0),[u,d]=z.useState(0),f=c===0,p=m(s,{outsidePressEvent(){return e.context.internalBackdropRef.current||e.context.backdropRef.current?`intentional`:{mouse:a===`trap-focus`?`sloppy`:`intentional`,touch:`sloppy`}},outsidePress(t){if(!e.context.outsidePressEnabledRef.current||`button`in t&&t.button!==0||`touches`in t&&t.touches.length!==1)return!1;let n=ze(t);return f&&!i?a&&(e.context.internalBackdropRef.current||e.context.backdropRef.current)?e.context.internalBackdropRef.current===n||e.context.backdropRef.current===n||Qe(n,o)&&!n?.hasAttribute(`data-base-ui-portal`):!0:!1},escapeKey:f});return xn(r&&a===!0,o),e.useContextCallback(`onNestedDialogOpen`,(e,t)=>{l(e),d(t)}),e.useContextCallback(`onNestedDialogClose`,()=>{l(0),d(0)}),z.useEffect(()=>(t?.onNestedDialogOpen&&r&&t.onNestedDialogOpen(c+1,u+ +!!n),t?.onNestedDialogClose&&!r&&t.onNestedDialogClose(),()=>{t?.onNestedDialogClose&&r&&t.onNestedDialogClose()}),[n,r,c,u,t]),$e(e,{activeTriggerProps:p.reference??Wt,inactiveTriggerProps:p.trigger??Wt,popupProps:p.floating??Wt,nestedOpenDialogCount:c,nestedOpenDrawerCount:u}),null}var ZI={...De,modal:St(e=>e.modal),nested:St(e=>e.nested),nestedOpenDialogCount:St(e=>e.nestedOpenDialogCount),nestedOpenDrawerCount:St(e=>e.nestedOpenDrawerCount),disablePointerDismissal:St(e=>e.disablePointerDismissal),openMethod:St(e=>e.openMethod),descriptionElementId:St(e=>e.descriptionElementId),titleElementId:St(e=>e.titleElementId),viewportElement:St(e=>e.viewportElement),role:St(e=>e.role)},QI=class e extends Tt{constructor(e,t,n=!1){let r=new at,i=$I(e);i.floatingRootContext=We(r,t,n),super(i,{popupRef:z.createRef(),backdropRef:z.createRef(),internalBackdropRef:z.createRef(),outsidePressEnabledRef:{current:!0},triggerElements:r,onOpenChange:void 0,onOpenChangeComplete:void 0},ZI)}setOpen=(e,t)=>{if(t.preventUnmountOnClose=()=>{this.set(`preventUnmountingOnClose`,!0)},!e&&t.trigger==null&&this.state.activeTriggerId!=null&&(t.trigger=this.state.activeTriggerElement??void 0),this.context.onOpenChange?.(e,t),t.isCanceled)return;this.state.floatingRootContext.dispatchOpenChange(e,t);let n={open:e};_t(n,e,t.trigger),this.update(n)};static useStore(t,n){return Le(t,(t,r)=>new e(n,t,r),!0).store}};function $I(e={}){return{...ft(),modal:!0,disablePointerDismissal:!1,popupElement:null,viewportElement:null,descriptionElementId:void 0,titleElementId:void 0,openMethod:null,nested:!1,nestedOpenDialogCount:0,nestedOpenDrawerCount:0,role:`dialog`,...e}}function eL(e,t=`dialog`){let{children:n,open:r,defaultOpen:i=!1,onOpenChange:a,onOpenChangeComplete:o,disablePointerDismissal:s=!1,modal:c=!0,actionsRef:l,handle:u,triggerId:d,defaultTriggerId:f=null}=e,p=t===`drawer`,m=t===`alert-dialog`,h=m?!0:c,g=m||s,_=m?`alertdialog`:`dialog`,v=LI(!0),y={modal:h,disablePointerDismissal:g,nested:!!v,role:_},b=QI.useStore(u?.store,{open:i,openProp:r,activeTriggerId:f,triggerIdProp:d,...y});pe(()=>{let e=r===void 0&&b.state.open===!1&&i===!0?{open:!0,activeTriggerId:f}:null;m?b.update(e?{...y,...e}:y):e&&b.update(e)}),b.useControlledProp(`openProp`,r),b.useControlledProp(`triggerIdProp`,d),b.useSyncedValues(y),b.useContextCallback(`onOpenChange`,a),b.useContextCallback(`onOpenChangeComplete`,o);let x=b.useState(`open`),S=b.useState(`mounted`),C=b.useState(`payload`);YI({store:b,actionsRef:l});let w=x||S,T=z.useMemo(()=>({store:b}),[b]);return(0,R.jsx)(FI.Provider,{value:!1,children:(0,R.jsxs)(II.Provider,{value:T,children:[w&&(0,R.jsx)(XI,{store:b,parentContext:v?.store.context,isDrawer:p}),typeof n==`function`?n({payload:C}):n]})})}function tL(e){return eL(e,z.useContext(FI)?`drawer`:`dialog`)}var nL=z.forwardRef(function(e,t){let{render:n,className:r,style:i,id:a,...o}=e,{store:s}=LI(),c=O(a);return s.useSyncedValueWithCleanup(`titleElementId`,c),Ft(`h2`,e,{ref:t,props:[{id:c},o]})}),rL=z.forwardRef(function(e,t){let{render:n,className:r,style:i,disabled:a=!1,nativeButton:o=!0,id:s,payload:c,handle:l,...u}=e,d=LI(!0),f=l?.store??d?.store;if(!f)throw Error(Vt(79));let p=O(s),m=f.useState(`floatingRootContext`),h=f.useState(`isOpenedByTrigger`,p),g=f.useState(`triggerPopupId`,p),_=z.useRef(null),{registerTrigger:v,isMountedByThisTrigger:y}=Ce(p,_,f,{payload:c}),{getButtonProps:b,buttonRef:S}=Lt({disabled:a,native:o}),C=Sn(m,{enabled:m!=null}),w=dn(()=>f.select(`open`),e=>{f.set(`openMethod`,e)}),T={disabled:a,open:h},E=f.useState(`triggerProps`,y);return Ft(`button`,e,{state:T,ref:[S,t,v,_],props:[C.reference,E,w,{[x]:``,id:p,"aria-haspopup":`dialog`,"aria-expanded":h,"aria-controls":g},u,b],stateAttributesMapping:Ee})}),iL=4,aL=`h-14`,oL=(0,z.createContext)(null);function sL({className:e}){let t=PI(`x`);return(0,R.jsx)(BI,{render:(0,R.jsxs)(Gt,{variant:`ghost`,size:`icon-sm`,className:e,children:[(0,R.jsx)(t,{}),(0,R.jsx)(`span`,{className:`sr-only`,children:`Close`})]})})}function cL({children:e,open:t,defaultOpen:n,onOpenChange:r,modal:i}){return(0,R.jsx)(tL,{open:t,defaultOpen:n,onOpenChange:e=>r?.(e),modal:i,children:e})}function lL(e){return(0,R.jsx)(rL,{"data-slot":`dialog-trigger`,...e})}var uL=(0,z.forwardRef)(({className:e,children:t,size:n=`sm`,scrollable:r=!1,container:i,...a},o)=>{let s=Nt(),c=un(),l=Math.min(c+iL,8),[u,d]=(0,z.useState)(!1),f=(0,z.useCallback)(e=>{d(e)},[]);return(0,R.jsxs)(JI,{container:i??void 0,children:[(0,R.jsx)(zI,{render:(e,t)=>{let n=t.transitionStatus===`ending`,{style:r,onDrag:a,onDragStart:o,onDragEnd:s,onAnimationStart:c,onAnimationEnd:l,onAnimationIteration:u,...d}=e;return(0,R.jsx)(Pe.div,{...d,className:L(i?`absolute`:`fixed`,`inset-0 z-50 bg-black/40 dark:bg-black/80`),initial:{opacity:0},animate:{opacity:+!n},transition:n?pt.slow.exit:pt.slow})}}),(0,R.jsx)(qI,{ref:o,render:(o,c)=>{let d=c.transitionStatus===`ending`,{style:p,onDrag:m,onDragStart:h,onDragEnd:g,onAnimationStart:_,onAnimationEnd:v,onAnimationIteration:y,...b}=o;return(0,R.jsx)(Pe.div,{...b,...a,className:L(i?`absolute`:`fixed`,`left-1/2 top-1/2 z-50 w-[calc(100%-2rem)]`,bn(l),`p-6 focus:outline-none`,n===`sm`&&`max-w-[400px]`,n===`lg`&&`max-w-[540px]`,s.container,r&&`flex flex-col overflow-hidden p-0`,e),style:{...p,...a.style},initial:{opacity:0,scale:.97,x:`-50%`,y:`-50%`},animate:{opacity:+!d,scale:d?.97:1,x:`-50%`,y:`-50%`},transition:d?pt.slow.exit:pt.slow,children:(0,R.jsx)(ln,{value:l,children:(0,R.jsxs)(oL.Provider,{value:{scrollable:r,setStickyHeader:f},children:[t,!u&&(0,R.jsx)(sL,{className:`absolute right-3 top-3 z-20`})]})})})}})]})});uL.displayName=`DialogContent`;function dL({className:e,sticky:t,children:n,...r}){let i=(0,z.useContext)(oL);return(0,z.useLayoutEffect)(()=>{if(t)return i?.setStickyHeader(!0),()=>i?.setStickyHeader(!1)},[t,i]),t?(0,R.jsxs)(`div`,{className:L(`sticky top-0 z-10 mb-0 flex shrink-0 items-center gap-2 border-b border-border/50 bg-white/50 px-6 backdrop-blur-xs dark:bg-black/50`,aL,e),...r,children:[n,(0,R.jsx)(sL,{className:`ml-auto shrink-0`})]}):(0,R.jsx)(`div`,{className:L(`mb-4 flex flex-col gap-1.5`,i?.scrollable&&`px-6 pt-6`,e),...r,children:n})}function fL({className:e,...t}){return(0,R.jsx)(`div`,{className:L(`flex-1 min-h-0 overflow-y-auto overscroll-none pt-2`,(0,z.useContext)(oL)?.scrollable?`px-6 pb-6`:`-mx-6 px-6`,e),...t})}function pL({className:e,onCopy:t,children:n,...r}){let i=PI(`copy`),a=PI(`check`),[o,s]=(0,z.useState)(!1),c=async()=>{if(t)try{await t(),s(!0),setTimeout(()=>s(!1),2e3)}catch{}};return(0,R.jsxs)(`div`,{className:L(`group/json relative -mx-6 bg-muted/20 px-6 pt-6 pb-4`,e),...r,children:[t?(0,R.jsx)(`div`,{className:`absolute top-2 right-2 z-10 opacity-0 transition-opacity group-hover/json:opacity-100`,children:(0,R.jsx)(Gt,{variant:`ghost`,size:`icon-sm`,onClick:c,title:`Copy`,children:o?(0,R.jsx)(a,{className:`text-green-600`}):(0,R.jsx)(i,{})})}):null,n]})}function mL({className:e,...t}){return(0,R.jsx)(`div`,{className:L(`mt-6 flex justify-end gap-2`,(0,z.useContext)(oL)?.scrollable&&`px-6 pb-6`,e),...t})}var hL=(0,z.forwardRef)(({className:e,...t},n)=>(0,R.jsx)(nL,{ref:n,className:L(`m-0 text-[16px] leading-none text-foreground`,e),style:{fontVariationSettings:`'wght' 700`},...t}));hL.displayName=`DialogTitle`;var gL=(0,z.forwardRef)(({className:e,...t},n)=>(0,R.jsx)(VI,{ref:n,className:L(`text-[13px] text-muted-foreground`,e),...t}));gL.displayName=`DialogDescription`;function _L({headers:e,onChange:t,onSave:n,className:r,title:i=`Custom Headers`,description:a=`Headers with both name and value will be sent`,maxHeaders:o=50}){let[s,c]=(0,z.useState)({}),[l,u]=(0,z.useState)(null),d=(0,z.useRef)({});(0,z.useEffect)(()=>{l&&d.current[l]&&(d.current[l]?.focus(),u(null))},[l,e]);let f=()=>Math.random().toString(36).slice(2,11),p=()=>{if(e.length>=o)return;let n={id:f(),name:``,value:``};t([...e,n])},m=n=>{t(e.filter(e=>e.id!==n))},h=(n,r,i)=>{t(e.map(e=>e.id===n?{...e,[r]:i}:e))},g=e=>{c(t=>({...t,[e]:!t[e]}))};return(0,R.jsxs)(`div`,{className:L(`space-y-3`,r),children:[(0,R.jsxs)(`div`,{className:`space-y-2`,children:[(0,R.jsx)(Xt,{className:`text-base font-medium`,children:i}),(0,R.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:a})]}),(0,R.jsxs)(`div`,{className:`space-y-2`,children:[(0,R.jsxs)(`div`,{className:`grid grid-cols-[1fr_1fr] gap-4 text-sm font-medium text-muted-foreground`,children:[(0,R.jsx)(`div`,{children:`Name`}),(0,R.jsx)(`div`,{children:`Value`})]}),e.length===0?(0,R.jsxs)(`div`,{className:`grid grid-cols-[1fr_1fr] gap-4 items-center`,children:[(0,R.jsx)(ht,{placeholder:`Authorization`,value:``,onChange:e=>{if(e.target.value.trim()){let n=f();t([{id:n,name:e.target.value,value:``}]),u(n)}},className:`text-sm`,autoComplete:`off`}),(0,R.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,R.jsx)(ht,{placeholder:`Bearer token...`,value:``,onChange:()=>{},type:`password`,className:`font-mono text-sm`,autoComplete:`off`,disabled:!0}),(0,R.jsx)(Gt,{type:`button`,variant:`ghost`,size:`icon-sm`,className:`h-8 w-8 p-0`,disabled:!0,children:(0,R.jsx)(Zr,{className:`h-4 w-4`})}),(0,R.jsx)(Gt,{type:`button`,variant:`ghost`,size:`icon-sm`,className:`h-8 w-8 p-0`,disabled:!0,children:(0,R.jsx)(Gi,{className:`h-4 w-4`})})]})]}):e.map(e=>(0,R.jsxs)(`div`,{className:`grid grid-cols-[1fr_1fr] gap-4 items-center`,children:[(0,R.jsx)(ht,{ref:t=>{d.current[e.id]=t},placeholder:`Authorization`,value:e.name,onChange:t=>h(e.id,`name`,t.target.value),className:`text-sm`,autoComplete:`off`}),(0,R.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,R.jsx)(ht,{placeholder:``,value:e.value,onChange:t=>h(e.id,`value`,t.target.value),type:s[e.id]?`text`:`password`,className:`font-mono text-sm`,autoComplete:`off`}),(0,R.jsx)(Gt,{type:`button`,variant:`ghost`,size:`icon-sm`,onClick:()=>g(e.id),className:`h-8 w-8 p-0`,children:s[e.id]?(0,R.jsx)(Xr,{className:`h-4 w-4`}):(0,R.jsx)(Zr,{className:`h-4 w-4`})}),(0,R.jsx)(Gt,{type:`button`,variant:`ghost`,size:`icon-sm`,onClick:()=>m(e.id),className:`h-8 w-8 p-0`,children:(0,R.jsx)(Gi,{className:`h-4 w-4`})})]})]},e.id)),(0,R.jsx)(`div`,{className:`flex justify-start mt-4`,children:(0,R.jsxs)(Gt,{type:`button`,variant:`outline`,size:`sm`,onClick:p,disabled:e.length>=o,className:`flex items-center gap-2`,children:[(0,R.jsx)(Ai,{className:`h-4 w-4`}),`Add`]})})]}),n&&(0,R.jsx)(`div`,{className:`flex justify-end`,children:(0,R.jsx)(Gt,{type:`button`,onClick:n,className:`bg-black text-white hover:bg-gray-800`,children:`Save`})})]})}function vL({alias:e,setAlias:t,url:n,setUrl:r,connectionMode:i,setConnectionMode:a,protocolMode:o,setProtocolMode:s,customHeaders:c,setCustomHeaders:l,requestTimeout:u,setRequestTimeout:d,resetTimeoutOnProgress:f,setResetTimeoutOnProgress:p,maxTotalTimeout:m,setMaxTotalTimeout:h,proxyAddress:g,setProxyAddress:_,clientId:v,setClientId:y,clientSecret:b,setClientSecret:x,scope:S,setScope:C,onConnect:w,onSave:T,onCancel:E,variant:ee=`default`,showConnectButton:D=!1,showSaveButton:te=!1,showExportButton:ne=!1,isConnecting:re=!1,inlineSections:O=!1,cardSections:ie=!1}){let[k,A]=(0,z.useState)(!1),[j,ae]=(0,z.useState)(!1),[oe,se]=(0,z.useState)(!1),ce=(0,z.useRef)(!1),M=async()=>{if(!n.trim()){oI.error(`Please enter a URL first`);return}let t={url:n,...e.trim()?{name:e.trim()}:{},transportType:`http`,connectionMode:i,protocolNegotiation:CM(o),connectionType:i===`proxy`?`Via Proxy`:`Direct`,proxyConfig:i===`proxy`&&g.trim()?{proxyAddress:g.trim(),customHeaders:c.reduce((e,t)=>(t.name&&t.value&&(e[t.name]=t.value),e),{})}:void 0,autoProxyFallback:i===`auto`&&g.trim()?{enabled:!0,proxyAddress:g.trim()}:void 0,customHeaders:c.reduce((e,t)=>(t.name&&t.value&&(e[t.name]=t.value),e),{}),requestTimeout:Number.parseInt(u,10),resetTimeoutOnProgress:f===`True`,maxTotalTimeout:Number.parseInt(m,10),oauth:v||S?{clientId:v,...v&&b?{clientSecret:b}:{},scope:S}:void 0};try{await lM(JSON.stringify(t,null,2)),oI.success(`Configuration copied to clipboard`)}catch{oI.error(`Failed to copy configuration to clipboard`)}},N=ee===`styled`,le=N?`bg-white/10 border-white/20 text-white placeholder:text-white/50`:``,ue=N?`text-white/90`:``,de=N?`bg-white/10 border-white/20 text-white hover:bg-white/20`:``,fe=async e=>{let n=e.clipboardData.getData(`text`);try{let i=JSON.parse(n);if(i.url&&typeof i.url==`string`){e.preventDefault(),r(i.url),t(typeof i.name==`string`&&i.name!==i.url?i.name:``);let n=i.proxyConfig?.proxyAddress||(typeof i.autoProxyFallback==`object`?i.autoProxyFallback.proxyAddress:void 0);a(EM(i.connectionMode,i.connectionType,!!n)),s(wM(i.protocolNegotiation)),n&&_(n);let o=i.proxyConfig?.customHeaders||i.proxyConfig?.headers||i.customHeaders||i.headers||{};Object.keys(o).length>0&&l(Object.entries(o).map(([e,t],n)=>({id:`header-${n}`,name:e,value:String(t)}))),i.requestTimeout&&d(String(i.requestTimeout)),i.resetTimeoutOnProgress!==void 0&&p(i.resetTimeoutOnProgress?`True`:`False`),i.maxTotalTimeout&&h(String(i.maxTotalTimeout)),i.oauth&&(y(i.oauth.clientId||``),x(i.oauth.clientSecret||``),C(i.oauth.scope||``)),oI.success(`Configuration pasted and form populated`)}}catch{}},pe=e=>{ce.current||e.nativeEvent.isComposing||e.keyCode===229||e.key===`Enter`&&!e.shiftKey&&!e.metaKey&&!e.ctrlKey&&e.target.tagName!==`TEXTAREA`&&(e.preventDefault(),w&&n.trim()&&w())},me=(0,R.jsxs)(`div`,{className:`grid gap-4 sm:grid-cols-2`,children:[!ie&&(0,R.jsx)(`h4`,{className:`text-sm font-medium sm:col-span-2`,children:`OAuth 2.0`}),(0,R.jsxs)(`div`,{className:`space-y-2`,children:[(0,R.jsx)(Xt,{className:`text-sm`,children:`Client ID`}),(0,R.jsx)(ht,{"data-testid":`auth-dialog-client-id-input`,placeholder:`Client ID`,value:v,onChange:e=>y(e.target.value)})]}),(0,R.jsxs)(`div`,{className:`space-y-2`,children:[(0,R.jsx)(Xt,{className:`text-sm`,children:`Client Secret`}),(0,R.jsx)(ht,{"data-testid":`auth-dialog-client-secret-input`,type:`password`,placeholder:`Client Secret (optional)`,value:b,onChange:e=>x(e.target.value)}),(0,R.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Stored in your browser's localStorage.`})]}),(0,R.jsxs)(`div`,{className:`space-y-2 sm:col-span-2`,children:[(0,R.jsx)(Xt,{className:`text-sm`,children:`Scope`}),(0,R.jsx)(ht,{"data-testid":`auth-dialog-scope-input`,placeholder:`Scope (space-separated)`,value:S,onChange:e=>C(e.target.value)})]})]}),he=(0,R.jsx)(_L,{title:(0,R.jsx)(R.Fragment,{}),headers:c,onChange:l}),ge=(0,R.jsxs)(`div`,{className:`grid gap-4 sm:grid-cols-2`,children:[(0,R.jsxs)(`div`,{className:`space-y-2`,children:[(0,R.jsx)(Xt,{className:`text-sm`,children:`Connection Mode`}),(0,R.jsxs)(yn,{value:i,onValueChange:e=>a(e),children:[(0,R.jsx)(pn,{className:`w-full`,"data-testid":`config-dialog-connection-mode-select`,children:(0,R.jsx)(on,{})}),(0,R.jsxs)(gn,{children:[(0,R.jsx)(vn,{value:`auto`,children:`Auto`}),(0,R.jsx)(vn,{value:`direct`,children:`Direct`}),(0,R.jsx)(vn,{value:`proxy`,children:`Proxy`})]})]}),(0,R.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Auto tries a direct connection first and falls back to the proxy. Direct bypasses the proxy; Proxy always routes through it.`})]}),(0,R.jsxs)(`div`,{className:`space-y-2`,children:[(0,R.jsx)(Xt,{className:`text-sm`,children:`Protocol`}),(0,R.jsxs)(yn,{value:o,onValueChange:e=>s(e),children:[(0,R.jsx)(pn,{className:`w-full`,"data-testid":`config-dialog-protocol-mode-select`,children:(0,R.jsx)(on,{})}),(0,R.jsxs)(gn,{children:[(0,R.jsx)(vn,{value:`auto`,children:`Auto (recommended)`}),(0,R.jsx)(vn,{value:`v1`,children:`Force v1 (2024/2025)`}),(0,R.jsx)(vn,{value:`v2`,children:`Force v2 (2026-07-28)`})]})]}),(0,R.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Auto probes for v2 and falls back to the legacy v1 initialize flow. Forced modes fail when the server is incompatible.`})]}),(0,R.jsxs)(`div`,{className:`space-y-2`,children:[(0,R.jsx)(Xt,{className:`text-sm`,children:`Proxy Endpoint`}),(0,R.jsx)(ht,{"data-testid":`config-dialog-proxy-address-input`,value:g,onChange:e=>_(e.target.value)})]}),(0,R.jsxs)(`div`,{className:`space-y-2`,children:[(0,R.jsx)(Xt,{className:`text-sm`,children:`Request Timeout`}),(0,R.jsx)(ht,{"data-testid":`config-dialog-request-timeout-input`,type:`number`,value:u,onChange:e=>d(e.target.value)})]}),(0,R.jsxs)(`div`,{className:`space-y-2`,children:[(0,R.jsx)(Xt,{className:`text-sm`,children:`Maximum Total Timeout`}),(0,R.jsx)(ht,{"data-testid":`config-dialog-max-timeout-input`,type:`number`,value:m,onChange:e=>h(e.target.value)})]}),(0,R.jsxs)(`div`,{className:`space-y-2`,children:[(0,R.jsx)(Xt,{className:`text-sm`,children:`Reset Timeout on Progress`}),(0,R.jsxs)(yn,{value:f,onValueChange:p,children:[(0,R.jsx)(pn,{className:`w-full`,"data-testid":`config-dialog-reset-timeout-select`,children:(0,R.jsx)(on,{})}),(0,R.jsxs)(gn,{children:[(0,R.jsx)(vn,{value:`True`,children:`True`}),(0,R.jsx)(vn,{value:`False`,children:`False`})]})]})]})]}),_e=(0,R.jsxs)(`div`,{className:O||ie?`grid gap-4 sm:grid-cols-2`:`space-y-4`,children:[(0,R.jsxs)(`div`,{className:`space-y-2`,children:[(0,R.jsx)(Xt,{className:ue,children:`Alias`}),(0,R.jsx)(ht,{"data-testid":`connection-form-alias-input`,placeholder:`Optional server alias`,value:e,onChange:e=>t(e.target.value),className:le})]}),(0,R.jsxs)(`div`,{className:`space-y-2`,children:[(0,R.jsx)(Xt,{className:ue,children:`URL`}),(0,R.jsx)(ht,{"data-testid":`connection-form-url-input`,placeholder:`http://localhost:3000`,value:n,onChange:e=>r(e.target.value),onPaste:fe,className:le}),(0,R.jsx)(`p`,{className:L(`text-xs text-muted-foreground`,N?`text-white/60`:``),children:`Tip: You can paste a copied connection config (JSON) to auto-populate the form`})]})]}),ve={onCompositionStart:()=>{ce.current=!0},onCompositionEnd:()=>{ce.current=!1},onKeyDown:pe},ye=ne?(0,R.jsxs)(Gt,{"data-testid":`connection-form-copy-config-button`,variant:`ghost`,onClick:M,className:L(N?`absolute top-0 right-0 z-10 text-white hover:bg-white/20 dark:hover:bg-white/20`:`w-full`,!N&&`mb-2`),children:[(0,R.jsx)(Wr,{className:`mr-2 h-4 w-4`}),`Copy Config`]}):null;return O&&ie?(0,R.jsxs)(`div`,{className:`relative space-y-6 @container`,...ve,children:[ye,(0,R.jsxs)(DI,{className:`border`,children:[(0,R.jsxs)(OI,{children:[(0,R.jsx)(kI,{className:`text-base font-medium`,children:`Endpoint`}),(0,R.jsx)(AI,{children:`MCP server URL and display alias`})]}),(0,R.jsx)(jI,{className:`pt-0`,children:_e})]}),(0,R.jsxs)(DI,{className:`border`,children:[(0,R.jsxs)(OI,{children:[(0,R.jsx)(kI,{className:`text-base font-medium`,children:`Authentication`}),(0,R.jsx)(AI,{children:`OAuth 2.0 client credentials`})]}),(0,R.jsx)(jI,{className:`pt-0`,children:me})]}),(0,R.jsxs)(DI,{className:`border`,children:[(0,R.jsxs)(OI,{children:[(0,R.jsx)(kI,{className:`text-base font-medium`,children:`Custom Headers`}),(0,R.jsx)(AI,{children:`Extra HTTP headers sent with MCP requests`})]}),(0,R.jsx)(jI,{className:`pt-0`,children:he})]}),(0,R.jsxs)(DI,{className:`border`,children:[(0,R.jsxs)(OI,{children:[(0,R.jsx)(kI,{className:`text-base font-medium`,children:`Configuration`}),(0,R.jsx)(AI,{children:`Connection mode, proxy, and request timeouts`})]}),(0,R.jsx)(jI,{className:`pt-0`,children:ge})]})]}):(0,R.jsxs)(`div`,{className:`relative space-y-4 @container`,...ve,children:[!O&&(0,R.jsx)(`h3`,{className:`mb-4 text-xl font-semibold text-white`,children:`Connect`}),ye,_e,O&&!ie&&(0,R.jsxs)(`div`,{className:`space-y-8 pt-2`,children:[(0,R.jsxs)(`section`,{className:`space-y-4`,children:[(0,R.jsx)(`h3`,{className:`text-xs font-medium uppercase tracking-wide text-muted-foreground`,children:`Authentication`}),me]}),(0,R.jsxs)(`section`,{className:`space-y-4`,children:[(0,R.jsx)(`h3`,{className:`text-xs font-medium uppercase tracking-wide text-muted-foreground`,children:`Custom Headers`}),he]}),(0,R.jsxs)(`section`,{className:`space-y-4`,children:[(0,R.jsx)(`h3`,{className:`text-xs font-medium uppercase tracking-wide text-muted-foreground`,children:`Configuration`}),ge]})]}),!O&&(0,R.jsxs)(`div`,{className:`flex flex-row gap-3 @lg:flex-col`,children:[(0,R.jsxs)(cL,{open:j,onOpenChange:ae,children:[(0,R.jsx)(lL,{render:(0,R.jsx)(`div`,{className:`relative flex-1 `,children:(0,R.jsxs)(Gt,{"data-testid":`connection-form-auth-button`,variant:`outline`,className:L((v||b||S)&&`border-2`,`w-full justify-center hover:text-white cursor-pointer`,de),children:[(0,R.jsx)(Li,{className:`w-4 h-4 mr-0`}),`Authentication`]})}),nativeButton:!1}),(0,R.jsxs)(uL,{scrollable:!0,className:`w-[calc(100vw-2rem)] sm:w-full max-w-2xl max-h-[80vh]`,children:[(0,R.jsx)(dL,{children:(0,R.jsx)(hL,{children:`Authentication`})}),(0,R.jsxs)(fL,{className:`space-y-4`,children:[me,(0,R.jsx)(`div`,{className:`flex justify-end`,children:(0,R.jsx)(Gt,{onClick:()=>ae(!1),children:`Save`})})]})]})]}),(0,R.jsxs)(cL,{open:k,onOpenChange:A,children:[(0,R.jsx)(lL,{render:(0,R.jsx)(`div`,{className:`relative flex-1 `,children:(0,R.jsxs)(Gt,{"data-testid":`connection-form-headers-button`,variant:`outline`,className:L(`w-full justify-center hover:text-white cursor-pointer`,de),children:[(0,R.jsx)(Qr,{className:`w-4 h-4`}),`Custom Headers`]})}),nativeButton:!1}),(0,R.jsxs)(uL,{scrollable:!0,className:`w-full max-w-2xl max-h-[80vh]`,children:[(0,R.jsx)(dL,{children:(0,R.jsx)(hL,{children:`Custom Headers`})}),(0,R.jsx)(fL,{children:(0,R.jsx)(_L,{title:(0,R.jsx)(R.Fragment,{}),headers:c,onChange:l,onSave:()=>A(!1)})})]})]}),(0,R.jsxs)(cL,{open:oe,onOpenChange:se,children:[(0,R.jsx)(lL,{render:(0,R.jsxs)(Gt,{"data-testid":`connection-form-config-button`,variant:`outline`,className:L(`flex-1 justify-center hover:text-white cursor-pointer`,de),children:[(0,R.jsx)(Hr,{className:`w-4 h-4`}),`Configuration`]}),nativeButton:!0}),(0,R.jsxs)(uL,{scrollable:!0,className:`w-full max-w-2xl max-h-[80vh]`,children:[(0,R.jsx)(dL,{children:(0,R.jsx)(hL,{children:`Configuration`})}),(0,R.jsxs)(fL,{className:`space-y-4`,children:[ge,(0,R.jsx)(`div`,{className:`flex justify-end`,children:(0,R.jsx)(Gt,{onClick:()=>se(!1),children:`Save`})})]})]})]})]}),D&&(0,R.jsx)(Gt,{"data-testid":`connection-form-connect-button`,onClick:w,disabled:!n.trim()||re,size:N?`lg`:void 0,className:L(`w-full font-semibold`,N?`rounded-full text-black [&_[aria-hidden]]:bg-white hover:[&_[aria-hidden]]:bg-white/90 group-active:[&_[aria-hidden]]:bg-white/80`:``),children:re?(0,R.jsxs)(R.Fragment,{children:[(0,R.jsx)(`svg`,{className:`w-4 h-4 mr-2 animate-spin`,fill:`none`,stroke:`currentColor`,viewBox:`0 0 24 24`,children:(0,R.jsx)(`path`,{strokeLinecap:`round`,strokeLinejoin:`round`,strokeWidth:2,d:`M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15`})}),`Connecting...`]}):(0,R.jsxs)(R.Fragment,{children:[(0,R.jsx)(`svg`,{className:`w-4 h-4 mr-2`,fill:`none`,stroke:`currentColor`,viewBox:`0 0 24 24`,children:(0,R.jsx)(`path`,{strokeLinecap:`round`,strokeLinejoin:`round`,strokeWidth:2,d:`M13 10V3L4 14h7v7l9-11h-7z`})}),`Connect`]})}),te&&(0,R.jsxs)(`div`,{className:`flex justify-end gap-2`,children:[E&&(0,R.jsx)(Gt,{variant:`outline`,onClick:E,children:`Cancel`}),(0,R.jsx)(Gt,{"data-testid":`connection-form-save-button`,onClick:T,children:`Save Connection Options`})]})]})}function yL({children:e,className:t,variant:n,duration:r=.4,delay:i=0,offset:a=6,direction:o=`down`,inView:s=!1,inViewMargin:c=`-50px`,blur:l=`6px`,...u}){let d=(0,z.useRef)(null),f=Ma(d,{once:!0,margin:c}),p=!s||f,m={hidden:{[o===`left`||o===`right`?`x`:`y`]:o===`right`||o===`down`?-a:a,opacity:0,filter:`blur(${l})`},visible:{[o===`left`||o===`right`?`x`:`y`]:0,opacity:1,filter:`blur(0px)`}},h=n||m;return(0,R.jsx)(en,{children:(0,R.jsx)(Pe.div,{ref:d,initial:`hidden`,animate:p?`visible`:`hidden`,exit:`hidden`,variants:h,transition:{delay:.04+i,duration:r,ease:`easeOut`},className:t,...u,children:e})})}function bL({className:e,...t}){return(0,R.jsx)(fi,{role:`status`,"aria-label":`Loading`,className:L(`size-4 animate-spin`,e),...t})}function xL({server:e,className:t,size:n=`md`}){let[r,i]=(0,z.useState)(!0),[a,o]=(0,z.useState)(!1),s={sm:`w-6 h-6`,md:`w-8 h-8`,lg:`w-12 h-12`,xs:`w-4 h-4`},c=(()=>{let t=e.serverInfo?.icons;return t&&Array.isArray(t)&&t.length>0?t[0].src:e.serverInfo?.icon?e.serverInfo.icon:null})();(0,z.useEffect)(()=>{i(c!==null),o(!1)},[c]);let l=bM(e);return!c||a?(0,R.jsx)(yL,{delay:.05,offset:0,children:(0,R.jsx)(lo,{className:L(`flex items-center justify-center rounded-full overflow-hidden`,s[n],t)})}):(0,R.jsx)(yL,{delay:.05,offset:0,children:(0,R.jsxs)(`div`,{className:L(`rounded-md overflow-hidden flex items-center justify-center bg-white dark:bg-zinc-800 relative`,s[n],t),children:[r&&(0,R.jsx)(`div`,{className:`absolute inset-0 flex items-center justify-center bg-zinc-100/80 dark:bg-zinc-800/80`,children:(0,R.jsx)(bL,{})}),(0,R.jsx)(`img`,{src:c,alt:l,className:L(`object-contain`,s[n]),onLoad:()=>i(!1),onError:()=>{i(!1),o(!0)},style:{imageRendering:`-webkit-optimize-contrast`,display:r?`none`:`block`}})]})})}var SL=[`#e0eaff`,`#f9ffbd`,`#dedede`,`#ffffff`];function CL(){let{servers:e,addServer:t,removeServer:n}=Aj(),r=(0,z.useRef)(new Set);(0,z.useEffect)(()=>{e.forEach(e=>{if(e.state===`ready`&&!r.current.has(e.id)){r.current.add(e.id);try{PT(new To({serverId:e.id,serverUrl:e.url??``,success:!0,connectionType:`http`})).catch(()=>{})}catch{}}else e.state===`failed`&&r.current.has(e.id)&&r.current.delete(e.id)})},[e]);let i=(0,z.useCallback)(e=>{try{PT(new Oo({serverId:e})).catch(()=>{})}catch{}r.current.delete(e),n(e,{clearCredentials:!0})},[n]),[a,o]=(0,z.useState)(new Set),s=(0,z.useRef)(new Set);(0,z.useEffect)(()=>{s.current=a},[a]);let c=(0,z.useCallback)(async t=>{if(s.current.has(t)){console.warn(`[InspectorDashboard] Connection ${t} is already being reconnected, skipping`);return}let n=e.find(e=>e.id===t);if(n){o(e=>new Set(e).add(t));try{await n.reconnect()}catch(e){console.error(`[InspectorDashboard] Failed to reconnect server ${t}:`,e)}finally{o(e=>{let n=new Set(e);return n.delete(t),n})}}},[e]),l=sP(),u=iP(),[d,f]=(0,z.useState)(new Set),[p,m]=(0,z.useState)(null);(0,z.useEffect)(()=>{FT({connectionCount:e.length}).catch(()=>{})},[]);let[h,g]=(0,z.useState)(``),[_,v]=(0,z.useState)(``),[y,b]=(0,z.useState)(`auto`),[x,S]=(0,z.useState)(`auto`),[C,w]=(0,z.useState)([]),[T,E]=(0,z.useState)(`10000`),[ee,D]=(0,z.useState)(`True`),[te,ne]=(0,z.useState)(`60000`),[re,O]=(0,z.useState)(TM()),[ie,k]=(0,z.useState)(``),[A,j]=(0,z.useState)(``),[ae,oe]=(0,z.useState)(``),se=(0,z.useRef)(null),{paused:ce,toggle:M}=vo(ho),N=(0,z.useCallback)(()=>{if(!_.trim())return;let e=_.trim();try{let t=new URL(e);if(!(t.protocol===`http:`||t.protocol===`https:`)){oI.error(`Invalid URL protocol. Please use http:// or https://`);return}}catch{try{let t=`https://${e}`,n=new URL(t);if(!(n.protocol===`http:`||n.protocol===`https:`)){oI.error(`Invalid URL protocol. Please use http:// or https://`);return}e=t}catch{oI.error(`Invalid URL format. Please enter a valid URL.`);return}}let n=C.reduce((e,t)=>(t.name&&t.value&&(e[t.name]=t.value),e),{}),r=y===`proxy`&&re.trim()?{proxyAddress:re.trim(),headers:n}:void 0,i=y===`auto`&&re.trim()?{enabled:!0,proxyAddress:re.trim()}:!1,a=jM(ie,A,ae),o={url:e,displayName:h.trim()||e,connectionMode:y,protocolNegotiation:CM(x),autoProxyFallback:i,...r?{proxyConfig:r}:{},...Object.keys(n).length>0&&!r?{headers:n}:{},...a?{oauth:a}:{}};t(e,o),PT(new Do({serverId:_.trim(),serverUrl:_.trim(),connectionType:`http`,viaProxy:!!r?.proxyAddress})).catch(()=>{}),g(``),v(``),w([]),b(`auto`),S(`auto`),k(``),j(``),oe(``),oI.success(`Server added successfully`)},[_,h,y,x,re,C,ie,A,ae,t]),le=()=>{e.forEach(e=>{i(e.id)})},ue=async e=>{try{await lM(e),oI.success(`Error message copied to clipboard`)}catch{oI.error(`Failed to copy error message`)}},de=async e=>{try{let t=FM(e,IM(e.id));await lM(JSON.stringify(t,null,2)),oI.success(`Connection configuration copied to clipboard`)}catch{oI.error(`Failed to copy connection configuration`)}},fe=(e,t)=>{e.stopPropagation(),t()},pe=(e,t)=>{let n=new URLSearchParams(u.search).get(`tunnelUrl`),r=new URLSearchParams;r.set(`server`,e.id),r.set(`tab`,t),n&&r.set(`tunnelUrl`,n),l(`/?${r.toString()}`)},me=e=>{if(e.state===`failed`)return;let t=new URLSearchParams(u.search),n=t.get(`tunnelUrl`),r=t.get(`tab`),i=new URLSearchParams;i.set(`server`,e.id),n&&i.set(`tunnelUrl`,n),r&&i.set(`tab`,r),l(`/?${i.toString()}`)},he=e=>{console.log(`[InspectorDashboard] Reconnecting server:`,e.id),e.state===`failed`&&e.retry?e.retry():c(e.id)};return(0,z.useEffect)(()=>{f(t=>{let n=new Set(t),r=!1;return t.forEach(t=>{let i=e.find(e=>e.id===t);i&&(i.state===`ready`||i.state===`failed`)&&(n.delete(t),r=!0)}),r?n:t})},[e]),(0,z.useEffect)(()=>{if(!p)return;let t=e.find(e=>e.id===p),n=(t?.tools?.length||0)>0||(t?.resources?.length||0)>0||(t?.prompts?.length||0)>0;if(t&&(t.state===`ready`||n&&t.state!==`discovering`)){m(null);let e=new URLSearchParams(u.search),n=e.get(`tunnelUrl`),r=e.get(`tab`),i=new URLSearchParams;i.set(`server`,t.id),n&&i.set(`tunnelUrl`,n),r&&i.set(`tab`,r),l(`/?${i.toString()}`)}else t&&t.state===`failed`&&!n&&t.error&&(console.warn(`[InspectorDashboard] Connection failed with no data, canceling navigation`),m(null))},[e,p,l]),(0,R.jsxs)(`div`,{className:`flex flex-col lg:flex-row items-start justify-start gap-4 h-auto lg:h-full relative`,children:[(0,R.jsxs)(`div`,{className:`w-full px-3 pt-6 sm:px-6 sm:pt-3 overflow-visible lg:overflow-auto`,children:[(0,R.jsxs)(`div`,{className:`flex mb-3 md:mb-0 flex-col sm:flex-row items-center sm:items-center gap-3 relative z-10`,children:[(0,R.jsxs)(et,{children:[(0,R.jsx)(we,{render:(0,R.jsx)(`a`,{href:`https://github.com/mcp-use/mcp-use`,target:`_blank`,rel:`noopener noreferrer`,className:`inline-block order-1 sm:order-2`,children:(0,R.jsxs)(F,{variant:`secondary`,className:`text-xs cursor-pointer hover:bg-secondary/80 transition-colors`,children:[`v`,Lo()]})}),nativeButton:!1}),(0,R.jsx)(lt,{children:(0,R.jsx)(`p`,{children:`Visit GitHub`})})]}),(0,R.jsx)(`h2`,{className:`text-2xl font-medium tracking-tight text-center sm:text-left order-2 sm:order-1`,children:`MCP Inspector`})]}),(0,R.jsx)(`p`,{className:`text-muted-foreground relative z-10 text-center sm:text-left`,children:`Inspect and debug MCP (Model Context Protocol) servers`}),(0,R.jsxs)(`div`,{className:`space-y-4 mt-4 sm:mt-8`,children:[(0,R.jsxs)(`div`,{className:`flex flex-col sm:flex-row items-center sm:items-center justify-between gap-3`,children:[(0,R.jsx)(`h3`,{className:`hidden sm:block text-base font-medium text-center sm:text-left`,children:`Connected Servers`}),(0,R.jsx)(`div`,{className:`hidden sm:flex items-center gap-3 justify-center sm:justify-start`,children:e.length>0&&(0,R.jsx)(Gt,{variant:`ghost`,size:`sm`,onClick:le,children:`Clear All`})})]}),e.length===0?(0,R.jsx)(ro,{message:`No servers connected yet. Add a server above to get started.`}):(0,R.jsx)(`div`,{className:`grid gap-3`,children:e.map(e=>(0,R.jsxs)(`div`,{"data-testid":`server-tile-${e.id}`,onClick:()=>me(e),className:`group rounded-lg bg-zinc-100 dark:bg-white/10 p-4 transition-colors ${e.state===`ready`?`hover:bg-zinc-200 dark:hover:bg-white/15 cursor-pointer`:``}`,children:[(0,R.jsxs)(`div`,{className:`flex items-center justify-between gap-3`,children:[(0,R.jsxs)(`div`,{className:`flex-1 min-w-0`,children:[(0,R.jsxs)(`div`,{className:`flex items-center gap-3`,children:[(0,R.jsx)(xL,{server:e,size:`md`}),(0,R.jsx)(`h4`,{className:`font-semibold text-sm`,children:bM(e)}),(0,R.jsx)(`div`,{className:`flex items-center gap-2`,children:a.has(e.id)?(0,R.jsx)(fi,{className:`w-3 h-3 animate-spin text-blue-500`}):e.error&&e.state!==`ready`?(0,R.jsxs)(et,{children:[(0,R.jsx)(we,{render:(0,R.jsx)(`button`,{type:`button`,"data-testid":`server-tile-status-${e.state}`,onClick:t=>{t.stopPropagation(),ue(e.error)},className:`w-2 h-2 rounded-full transition-colors ${(e.error.includes(`401`)||e.error.includes(`Unauthorized`))&&e.error.includes(`does not support OAuth`)?`bg-yellow-500 animate-status-pulse-yellow hover:bg-yellow-600`:`bg-rose-500 animate-status-pulse-red hover:bg-rose-600`}`,title:`Click to copy error message`,"aria-label":`Copy error message to clipboard`}),nativeButton:!0}),(0,R.jsx)(lt,{children:(0,R.jsx)(`p`,{className:`max-w-xs`,children:e.error})})]}):(0,R.jsx)(`div`,{"data-testid":`server-tile-status-${e.state}`,className:`w-2 h-2 rounded-full ${e.state===`ready`?`bg-emerald-600 animate-status-pulse`:e.state===`failed`?`bg-rose-600 animate-status-pulse-red`:`bg-yellow-500 animate-status-pulse-yellow`}`})})]}),(0,R.jsxs)(`div`,{className:`flex items-center gap-2 mt-1`,children:[(0,R.jsx)(`p`,{className:`text-xs text-muted-foreground dark:text-zinc-400 font-mono`,children:e.url}),(0,R.jsxs)(et,{children:[(0,R.jsx)(we,{render:(0,R.jsx)(`button`,{type:`button`,onClick:async t=>{t.stopPropagation();try{await lM(e.url??``),oI.success(`URL copied to clipboard`)}catch{oI.error(`Failed to copy URL`)}},className:`opacity-0 group-hover:opacity-100 transition-opacity p-1 hover:bg-white/10 rounded`,title:`Copy URL`,children:(0,R.jsx)(Wr,{className:`w-3 h-3 text-muted-foreground`})}),nativeButton:!0}),(0,R.jsx)(lt,{children:(0,R.jsx)(`p`,{children:`Copy URL`})})]})]})]}),(0,R.jsxs)(`div`,{className:`hidden lg:flex items-center gap-1 flex-shrink-0`,children:[(0,R.jsxs)(et,{children:[(0,R.jsx)(we,{render:(0,R.jsx)(Gt,{"data-testid":`server-tile-copy-config`,variant:`secondary`,size:`sm`,onClick:t=>fe(t,()=>de(e)),className:`h-8 w-8 p-0`,children:(0,R.jsx)(Wr,{className:`w-4 h-4`})}),nativeButton:!0}),(0,R.jsx)(lt,{children:(0,R.jsx)(`p`,{children:`Copy connection config`})})]}),(0,R.jsxs)(et,{children:[(0,R.jsx)(we,{render:(0,R.jsx)(Gt,{"data-testid":`server-tile-info`,variant:`secondary`,size:`sm`,onClick:t=>fe(t,()=>pe(e,`server-metadata`)),className:`h-8 w-8 p-0`,children:(0,R.jsx)(si,{className:`w-4 h-4`})}),nativeButton:!0}),(0,R.jsx)(lt,{children:(0,R.jsx)(`p`,{children:`View server info`})})]}),(0,R.jsxs)(et,{children:[(0,R.jsx)(we,{render:(0,R.jsx)(Gt,{"data-testid":`server-tile-settings`,variant:`secondary`,size:`sm`,onClick:t=>fe(t,()=>pe(e,`connection-settings`)),className:`h-8 w-8 p-0`,children:(0,R.jsx)(Ii,{className:`w-4 h-4`})}),nativeButton:!0}),(0,R.jsx)(lt,{children:(0,R.jsx)(`p`,{children:`Edit connection settings`})})]}),(0,R.jsxs)(et,{children:[(0,R.jsx)(we,{render:(0,R.jsx)(Gt,{"data-testid":`server-tile-remove`,variant:`secondary`,size:`sm`,onClick:t=>fe(t,()=>i(e.id)),className:`h-8 w-8 p-0`,children:(0,R.jsx)(Rr,{className:`w-4 h-4`})}),nativeButton:!0}),(0,R.jsx)(lt,{children:(0,R.jsx)(`p`,{children:`Remove connection`})})]}),(e.state===`ready`||e.state===`failed`||e.state===`discovering`)&&(0,R.jsxs)(et,{children:[(0,R.jsx)(we,{render:(0,R.jsx)(Gt,{"data-testid":`server-tile-reconnect`,variant:`secondary`,size:`sm`,onClick:t=>fe(t,()=>he(e)),className:`h-8 w-8 p-0`,children:(0,R.jsx)(Ni,{className:`w-4 h-4`})}),nativeButton:!0}),(0,R.jsx)(lt,{children:(0,R.jsx)(`p`,{children:e.state===`failed`?`Retry connection`:e.state===`discovering`?`Reconnect`:`Resync connection`})})]})]}),(0,R.jsx)(`div`,{className:`lg:hidden flex-shrink-0`,children:(0,R.jsxs)(Ya,{children:[(0,R.jsx)(Xa,{render:(0,R.jsx)(Gt,{variant:`ghost`,size:`sm`,className:`h-8 w-8 p-0`,onClick:e=>e.stopPropagation(),children:(0,R.jsx)(Jr,{className:`h-4 w-4`})}),nativeButton:!0}),(0,R.jsxs)(Za,{align:`end`,children:[(0,R.jsxs)($a,{onClick:t=>{t.stopPropagation(),de(e)},children:[(0,R.jsx)(Wr,{className:`h-4 w-4 mr-2`}),`Copy connection config`]}),(0,R.jsxs)($a,{onClick:t=>{t.stopPropagation(),pe(e,`server-metadata`)},children:[(0,R.jsx)(si,{className:`h-4 w-4 mr-2`}),`View server info`]}),(0,R.jsxs)($a,{onClick:t=>{t.stopPropagation(),pe(e,`connection-settings`)},children:[(0,R.jsx)(Ii,{className:`h-4 w-4 mr-2`}),`Edit connection settings`]}),(e.state===`ready`||e.state===`failed`||e.state===`discovering`)&&(0,R.jsxs)($a,{onClick:t=>{t.stopPropagation(),he(e)},children:[(0,R.jsx)(Ni,{className:`h-4 w-4 mr-2`}),e.state===`failed`?`Retry connection`:e.state===`discovering`?`Reconnect`:`Resync connection`]}),(0,R.jsxs)($a,{onClick:t=>{t.stopPropagation(),i(e.id)},className:`text-destructive focus:text-destructive`,children:[(0,R.jsx)(Rr,{className:`h-4 w-4 mr-2`}),`Remove connection`]})]})]})})]}),(e.state===`pending_auth`||e.state===`authenticating`)&&(0,R.jsx)(`div`,{className:`text-sm text-yellow-600 dark:text-yellow-400 mt-2`,children:e.state===`authenticating`?(0,R.jsxs)(Gt,{size:`sm`,className:`bg-yellow-500/20 border-0 dark:bg-yellow-400/10 text-yellow-800 dark:text-yellow-500`,variant:`outline`,disabled:!0,children:[(0,R.jsx)(fi,{className:`mr-2 h-4 w-4 animate-spin`}),`Authenticating...`]}):e.authUrl?(0,R.jsx)(Gt,{"data-testid":`server-tile-authenticate`,size:`sm`,className:`bg-yellow-500/20 border-0 dark:bg-yellow-400/10 text-yellow-800 dark:text-yellow-500`,variant:`outline`,render:(0,R.jsx)(`a`,{href:e.authUrl,onClick:t=>{t.stopPropagation();try{sessionStorage.setItem(`__mcpUseInspectorReconnect`,JSON.stringify({url:e.url,name:e.name||`Auto-connected Server`,transportType:e.transportType||`http`,connectionMode:`auto`}))}catch{}}}),nativeButton:!1,children:`Authenticate`}):null}),e.state===`failed`&&e.error&&(e.error.includes(`401`)||e.error.includes(`Unauthorized`))&&e.error.includes(`does not support OAuth`)&&(0,R.jsx)(`div`,{className:`text-sm mt-2 p-2 bg-yellow-500/10 dark:bg-yellow-400/10 border border-yellow-500/20 dark:border-yellow-400/20 rounded text-yellow-800 dark:text-yellow-400`,children:e.error})]},e.id))})]})]}),(0,R.jsxs)(`div`,{ref:se,className:`w-full relative overflow-hidden h-auto lg:h-full py-4 px-4 sm:py-6 sm:px-6 lg:p-10 items-center justify-center flex`,children:[(0,R.jsx)(`div`,{className:`absolute inset-0 z-0 overflow-hidden dark:opacity-60 pointer-events-none`,children:(0,R.jsx)(mo,{className:`h-full w-full`,colors:SL,distortion:.8,swirl:.1,grainMixer:0,grainOverlay:.2,speed:+!ce})}),(0,R.jsx)(`div`,{className:`absolute inset-0 z-[1] pointer-events-none opacity-[0.07] mix-blend-soft-light dark:opacity-[0.06]`,"aria-hidden":!0,children:(0,R.jsx)(`div`,{className:`absolute inset-0 noise`,style:{background:`url("${oo}")`,filter:`contrast(150%) brightness(550%)`}})}),(0,R.jsx)(bo,{paused:ce,onToggle:M,className:`absolute bottom-3 right-3 sm:bottom-5 sm:right-5`}),(0,R.jsx)(`div`,{className:`relative w-full max-w-xl mx-auto z-10 flex flex-col gap-3 rounded-3xl p-4 sm:p-6 bg-black/70 dark:bg-black/90 shadow-2xl shadow-black/50 backdrop-blur-md`,children:(0,R.jsx)(vL,{alias:h,setAlias:g,url:_,setUrl:v,connectionMode:y,setConnectionMode:b,protocolMode:x,setProtocolMode:S,customHeaders:C,setCustomHeaders:w,requestTimeout:T,setRequestTimeout:E,resetTimeoutOnProgress:ee,setResetTimeoutOnProgress:D,maxTotalTimeout:te,setMaxTotalTimeout:ne,proxyAddress:re,setProxyAddress:O,clientId:ie,setClientId:k,clientSecret:A,setClientSecret:j,scope:ae,setScope:oe,onConnect:N,variant:`styled`,showConnectButton:!0,showExportButton:!0})})]})]})}var wL=(0,z.createContext)(void 0);function TL({children:e}){let t=(typeof window<`u`?window.__MANUFACT_CHAT_URL__:void 0)??void 0,[n,r]=(0,z.useState)({selectedServerId:null,activeTab:`tools`,selectedToolName:null,selectedPromptName:null,selectedResourceUri:null,selectedSamplingRequestId:null,selectedElicitationRequestId:null,tunnelUrl:null,isTunnelStarting:!1,isEmbedded:!1,embeddedConfig:t?{chatApiUrl:t,chatStreamProtocol:`data-stream`,chatEnableFreeTierUpgrade:!0}:{}}),i=(0,z.useCallback)(e=>{r(t=>({...t,selectedServerId:e}))},[]),a=(0,z.useCallback)(e=>{r(t=>({...t,activeTab:e}))},[]),o=(0,z.useCallback)(e=>{r(t=>({...t,selectedToolName:e}))},[]),s=(0,z.useCallback)(e=>{r(t=>({...t,selectedPromptName:e}))},[]),c=(0,z.useCallback)(e=>{r(t=>({...t,selectedResourceUri:e}))},[]),l=(0,z.useCallback)(e=>{r(t=>({...t,selectedSamplingRequestId:e}))},[]),u=(0,z.useCallback)(e=>{r(t=>({...t,selectedElicitationRequestId:e}))},[]),d=(0,z.useCallback)(e=>{r(t=>({...t,tunnelUrl:e}))},[]),f=(0,z.useCallback)(e=>{r(t=>({...t,isTunnelStarting:e}))},[]),p=(0,z.useCallback)((e,t={})=>{r(n=>({...n,isEmbedded:e,embeddedConfig:t}))},[]),m=(0,z.useCallback)((e,t,n)=>{console.warn(`[InspectorContext] navigateToItem called:`,{serverId:e,tab:t,itemIdentifier:n}),r(r=>({...r,selectedServerId:e,activeTab:t,selectedToolName:t===`tools`&&n||null,selectedPromptName:t===`prompts`&&n||null,selectedResourceUri:t===`resources`&&n||null,selectedSamplingRequestId:t===`sampling`&&n||null,selectedElicitationRequestId:t===`elicitation`&&n||null}))},[]),h=(0,z.useCallback)(()=>{r(e=>({...e,selectedToolName:null,selectedPromptName:null,selectedResourceUri:null,selectedSamplingRequestId:null,selectedElicitationRequestId:null}))},[]);return(0,R.jsx)(wL,{value:{...n,setSelectedServerId:i,setActiveTab:a,setSelectedToolName:o,setSelectedPromptName:s,setSelectedResourceUri:c,setSelectedSamplingRequestId:l,setSelectedElicitationRequestId:u,setTunnelUrl:d,setIsTunnelStarting:f,setEmbeddedMode:p,navigateToItem:m,clearSelection:h},children:e})}function EL(){let e=(0,z.use)(wL);if(!e)throw Error(`useInspector must be used within InspectorProvider`);return e}function DL(e){(0,z.useEffect)(()=>{let t=t=>{let n=t.target,r=n.tagName===`INPUT`||n.tagName===`TEXTAREA`||n.contentEditable===`true`;if((t.metaKey||t.ctrlKey)&&t.key===`k`){t.preventDefault(),e.onCommandPalette?.();return}if((t.metaKey||t.ctrlKey)&&t.key===`o`&&e.onNewChat){t.preventDefault(),e.onNewChat();return}if(t.key===`Escape`){t.preventDefault(),document.activeElement instanceof HTMLElement&&document.activeElement.blur(),e.onBlurSearch?.();return}if(!r&&!(t.metaKey||t.ctrlKey||t.altKey||t.shiftKey))switch(t.key.toLowerCase()){case`t`:t.preventDefault(),e.onToolsTab?.();break;case`p`:t.preventDefault(),e.onPromptsTab?.();break;case`r`:t.preventDefault(),e.onResourcesTab?.();break;case`c`:t.preventDefault(),e.onChatTab?.();break;case`h`:t.preventDefault(),e.onHome?.();break;case`f`:t.preventDefault(),e.onFocusSearch?.();break;default:break}};return document.addEventListener(`keydown`,t),()=>document.removeEventListener(`keydown`,t)},[e])}var OL=`mcp-inspector-saved-requests`;function kL(){let[e,t]=(0,z.useState)([]);return(0,z.useEffect)(()=>{try{let e=localStorage.getItem(OL);e&&t(JSON.parse(e))}catch(e){console.error(`[useSavedRequests] Failed to load saved requests:`,e)}},[]),(0,z.useEffect)(()=>{let e=e=>{if(e.key===OL&&e.newValue)try{t(JSON.parse(e.newValue))}catch(e){console.error(`[useSavedRequests] Failed to parse saved requests:`,e)}};return window.addEventListener(`storage`,e),()=>window.removeEventListener(`storage`,e)},[]),{savedRequests:e,saveSavedRequests:(0,z.useCallback)(e=>{try{localStorage.setItem(OL,JSON.stringify(e)),t(e)}catch(e){console.error(`[useSavedRequests] Failed to save requests:`,e)}},[])}}function AL(e){return e.replace(/[^a-zA-Z0-9-_]/g,`_`).toLowerCase()}function jL(e){return`'${e.replace(/'/g,`'\\''`)}'`}function ML(e){return e.replace(/[^a-zA-Z0-9]/g,`_`).toUpperCase().replace(/^_+|_+$/g,``)}function NL(e,t,n){let r={url:e};if(n&&Object.keys(n).length>0){let e={};for(let[t]of Object.entries(n))e[t]=`{{${ML(t)}}}`;r.headers=e}let i=JSON.stringify(r);return`cursor://anysphere.cursor-deeplink/mcp/install?config=${btoa(i)}&name=${encodeURIComponent(AL(t))}`}function PL(e,t,n){let r={url:e,name:AL(t),type:`http`};if(n&&Object.keys(n).length>0){let e={};for(let[t]of Object.entries(n))e[t]=`your-${ML(t)}-value`;r.headers=e}let i=JSON.stringify(r);return`vscode:mcp/install?${encodeURIComponent(i)}`}function FL(e,t,n){let r={url:e,name:AL(t),type:`http`};if(n&&Object.keys(n).length>0){let e={};for(let[t]of Object.entries(n))e[t]=`your-${ML(t)}-value`;r.headers=e}let i=JSON.stringify(r);return`vscode-insiders:mcp/install?${encodeURIComponent(i)}`}function IL(e,t,n){let r={url:e,name:AL(t)};if(n&&Object.keys(n).length>0){let e={};for(let[t]of Object.entries(n))e[t]=`your-${ML(t)}-value`;r.headers=e}return r}function LL(e,t,n){try{let r=IL(e,t,n),i=JSON.stringify(r,null,2),a=globalThis.Blob,o=new a([i],{type:`application/json`}),s=URL.createObjectURL(o),c=document.createElement(`a`);c.href=s,c.download=`${AL(t)}.mcpb`,document.body.appendChild(c),c.click(),document.body.removeChild(c),URL.revokeObjectURL(s)}catch(e){throw console.error(`Failed to download .mcpb file:`,e),e}}function RL(e,t,n){let r=`claude mcp add --transport http "${AL(t)}" \\\n ${jL(e)}`,i=[];if(n&&Object.keys(n).length>0)for(let[e]of Object.entries(n)){let t=ML(e);r+=` \\\n --header ${jL(`${e}:\${${t}}`)}`,i.push({name:t,header:e})}return{command:r,envVars:i}}function zL(e,t,n){let r=`gemini mcp add --transport http "${AL(t)}" ${jL(e)}`,i=[];if(n&&Object.keys(n).length>0)for(let[e]of Object.entries(n)){let t=ML(e);r+=` \\\n --header ${jL(`${e}:\${${t}}`)}`,i.push({name:t,header:e})}return{command:r,envVars:i}}function BL(e,t,n){let r=`[mcp_servers.${AL(t)}]\nurl = "${e}"`,i=[];if(n&&Object.keys(n).length>0){let e=[];for(let[t]of Object.entries(n)){let n=ML(t);e.push(`"${t}" = "your-${n}-value"`),i.push({name:n,header:t})}if(r+=`\nhttp_headers = { ${e.join(`, `)} }`,i.length>0){r+=`
|
|
494
|
+
Please change the parent <Route path="${e}"> to <Route path="${e===`/`?`*`:`${e}/*`}">.`)}let u=PN(),d;if(t){let e=typeof t==`string`?EM(t):t;bM(c===`/`||e.pathname?.startsWith(c),`When overriding the location using \`<Routes location>\` or \`useRoutes(routes, location)\`, the location pathname must begin with the portion of the URL pathname that was matched by all parent routes. The current pathname base is "${c}" but pathname "${e.pathname}" was given in the \`location\` prop.`),d=e}else d=u;let f=d.pathname||`/`,p=f;if(c!==`/`){let e=c.replace(/^\//,``).split(`/`);p=`/`+f.replace(/^\//,``).split(`/`).slice(e.length).join(`/`)}let m=n&&n.state.matches.length?n.state.matches.map(e=>Object.assign(e,{route:n.manifest[e.route.id]||e.route})):kM(e,{pathname:p});xM(l||m!=null,`No routes matched location "${d.pathname}${d.search}${d.hash}" `),xM(m==null||m[m.length-1].route.element!==void 0||m[m.length-1].route.Component!==void 0||m[m.length-1].route.lazy!==void 0,`Matched leaf route at location "${d.pathname}${d.search}${d.hash}" does not have an element or Component. This means it will render an <Outlet /> with a null value by default resulting in an "empty" page.`);let h=YN(m&&m.map(e=>Object.assign({},e,{params:Object.assign({},o,e.params),pathname:iN([c,r.encodeLocation?r.encodeLocation(e.pathname.replace(/%/g,`%25`).replace(/\?/g,`%3F`).replace(/#/g,`%23`)).pathname:e.pathname]),pathnameBase:e.pathnameBase===`/`?c:iN([c,r.encodeLocation?r.encodeLocation(e.pathnameBase.replace(/%/g,`%25`).replace(/\?/g,`%3F`).replace(/#/g,`%23`)).pathname:e.pathnameBase])})),i,n);return t&&h?z.createElement(wN.Provider,{value:{location:{pathname:`/`,search:``,hash:``,state:null,key:`default`,mask:void 0,...d},navigationType:`POP`}},h):h}function UN(){let e=iP(),t=uN(e)?`${e.status} ${e.statusText}`:e instanceof Error?e.message:JSON.stringify(e),n=e instanceof Error?e.stack:null,r=`rgba(200,200,200, 0.5)`,i={padding:`0.5rem`,backgroundColor:r},a={padding:`2px 4px`,backgroundColor:r},o=null;return console.error(`Error handled by React Router default ErrorBoundary:`,e),o=z.createElement(z.Fragment,null,z.createElement(`p`,null,`💿 Hey developer 👋`),z.createElement(`p`,null,`You can provide a way better UX than this when your app throws errors by providing your own `,z.createElement(`code`,{style:a},`ErrorBoundary`),` or`,` `,z.createElement(`code`,{style:a},`errorElement`),` prop on your route.`)),z.createElement(z.Fragment,null,z.createElement(`h2`,null,`Unexpected Application Error!`),z.createElement(`h3`,{style:{fontStyle:`italic`}},t),n?z.createElement(`pre`,{style:i},n):null,o)}var WN=z.createElement(UN,null),GN=class extends z.Component{constructor(e){super(e),this.state={location:e.location,revalidation:e.revalidation,error:e.error}}static getDerivedStateFromError(e){return{error:e}}static getDerivedStateFromProps(e,t){return t.location!==e.location||t.revalidation!==`idle`&&e.revalidation===`idle`?{error:e.error,location:e.location,revalidation:e.revalidation}:{error:e.error===void 0?t.error:e.error,location:t.location,revalidation:e.revalidation||t.revalidation}}componentDidCatch(e,t){this.props.onError?this.props.onError(e,t):console.error(`React Router caught the following error during render`,e)}render(){let e=this.state.error;if(this.context&&typeof e==`object`&&e&&`digest`in e&&typeof e.digest==`string`){let t=jN(e.digest);t&&(e=t)}let t=e===void 0?this.props.children:z.createElement(TN.Provider,{value:this.props.routeContext},z.createElement(EN.Provider,{value:e,children:this.props.component}));return this.context?z.createElement(qN,{error:e},t):t}};GN.contextType=vN;var KN=new WeakMap;function qN({children:e,error:t}){let{basename:n}=z.useContext(CN);if(typeof t==`object`&&t&&`digest`in t&&typeof t.digest==`string`){let e=AN(t.digest);if(e){let r=KN.get(t);if(r)throw r;let i=pN(e.location,n);if(fN&&!KN.get(t))if(i.isExternal||e.reloadDocument)window.location.href=i.absoluteURL||i.to;else{let n=Promise.resolve().then(()=>window.__reactRouterDataRouter.navigate(i.to,{replace:e.replace}));throw KN.set(t,n),n}return z.createElement(`meta`,{httpEquiv:`refresh`,content:`0;url=${i.absoluteURL||i.to}`})}}return e}function JN({routeContext:e,match:t,children:n}){let r=z.useContext(gN);return r&&r.static&&r.staticContext&&(t.route.errorElement||t.route.ErrorBoundary)&&(r.staticContext._deepestRenderedBoundaryId=t.route.id),z.createElement(TN.Provider,{value:e},n)}function YN(e,t=[],n){let r=n?.state;if(e==null){if(!r)return null;if(r.errors)e=r.matches;else if(t.length===0&&!r.initialized&&r.matches.length>0)e=r.matches;else return null}let i=e,a=r?.errors;if(a!=null){let e=i.findIndex(e=>e.route.id&&a?.[e.route.id]!==void 0);bM(e>=0,`Could not find a matching route for errors on route IDs: ${Object.keys(a).join(`,`)}`),i=i.slice(0,Math.min(i.length,e+1))}let o=!1,s=-1;if(n&&r){o=r.renderFallback;for(let e=0;e<i.length;e++){let t=i[e];if((t.route.HydrateFallback||t.route.hydrateFallbackElement)&&(s=e),t.route.id){let{loaderData:e,errors:a}=r,c=t.route.loader&&!e.hasOwnProperty(t.route.id)&&(!a||a[t.route.id]===void 0);if(t.route.lazy||c){n.isStatic&&(o=!0),i=s>=0?i.slice(0,s+1):[i[0]];break}}}}let c=n?.onError,l=r&&c?(e,t)=>{c(e,{location:r.location,params:r.matches?.[0]?.params??{},pattern:dN(r.matches),errorInfo:t})}:void 0;return i.reduceRight((e,n,c)=>{let u,d=!1,f=null,p=null;r&&(u=a&&n.route.id?a[n.route.id]:void 0,f=n.route.errorElement||WN,o&&(s<0&&c===0?(sP(`route-fallback`,!1,"No `HydrateFallback` element provided to render during initial hydration"),d=!0,p=null):s===c&&(d=!0,p=n.route.hydrateFallbackElement||null)));let m=t.concat(i.slice(0,c+1)),h=()=>{let t;return t=u?f:d?p:n.route.Component?z.createElement(n.route.Component,null):n.route.element?n.route.element:e,z.createElement(JN,{match:n,routeContext:{outlet:e,matches:m,isDataRoute:r!=null},children:t})};return r&&(n.route.ErrorBoundary||n.route.errorElement||c===0)?z.createElement(GN,{location:r.location,revalidation:r.revalidation,component:f,error:u,children:h(),routeContext:{outlet:null,matches:m,isDataRoute:!0},onError:l}):h()},null)}function XN(e){return`${e} must be used within a data router. See https://reactrouter.com/en/main/routers/picking-a-router.`}function ZN(e){let t=z.useContext(gN);return bM(t,XN(e)),t}function QN(e){let t=z.useContext(_N);return bM(t,XN(e)),t}function $N(e){let t=z.useContext(TN);return bM(t,XN(e)),t}function eP(e){let t=$N(e),n=t.matches[t.matches.length-1];return bM(n.route.id,`${e} can only be used on routes that contain a unique "id"`),n.route.id}function tP(){return eP(`useRouteId`)}function nP(){let e=QN(`useNavigation`);return z.useMemo(()=>{let{matches:t,historyAction:n,...r}=e.navigation;return r},[e.navigation])}function rP(){let{matches:e,loaderData:t}=QN(`useMatches`);return z.useMemo(()=>e.map(e=>jM(e,t)),[e,t])}function iP(){let e=z.useContext(EN),t=QN(`useRouteError`),n=eP(`useRouteError`);return e===void 0?t.errors?.[n]:e}function aP(){let{router:e}=ZN(`useNavigate`),t=eP(`useNavigate`),n=z.useRef(!1);return IN(()=>{n.current=!0}),z.useCallback(async(r,i={})=>{xM(n.current,FN),n.current&&(typeof r==`number`?await e.navigate(r):await e.navigate(r,{fromRouteId:t,...i}))},[e,t])}var oP={};function sP(e,t,n){!t&&!oP[e]&&(oP[e]=!0,xM(!1,n))}z.memo(cP);function cP({routes:e,manifest:t,future:n,state:r,isStatic:i,onError:a}){return HN(e,void 0,{manifest:t,state:r,isStatic:i,onError:a,future:n})}function lP(e){bM(!1,`A <Route> is only ever to be used as the child of <Routes> element, never rendered directly. Please wrap your <Route> in a <Routes>.`)}function uP({basename:e=`/`,children:t=null,location:n,navigationType:r=`POP`,navigator:i,static:a=!1,useTransitions:o}){bM(!NN(),`You cannot render a <Router> inside another <Router>. You should never have more than one in your app.`);let s=e.replace(/^\/*/,`/`),c=z.useMemo(()=>({basename:s,navigator:i,static:a,useTransitions:o,future:{}}),[s,i,a,o]);typeof n==`string`&&(n=EM(n));let{pathname:l=`/`,search:u=``,hash:d=``,state:f=null,key:p=`default`,mask:m}=n,h=z.useMemo(()=>{let e=YM(l,s);return e==null?null:{location:{pathname:e,search:u,hash:d,state:f,key:p,mask:m},navigationType:r}},[s,l,u,d,f,p,r,m]);return xM(h!=null,`<Router basename="${s}"> is not able to match the URL "${l}${u}${d}" because it does not start with the basename, so the <Router> won't render anything.`),h==null?null:z.createElement(CN.Provider,{value:c},z.createElement(wN.Provider,{children:t,value:h}))}function dP({children:e,location:t}){return VN(fP(e),t)}z.Component;function fP(e,t=[]){let n=[];return z.Children.forEach(e,(e,r)=>{if(!z.isValidElement(e))return;let i=[...t,r];if(e.type===z.Fragment){n.push.apply(n,fP(e.props.children,i));return}bM(e.type===lP,`[${typeof e.type==`string`?e.type:e.type.name}] is not a <Route> component. All component children of <Routes> must be a <Route> or <React.Fragment>`),bM(!e.props.index||!e.props.children,`An index route cannot have child routes.`);let a={id:e.props.id||i.join(`-`),caseSensitive:e.props.caseSensitive,element:e.props.element,Component:e.props.Component,index:e.props.index,path:e.props.path,middleware:e.props.middleware,loader:e.props.loader,action:e.props.action,hydrateFallbackElement:e.props.hydrateFallbackElement,HydrateFallback:e.props.HydrateFallback,errorElement:e.props.errorElement,ErrorBoundary:e.props.ErrorBoundary,hasErrorBoundary:e.props.hasErrorBoundary===!0||e.props.ErrorBoundary!=null||e.props.errorElement!=null,shouldRevalidate:e.props.shouldRevalidate,handle:e.props.handle,lazy:e.props.lazy};e.props.children&&(a.children=fP(e.props.children,i)),n.push(a)}),n}var pP=`get`,mP=`application/x-www-form-urlencoded`;function hP(e){return typeof HTMLElement<`u`&&e instanceof HTMLElement}function gP(e){return hP(e)&&e.tagName.toLowerCase()===`button`}function _P(e){return hP(e)&&e.tagName.toLowerCase()===`form`}function vP(e){return hP(e)&&e.tagName.toLowerCase()===`input`}function yP(e){return!!(e.metaKey||e.altKey||e.ctrlKey||e.shiftKey)}function bP(e,t){return e.button===0&&(!t||t===`_self`)&&!yP(e)}function xP(e=``){return new URLSearchParams(typeof e==`string`||Array.isArray(e)||e instanceof URLSearchParams?e:Object.keys(e).reduce((t,n)=>{let r=e[n];return t.concat(Array.isArray(r)?r.map(e=>[n,e]):[[n,r]])},[]))}function SP(e,t){let n=xP(e);return t&&t.forEach((e,r)=>{n.has(r)||t.getAll(r).forEach(e=>{n.append(r,e)})}),n}var CP=null;function wP(){if(CP===null)try{new FormData(document.createElement(`form`),0),CP=!1}catch{CP=!0}return CP}var TP=new Set([`application/x-www-form-urlencoded`,`multipart/form-data`,`text/plain`]);function EP(e){return e!=null&&!TP.has(e)?(xM(!1,`"${e}" is not a valid \`encType\` for \`<Form>\`/\`<fetcher.Form>\` and will default to "${mP}"`),null):e}function DP(e,t){let n,r,i,a,o;if(_P(e)){let o=e.getAttribute(`action`);r=o?YM(o,t):null,n=e.getAttribute(`method`)||pP,i=EP(e.getAttribute(`enctype`))||mP,a=new FormData(e)}else if(gP(e)||vP(e)&&(e.type===`submit`||e.type===`image`)){let o=e.form;if(o==null)throw Error(`Cannot submit a <button> or <input type="submit"> without a <form>`);let s=e.getAttribute(`formaction`)||o.getAttribute(`action`);if(r=s?YM(s,t):null,n=e.getAttribute(`formmethod`)||o.getAttribute(`method`)||pP,i=EP(e.getAttribute(`formenctype`))||EP(o.getAttribute(`enctype`))||mP,a=new FormData(o,e),!wP()){let{name:t,type:n,value:r}=e;if(n===`image`){let e=t?`${t}.`:``;a.append(`${e}x`,`0`),a.append(`${e}y`,`0`)}else t&&a.append(t,r)}}else if(hP(e))throw Error(`Cannot submit element that is not <form>, <button>, or <input type="submit|image">`);else n=pP,r=null,i=mP,o=e;return a&&i===`text/plain`&&(o=a,a=void 0),{action:r,method:n.toLowerCase(),encType:i,formData:a,body:o}}Object.getOwnPropertyNames(Object.prototype).sort().join(`\0`);var OP={"&":`\\u0026`,">":`\\u003e`,"<":`\\u003c`,"\u2028":`\\u2028`,"\u2029":`\\u2029`},kP=/[&><\u2028\u2029]/g;function AP(e){return e.replace(kP,e=>OP[e])}function jP(e,t){if(e===!1||e==null)throw Error(t)}function MP(e,t,n,r){let i=typeof e==`string`?new URL(e,typeof window>`u`?`server://singlefetch/`:window.location.origin):e;return n?i.pathname.endsWith(`/`)?i.pathname=`${i.pathname}_.${r}`:i.pathname=`${i.pathname}.${r}`:i.pathname===`/`?i.pathname=`_root.${r}`:t&&YM(i.pathname,t)===`/`?i.pathname=`${aN(t)}/_root.${r}`:i.pathname=`${aN(i.pathname)}.${r}`,i}async function NP(e,t){if(e.id in t)return t[e.id];try{let n=await lS(()=>import(e.module),[]);return t[e.id]=n,n}catch(t){return console.error(`Error loading route module \`${e.module}\`, reloading page...`),console.error(t),window.__reactRouterContext&&window.__reactRouterContext.isSpaMode,window.location.reload(),new Promise(()=>{})}}function PP(e){return e!=null&&typeof e.page==`string`}function FP(e){return e==null?!1:e.href==null?e.rel===`preload`&&typeof e.imageSrcSet==`string`&&typeof e.imageSizes==`string`:typeof e.rel==`string`&&typeof e.href==`string`}async function IP(e,t,n){return VP((await Promise.all(e.map(async e=>{let r=t.routes[e.route.id];if(r){let e=await NP(r,n);return e.links?e.links():[]}return[]}))).flat(1).filter(FP).filter(e=>e.rel===`stylesheet`||e.rel===`preload`).map(e=>e.rel===`stylesheet`?{...e,rel:`prefetch`,as:`style`}:{...e,rel:`prefetch`}))}function LP(e,t,n,r,i,a){let o=(e,t)=>n[t]?e.route.id!==n[t].route.id:!0,s=(e,t)=>n[t].pathname!==e.pathname||n[t].route.path?.endsWith(`*`)&&n[t].params[`*`]!==e.params[`*`];return a===`assets`?t.filter((e,t)=>o(e,t)||s(e,t)):a===`data`?t.filter((t,a)=>{let c=r.routes[t.route.id];if(!c||!c.hasLoader)return!1;if(o(t,a)||s(t,a))return!0;if(t.route.shouldRevalidate){let r=t.route.shouldRevalidate({currentUrl:new URL(i.pathname+i.search+i.hash,window.origin),currentParams:n[0]?.params||{},nextUrl:new URL(e,window.origin),nextParams:t.params,defaultShouldRevalidate:!0});if(typeof r==`boolean`)return r}return!0}):[]}function RP(e,t,{includeHydrateFallback:n}={}){return zP(e.map(e=>{let r=t.routes[e.route.id];if(!r)return[];let i=[r.module];return r.clientActionModule&&(i=i.concat(r.clientActionModule)),r.clientLoaderModule&&(i=i.concat(r.clientLoaderModule)),n&&r.hydrateFallbackModule&&(i=i.concat(r.hydrateFallbackModule)),r.imports&&(i=i.concat(r.imports)),i}).flat(1))}function zP(e){return[...new Set(e)]}function BP(e){let t={},n=Object.keys(e).sort();for(let r of n)t[r]=e[r];return t}function VP(e,t){let n=new Set,r=new Set(t);return e.reduce((e,i)=>{if(t&&!PP(i)&&i.as===`script`&&i.href&&r.has(i.href))return e;let a=JSON.stringify(BP(i));return n.has(a)||(n.add(a),e.push({key:a,link:i})),e},[])}function HP(){let e=z.useContext(gN);return jP(e,`You must render this element inside a <DataRouterContext.Provider> element`),e}function UP(){let e=z.useContext(_N);return jP(e,`You must render this element inside a <DataRouterStateContext.Provider> element`),e}var WP=z.createContext(void 0);WP.displayName=`FrameworkContext`;function GP(){let e=z.useContext(WP);return jP(e,`You must render this element inside a <HydratedRouter> element`),e}function KP(e,t){let n=z.useContext(WP),[r,i]=z.useState(!1),[a,o]=z.useState(!1),{onFocus:s,onBlur:c,onMouseEnter:l,onMouseLeave:u,onTouchStart:d}=t,f=z.useRef(null);z.useEffect(()=>{if(e===`render`&&o(!0),e===`viewport`){let e=new IntersectionObserver(e=>{e.forEach(e=>{o(e.isIntersecting)})},{threshold:.5});return f.current&&e.observe(f.current),()=>{e.disconnect()}}},[e]),z.useEffect(()=>{if(r){let e=setTimeout(()=>{o(!0)},100);return()=>{clearTimeout(e)}}},[r]);let p=()=>{i(!0)},m=()=>{i(!1),o(!1)};return n?e===`intent`?[a,f,{onFocus:qP(s,p),onBlur:qP(c,m),onMouseEnter:qP(l,p),onMouseLeave:qP(u,m),onTouchStart:qP(d,p)}]:[a,f,{}]:[!1,f,{}]}function qP(e,t){return n=>{e&&e(n),n.defaultPrevented||t(n)}}function JP({page:e,...t}){let n=yN(),{router:r}=HP(),i=z.useMemo(()=>kM(r.routes,e,r.basename),[r.routes,e,r.basename]);return i?n?z.createElement(XP,{page:e,matches:i,...t}):z.createElement(ZP,{page:e,matches:i,...t}):null}function YP(e){let{manifest:t,routeModules:n}=GP(),[r,i]=z.useState([]);return z.useEffect(()=>{let r=!1;return IP(e,t,n).then(e=>{r||i(e)}),()=>{r=!0}},[e,t,n]),r}function XP({page:e,matches:t,...n}){let r=PN(),{future:i}=GP(),{basename:a}=HP(),o=z.useMemo(()=>{if(e===r.pathname+r.search+r.hash)return[];let n=MP(e,a,i.v8_trailingSlashAwareDataRequests,`rsc`),o=!1,s=[];for(let e of t)typeof e.route.shouldRevalidate==`function`?o=!0:s.push(e.route.id);return o&&s.length>0&&n.searchParams.set(`_routes`,s.join(`,`)),[n.pathname+n.search]},[a,i.v8_trailingSlashAwareDataRequests,e,r,t]);return z.createElement(z.Fragment,null,o.map(e=>z.createElement(`link`,{key:e,rel:`prefetch`,as:`fetch`,href:e,...n})))}function ZP({page:e,matches:t,...n}){let r=PN(),{future:i,manifest:a,routeModules:o}=GP(),{basename:s}=HP(),{loaderData:c,matches:l}=UP(),u=z.useMemo(()=>LP(e,t,l,a,r,`data`),[e,t,l,a,r]),d=z.useMemo(()=>LP(e,t,l,a,r,`assets`),[e,t,l,a,r]),f=z.useMemo(()=>{if(e===r.pathname+r.search+r.hash)return[];let n=new Set,l=!1;if(t.forEach(e=>{let t=a.routes[e.route.id];!t||!t.hasLoader||(!u.some(t=>t.route.id===e.route.id)&&e.route.id in c&&o[e.route.id]?.shouldRevalidate||t.hasClientLoader?l=!0:n.add(e.route.id))}),n.size===0)return[];let d=MP(e,s,i.v8_trailingSlashAwareDataRequests,`data`);return l&&n.size>0&&d.searchParams.set(`_routes`,t.filter(e=>n.has(e.route.id)).map(e=>e.route.id).join(`,`)),[d.pathname+d.search]},[s,i.v8_trailingSlashAwareDataRequests,c,r,a,u,t,e,o]),p=z.useMemo(()=>RP(d,a),[d,a]),m=YP(d);return z.createElement(z.Fragment,null,f.map(e=>z.createElement(`link`,{key:e,rel:`prefetch`,as:`fetch`,href:e,...n})),p.map(e=>z.createElement(`link`,{key:e,rel:`modulepreload`,href:e,...n})),m.map(({key:e,link:t})=>z.createElement(`link`,{key:e,nonce:n.nonce,...t,crossOrigin:t.crossOrigin??n.crossOrigin})))}function QP(...e){return t=>{e.forEach(e=>{typeof e==`function`?e(t):e!=null&&(e.current=t)})}}z.Component;var $P=typeof window<`u`&&window.document!==void 0&&window.document.createElement!==void 0;try{$P&&(window.__reactRouterVersion=`7.16.0`)}catch{}function eF({basename:e,children:t,useTransitions:n,window:r}){let i=z.useRef();i.current??=yM({window:r,v5Compat:!0});let a=i.current,[o,s]=z.useState({action:a.action,location:a.location}),c=z.useCallback(e=>{n===!1?s(e):z.startTransition(()=>s(e))},[n]);return z.useLayoutEffect(()=>a.listen(c),[a,c]),z.createElement(uP,{basename:e,children:t,location:o.location,navigationType:o.action,navigator:a,useTransitions:n})}function tF({basename:e,children:t,history:n,useTransitions:r}){let[i,a]=z.useState({action:n.action,location:n.location}),o=z.useCallback(e=>{r===!1?a(e):z.startTransition(()=>a(e))},[r]);return z.useLayoutEffect(()=>n.listen(o),[n,o]),z.createElement(uP,{basename:e,children:t,location:i.location,navigationType:i.action,navigator:n,useTransitions:r})}tF.displayName=`unstable_HistoryRouter`;var nF=/^(?:[a-z][a-z0-9+.-]*:|\/\/)/i,rF=z.forwardRef(function({onClick:e,discover:t=`render`,prefetch:n=`none`,relative:r,reloadDocument:i,replace:a,mask:o,state:s,target:c,to:l,preventScrollReset:u,viewTransition:d,defaultShouldRevalidate:f,...p},m){let{basename:h,navigator:g,useTransitions:_}=z.useContext(CN),v=typeof l==`string`&&nF.test(l),y=pN(l,h);l=y.to;let b=MN(l,{relative:r}),x=PN(),S=null;if(o){let e=nN(o,[],x.mask?x.mask.pathname:`/`,!0);h!==`/`&&(e.pathname=e.pathname===`/`?h:iN([h,e.pathname])),S=g.createHref(e)}let[C,w,T]=KP(n,p),E=uF(l,{replace:a,mask:o,state:s,target:c,preventScrollReset:u,relative:r,viewTransition:d,defaultShouldRevalidate:f,useTransitions:_});function ee(t){e&&e(t),t.defaultPrevented||E(t)}let D=!(y.isExternal||i),te=z.createElement(`a`,{...p,...T,href:(D?S:void 0)||y.absoluteURL||b,onClick:D?ee:e,ref:QP(m,w),target:c,"data-discover":!v&&t===`render`?`true`:void 0});return C&&!v?z.createElement(z.Fragment,null,te,z.createElement(JP,{page:b})):te});rF.displayName=`Link`;var iF=z.forwardRef(function({"aria-current":e=`page`,caseSensitive:t=!1,className:n=``,end:r=!1,style:i,to:a,viewTransition:o,children:s,...c},l){let u=BN(a,{relative:c.relative}),d=PN(),f=z.useContext(_N),{navigator:p,basename:m}=z.useContext(CN),h=f!=null&&xF(u)&&o===!0,g=p.encodeLocation?p.encodeLocation(u).pathname:u.pathname,_=d.pathname,v=f&&f.navigation&&f.navigation.location?f.navigation.location.pathname:null;t||(_=_.toLowerCase(),v=v?v.toLowerCase():null,g=g.toLowerCase()),v&&m&&(v=YM(v,m)||v);let y=g!==`/`&&g.endsWith(`/`)?g.length-1:g.length,b=_===g||!r&&_.startsWith(g)&&_.charAt(y)===`/`,x=v!=null&&(v===g||!r&&v.startsWith(g)&&v.charAt(g.length)===`/`),S={isActive:b,isPending:x,isTransitioning:h},C=b?e:void 0,w;w=typeof n==`function`?n(S):[n,b?`active`:null,x?`pending`:null,h?`transitioning`:null].filter(Boolean).join(` `);let T=typeof i==`function`?i(S):i;return z.createElement(rF,{...c,"aria-current":C,className:w,ref:l,style:T,to:a,viewTransition:o},typeof s==`function`?s(S):s)});iF.displayName=`NavLink`;var aF=z.forwardRef(({discover:e=`render`,fetcherKey:t,navigate:n,reloadDocument:r,replace:i,state:a,method:o=pP,action:s,onSubmit:c,relative:l,preventScrollReset:u,viewTransition:d,defaultShouldRevalidate:f,...p},m)=>{let{useTransitions:h}=z.useContext(CN),g=mF(),_=hF(s,{relative:l}),v=o.toLowerCase()===`get`?`get`:`post`,y=typeof s==`string`&&nF.test(s);return z.createElement(`form`,{ref:m,method:v,action:_,onSubmit:r?c:e=>{if(c&&c(e),e.defaultPrevented)return;e.preventDefault();let r=e.nativeEvent.submitter,s=r?.getAttribute(`formmethod`)||o,p=()=>g(r||e.currentTarget,{fetcherKey:t,method:s,navigate:n,replace:i,state:a,relative:l,preventScrollReset:u,viewTransition:d,defaultShouldRevalidate:f});h&&n!==!1?z.startTransition(()=>p()):p()},...p,"data-discover":!y&&e===`render`?`true`:void 0})});aF.displayName=`Form`;function oF({getKey:e,storageKey:t,...n}){let r=z.useContext(WP),{basename:i}=z.useContext(CN),a=PN(),o=rP();yF({getKey:e,storageKey:t});let s=z.useMemo(()=>{if(!r||!e)return null;let t=vF(a,o,i,e);return t===a.key?null:t},[]);if(!r||r.isSpaMode)return null;let c=((e,t)=>{if(!window.history.state||!window.history.state.key){let e=Math.random().toString(32).slice(2);window.history.replaceState({key:e},``)}try{let n=JSON.parse(sessionStorage.getItem(e)||`{}`)[t||window.history.state.key];typeof n==`number`&&window.scrollTo(0,n)}catch(t){console.error(t),sessionStorage.removeItem(e)}}).toString();return z.createElement(`script`,{...n,suppressHydrationWarning:!0,dangerouslySetInnerHTML:{__html:`(${c})(${AP(JSON.stringify(t||gF))}, ${AP(JSON.stringify(s))})`}})}oF.displayName=`ScrollRestoration`;function sF(e){return`${e} must be used within a data router. See https://reactrouter.com/en/main/routers/picking-a-router.`}function cF(e){let t=z.useContext(gN);return bM(t,sF(e)),t}function lF(e){let t=z.useContext(_N);return bM(t,sF(e)),t}function uF(e,{target:t,replace:n,mask:r,state:i,preventScrollReset:a,relative:o,viewTransition:s,defaultShouldRevalidate:c,useTransitions:l}={}){let u=LN(),d=PN(),f=BN(e,{relative:o});return z.useCallback(p=>{if(bP(p,t)){p.preventDefault();let t=n===void 0?TM(d)===TM(f):n,m=()=>u(e,{replace:t,mask:r,state:i,preventScrollReset:a,relative:o,viewTransition:s,defaultShouldRevalidate:c});l?z.startTransition(()=>m()):m()}},[d,u,f,n,r,i,t,e,a,o,s,c,l])}function dF(e){xM(typeof URLSearchParams<`u`,"You cannot use the `useSearchParams` hook in a browser that does not support the URLSearchParams API. If you need to support Internet Explorer 11, we recommend you load a polyfill such as https://github.com/ungap/url-search-params.");let t=z.useRef(xP(e)),n=z.useRef(!1),r=PN(),i=z.useMemo(()=>SP(r.search,n.current?null:t.current),[r.search]),a=LN();return[i,z.useCallback((e,t)=>{let r=xP(typeof e==`function`?e(new URLSearchParams(i)):e);n.current=!0,a(`?`+r,t)},[a,i])]}var fF=0,pF=()=>`__${String(++fF)}__`;function mF(){let{router:e}=cF(`useSubmit`),{basename:t}=z.useContext(CN),n=tP(),r=e.fetch,i=e.navigate;return z.useCallback(async(e,a={})=>{let{action:o,method:s,encType:c,formData:l,body:u}=DP(e,t);a.navigate===!1?await r(a.fetcherKey||pF(),n,a.action||o,{defaultShouldRevalidate:a.defaultShouldRevalidate,preventScrollReset:a.preventScrollReset,formData:l,body:u,formMethod:a.method||s,formEncType:a.encType||c,flushSync:a.flushSync}):await i(a.action||o,{defaultShouldRevalidate:a.defaultShouldRevalidate,preventScrollReset:a.preventScrollReset,formData:l,body:u,formMethod:a.method||s,formEncType:a.encType||c,replace:a.replace,state:a.state,fromRouteId:n,flushSync:a.flushSync,viewTransition:a.viewTransition})},[r,i,t,n])}function hF(e,{relative:t}={}){let{basename:n}=z.useContext(CN),r=z.useContext(TN);bM(r,`useFormAction must be used inside a RouteContext`);let[i]=r.matches.slice(-1),a={...BN(e||`.`,{relative:t})},o=PN();if(e==null){a.search=o.search;let e=new URLSearchParams(a.search),t=e.getAll(`index`);if(t.some(e=>e===``)){e.delete(`index`),t.filter(e=>e).forEach(t=>e.append(`index`,t));let n=e.toString();a.search=n?`?${n}`:``}}return(!e||e===`.`)&&i.route.index&&(a.search=a.search?a.search.replace(/^\?/,`?index&`):`?index`),n!==`/`&&(a.pathname=a.pathname===`/`?n:iN([n,a.pathname])),TM(a)}var gF=`react-router-scroll-positions`,_F={};function vF(e,t,n,r){let i=null;return r&&(i=r(n===`/`?e:{...e,pathname:YM(e.pathname,n)||e.pathname},t)),i??=e.key,i}function yF({getKey:e,storageKey:t}={}){let{router:n}=cF(`useScrollRestoration`),{restoreScrollPosition:r,preventScrollReset:i}=lF(`useScrollRestoration`),{basename:a}=z.useContext(CN),o=PN(),s=rP(),c=nP();z.useEffect(()=>(window.history.scrollRestoration=`manual`,()=>{window.history.scrollRestoration=`auto`}),[]),bF(z.useCallback(()=>{if(c.state===`idle`){let t=vF(o,s,a,e);_F[t]=window.scrollY}try{sessionStorage.setItem(t||gF,JSON.stringify(_F))}catch(e){xM(!1,`Failed to save scroll positions in sessionStorage, <ScrollRestoration /> will not work properly (${e}).`)}window.history.scrollRestoration=`auto`},[c.state,e,a,o,s,t])),typeof document<`u`&&(z.useLayoutEffect(()=>{try{let e=sessionStorage.getItem(t||gF);e&&(_F=JSON.parse(e))}catch{}},[t]),z.useLayoutEffect(()=>{let t=n?.enableScrollRestoration(_F,()=>window.scrollY,e?(t,n)=>vF(t,n,a,e):void 0);return()=>t&&t()},[n,a,e]),z.useLayoutEffect(()=>{if(r!==!1){if(typeof r==`number`){window.scrollTo(0,r);return}try{if(o.hash){let e=document.getElementById(decodeURIComponent(o.hash.slice(1)));if(e){e.scrollIntoView();return}}}catch{xM(!1,`"${o.hash.slice(1)}" is not a decodable element ID. The view will not scroll to it.`)}i!==!0&&window.scrollTo(0,0)}},[o,r,i]))}function bF(e,t){let{capture:n}=t||{};z.useEffect(()=>{let t=n==null?void 0:{capture:n};return window.addEventListener(`pagehide`,e,t),()=>{window.removeEventListener(`pagehide`,e,t)}},[e,n])}function xF(e,{relative:t}={}){let n=z.useContext(bN);bM(n!=null,"`useViewTransitionState` must be used within `react-router-dom`'s `RouterProvider`. Did you accidentally import `RouterProvider` from `react-router`?");let{basename:r}=cF(`useViewTransitionState`),i=BN(e,{relative:t});if(!n.isTransitioning)return!1;let a=YM(n.currentLocation.pathname,r)||n.currentLocation.pathname,o=YM(n.nextLocation.pathname,r)||n.nextLocation.pathname;return KM(i.pathname,o)!=null||KM(i.pathname,a)!=null}function SF(e){if(!e||typeof document>`u`)return;let t=document.head||document.getElementsByTagName(`head`)[0],n=document.createElement(`style`);n.type=`text/css`,t.appendChild(n),n.styleSheet?n.styleSheet.cssText=e:n.appendChild(document.createTextNode(e))}var CF=e=>{switch(e){case`success`:return EF;case`info`:return OF;case`warning`:return DF;case`error`:return kF;default:return null}},wF=Array(12).fill(0),TF=({visible:e,className:t})=>z.createElement(`div`,{className:[`sonner-loading-wrapper`,t].filter(Boolean).join(` `),"data-visible":e},z.createElement(`div`,{className:`sonner-spinner`},wF.map((e,t)=>z.createElement(`div`,{className:`sonner-loading-bar`,key:`spinner-bar-${t}`})))),EF=z.createElement(`svg`,{xmlns:`http://www.w3.org/2000/svg`,viewBox:`0 0 20 20`,fill:`currentColor`,height:`20`,width:`20`},z.createElement(`path`,{fillRule:`evenodd`,d:`M10 18a8 8 0 100-16 8 8 0 000 16zm3.857-9.809a.75.75 0 00-1.214-.882l-3.483 4.79-1.88-1.88a.75.75 0 10-1.06 1.061l2.5 2.5a.75.75 0 001.137-.089l4-5.5z`,clipRule:`evenodd`})),DF=z.createElement(`svg`,{xmlns:`http://www.w3.org/2000/svg`,viewBox:`0 0 24 24`,fill:`currentColor`,height:`20`,width:`20`},z.createElement(`path`,{fillRule:`evenodd`,d:`M9.401 3.003c1.155-2 4.043-2 5.197 0l7.355 12.748c1.154 2-.29 4.5-2.599 4.5H4.645c-2.309 0-3.752-2.5-2.598-4.5L9.4 3.003zM12 8.25a.75.75 0 01.75.75v3.75a.75.75 0 01-1.5 0V9a.75.75 0 01.75-.75zm0 8.25a.75.75 0 100-1.5.75.75 0 000 1.5z`,clipRule:`evenodd`})),OF=z.createElement(`svg`,{xmlns:`http://www.w3.org/2000/svg`,viewBox:`0 0 20 20`,fill:`currentColor`,height:`20`,width:`20`},z.createElement(`path`,{fillRule:`evenodd`,d:`M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7-4a1 1 0 11-2 0 1 1 0 012 0zM9 9a.75.75 0 000 1.5h.253a.25.25 0 01.244.304l-.459 2.066A1.75 1.75 0 0010.747 15H11a.75.75 0 000-1.5h-.253a.25.25 0 01-.244-.304l.459-2.066A1.75 1.75 0 009.253 9H9z`,clipRule:`evenodd`})),kF=z.createElement(`svg`,{xmlns:`http://www.w3.org/2000/svg`,viewBox:`0 0 20 20`,fill:`currentColor`,height:`20`,width:`20`},z.createElement(`path`,{fillRule:`evenodd`,d:`M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-8-5a.75.75 0 01.75.75v4.5a.75.75 0 01-1.5 0v-4.5A.75.75 0 0110 5zm0 10a1 1 0 100-2 1 1 0 000 2z`,clipRule:`evenodd`})),AF=z.createElement(`svg`,{xmlns:`http://www.w3.org/2000/svg`,width:`12`,height:`12`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`1.5`,strokeLinecap:`round`,strokeLinejoin:`round`},z.createElement(`line`,{x1:`18`,y1:`6`,x2:`6`,y2:`18`}),z.createElement(`line`,{x1:`6`,y1:`6`,x2:`18`,y2:`18`})),jF=()=>{let[e,t]=z.useState(document.hidden);return z.useEffect(()=>{let e=()=>{t(document.hidden)};return document.addEventListener(`visibilitychange`,e),()=>window.removeEventListener(`visibilitychange`,e)},[]),e},MF=1,NF=new class{constructor(){this.subscribe=e=>(this.subscribers.push(e),()=>{let t=this.subscribers.indexOf(e);this.subscribers.splice(t,1)}),this.publish=e=>{this.subscribers.forEach(t=>t(e))},this.addToast=e=>{this.publish(e),this.toasts=[...this.toasts,e]},this.create=e=>{let{message:t,...n}=e,r=typeof e?.id==`number`||e.id?.length>0?e.id:MF++,i=this.toasts.find(e=>e.id===r),a=e.dismissible===void 0?!0:e.dismissible;return this.dismissedToasts.has(r)&&this.dismissedToasts.delete(r),i?this.toasts=this.toasts.map(n=>n.id===r?(this.publish({...n,...e,id:r,title:t}),{...n,...e,id:r,dismissible:a,title:t}):n):this.addToast({title:t,...n,dismissible:a,id:r}),r},this.dismiss=e=>(e?(this.dismissedToasts.add(e),requestAnimationFrame(()=>this.subscribers.forEach(t=>t({id:e,dismiss:!0})))):this.toasts.forEach(e=>{this.subscribers.forEach(t=>t({id:e.id,dismiss:!0}))}),e),this.message=(e,t)=>this.create({...t,message:e}),this.error=(e,t)=>this.create({...t,message:e,type:`error`}),this.success=(e,t)=>this.create({...t,type:`success`,message:e}),this.info=(e,t)=>this.create({...t,type:`info`,message:e}),this.warning=(e,t)=>this.create({...t,type:`warning`,message:e}),this.loading=(e,t)=>this.create({...t,type:`loading`,message:e}),this.promise=(e,t)=>{if(!t)return;let n;t.loading!==void 0&&(n=this.create({...t,promise:e,type:`loading`,message:t.loading,description:typeof t.description==`function`?void 0:t.description}));let r=Promise.resolve(e instanceof Function?e():e),i=n!==void 0,a,o=r.then(async e=>{if(a=[`resolve`,e],z.isValidElement(e))i=!1,this.create({id:n,type:`default`,message:e});else if(FF(e)&&!e.ok){i=!1;let r=typeof t.error==`function`?await t.error(`HTTP error! status: ${e.status}`):t.error,a=typeof t.description==`function`?await t.description(`HTTP error! status: ${e.status}`):t.description,o=typeof r==`object`&&!z.isValidElement(r)?r:{message:r};this.create({id:n,type:`error`,description:a,...o})}else if(e instanceof Error){i=!1;let r=typeof t.error==`function`?await t.error(e):t.error,a=typeof t.description==`function`?await t.description(e):t.description,o=typeof r==`object`&&!z.isValidElement(r)?r:{message:r};this.create({id:n,type:`error`,description:a,...o})}else if(t.success!==void 0){i=!1;let r=typeof t.success==`function`?await t.success(e):t.success,a=typeof t.description==`function`?await t.description(e):t.description,o=typeof r==`object`&&!z.isValidElement(r)?r:{message:r};this.create({id:n,type:`success`,description:a,...o})}}).catch(async e=>{if(a=[`reject`,e],t.error!==void 0){i=!1;let r=typeof t.error==`function`?await t.error(e):t.error,a=typeof t.description==`function`?await t.description(e):t.description,o=typeof r==`object`&&!z.isValidElement(r)?r:{message:r};this.create({id:n,type:`error`,description:a,...o})}}).finally(()=>{i&&(this.dismiss(n),n=void 0),t.finally==null||t.finally.call(t)}),s=()=>new Promise((e,t)=>o.then(()=>a[0]===`reject`?t(a[1]):e(a[1])).catch(t));return typeof n!=`string`&&typeof n!=`number`?{unwrap:s}:Object.assign(n,{unwrap:s})},this.custom=(e,t)=>{let n=t?.id||MF++;return this.create({jsx:e(n),id:n,...t}),n},this.getActiveToasts=()=>this.toasts.filter(e=>!this.dismissedToasts.has(e.id)),this.subscribers=[],this.toasts=[],this.dismissedToasts=new Set}},PF=(e,t)=>{let n=t?.id||MF++;return NF.addToast({title:e,...t,id:n}),n},FF=e=>e&&typeof e==`object`&&`ok`in e&&typeof e.ok==`boolean`&&`status`in e&&typeof e.status==`number`,IF=Object.assign(PF,{success:NF.success,info:NF.info,warning:NF.warning,error:NF.error,custom:NF.custom,message:NF.message,promise:NF.promise,dismiss:NF.dismiss,loading:NF.loading},{getHistory:()=>NF.toasts,getToasts:()=>NF.getActiveToasts()});SF(`[data-sonner-toaster][dir=ltr],html[dir=ltr]{--toast-icon-margin-start:-3px;--toast-icon-margin-end:4px;--toast-svg-margin-start:-1px;--toast-svg-margin-end:0px;--toast-button-margin-start:auto;--toast-button-margin-end:0;--toast-close-button-start:0;--toast-close-button-end:unset;--toast-close-button-transform:translate(-35%, -35%)}[data-sonner-toaster][dir=rtl],html[dir=rtl]{--toast-icon-margin-start:4px;--toast-icon-margin-end:-3px;--toast-svg-margin-start:0px;--toast-svg-margin-end:-1px;--toast-button-margin-start:0;--toast-button-margin-end:auto;--toast-close-button-start:unset;--toast-close-button-end:0;--toast-close-button-transform:translate(35%, -35%)}[data-sonner-toaster]{position:fixed;width:var(--width);font-family:ui-sans-serif,system-ui,-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Helvetica Neue,Arial,Noto Sans,sans-serif,Apple Color Emoji,Segoe UI Emoji,Segoe UI Symbol,Noto Color Emoji;--gray1:hsl(0, 0%, 99%);--gray2:hsl(0, 0%, 97.3%);--gray3:hsl(0, 0%, 95.1%);--gray4:hsl(0, 0%, 93%);--gray5:hsl(0, 0%, 90.9%);--gray6:hsl(0, 0%, 88.7%);--gray7:hsl(0, 0%, 85.8%);--gray8:hsl(0, 0%, 78%);--gray9:hsl(0, 0%, 56.1%);--gray10:hsl(0, 0%, 52.3%);--gray11:hsl(0, 0%, 43.5%);--gray12:hsl(0, 0%, 9%);--border-radius:8px;box-sizing:border-box;padding:0;margin:0;list-style:none;outline:0;z-index:999999999;transition:transform .4s ease}@media (hover:none) and (pointer:coarse){[data-sonner-toaster][data-lifted=true]{transform:none}}[data-sonner-toaster][data-x-position=right]{right:var(--offset-right)}[data-sonner-toaster][data-x-position=left]{left:var(--offset-left)}[data-sonner-toaster][data-x-position=center]{left:50%;transform:translateX(-50%)}[data-sonner-toaster][data-y-position=top]{top:var(--offset-top)}[data-sonner-toaster][data-y-position=bottom]{bottom:var(--offset-bottom)}[data-sonner-toast]{--y:translateY(100%);--lift-amount:calc(var(--lift) * var(--gap));z-index:var(--z-index);position:absolute;opacity:0;transform:var(--y);touch-action:none;transition:transform .4s,opacity .4s,height .4s,box-shadow .2s;box-sizing:border-box;outline:0;overflow-wrap:anywhere}[data-sonner-toast][data-styled=true]{padding:16px;background:var(--normal-bg);border:1px solid var(--normal-border);color:var(--normal-text);border-radius:var(--border-radius);box-shadow:0 4px 12px rgba(0,0,0,.1);width:var(--width);font-size:13px;display:flex;align-items:center;gap:6px}[data-sonner-toast]:focus-visible{box-shadow:0 4px 12px rgba(0,0,0,.1),0 0 0 2px rgba(0,0,0,.2)}[data-sonner-toast][data-y-position=top]{top:0;--y:translateY(-100%);--lift:1;--lift-amount:calc(1 * var(--gap))}[data-sonner-toast][data-y-position=bottom]{bottom:0;--y:translateY(100%);--lift:-1;--lift-amount:calc(var(--lift) * var(--gap))}[data-sonner-toast][data-styled=true] [data-description]{font-weight:400;line-height:1.4;color:#3f3f3f}[data-rich-colors=true][data-sonner-toast][data-styled=true] [data-description]{color:inherit}[data-sonner-toaster][data-sonner-theme=dark] [data-description]{color:#e8e8e8}[data-sonner-toast][data-styled=true] [data-title]{font-weight:500;line-height:1.5;color:inherit}[data-sonner-toast][data-styled=true] [data-icon]{display:flex;height:16px;width:16px;position:relative;justify-content:flex-start;align-items:center;flex-shrink:0;margin-left:var(--toast-icon-margin-start);margin-right:var(--toast-icon-margin-end)}[data-sonner-toast][data-promise=true] [data-icon]>svg{opacity:0;transform:scale(.8);transform-origin:center;animation:sonner-fade-in .3s ease forwards}[data-sonner-toast][data-styled=true] [data-icon]>*{flex-shrink:0}[data-sonner-toast][data-styled=true] [data-icon] svg{margin-left:var(--toast-svg-margin-start);margin-right:var(--toast-svg-margin-end)}[data-sonner-toast][data-styled=true] [data-content]{display:flex;flex-direction:column;gap:2px}[data-sonner-toast][data-styled=true] [data-button]{border-radius:4px;padding-left:8px;padding-right:8px;height:24px;font-size:12px;color:var(--normal-bg);background:var(--normal-text);margin-left:var(--toast-button-margin-start);margin-right:var(--toast-button-margin-end);border:none;font-weight:500;cursor:pointer;outline:0;display:flex;align-items:center;flex-shrink:0;transition:opacity .4s,box-shadow .2s}[data-sonner-toast][data-styled=true] [data-button]:focus-visible{box-shadow:0 0 0 2px rgba(0,0,0,.4)}[data-sonner-toast][data-styled=true] [data-button]:first-of-type{margin-left:var(--toast-button-margin-start);margin-right:var(--toast-button-margin-end)}[data-sonner-toast][data-styled=true] [data-cancel]{color:var(--normal-text);background:rgba(0,0,0,.08)}[data-sonner-toaster][data-sonner-theme=dark] [data-sonner-toast][data-styled=true] [data-cancel]{background:rgba(255,255,255,.3)}[data-sonner-toast][data-styled=true] [data-close-button]{position:absolute;left:var(--toast-close-button-start);right:var(--toast-close-button-end);top:0;height:20px;width:20px;display:flex;justify-content:center;align-items:center;padding:0;color:var(--gray12);background:var(--normal-bg);border:1px solid var(--gray4);transform:var(--toast-close-button-transform);border-radius:50%;cursor:pointer;z-index:1;transition:opacity .1s,background .2s,border-color .2s}[data-sonner-toast][data-styled=true] [data-close-button]:focus-visible{box-shadow:0 4px 12px rgba(0,0,0,.1),0 0 0 2px rgba(0,0,0,.2)}[data-sonner-toast][data-styled=true] [data-disabled=true]{cursor:not-allowed}[data-sonner-toast][data-styled=true]:hover [data-close-button]:hover{background:var(--gray2);border-color:var(--gray5)}[data-sonner-toast][data-swiping=true]::before{content:'';position:absolute;left:-100%;right:-100%;height:100%;z-index:-1}[data-sonner-toast][data-y-position=top][data-swiping=true]::before{bottom:50%;transform:scaleY(3) translateY(50%)}[data-sonner-toast][data-y-position=bottom][data-swiping=true]::before{top:50%;transform:scaleY(3) translateY(-50%)}[data-sonner-toast][data-swiping=false][data-removed=true]::before{content:'';position:absolute;inset:0;transform:scaleY(2)}[data-sonner-toast][data-expanded=true]::after{content:'';position:absolute;left:0;height:calc(var(--gap) + 1px);bottom:100%;width:100%}[data-sonner-toast][data-mounted=true]{--y:translateY(0);opacity:1}[data-sonner-toast][data-expanded=false][data-front=false]{--scale:var(--toasts-before) * 0.05 + 1;--y:translateY(calc(var(--lift-amount) * var(--toasts-before))) scale(calc(-1 * var(--scale)));height:var(--front-toast-height)}[data-sonner-toast]>*{transition:opacity .4s}[data-sonner-toast][data-x-position=right]{right:0}[data-sonner-toast][data-x-position=left]{left:0}[data-sonner-toast][data-expanded=false][data-front=false][data-styled=true]>*{opacity:0}[data-sonner-toast][data-visible=false]{opacity:0;pointer-events:none}[data-sonner-toast][data-mounted=true][data-expanded=true]{--y:translateY(calc(var(--lift) * var(--offset)));height:var(--initial-height)}[data-sonner-toast][data-removed=true][data-front=true][data-swipe-out=false]{--y:translateY(calc(var(--lift) * -100%));opacity:0}[data-sonner-toast][data-removed=true][data-front=false][data-swipe-out=false][data-expanded=true]{--y:translateY(calc(var(--lift) * var(--offset) + var(--lift) * -100%));opacity:0}[data-sonner-toast][data-removed=true][data-front=false][data-swipe-out=false][data-expanded=false]{--y:translateY(40%);opacity:0;transition:transform .5s,opacity .2s}[data-sonner-toast][data-removed=true][data-front=false]::before{height:calc(var(--initial-height) + 20%)}[data-sonner-toast][data-swiping=true]{transform:var(--y) translateY(var(--swipe-amount-y,0)) translateX(var(--swipe-amount-x,0));transition:none}[data-sonner-toast][data-swiped=true]{user-select:none}[data-sonner-toast][data-swipe-out=true][data-y-position=bottom],[data-sonner-toast][data-swipe-out=true][data-y-position=top]{animation-duration:.2s;animation-timing-function:ease-out;animation-fill-mode:forwards}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=left]{animation-name:swipe-out-left}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=right]{animation-name:swipe-out-right}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=up]{animation-name:swipe-out-up}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=down]{animation-name:swipe-out-down}@keyframes swipe-out-left{from{transform:var(--y) translateX(var(--swipe-amount-x));opacity:1}to{transform:var(--y) translateX(calc(var(--swipe-amount-x) - 100%));opacity:0}}@keyframes swipe-out-right{from{transform:var(--y) translateX(var(--swipe-amount-x));opacity:1}to{transform:var(--y) translateX(calc(var(--swipe-amount-x) + 100%));opacity:0}}@keyframes swipe-out-up{from{transform:var(--y) translateY(var(--swipe-amount-y));opacity:1}to{transform:var(--y) translateY(calc(var(--swipe-amount-y) - 100%));opacity:0}}@keyframes swipe-out-down{from{transform:var(--y) translateY(var(--swipe-amount-y));opacity:1}to{transform:var(--y) translateY(calc(var(--swipe-amount-y) + 100%));opacity:0}}@media (max-width:600px){[data-sonner-toaster]{position:fixed;right:var(--mobile-offset-right);left:var(--mobile-offset-left);width:100%}[data-sonner-toaster][dir=rtl]{left:calc(var(--mobile-offset-left) * -1)}[data-sonner-toaster] [data-sonner-toast]{left:0;right:0;width:calc(100% - var(--mobile-offset-left) * 2)}[data-sonner-toaster][data-x-position=left]{left:var(--mobile-offset-left)}[data-sonner-toaster][data-y-position=bottom]{bottom:var(--mobile-offset-bottom)}[data-sonner-toaster][data-y-position=top]{top:var(--mobile-offset-top)}[data-sonner-toaster][data-x-position=center]{left:var(--mobile-offset-left);right:var(--mobile-offset-right);transform:none}}[data-sonner-toaster][data-sonner-theme=light]{--normal-bg:#fff;--normal-border:var(--gray4);--normal-text:var(--gray12);--success-bg:hsl(143, 85%, 96%);--success-border:hsl(145, 92%, 87%);--success-text:hsl(140, 100%, 27%);--info-bg:hsl(208, 100%, 97%);--info-border:hsl(221, 91%, 93%);--info-text:hsl(210, 92%, 45%);--warning-bg:hsl(49, 100%, 97%);--warning-border:hsl(49, 91%, 84%);--warning-text:hsl(31, 92%, 45%);--error-bg:hsl(359, 100%, 97%);--error-border:hsl(359, 100%, 94%);--error-text:hsl(360, 100%, 45%)}[data-sonner-toaster][data-sonner-theme=light] [data-sonner-toast][data-invert=true]{--normal-bg:#000;--normal-border:hsl(0, 0%, 20%);--normal-text:var(--gray1)}[data-sonner-toaster][data-sonner-theme=dark] [data-sonner-toast][data-invert=true]{--normal-bg:#fff;--normal-border:var(--gray3);--normal-text:var(--gray12)}[data-sonner-toaster][data-sonner-theme=dark]{--normal-bg:#000;--normal-bg-hover:hsl(0, 0%, 12%);--normal-border:hsl(0, 0%, 20%);--normal-border-hover:hsl(0, 0%, 25%);--normal-text:var(--gray1);--success-bg:hsl(150, 100%, 6%);--success-border:hsl(147, 100%, 12%);--success-text:hsl(150, 86%, 65%);--info-bg:hsl(215, 100%, 6%);--info-border:hsl(223, 43%, 17%);--info-text:hsl(216, 87%, 65%);--warning-bg:hsl(64, 100%, 6%);--warning-border:hsl(60, 100%, 9%);--warning-text:hsl(46, 87%, 65%);--error-bg:hsl(358, 76%, 10%);--error-border:hsl(357, 89%, 16%);--error-text:hsl(358, 100%, 81%)}[data-sonner-toaster][data-sonner-theme=dark] [data-sonner-toast] [data-close-button]{background:var(--normal-bg);border-color:var(--normal-border);color:var(--normal-text)}[data-sonner-toaster][data-sonner-theme=dark] [data-sonner-toast] [data-close-button]:hover{background:var(--normal-bg-hover);border-color:var(--normal-border-hover)}[data-rich-colors=true][data-sonner-toast][data-type=success]{background:var(--success-bg);border-color:var(--success-border);color:var(--success-text)}[data-rich-colors=true][data-sonner-toast][data-type=success] [data-close-button]{background:var(--success-bg);border-color:var(--success-border);color:var(--success-text)}[data-rich-colors=true][data-sonner-toast][data-type=info]{background:var(--info-bg);border-color:var(--info-border);color:var(--info-text)}[data-rich-colors=true][data-sonner-toast][data-type=info] [data-close-button]{background:var(--info-bg);border-color:var(--info-border);color:var(--info-text)}[data-rich-colors=true][data-sonner-toast][data-type=warning]{background:var(--warning-bg);border-color:var(--warning-border);color:var(--warning-text)}[data-rich-colors=true][data-sonner-toast][data-type=warning] [data-close-button]{background:var(--warning-bg);border-color:var(--warning-border);color:var(--warning-text)}[data-rich-colors=true][data-sonner-toast][data-type=error]{background:var(--error-bg);border-color:var(--error-border);color:var(--error-text)}[data-rich-colors=true][data-sonner-toast][data-type=error] [data-close-button]{background:var(--error-bg);border-color:var(--error-border);color:var(--error-text)}.sonner-loading-wrapper{--size:16px;height:var(--size);width:var(--size);position:absolute;inset:0;z-index:10}.sonner-loading-wrapper[data-visible=false]{transform-origin:center;animation:sonner-fade-out .2s ease forwards}.sonner-spinner{position:relative;top:50%;left:50%;height:var(--size);width:var(--size)}.sonner-loading-bar{animation:sonner-spin 1.2s linear infinite;background:var(--gray11);border-radius:6px;height:8%;left:-10%;position:absolute;top:-3.9%;width:24%}.sonner-loading-bar:first-child{animation-delay:-1.2s;transform:rotate(.0001deg) translate(146%)}.sonner-loading-bar:nth-child(2){animation-delay:-1.1s;transform:rotate(30deg) translate(146%)}.sonner-loading-bar:nth-child(3){animation-delay:-1s;transform:rotate(60deg) translate(146%)}.sonner-loading-bar:nth-child(4){animation-delay:-.9s;transform:rotate(90deg) translate(146%)}.sonner-loading-bar:nth-child(5){animation-delay:-.8s;transform:rotate(120deg) translate(146%)}.sonner-loading-bar:nth-child(6){animation-delay:-.7s;transform:rotate(150deg) translate(146%)}.sonner-loading-bar:nth-child(7){animation-delay:-.6s;transform:rotate(180deg) translate(146%)}.sonner-loading-bar:nth-child(8){animation-delay:-.5s;transform:rotate(210deg) translate(146%)}.sonner-loading-bar:nth-child(9){animation-delay:-.4s;transform:rotate(240deg) translate(146%)}.sonner-loading-bar:nth-child(10){animation-delay:-.3s;transform:rotate(270deg) translate(146%)}.sonner-loading-bar:nth-child(11){animation-delay:-.2s;transform:rotate(300deg) translate(146%)}.sonner-loading-bar:nth-child(12){animation-delay:-.1s;transform:rotate(330deg) translate(146%)}@keyframes sonner-fade-in{0%{opacity:0;transform:scale(.8)}100%{opacity:1;transform:scale(1)}}@keyframes sonner-fade-out{0%{opacity:1;transform:scale(1)}100%{opacity:0;transform:scale(.8)}}@keyframes sonner-spin{0%{opacity:1}100%{opacity:.15}}@media (prefers-reduced-motion){.sonner-loading-bar,[data-sonner-toast],[data-sonner-toast]>*{transition:none!important;animation:none!important}}.sonner-loader{position:absolute;top:50%;left:50%;transform:translate(-50%,-50%);transform-origin:center;transition:opacity .2s,transform .2s}.sonner-loader[data-visible=false]{opacity:0;transform:scale(.8) translate(-50%,-50%)}`);function LF(e){return e.label!==void 0}var RF=3,zF=`24px`,BF=`16px`,VF=4e3,HF=356,UF=14,WF=45,GF=200;function KF(...e){return e.filter(Boolean).join(` `)}function qF(e){let[t,n]=e.split(`-`),r=[];return t&&r.push(t),n&&r.push(n),r}var JF=e=>{let{invert:t,toast:n,unstyled:r,interacting:i,setHeights:a,visibleToasts:o,heights:s,index:c,toasts:l,expanded:u,removeToast:d,defaultRichColors:f,closeButton:p,style:m,cancelButtonStyle:h,actionButtonStyle:g,className:_=``,descriptionClassName:v=``,duration:y,position:b,gap:x,expandByDefault:S,classNames:C,icons:w,closeButtonAriaLabel:T=`Close toast`}=e,[E,ee]=z.useState(null),[D,te]=z.useState(null),[ne,re]=z.useState(!1),[O,ie]=z.useState(!1),[k,A]=z.useState(!1),[j,ae]=z.useState(!1),[oe,se]=z.useState(!1),[ce,M]=z.useState(0),[N,le]=z.useState(0),ue=z.useRef(n.duration||y||VF),de=z.useRef(null),fe=z.useRef(null),pe=c===0,me=c+1<=o,he=n.type,ge=n.dismissible!==!1,_e=n.className||``,ve=n.descriptionClassName||``,ye=z.useMemo(()=>s.findIndex(e=>e.toastId===n.id)||0,[s,n.id]),be=z.useMemo(()=>n.closeButton??p,[n.closeButton,p]),xe=z.useMemo(()=>n.duration||y||VF,[n.duration,y]),P=z.useRef(0),Se=z.useRef(0),Ce=z.useRef(0),we=z.useRef(null),[Te,Ee]=b.split(`-`),De=z.useMemo(()=>s.reduce((e,t,n)=>n>=ye?e:e+t.height,0),[s,ye]),Oe=jF(),ke=n.invert||t,Ae=he===`loading`;Se.current=z.useMemo(()=>ye*x+De,[ye,De]),z.useEffect(()=>{ue.current=xe},[xe]),z.useEffect(()=>{re(!0)},[]),z.useEffect(()=>{let e=fe.current;if(e){let t=e.getBoundingClientRect().height;return le(t),a(e=>[{toastId:n.id,height:t,position:n.position},...e]),()=>a(e=>e.filter(e=>e.toastId!==n.id))}},[a,n.id]),z.useLayoutEffect(()=>{if(!ne)return;let e=fe.current,t=e.style.height;e.style.height=`auto`;let r=e.getBoundingClientRect().height;e.style.height=t,le(r),a(e=>e.find(e=>e.toastId===n.id)?e.map(e=>e.toastId===n.id?{...e,height:r}:e):[{toastId:n.id,height:r,position:n.position},...e])},[ne,n.title,n.description,a,n.id,n.jsx,n.action,n.cancel]);let je=z.useCallback(()=>{ie(!0),M(Se.current),a(e=>e.filter(e=>e.toastId!==n.id)),setTimeout(()=>{d(n)},GF)},[n,d,a,Se]);z.useEffect(()=>{if(n.promise&&he===`loading`||n.duration===1/0||n.type===`loading`)return;let e;return u||i||Oe?(()=>{if(Ce.current<P.current){let e=new Date().getTime()-P.current;ue.current-=e}Ce.current=new Date().getTime()})():ue.current!==1/0&&(P.current=new Date().getTime(),e=setTimeout(()=>{n.onAutoClose==null||n.onAutoClose.call(n,n),je()},ue.current)),()=>clearTimeout(e)},[u,i,n,he,Oe,je]),z.useEffect(()=>{n.delete&&(je(),n.onDismiss==null||n.onDismiss.call(n,n))},[je,n.delete]);function Me(){return w?.loading?z.createElement(`div`,{className:KF(C?.loader,n?.classNames?.loader,`sonner-loader`),"data-visible":he===`loading`},w.loading):z.createElement(TF,{className:KF(C?.loader,n?.classNames?.loader),visible:he===`loading`})}let Ne=n.icon||w?.[he]||CF(he);return z.createElement(`li`,{tabIndex:0,ref:fe,className:KF(_,_e,C?.toast,n?.classNames?.toast,C?.default,C?.[he],n?.classNames?.[he]),"data-sonner-toast":``,"data-rich-colors":n.richColors??f,"data-styled":!(n.jsx||n.unstyled||r),"data-mounted":ne,"data-promise":!!n.promise,"data-swiped":oe,"data-removed":O,"data-visible":me,"data-y-position":Te,"data-x-position":Ee,"data-index":c,"data-front":pe,"data-swiping":k,"data-dismissible":ge,"data-type":he,"data-invert":ke,"data-swipe-out":j,"data-swipe-direction":D,"data-expanded":!!(u||S&&ne),"data-testid":n.testId,style:{"--index":c,"--toasts-before":c,"--z-index":l.length-c,"--offset":`${O?ce:Se.current}px`,"--initial-height":S?`auto`:`${N}px`,...m,...n.style},onDragEnd:()=>{A(!1),ee(null),we.current=null},onPointerDown:e=>{e.button!==2&&(Ae||!ge||(de.current=new Date,M(Se.current),e.target.setPointerCapture(e.pointerId),e.target.tagName!==`BUTTON`&&(A(!0),we.current={x:e.clientX,y:e.clientY})))},onPointerUp:()=>{if(j||!ge)return;we.current=null;let e=Number(fe.current?.style.getPropertyValue(`--swipe-amount-x`).replace(`px`,``)||0),t=Number(fe.current?.style.getPropertyValue(`--swipe-amount-y`).replace(`px`,``)||0),r=new Date().getTime()-de.current?.getTime(),i=E===`x`?e:t,a=Math.abs(i)/r;if(Math.abs(i)>=WF||a>.11){M(Se.current),n.onDismiss==null||n.onDismiss.call(n,n),te(E===`x`?e>0?`right`:`left`:t>0?`down`:`up`),je(),ae(!0);return}else{var o,s;(o=fe.current)==null||o.style.setProperty(`--swipe-amount-x`,`0px`),(s=fe.current)==null||s.style.setProperty(`--swipe-amount-y`,`0px`)}se(!1),A(!1),ee(null)},onPointerMove:t=>{var n,r;if(!we.current||!ge||window.getSelection()?.toString().length>0)return;let i=t.clientY-we.current.y,a=t.clientX-we.current.x,o=e.swipeDirections??qF(b);!E&&(Math.abs(a)>1||Math.abs(i)>1)&&ee(Math.abs(a)>Math.abs(i)?`x`:`y`);let s={x:0,y:0},c=e=>1/(1.5+Math.abs(e)/20);if(E===`y`){if(o.includes(`top`)||o.includes(`bottom`))if(o.includes(`top`)&&i<0||o.includes(`bottom`)&&i>0)s.y=i;else{let e=i*c(i);s.y=Math.abs(e)<Math.abs(i)?e:i}}else if(E===`x`&&(o.includes(`left`)||o.includes(`right`)))if(o.includes(`left`)&&a<0||o.includes(`right`)&&a>0)s.x=a;else{let e=a*c(a);s.x=Math.abs(e)<Math.abs(a)?e:a}(Math.abs(s.x)>0||Math.abs(s.y)>0)&&se(!0),(n=fe.current)==null||n.style.setProperty(`--swipe-amount-x`,`${s.x}px`),(r=fe.current)==null||r.style.setProperty(`--swipe-amount-y`,`${s.y}px`)}},be&&!n.jsx&&he!==`loading`?z.createElement(`button`,{"aria-label":T,"data-disabled":Ae,"data-close-button":!0,onClick:Ae||!ge?()=>{}:()=>{je(),n.onDismiss==null||n.onDismiss.call(n,n)},className:KF(C?.closeButton,n?.classNames?.closeButton)},w?.close??AF):null,(he||n.icon||n.promise)&&n.icon!==null&&(w?.[he]!==null||n.icon)?z.createElement(`div`,{"data-icon":``,className:KF(C?.icon,n?.classNames?.icon)},n.promise||n.type===`loading`&&!n.icon?n.icon||Me():null,n.type===`loading`?null:Ne):null,z.createElement(`div`,{"data-content":``,className:KF(C?.content,n?.classNames?.content)},z.createElement(`div`,{"data-title":``,className:KF(C?.title,n?.classNames?.title)},n.jsx?n.jsx:typeof n.title==`function`?n.title():n.title),n.description?z.createElement(`div`,{"data-description":``,className:KF(v,ve,C?.description,n?.classNames?.description)},typeof n.description==`function`?n.description():n.description):null),z.isValidElement(n.cancel)?n.cancel:n.cancel&&LF(n.cancel)?z.createElement(`button`,{"data-button":!0,"data-cancel":!0,style:n.cancelButtonStyle||h,onClick:e=>{LF(n.cancel)&&ge&&(n.cancel.onClick==null||n.cancel.onClick.call(n.cancel,e),je())},className:KF(C?.cancelButton,n?.classNames?.cancelButton)},n.cancel.label):null,z.isValidElement(n.action)?n.action:n.action&&LF(n.action)?z.createElement(`button`,{"data-button":!0,"data-action":!0,style:n.actionButtonStyle||g,onClick:e=>{LF(n.action)&&(n.action.onClick==null||n.action.onClick.call(n.action,e),!e.defaultPrevented&&je())},className:KF(C?.actionButton,n?.classNames?.actionButton)},n.action.label):null)};function YF(){if(typeof window>`u`||typeof document>`u`)return`ltr`;let e=document.documentElement.getAttribute(`dir`);return e===`auto`||!e?window.getComputedStyle(document.documentElement).direction:e}function XF(e,t){let n={};return[e,t].forEach((e,t)=>{let r=t===1,i=r?`--mobile-offset`:`--offset`,a=r?BF:zF;function o(e){[`top`,`right`,`bottom`,`left`].forEach(t=>{n[`${i}-${t}`]=typeof e==`number`?`${e}px`:e})}typeof e==`number`||typeof e==`string`?o(e):typeof e==`object`?[`top`,`right`,`bottom`,`left`].forEach(t=>{e[t]===void 0?n[`${i}-${t}`]=a:n[`${i}-${t}`]=typeof e[t]==`number`?`${e[t]}px`:e[t]}):o(a)}),n}var ZF=z.forwardRef(function(e,t){let{id:n,invert:r,position:i=`bottom-right`,hotkey:a=[`altKey`,`KeyT`],expand:o,closeButton:s,className:c,offset:l,mobileOffset:u,theme:d=`light`,richColors:f,duration:p,style:m,visibleToasts:h=RF,toastOptions:g,dir:_=YF(),gap:v=UF,icons:y,containerAriaLabel:b=`Notifications`}=e,[x,S]=z.useState([]),C=z.useMemo(()=>n?x.filter(e=>e.toasterId===n):x.filter(e=>!e.toasterId),[x,n]),w=z.useMemo(()=>Array.from(new Set([i].concat(C.filter(e=>e.position).map(e=>e.position)))),[C,i]),[T,E]=z.useState([]),[ee,D]=z.useState(!1),[te,ne]=z.useState(!1),[re,O]=z.useState(d===`system`?typeof window<`u`&&window.matchMedia&&window.matchMedia(`(prefers-color-scheme: dark)`).matches?`dark`:`light`:d),ie=z.useRef(null),k=a.join(`+`).replace(/Key/g,``).replace(/Digit/g,``),A=z.useRef(null),j=z.useRef(!1),ae=z.useCallback(e=>{S(t=>(t.find(t=>t.id===e.id)?.delete||NF.dismiss(e.id),t.filter(({id:t})=>t!==e.id)))},[]);return z.useEffect(()=>NF.subscribe(e=>{if(e.dismiss){requestAnimationFrame(()=>{S(t=>t.map(t=>t.id===e.id?{...t,delete:!0}:t))});return}setTimeout(()=>{br.flushSync(()=>{S(t=>{let n=t.findIndex(t=>t.id===e.id);return n===-1?[e,...t]:[...t.slice(0,n),{...t[n],...e},...t.slice(n+1)]})})})}),[x]),z.useEffect(()=>{if(d!==`system`){O(d);return}if(d===`system`&&(window.matchMedia&&window.matchMedia(`(prefers-color-scheme: dark)`).matches?O(`dark`):O(`light`)),typeof window>`u`)return;let e=window.matchMedia(`(prefers-color-scheme: dark)`);try{e.addEventListener(`change`,({matches:e})=>{O(e?`dark`:`light`)})}catch{e.addListener(({matches:e})=>{try{O(e?`dark`:`light`)}catch(e){console.error(e)}})}},[d]),z.useEffect(()=>{x.length<=1&&D(!1)},[x]),z.useEffect(()=>{let e=e=>{if(a.every(t=>e[t]||e.code===t)){var t;D(!0),(t=ie.current)==null||t.focus()}e.code===`Escape`&&(document.activeElement===ie.current||ie.current?.contains(document.activeElement))&&D(!1)};return document.addEventListener(`keydown`,e),()=>document.removeEventListener(`keydown`,e)},[a]),z.useEffect(()=>{if(ie.current)return()=>{A.current&&(A.current.focus({preventScroll:!0}),A.current=null,j.current=!1)}},[ie.current]),z.createElement(`section`,{ref:t,"aria-label":`${b} ${k}`,tabIndex:-1,"aria-live":`polite`,"aria-relevant":`additions text`,"aria-atomic":`false`,suppressHydrationWarning:!0},w.map((t,n)=>{let[i,a]=t.split(`-`);return C.length?z.createElement(`ol`,{key:t,dir:_===`auto`?YF():_,tabIndex:-1,ref:ie,className:c,"data-sonner-toaster":!0,"data-sonner-theme":re,"data-y-position":i,"data-x-position":a,style:{"--front-toast-height":`${T[0]?.height||0}px`,"--width":`${HF}px`,"--gap":`${v}px`,...m,...XF(l,u)},onBlur:e=>{j.current&&!e.currentTarget.contains(e.relatedTarget)&&(j.current=!1,A.current&&=(A.current.focus({preventScroll:!0}),null))},onFocus:e=>{e.target instanceof HTMLElement&&e.target.dataset.dismissible===`false`||j.current||(j.current=!0,A.current=e.relatedTarget)},onMouseEnter:()=>D(!0),onMouseMove:()=>D(!0),onMouseLeave:()=>{te||D(!1)},onDragEnd:()=>D(!1),onPointerDown:e=>{e.target instanceof HTMLElement&&e.target.dataset.dismissible===`false`||ne(!0)},onPointerUp:()=>ne(!1)},C.filter(e=>!e.position&&n===0||e.position===t).map((n,i)=>z.createElement(JF,{key:n.id,icons:y,index:i,toast:n,defaultRichColors:f,duration:g?.duration??p,className:g?.className,descriptionClassName:g?.descriptionClassName,invert:r,visibleToasts:h,closeButton:g?.closeButton??s,interacting:te,position:t,style:g?.style,unstyled:g?.unstyled,classNames:g?.classNames,cancelButtonStyle:g?.cancelButtonStyle,actionButtonStyle:g?.actionButtonStyle,closeButtonAriaLabel:g?.closeButtonAriaLabel,removeToast:ae,toasts:C.filter(e=>e.position==n.position),heights:T.filter(e=>e.position==n.position),setHeights:E,expandByDefault:o,gap:v,expanded:ee,swipeDirections:e.swipeDirections}))):null}))}),QF=`__mcpUseInspectorReconnect`;function $F(e){let t=e??(typeof window<`u`?window.location.search:``);if(typeof window<`u`){try{if(sessionStorage.getItem(`__mcpUseInspectorReconnect`))return!0}catch{}if(window.__MCP_USE_INSPECTOR__?.autoConnectUrl)return!0}return!!new URLSearchParams(t).get(`autoConnect`)}function eI(e,t){return e.url===t.url&&e.state!==`ready`&&((e.transportType??`http`)!==t.transportType||eM(e.protocolNegotiation)!==eM(t.protocolNegotiation))}function tI(e){if(!e||typeof e!=`string`)return console.warn(`[useAutoConnect] parseAutoConnectParam: invalid param`,e),null;let t=e.trim();if((t.startsWith(`{`)||t.startsWith(`[`))&&t.endsWith(`/`)&&(t=t.replace(/\/+$/,``)),t.startsWith(`http://`)||t.startsWith(`https://`))return console.log(`[useAutoConnect] parseAutoConnectParam: treating as plain URL:`,t),{url:t,name:`Auto-connected Server`,transportType:`http`,connectionType:`Direct`,connectionMode:`auto`};try{let e=JSON.parse(t);if(console.log(`[useAutoConnect] parseAutoConnectParam: parsed JSON:`,e),e&&typeof e==`object`&&!Array.isArray(e))if(e.url&&typeof e.url==`string`){let t=e.url.trim();if((t.startsWith(`{`)||t.startsWith(`[`))&&t.length>2)try{let e=JSON.parse(t);e&&typeof e==`object`&&e.url&&typeof e.url==`string`?(t=e.url.trim(),console.log(`[useAutoConnect] parseAutoConnectParam: extracted URL from nested JSON:`,t)):console.warn(`[useAutoConnect] parseAutoConnectParam: url field is JSON but doesn't contain a url:`,e)}catch(e){console.warn(`[useAutoConnect] parseAutoConnectParam: url field looks like JSON but failed to parse, using as-is:`,e)}return!t.startsWith(`http://`)&&!t.startsWith(`https://`)?(console.error(`[useAutoConnect] parseAutoConnectParam: extracted URL is not a valid HTTP(S) URL:`,t),null):(console.log(`[useAutoConnect] parseAutoConnectParam: extracted URL:`,t),{url:t,name:e.name||`Auto-connected Server`,transportType:e.transportType===`sse`?`sse`:`http`,connectionMode:nM(e.connectionMode,e.connectionType,!!e.proxyConfig?.proxyAddress),connectionType:e.connectionType===`Via Proxy`?`Via Proxy`:`Direct`,autoProxyFallback:e.autoProxyFallback,protocolNegotiation:$j(eM(e.protocolNegotiation)),customHeaders:e.customHeaders||{},requestTimeout:e.requestTimeout,resetTimeoutOnProgress:e.resetTimeoutOnProgress,maxTotalTimeout:e.maxTotalTimeout,auth:e.auth})}else return console.warn(`[useAutoConnect] parseAutoConnectParam: parsed object missing or invalid url field:`,e),null;else return typeof e==`string`&&(e.startsWith(`http://`)||e.startsWith(`https://`))?(console.log(`[useAutoConnect] parseAutoConnectParam: JSON parsed to URL string:`,e),{url:e,name:`Auto-connected Server`,transportType:`http`,connectionType:`Direct`,connectionMode:`auto`}):(console.warn(`[useAutoConnect] parseAutoConnectParam: parsed value is not a valid object:`,e),null)}catch(e){return console.error(`[useAutoConnect] parseAutoConnectParam: Failed to parse as JSON and not a valid URL:`,e,`Param:`,t),null}}function nI({connections:e,addServer:t,removeConnection:n,configLoaded:r,embedded:i=!1}){let a=LN(),[o,s]=(0,z.useState)(()=>$F()),[c,l]=(0,z.useState)(null),[u,d]=(0,z.useState)(!1),f=(0,z.useCallback)(e=>{let{url:n,name:r,transportType:a,connectionMode:o,protocolNegotiation:s,customHeaders:c,auth:l}=e;console.log(`[useAutoConnect] Config received:`,e),console.log(`[useAutoConnect] Custom headers before auth:`,c),console.log(`[useAutoConnect] Auth config:`,l);let u={...c};if(l?.access_token){let e=l.token_type||`bearer`;if(u.Authorization=`${e.charAt(0).toUpperCase()+e.slice(1)} ${l.access_token}`,console.log(`[useAutoConnect] Added Authorization header:`,u.Authorization),typeof window<`u`&&!i){let e=`mcp:auth:${n}`,t={access_token:l.access_token,token_type:l.token_type||`bearer`,expires_at:l.expires_at,refresh_token:l.refresh_token,scope:l.scope||``};try{localStorage.setItem(e,JSON.stringify(t)),console.log(`[useAutoConnect] Pre-stored OAuth tokens for ${n}`)}catch(e){console.error(`[useAutoConnect] Failed to store OAuth tokens:`,e)}}}console.log(`[useAutoConnect] Final custom headers:`,u);let d;try{let e=new URL(n).origin;window.location.origin!==e&&(d=tM())}catch{d=tM()}let f=o===`proxy`&&d?{proxyAddress:d,...Object.keys(u).length>0&&{headers:u}}:Object.keys(u).length>0?{headers:u}:void 0,p=o===`auto`?e.autoProxyFallback===void 0?d?{enabled:!0,proxyAddress:d}:!1:e.autoProxyFallback:!1;console.warn(`[useAutoConnect] Attempting connection (${o}):`,{url:n,transportType:a,proxyConfig:f,autoProxyFallback:p}),t(n,uM({url:n,name:r,transportType:a,connectionMode:o,protocolNegotiation:s??`auto`,connectionType:o===`proxy`?`Via Proxy`:`Direct`,proxyConfig:f,headers:u,autoProxyFallback:p}))},[t]),p=(0,z.useCallback)(t=>{let r=e.find(e=>e.url===t.url);if(r){if(eI(r,t)){console.warn(`[useAutoConnect] Existing connection transport differs from auto-connect config; replacing it`),n(r.id),l(t),s(!0),f(t);return}if(r.state===`ready`){console.warn(`[useAutoConnect] Connection already ready, navigating to server`);let e=new URLSearchParams(window.location.search),t=e.get(`tunnelUrl`),n=e.get(`tab`),i=e.get(`openTunnelPopover`),o=new URLSearchParams;o.set(`server`,r.id),t&&o.set(`tunnelUrl`,t),n&&o.set(`tab`,n),i&&o.set(`openTunnelPopover`,i),a(`/?${o.toString()}`)}else console.warn(`[useAutoConnect] Connection exists, waiting for ready state`),l(t),s(!0)}else l(t),s(!0),f(t)},[e,a,n,f]);return(0,z.useEffect)(()=>{if(u)return;let e=()=>{if(typeof sessionStorage>`u`)return!1;try{let e=sessionStorage.getItem(QF);if(!e)return!1;let t=JSON.parse(e);return sessionStorage.removeItem(QF),!t?.url||!t.transportType?!1:(p(t),!0)}catch{try{sessionStorage.removeItem(QF)}catch{}return!1}};if(i){if(e()){d(!0);return}let t=new URLSearchParams(window.location.search).get(`autoConnect`);if(t){try{t=decodeURIComponent(t)}catch{}console.log(`[useAutoConnect] Raw autoConnect param:`,t);let e=tI(t);console.log(`[useAutoConnect] Parsed config:`,e),e&&p(e),d(!0);return}d(!0);return}if(r!==!0)return;if(e()){d(!0);return}let t=new URLSearchParams(window.location.search).get(`autoConnect`);if(t)try{t=decodeURIComponent(t)}catch{}if(t){let e=tI(t);e&&p(e),d(!0);return}let n=window.__MCP_USE_INSPECTOR__?.autoConnectUrl;if(n){let e=tI(n);e&&p(e),d(!0);return}fetch(`${Wj()}/config.json`).then(e=>e.json()).then(e=>{if(d(!0),e.autoConnectUrl){let t=tI(e.autoConnectUrl);t&&p(t)}}).catch(()=>d(!0))},[u,r,p,i]),(0,z.useEffect)(()=>{if(!c)return;let t=e.find(e=>e.url===c.url);if(t?.state===`ready`){console.warn(`[useAutoConnect] Connection succeeded, navigating to server`);let e=new URLSearchParams(window.location.search),n=e.get(`tunnelUrl`),r=e.get(`tab`),i=e.get(`openTunnelPopover`),o=new URLSearchParams;o.set(`server`,t.id),n&&o.set(`tunnelUrl`,n),r&&o.set(`tab`,r),i&&o.set(`openTunnelPopover`,i),a(`/?${o.toString()}`),setTimeout(()=>{l(null),s(!1)},100);return}if(t?.state===`pending_auth`||t?.state===`authenticating`){console.warn(`[useAutoConnect] Connection requires authentication, clearing loading overlay`),setTimeout(()=>{s(!1)},100);return}t?.state===`failed`&&(console.warn(`[useAutoConnect] Connection failed after all retries`),IF.error(`Cannot connect to server. Please check the URL and try again.`),queueMicrotask(()=>{s(!1),l(null)}))},[e,c,a]),(0,z.useEffect)(()=>{if(o&&e.length>0&&!c&&e.some(e=>e.state===`ready`||e.state===`failed`||e.state===`pending_auth`)){let e=setTimeout(()=>s(!1),500);return()=>clearTimeout(e)}},[o,e,c]),(0,z.useEffect)(()=>{if(!o)return;let e=setTimeout(()=>{o&&(console.warn(`[useAutoConnect] Auto-connect timeout - clearing loading state`),s(!1),l(null))},3e4);return()=>clearTimeout(e)},[o]),{isAutoConnecting:o,autoConnectUrl:c?.url||null}}function rI({className:e,...t}){return(0,R.jsx)(`div`,{"data-slot":`card`,className:L(`flex flex-col gap-6 rounded-xl border border-border bg-transparent py-6 text-card-foreground`,e),...t})}function iI({className:e,...t}){return(0,R.jsx)(`div`,{"data-slot":`card-header`,className:L(`@container/card-header grid auto-rows-min grid-rows-[auto_auto] items-start gap-1.5 px-6 has-data-[slot=card-action]:grid-cols-[1fr_auto]`,e),...t})}function aI({className:e,...t}){return(0,R.jsx)(`div`,{"data-slot":`card-title`,className:L(`font-semibold leading-none`,e),...t})}function oI({className:e,...t}){return(0,R.jsx)(`div`,{"data-slot":`card-description`,className:L(`text-sm text-muted-foreground`,e),...t})}function sI({className:e,...t}){return(0,R.jsx)(`div`,{"data-slot":`card-content`,className:L(`px-6`,e),...t})}var cI={"chevron-right":C,"chevron-down":Ir,pipette:Oi,x:Xi,copy:Wr,menu:_i,dot:Kr,monitor:bi,sun:Wi,moon:xi,"rectangle-horizontal":ji,circle:Br,"square-library":Bi,clock:Vr,star:Hi,settings:Ii,plus:Ai,"arrow-left":Or,"arrow-right":kr,"arrow-up":jr,search:v,loader:pi,users:Ji,lock:mi,mail:gi,bell:Mr,shield:Li,palette:Ci,lightbulb:ui,rocket:Mi,heart:ni,paintbrush:Si,brain:Nr,globe:ei,user:qi,image:ai,link:di,check:Fr,"rotate-ccw":Ni,play:ki,pause:Ei,home:ii,"message-circle":vi,inbox:oi,pencil:Di,"skip-forward":Ri,"corner-down-right":Gr},lI=(0,z.createContext)(null);function uI(e){return((0,z.useContext)(lI)??cI)[e]}var dI=z.createContext(!1),fI=z.createContext(void 0);function pI(e){let t=z.useContext(fI);if(e===!1&&t===void 0)throw Error(Vt(27));return t}var mI={...dt,...it},hI=z.forwardRef(function(e,t){let{render:n,className:r,style:i,forceRender:a=!1,...o}=e,{store:s}=pI(),c=s.useState(`open`),l=s.useState(`nested`),u=s.useState(`mounted`);return Ft(`div`,e,{state:{open:c,transitionStatus:s.useState(`transitionStatus`)},ref:[s.context.backdropRef,t],stateAttributesMapping:mI,props:[{role:`presentation`,hidden:!u,style:{userSelect:`none`,WebkitUserSelect:`none`}},o],enabled:a||!l})}),gI=z.forwardRef(function(e,t){let{render:n,className:r,style:i,disabled:a=!1,nativeButton:o=!0,...s}=e,{store:c}=pI(),l=c.useState(`open`),{getButtonProps:d,buttonRef:f}=Lt({disabled:a,native:o}),p={disabled:a};function m(e){l&&c.setOpen(!1,te(u,e.nativeEvent))}return Ft(`button`,e,{state:p,ref:[t,f],props:[{onClick:m},s,d]})}),_I=z.forwardRef(function(e,t){let{render:n,className:r,style:i,id:a,...o}=e,{store:s}=pI(),c=O(a);return s.useSyncedValueWithCleanup(`descriptionElementId`,c),Ft(`p`,e,{ref:t,props:[{id:c},o]})}),vI=function(e){return e.nestedDialogs=`--nested-dialogs`,e}({}),yI=function(e){return e[e.open=tt.open]=`open`,e[e.closed=tt.closed]=`closed`,e[e.startingStyle=tt.startingStyle]=`startingStyle`,e[e.endingStyle=tt.endingStyle]=`endingStyle`,e.nested=`data-nested`,e.nestedDialogOpen=`data-nested-dialog-open`,e}({}),bI=z.createContext(void 0);function xI(){let e=z.useContext(bI);if(e===void 0)throw Error(Vt(26));return e}var SI={...dt,...it,nestedDialogOpen(e){return e?{[yI.nestedDialogOpen]:``}:null}},CI=z.forwardRef(function(e,t){let{render:n,className:r,style:i,finalFocus:a,initialFocus:o,...s}=e,{store:c}=pI(),l=c.useState(`descriptionElementId`),u=c.useState(`disablePointerDismissal`),d=c.useState(`floatingRootContext`),f=c.useState(`popupProps`),p=c.useState(`modal`),m=c.useState(`mounted`),h=c.useState(`nested`),_=c.useState(`nestedOpenDialogCount`),v=c.useState(`open`),y=c.useState(`openMethod`),b=c.useState(`titleElementId`),x=c.useState(`transitionStatus`),S=c.useState(`role`),C=d.useState(`floatingId`),w=s.id??C;xI(),g({open:v,ref:c.context.popupRef,onComplete(){v&&c.context.onOpenChangeComplete?.(!0)}});let T=o===void 0?Xe(c.context.popupRef):o,E=_>0,ee=c.useStateSetter(`popupElement`),D=Ft(`div`,e,{state:{open:v,nested:h,transitionStatus:x,nestedDialogOpen:E},props:[f,{id:w,"aria-labelledby":b??void 0,"aria-describedby":l??void 0,role:S,...mt,hidden:!m,onKeyDown(e){Qt.has(e.key)&&e.stopPropagation()},style:{[vI.nestedDialogs]:_}},s],ref:[t,c.context.popupRef,ee],stateAttributesMapping:SI});return(0,R.jsx)(rn,{context:d,openInteractionType:y,disabled:!m,closeOnFocusOut:!u,initialFocus:T,returnFocus:a,modal:p!==!1,restoreFocus:`popup`,children:D})}),wI=z.forwardRef(function(e,t){let{keepMounted:n=!1,...r}=e,{store:i}=pI(),a=i.useState(`mounted`),o=i.useState(`modal`),s=i.useState(`open`);return a||n?(0,R.jsx)(bI.Provider,{value:n,children:(0,R.jsxs)(oe,{ref:t,...r,children:[a&&o===!0&&(0,R.jsx)(wn,{ref:i.context.internalBackdropRef,inert:sn(!s)}),e.children]})}):null});function TI(e){let{store:t,actionsRef:n}=e,r=t.useState(`open`);Be(t,r),Me(t);let{forceUnmount:i}=ot(r,t),a=z.useCallback(()=>{t.setOpen(!1,te(_e))},[t]);z.useImperativeHandle(n,()=>({unmount:i,close:a}),[i,a])}function EI({store:e,parentContext:t,isDrawer:n}){let r=e.useState(`open`),i=e.useState(`disablePointerDismissal`),a=e.useState(`modal`),o=e.useState(`popupElement`),s=e.useState(`floatingRootContext`),[c,l]=z.useState(0),[u,d]=z.useState(0),f=c===0,p=m(s,{outsidePressEvent(){return e.context.internalBackdropRef.current||e.context.backdropRef.current?`intentional`:{mouse:a===`trap-focus`?`sloppy`:`intentional`,touch:`sloppy`}},outsidePress(t){if(!e.context.outsidePressEnabledRef.current||`button`in t&&t.button!==0||`touches`in t&&t.touches.length!==1)return!1;let n=ze(t);return f&&!i?a&&(e.context.internalBackdropRef.current||e.context.backdropRef.current)?e.context.internalBackdropRef.current===n||e.context.backdropRef.current===n||Qe(n,o)&&!n?.hasAttribute(`data-base-ui-portal`):!0:!1},escapeKey:f});return xn(r&&a===!0,o),e.useContextCallback(`onNestedDialogOpen`,(e,t)=>{l(e),d(t)}),e.useContextCallback(`onNestedDialogClose`,()=>{l(0),d(0)}),z.useEffect(()=>(t?.onNestedDialogOpen&&r&&t.onNestedDialogOpen(c+1,u+ +!!n),t?.onNestedDialogClose&&!r&&t.onNestedDialogClose(),()=>{t?.onNestedDialogClose&&r&&t.onNestedDialogClose()}),[n,r,c,u,t]),$e(e,{activeTriggerProps:p.reference??Wt,inactiveTriggerProps:p.trigger??Wt,popupProps:p.floating??Wt,nestedOpenDialogCount:c,nestedOpenDrawerCount:u}),null}var DI={...De,modal:St(e=>e.modal),nested:St(e=>e.nested),nestedOpenDialogCount:St(e=>e.nestedOpenDialogCount),nestedOpenDrawerCount:St(e=>e.nestedOpenDrawerCount),disablePointerDismissal:St(e=>e.disablePointerDismissal),openMethod:St(e=>e.openMethod),descriptionElementId:St(e=>e.descriptionElementId),titleElementId:St(e=>e.titleElementId),viewportElement:St(e=>e.viewportElement),role:St(e=>e.role)},OI=class e extends Tt{constructor(e,t,n=!1){let r=new at,i=kI(e);i.floatingRootContext=We(r,t,n),super(i,{popupRef:z.createRef(),backdropRef:z.createRef(),internalBackdropRef:z.createRef(),outsidePressEnabledRef:{current:!0},triggerElements:r,onOpenChange:void 0,onOpenChangeComplete:void 0},DI)}setOpen=(e,t)=>{if(t.preventUnmountOnClose=()=>{this.set(`preventUnmountingOnClose`,!0)},!e&&t.trigger==null&&this.state.activeTriggerId!=null&&(t.trigger=this.state.activeTriggerElement??void 0),this.context.onOpenChange?.(e,t),t.isCanceled)return;this.state.floatingRootContext.dispatchOpenChange(e,t);let n={open:e};_t(n,e,t.trigger),this.update(n)};static useStore(t,n){return Le(t,(t,r)=>new e(n,t,r),!0).store}};function kI(e={}){return{...ft(),modal:!0,disablePointerDismissal:!1,popupElement:null,viewportElement:null,descriptionElementId:void 0,titleElementId:void 0,openMethod:null,nested:!1,nestedOpenDialogCount:0,nestedOpenDrawerCount:0,role:`dialog`,...e}}function AI(e,t=`dialog`){let{children:n,open:r,defaultOpen:i=!1,onOpenChange:a,onOpenChangeComplete:o,disablePointerDismissal:s=!1,modal:c=!0,actionsRef:l,handle:u,triggerId:d,defaultTriggerId:f=null}=e,p=t===`drawer`,m=t===`alert-dialog`,h=m?!0:c,g=m||s,_=m?`alertdialog`:`dialog`,v=pI(!0),y={modal:h,disablePointerDismissal:g,nested:!!v,role:_},b=OI.useStore(u?.store,{open:i,openProp:r,activeTriggerId:f,triggerIdProp:d,...y});pe(()=>{let e=r===void 0&&b.state.open===!1&&i===!0?{open:!0,activeTriggerId:f}:null;m?b.update(e?{...y,...e}:y):e&&b.update(e)}),b.useControlledProp(`openProp`,r),b.useControlledProp(`triggerIdProp`,d),b.useSyncedValues(y),b.useContextCallback(`onOpenChange`,a),b.useContextCallback(`onOpenChangeComplete`,o);let x=b.useState(`open`),S=b.useState(`mounted`),C=b.useState(`payload`);TI({store:b,actionsRef:l});let w=x||S,T=z.useMemo(()=>({store:b}),[b]);return(0,R.jsx)(dI.Provider,{value:!1,children:(0,R.jsxs)(fI.Provider,{value:T,children:[w&&(0,R.jsx)(EI,{store:b,parentContext:v?.store.context,isDrawer:p}),typeof n==`function`?n({payload:C}):n]})})}function jI(e){return AI(e,z.useContext(dI)?`drawer`:`dialog`)}var MI=z.forwardRef(function(e,t){let{render:n,className:r,style:i,id:a,...o}=e,{store:s}=pI(),c=O(a);return s.useSyncedValueWithCleanup(`titleElementId`,c),Ft(`h2`,e,{ref:t,props:[{id:c},o]})}),NI=z.forwardRef(function(e,t){let{render:n,className:r,style:i,disabled:a=!1,nativeButton:o=!0,id:s,payload:c,handle:l,...u}=e,d=pI(!0),f=l?.store??d?.store;if(!f)throw Error(Vt(79));let p=O(s),m=f.useState(`floatingRootContext`),h=f.useState(`isOpenedByTrigger`,p),g=f.useState(`triggerPopupId`,p),_=z.useRef(null),{registerTrigger:v,isMountedByThisTrigger:y}=Ce(p,_,f,{payload:c}),{getButtonProps:b,buttonRef:S}=Lt({disabled:a,native:o}),C=Sn(m,{enabled:m!=null}),w=dn(()=>f.select(`open`),e=>{f.set(`openMethod`,e)}),T={disabled:a,open:h},E=f.useState(`triggerProps`,y);return Ft(`button`,e,{state:T,ref:[S,t,v,_],props:[C.reference,E,w,{[x]:``,id:p,"aria-haspopup":`dialog`,"aria-expanded":h,"aria-controls":g},u,b],stateAttributesMapping:Ee})}),PI=4,FI=`h-14`,II=(0,z.createContext)(null);function LI({className:e}){let t=uI(`x`);return(0,R.jsx)(gI,{render:(0,R.jsxs)(Gt,{variant:`ghost`,size:`icon-sm`,className:e,children:[(0,R.jsx)(t,{}),(0,R.jsx)(`span`,{className:`sr-only`,children:`Close`})]})})}function RI({children:e,open:t,defaultOpen:n,onOpenChange:r,modal:i}){return(0,R.jsx)(jI,{open:t,defaultOpen:n,onOpenChange:e=>r?.(e),modal:i,children:e})}function zI(e){return(0,R.jsx)(NI,{"data-slot":`dialog-trigger`,...e})}var BI=(0,z.forwardRef)(({className:e,children:t,size:n=`sm`,scrollable:r=!1,container:i,...a},o)=>{let s=Nt(),c=un(),l=Math.min(c+PI,8),[u,d]=(0,z.useState)(!1),f=(0,z.useCallback)(e=>{d(e)},[]);return(0,R.jsxs)(wI,{container:i??void 0,children:[(0,R.jsx)(hI,{render:(e,t)=>{let n=t.transitionStatus===`ending`,{style:r,onDrag:a,onDragStart:o,onDragEnd:s,onAnimationStart:c,onAnimationEnd:l,onAnimationIteration:u,...d}=e;return(0,R.jsx)(Pe.div,{...d,className:L(i?`absolute`:`fixed`,`inset-0 z-50 bg-black/40 dark:bg-black/80`),initial:{opacity:0},animate:{opacity:+!n},transition:n?pt.slow.exit:pt.slow})}}),(0,R.jsx)(CI,{ref:o,render:(o,c)=>{let d=c.transitionStatus===`ending`,{style:p,onDrag:m,onDragStart:h,onDragEnd:g,onAnimationStart:_,onAnimationEnd:v,onAnimationIteration:y,...b}=o;return(0,R.jsx)(Pe.div,{...b,...a,className:L(i?`absolute`:`fixed`,`left-1/2 top-1/2 z-50 w-[calc(100%-2rem)]`,bn(l),`p-6 focus:outline-none`,n===`sm`&&`max-w-[400px]`,n===`lg`&&`max-w-[540px]`,s.container,r&&`flex flex-col overflow-hidden p-0`,e),style:{...p,...a.style},initial:{opacity:0,scale:.97,x:`-50%`,y:`-50%`},animate:{opacity:+!d,scale:d?.97:1,x:`-50%`,y:`-50%`},transition:d?pt.slow.exit:pt.slow,children:(0,R.jsx)(ln,{value:l,children:(0,R.jsxs)(II.Provider,{value:{scrollable:r,setStickyHeader:f},children:[t,!u&&(0,R.jsx)(LI,{className:`absolute right-3 top-3 z-20`})]})})})}})]})});BI.displayName=`DialogContent`;function VI({className:e,sticky:t,children:n,...r}){let i=(0,z.useContext)(II);return(0,z.useLayoutEffect)(()=>{if(t)return i?.setStickyHeader(!0),()=>i?.setStickyHeader(!1)},[t,i]),t?(0,R.jsxs)(`div`,{className:L(`sticky top-0 z-10 mb-0 flex shrink-0 items-center gap-2 border-b border-border/50 bg-white/50 px-6 backdrop-blur-xs dark:bg-black/50`,FI,e),...r,children:[n,(0,R.jsx)(LI,{className:`ml-auto shrink-0`})]}):(0,R.jsx)(`div`,{className:L(`mb-4 flex flex-col gap-1.5`,i?.scrollable&&`px-6 pt-6`,e),...r,children:n})}function HI({className:e,...t}){return(0,R.jsx)(`div`,{className:L(`flex-1 min-h-0 overflow-y-auto overscroll-none pt-2`,(0,z.useContext)(II)?.scrollable?`px-6 pb-6`:`-mx-6 px-6`,e),...t})}function UI({className:e,onCopy:t,children:n,...r}){let i=uI(`copy`),a=uI(`check`),[o,s]=(0,z.useState)(!1),c=async()=>{if(t)try{await t(),s(!0),setTimeout(()=>s(!1),2e3)}catch{}};return(0,R.jsxs)(`div`,{className:L(`group/json relative -mx-6 bg-muted/20 px-6 pt-6 pb-4`,e),...r,children:[t?(0,R.jsx)(`div`,{className:`absolute top-2 right-2 z-10 opacity-0 transition-opacity group-hover/json:opacity-100`,children:(0,R.jsx)(Gt,{variant:`ghost`,size:`icon-sm`,onClick:c,title:`Copy`,children:o?(0,R.jsx)(a,{className:`text-green-600`}):(0,R.jsx)(i,{})})}):null,n]})}function WI({className:e,...t}){return(0,R.jsx)(`div`,{className:L(`mt-6 flex justify-end gap-2`,(0,z.useContext)(II)?.scrollable&&`px-6 pb-6`,e),...t})}var GI=(0,z.forwardRef)(({className:e,...t},n)=>(0,R.jsx)(MI,{ref:n,className:L(`m-0 text-[16px] leading-none text-foreground`,e),style:{fontVariationSettings:`'wght' 700`},...t}));GI.displayName=`DialogTitle`;var KI=(0,z.forwardRef)(({className:e,...t},n)=>(0,R.jsx)(_I,{ref:n,className:L(`text-[13px] text-muted-foreground`,e),...t}));KI.displayName=`DialogDescription`;function qI({headers:e,onChange:t,onSave:n,className:r,title:i=`Custom Headers`,description:a=`Headers with both name and value will be sent`,maxHeaders:o=50}){let[s,c]=(0,z.useState)({}),[l,u]=(0,z.useState)(null),d=(0,z.useRef)({});(0,z.useEffect)(()=>{l&&d.current[l]&&(d.current[l]?.focus(),u(null))},[l,e]);let f=()=>Math.random().toString(36).slice(2,11),p=()=>{if(e.length>=o)return;let n={id:f(),name:``,value:``};t([...e,n])},m=n=>{t(e.filter(e=>e.id!==n))},h=(n,r,i)=>{t(e.map(e=>e.id===n?{...e,[r]:i}:e))},g=e=>{c(t=>({...t,[e]:!t[e]}))};return(0,R.jsxs)(`div`,{className:L(`space-y-3`,r),children:[(0,R.jsxs)(`div`,{className:`space-y-2`,children:[(0,R.jsx)(Xt,{className:`text-base font-medium`,children:i}),(0,R.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:a})]}),(0,R.jsxs)(`div`,{className:`space-y-2`,children:[(0,R.jsxs)(`div`,{className:`grid grid-cols-[1fr_1fr] gap-4 text-sm font-medium text-muted-foreground`,children:[(0,R.jsx)(`div`,{children:`Name`}),(0,R.jsx)(`div`,{children:`Value`})]}),e.length===0?(0,R.jsxs)(`div`,{className:`grid grid-cols-[1fr_1fr] gap-4 items-center`,children:[(0,R.jsx)(ht,{placeholder:`Authorization`,value:``,onChange:e=>{if(e.target.value.trim()){let n=f();t([{id:n,name:e.target.value,value:``}]),u(n)}},className:`text-sm`,autoComplete:`off`}),(0,R.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,R.jsx)(ht,{placeholder:`Bearer token...`,value:``,onChange:()=>{},type:`password`,className:`font-mono text-sm`,autoComplete:`off`,disabled:!0}),(0,R.jsx)(Gt,{type:`button`,variant:`ghost`,size:`icon-sm`,className:`h-8 w-8 p-0`,disabled:!0,children:(0,R.jsx)(Zr,{className:`h-4 w-4`})}),(0,R.jsx)(Gt,{type:`button`,variant:`ghost`,size:`icon-sm`,className:`h-8 w-8 p-0`,disabled:!0,children:(0,R.jsx)(Gi,{className:`h-4 w-4`})})]})]}):e.map(e=>(0,R.jsxs)(`div`,{className:`grid grid-cols-[1fr_1fr] gap-4 items-center`,children:[(0,R.jsx)(ht,{ref:t=>{d.current[e.id]=t},placeholder:`Authorization`,value:e.name,onChange:t=>h(e.id,`name`,t.target.value),className:`text-sm`,autoComplete:`off`}),(0,R.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,R.jsx)(ht,{placeholder:``,value:e.value,onChange:t=>h(e.id,`value`,t.target.value),type:s[e.id]?`text`:`password`,className:`font-mono text-sm`,autoComplete:`off`}),(0,R.jsx)(Gt,{type:`button`,variant:`ghost`,size:`icon-sm`,onClick:()=>g(e.id),className:`h-8 w-8 p-0`,children:s[e.id]?(0,R.jsx)(Xr,{className:`h-4 w-4`}):(0,R.jsx)(Zr,{className:`h-4 w-4`})}),(0,R.jsx)(Gt,{type:`button`,variant:`ghost`,size:`icon-sm`,onClick:()=>m(e.id),className:`h-8 w-8 p-0`,children:(0,R.jsx)(Gi,{className:`h-4 w-4`})})]})]},e.id)),(0,R.jsx)(`div`,{className:`flex justify-start mt-4`,children:(0,R.jsxs)(Gt,{type:`button`,variant:`outline`,size:`sm`,onClick:p,disabled:e.length>=o,className:`flex items-center gap-2`,children:[(0,R.jsx)(Ai,{className:`h-4 w-4`}),`Add`]})})]}),n&&(0,R.jsx)(`div`,{className:`flex justify-end`,children:(0,R.jsx)(Gt,{type:`button`,onClick:n,className:`bg-black text-white hover:bg-gray-800`,children:`Save`})})]})}function JI({alias:e,setAlias:t,url:n,setUrl:r,connectionMode:i,setConnectionMode:a,protocolMode:o,setProtocolMode:s,customHeaders:c,setCustomHeaders:l,requestTimeout:u,setRequestTimeout:d,resetTimeoutOnProgress:f,setResetTimeoutOnProgress:p,maxTotalTimeout:m,setMaxTotalTimeout:h,proxyAddress:g,setProxyAddress:_,clientId:v,setClientId:y,clientSecret:b,setClientSecret:x,scope:S,setScope:C,onConnect:w,onSave:T,onCancel:E,variant:ee=`default`,showConnectButton:D=!1,showSaveButton:te=!1,showExportButton:ne=!1,isConnecting:re=!1,inlineSections:O=!1,cardSections:ie=!1}){let[k,A]=(0,z.useState)(!1),[j,ae]=(0,z.useState)(!1),[oe,se]=(0,z.useState)(!1),ce=(0,z.useRef)(!1),M=async()=>{if(!n.trim()){IF.error(`Please enter a URL first`);return}let t={url:n,...e.trim()?{name:e.trim()}:{},transportType:`http`,connectionMode:i,protocolNegotiation:$j(o),connectionType:i===`proxy`?`Via Proxy`:`Direct`,proxyConfig:i===`proxy`&&g.trim()?{proxyAddress:g.trim(),customHeaders:c.reduce((e,t)=>(t.name&&t.value&&(e[t.name]=t.value),e),{})}:void 0,autoProxyFallback:i===`auto`&&g.trim()?{enabled:!0,proxyAddress:g.trim()}:void 0,customHeaders:c.reduce((e,t)=>(t.name&&t.value&&(e[t.name]=t.value),e),{}),requestTimeout:Number.parseInt(u,10),resetTimeoutOnProgress:f===`True`,maxTotalTimeout:Number.parseInt(m,10),oauth:v||S?{clientId:v,...v&&b?{clientSecret:b}:{},scope:S}:void 0};try{await zj(JSON.stringify(t,null,2)),IF.success(`Configuration copied to clipboard`)}catch{IF.error(`Failed to copy configuration to clipboard`)}},N=ee===`styled`,le=N?`bg-white/10 border-white/20 text-white placeholder:text-white/50`:``,ue=N?`text-white/90`:``,de=N?`bg-white/10 border-white/20 text-white hover:bg-white/20`:``,fe=async e=>{let n=e.clipboardData.getData(`text`);try{let i=JSON.parse(n);if(i.url&&typeof i.url==`string`){e.preventDefault(),r(i.url),t(typeof i.name==`string`&&i.name!==i.url?i.name:``);let n=i.proxyConfig?.proxyAddress||(typeof i.autoProxyFallback==`object`?i.autoProxyFallback.proxyAddress:void 0);a(nM(i.connectionMode,i.connectionType,!!n)),s(eM(i.protocolNegotiation)),n&&_(n);let o=i.proxyConfig?.customHeaders||i.proxyConfig?.headers||i.customHeaders||i.headers||{};Object.keys(o).length>0&&l(Object.entries(o).map(([e,t],n)=>({id:`header-${n}`,name:e,value:String(t)}))),i.requestTimeout&&d(String(i.requestTimeout)),i.resetTimeoutOnProgress!==void 0&&p(i.resetTimeoutOnProgress?`True`:`False`),i.maxTotalTimeout&&h(String(i.maxTotalTimeout)),i.oauth&&(y(i.oauth.clientId||``),x(i.oauth.clientSecret||``),C(i.oauth.scope||``)),IF.success(`Configuration pasted and form populated`)}}catch{}},pe=e=>{ce.current||e.nativeEvent.isComposing||e.keyCode===229||e.key===`Enter`&&!e.shiftKey&&!e.metaKey&&!e.ctrlKey&&e.target.tagName!==`TEXTAREA`&&(e.preventDefault(),w&&n.trim()&&w())},me=(0,R.jsxs)(`div`,{className:`grid gap-4 sm:grid-cols-2`,children:[!ie&&(0,R.jsx)(`h4`,{className:`text-sm font-medium sm:col-span-2`,children:`OAuth 2.0`}),(0,R.jsxs)(`div`,{className:`space-y-2`,children:[(0,R.jsx)(Xt,{className:`text-sm`,children:`Client ID`}),(0,R.jsx)(ht,{"data-testid":`auth-dialog-client-id-input`,placeholder:`Client ID`,value:v,onChange:e=>y(e.target.value)})]}),(0,R.jsxs)(`div`,{className:`space-y-2`,children:[(0,R.jsx)(Xt,{className:`text-sm`,children:`Client Secret`}),(0,R.jsx)(ht,{"data-testid":`auth-dialog-client-secret-input`,type:`password`,placeholder:`Client Secret (optional)`,value:b,onChange:e=>x(e.target.value)}),(0,R.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Stored in your browser's localStorage.`})]}),(0,R.jsxs)(`div`,{className:`space-y-2 sm:col-span-2`,children:[(0,R.jsx)(Xt,{className:`text-sm`,children:`Scope`}),(0,R.jsx)(ht,{"data-testid":`auth-dialog-scope-input`,placeholder:`Scope (space-separated)`,value:S,onChange:e=>C(e.target.value)})]})]}),he=(0,R.jsx)(qI,{title:(0,R.jsx)(R.Fragment,{}),headers:c,onChange:l}),ge=(0,R.jsxs)(`div`,{className:`grid gap-4 sm:grid-cols-2`,children:[(0,R.jsxs)(`div`,{className:`space-y-2`,children:[(0,R.jsx)(Xt,{className:`text-sm`,children:`Connection Mode`}),(0,R.jsxs)(yn,{value:i,onValueChange:e=>a(e),children:[(0,R.jsx)(pn,{className:`w-full`,"data-testid":`config-dialog-connection-mode-select`,children:(0,R.jsx)(on,{})}),(0,R.jsxs)(gn,{children:[(0,R.jsx)(vn,{value:`auto`,children:`Auto`}),(0,R.jsx)(vn,{value:`direct`,children:`Direct`}),(0,R.jsx)(vn,{value:`proxy`,children:`Proxy`})]})]}),(0,R.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Auto tries a direct connection first and falls back to the proxy. Direct bypasses the proxy; Proxy always routes through it.`})]}),(0,R.jsxs)(`div`,{className:`space-y-2`,children:[(0,R.jsx)(Xt,{className:`text-sm`,children:`Protocol`}),(0,R.jsxs)(yn,{value:o,onValueChange:e=>s(e),children:[(0,R.jsx)(pn,{className:`w-full`,"data-testid":`config-dialog-protocol-mode-select`,children:(0,R.jsx)(on,{})}),(0,R.jsxs)(gn,{children:[(0,R.jsx)(vn,{value:`auto`,children:`Auto (recommended)`}),(0,R.jsx)(vn,{value:`v1`,children:`Force v1 (2024/2025)`}),(0,R.jsx)(vn,{value:`v2`,children:`Force v2 (2026-07-28)`})]})]}),(0,R.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Auto probes for v2 and falls back to the legacy v1 initialize flow. Forced modes fail when the server is incompatible.`})]}),(0,R.jsxs)(`div`,{className:`space-y-2`,children:[(0,R.jsx)(Xt,{className:`text-sm`,children:`Proxy Endpoint`}),(0,R.jsx)(ht,{"data-testid":`config-dialog-proxy-address-input`,value:g,onChange:e=>_(e.target.value)})]}),(0,R.jsxs)(`div`,{className:`space-y-2`,children:[(0,R.jsx)(Xt,{className:`text-sm`,children:`Request Timeout`}),(0,R.jsx)(ht,{"data-testid":`config-dialog-request-timeout-input`,type:`number`,value:u,onChange:e=>d(e.target.value)})]}),(0,R.jsxs)(`div`,{className:`space-y-2`,children:[(0,R.jsx)(Xt,{className:`text-sm`,children:`Maximum Total Timeout`}),(0,R.jsx)(ht,{"data-testid":`config-dialog-max-timeout-input`,type:`number`,value:m,onChange:e=>h(e.target.value)})]}),(0,R.jsxs)(`div`,{className:`space-y-2`,children:[(0,R.jsx)(Xt,{className:`text-sm`,children:`Reset Timeout on Progress`}),(0,R.jsxs)(yn,{value:f,onValueChange:p,children:[(0,R.jsx)(pn,{className:`w-full`,"data-testid":`config-dialog-reset-timeout-select`,children:(0,R.jsx)(on,{})}),(0,R.jsxs)(gn,{children:[(0,R.jsx)(vn,{value:`True`,children:`True`}),(0,R.jsx)(vn,{value:`False`,children:`False`})]})]})]})]}),_e=(0,R.jsxs)(`div`,{className:O||ie?`grid gap-4 sm:grid-cols-2`:`space-y-4`,children:[(0,R.jsxs)(`div`,{className:`space-y-2`,children:[(0,R.jsx)(Xt,{className:ue,children:`Alias`}),(0,R.jsx)(ht,{"data-testid":`connection-form-alias-input`,placeholder:`Optional server alias`,value:e,onChange:e=>t(e.target.value),className:le})]}),(0,R.jsxs)(`div`,{className:`space-y-2`,children:[(0,R.jsx)(Xt,{className:ue,children:`URL`}),(0,R.jsx)(ht,{"data-testid":`connection-form-url-input`,placeholder:`http://localhost:3000`,value:n,onChange:e=>r(e.target.value),onPaste:fe,className:le}),(0,R.jsx)(`p`,{className:L(`text-xs text-muted-foreground`,N?`text-white/60`:``),children:`Tip: You can paste a copied connection config (JSON) to auto-populate the form`})]})]}),ve={onCompositionStart:()=>{ce.current=!0},onCompositionEnd:()=>{ce.current=!1},onKeyDown:pe},ye=ne?(0,R.jsxs)(Gt,{"data-testid":`connection-form-copy-config-button`,variant:`ghost`,onClick:M,className:L(N?`absolute top-0 right-0 z-10 text-white hover:bg-white/20 dark:hover:bg-white/20`:`w-full`,!N&&`mb-2`),children:[(0,R.jsx)(Wr,{className:`mr-2 h-4 w-4`}),`Copy Config`]}):null;return O&&ie?(0,R.jsxs)(`div`,{className:`relative space-y-6 @container`,...ve,children:[ye,(0,R.jsxs)(rI,{className:`border`,children:[(0,R.jsxs)(iI,{children:[(0,R.jsx)(aI,{className:`text-base font-medium`,children:`Endpoint`}),(0,R.jsx)(oI,{children:`MCP server URL and display alias`})]}),(0,R.jsx)(sI,{className:`pt-0`,children:_e})]}),(0,R.jsxs)(rI,{className:`border`,children:[(0,R.jsxs)(iI,{children:[(0,R.jsx)(aI,{className:`text-base font-medium`,children:`Authentication`}),(0,R.jsx)(oI,{children:`OAuth 2.0 client credentials`})]}),(0,R.jsx)(sI,{className:`pt-0`,children:me})]}),(0,R.jsxs)(rI,{className:`border`,children:[(0,R.jsxs)(iI,{children:[(0,R.jsx)(aI,{className:`text-base font-medium`,children:`Custom Headers`}),(0,R.jsx)(oI,{children:`Extra HTTP headers sent with MCP requests`})]}),(0,R.jsx)(sI,{className:`pt-0`,children:he})]}),(0,R.jsxs)(rI,{className:`border`,children:[(0,R.jsxs)(iI,{children:[(0,R.jsx)(aI,{className:`text-base font-medium`,children:`Configuration`}),(0,R.jsx)(oI,{children:`Connection mode, proxy, and request timeouts`})]}),(0,R.jsx)(sI,{className:`pt-0`,children:ge})]})]}):(0,R.jsxs)(`div`,{className:`relative space-y-4 @container`,...ve,children:[!O&&(0,R.jsx)(`h3`,{className:`mb-4 text-xl font-semibold text-white`,children:`Connect`}),ye,_e,O&&!ie&&(0,R.jsxs)(`div`,{className:`space-y-8 pt-2`,children:[(0,R.jsxs)(`section`,{className:`space-y-4`,children:[(0,R.jsx)(`h3`,{className:`text-xs font-medium uppercase tracking-wide text-muted-foreground`,children:`Authentication`}),me]}),(0,R.jsxs)(`section`,{className:`space-y-4`,children:[(0,R.jsx)(`h3`,{className:`text-xs font-medium uppercase tracking-wide text-muted-foreground`,children:`Custom Headers`}),he]}),(0,R.jsxs)(`section`,{className:`space-y-4`,children:[(0,R.jsx)(`h3`,{className:`text-xs font-medium uppercase tracking-wide text-muted-foreground`,children:`Configuration`}),ge]})]}),!O&&(0,R.jsxs)(`div`,{className:`flex flex-row gap-3 @lg:flex-col`,children:[(0,R.jsxs)(RI,{open:j,onOpenChange:ae,children:[(0,R.jsx)(zI,{render:(0,R.jsx)(`div`,{className:`relative flex-1 `,children:(0,R.jsxs)(Gt,{"data-testid":`connection-form-auth-button`,variant:`outline`,className:L((v||b||S)&&`border-2`,`w-full justify-center hover:text-white cursor-pointer`,de),children:[(0,R.jsx)(Li,{className:`w-4 h-4 mr-0`}),`Authentication`]})}),nativeButton:!1}),(0,R.jsxs)(BI,{scrollable:!0,className:`w-[calc(100vw-2rem)] sm:w-full max-w-2xl max-h-[80vh]`,children:[(0,R.jsx)(VI,{children:(0,R.jsx)(GI,{children:`Authentication`})}),(0,R.jsxs)(HI,{className:`space-y-4`,children:[me,(0,R.jsx)(`div`,{className:`flex justify-end`,children:(0,R.jsx)(Gt,{onClick:()=>ae(!1),children:`Save`})})]})]})]}),(0,R.jsxs)(RI,{open:k,onOpenChange:A,children:[(0,R.jsx)(zI,{render:(0,R.jsx)(`div`,{className:`relative flex-1 `,children:(0,R.jsxs)(Gt,{"data-testid":`connection-form-headers-button`,variant:`outline`,className:L(`w-full justify-center hover:text-white cursor-pointer`,de),children:[(0,R.jsx)(Qr,{className:`w-4 h-4`}),`Custom Headers`]})}),nativeButton:!1}),(0,R.jsxs)(BI,{scrollable:!0,className:`w-full max-w-2xl max-h-[80vh]`,children:[(0,R.jsx)(VI,{children:(0,R.jsx)(GI,{children:`Custom Headers`})}),(0,R.jsx)(HI,{children:(0,R.jsx)(qI,{title:(0,R.jsx)(R.Fragment,{}),headers:c,onChange:l,onSave:()=>A(!1)})})]})]}),(0,R.jsxs)(RI,{open:oe,onOpenChange:se,children:[(0,R.jsx)(zI,{render:(0,R.jsxs)(Gt,{"data-testid":`connection-form-config-button`,variant:`outline`,className:L(`flex-1 justify-center hover:text-white cursor-pointer`,de),children:[(0,R.jsx)(Hr,{className:`w-4 h-4`}),`Configuration`]}),nativeButton:!0}),(0,R.jsxs)(BI,{scrollable:!0,className:`w-full max-w-2xl max-h-[80vh]`,children:[(0,R.jsx)(VI,{children:(0,R.jsx)(GI,{children:`Configuration`})}),(0,R.jsxs)(HI,{className:`space-y-4`,children:[ge,(0,R.jsx)(`div`,{className:`flex justify-end`,children:(0,R.jsx)(Gt,{onClick:()=>se(!1),children:`Save`})})]})]})]})]}),D&&(0,R.jsx)(Gt,{"data-testid":`connection-form-connect-button`,onClick:w,disabled:!n.trim()||re,size:N?`lg`:void 0,className:L(`w-full font-semibold`,N?`rounded-full text-black [&_[aria-hidden]]:bg-white hover:[&_[aria-hidden]]:bg-white/90 group-active:[&_[aria-hidden]]:bg-white/80`:``),children:re?(0,R.jsxs)(R.Fragment,{children:[(0,R.jsx)(`svg`,{className:`w-4 h-4 mr-2 animate-spin`,fill:`none`,stroke:`currentColor`,viewBox:`0 0 24 24`,children:(0,R.jsx)(`path`,{strokeLinecap:`round`,strokeLinejoin:`round`,strokeWidth:2,d:`M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15`})}),`Connecting...`]}):(0,R.jsxs)(R.Fragment,{children:[(0,R.jsx)(`svg`,{className:`w-4 h-4 mr-2`,fill:`none`,stroke:`currentColor`,viewBox:`0 0 24 24`,children:(0,R.jsx)(`path`,{strokeLinecap:`round`,strokeLinejoin:`round`,strokeWidth:2,d:`M13 10V3L4 14h7v7l9-11h-7z`})}),`Connect`]})}),te&&(0,R.jsxs)(`div`,{className:`flex justify-end gap-2`,children:[E&&(0,R.jsx)(Gt,{variant:`outline`,onClick:E,children:`Cancel`}),(0,R.jsx)(Gt,{"data-testid":`connection-form-save-button`,onClick:T,children:`Save Connection Options`})]})]})}function YI({children:e,className:t,variant:n,duration:r=.4,delay:i=0,offset:a=6,direction:o=`down`,inView:s=!1,inViewMargin:c=`-50px`,blur:l=`6px`,...u}){let d=(0,z.useRef)(null),f=Ma(d,{once:!0,margin:c}),p=!s||f,m={hidden:{[o===`left`||o===`right`?`x`:`y`]:o===`right`||o===`down`?-a:a,opacity:0,filter:`blur(${l})`},visible:{[o===`left`||o===`right`?`x`:`y`]:0,opacity:1,filter:`blur(0px)`}},h=n||m;return(0,R.jsx)(en,{children:(0,R.jsx)(Pe.div,{ref:d,initial:`hidden`,animate:p?`visible`:`hidden`,exit:`hidden`,variants:h,transition:{delay:.04+i,duration:r,ease:`easeOut`},className:t,...u,children:e})})}function XI({className:e,...t}){return(0,R.jsx)(fi,{role:`status`,"aria-label":`Loading`,className:L(`size-4 animate-spin`,e),...t})}function ZI({server:e,className:t,size:n=`md`}){let[r,i]=(0,z.useState)(!0),[a,o]=(0,z.useState)(!1),s={sm:`w-6 h-6`,md:`w-8 h-8`,lg:`w-12 h-12`,xs:`w-4 h-4`},c=(()=>{let t=e.serverInfo?.icons;return t&&Array.isArray(t)&&t.length>0?t[0].src:e.serverInfo?.icon?e.serverInfo.icon:null})();(0,z.useEffect)(()=>{i(c!==null),o(!1)},[c]);let l=Xj(e);return!c||a?(0,R.jsx)(YI,{delay:.05,offset:0,children:(0,R.jsx)(lo,{className:L(`flex items-center justify-center rounded-full overflow-hidden`,s[n],t)})}):(0,R.jsx)(YI,{delay:.05,offset:0,children:(0,R.jsxs)(`div`,{className:L(`rounded-md overflow-hidden flex items-center justify-center bg-white dark:bg-zinc-800 relative`,s[n],t),children:[r&&(0,R.jsx)(`div`,{className:`absolute inset-0 flex items-center justify-center bg-zinc-100/80 dark:bg-zinc-800/80`,children:(0,R.jsx)(XI,{})}),(0,R.jsx)(`img`,{src:c,alt:l,className:L(`object-contain`,s[n]),onLoad:()=>i(!1),onError:()=>{i(!1),o(!0)},style:{imageRendering:`-webkit-optimize-contrast`,display:r?`none`:`block`}})]})})}var QI=[`#e0eaff`,`#f9ffbd`,`#dedede`,`#ffffff`];function $I(){let{servers:e,addServer:t,removeServer:n}=oj(),r=(0,z.useRef)(new Set);(0,z.useEffect)(()=>{e.forEach(e=>{if(e.state===`ready`&&!r.current.has(e.id)){r.current.add(e.id);try{bT(new To({serverId:e.id,serverUrl:e.url??``,success:!0,connectionType:`http`})).catch(()=>{})}catch{}}else e.state===`failed`&&r.current.has(e.id)&&r.current.delete(e.id)})},[e]);let i=(0,z.useCallback)(e=>{try{bT(new Oo({serverId:e})).catch(()=>{})}catch{}r.current.delete(e),n(e,{clearCredentials:!0})},[n]),[a,o]=(0,z.useState)(new Set),s=(0,z.useRef)(new Set);(0,z.useEffect)(()=>{s.current=a},[a]);let c=(0,z.useCallback)(async t=>{if(s.current.has(t)){console.warn(`[InspectorDashboard] Connection ${t} is already being reconnected, skipping`);return}let n=e.find(e=>e.id===t);if(n){o(e=>new Set(e).add(t));try{await n.reconnect()}catch(e){console.error(`[InspectorDashboard] Failed to reconnect server ${t}:`,e)}finally{o(e=>{let n=new Set(e);return n.delete(t),n})}}},[e]),l=LN(),u=PN(),[d,f]=(0,z.useState)(new Set),[p,m]=(0,z.useState)(null);(0,z.useEffect)(()=>{xT({connectionCount:e.length}).catch(()=>{})},[]);let[h,g]=(0,z.useState)(``),[_,v]=(0,z.useState)(``),[y,b]=(0,z.useState)(`auto`),[x,S]=(0,z.useState)(`auto`),[C,w]=(0,z.useState)([]),[T,E]=(0,z.useState)(`10000`),[ee,D]=(0,z.useState)(`True`),[te,ne]=(0,z.useState)(`60000`),[re,O]=(0,z.useState)(tM()),[ie,k]=(0,z.useState)(``),[A,j]=(0,z.useState)(``),[ae,oe]=(0,z.useState)(``),se=(0,z.useRef)(null),{paused:ce,toggle:M}=vo(ho),N=(0,z.useCallback)(()=>{if(!_.trim())return;let e=_.trim();try{let t=new URL(e);if(!(t.protocol===`http:`||t.protocol===`https:`)){IF.error(`Invalid URL protocol. Please use http:// or https://`);return}}catch{try{let t=`https://${e}`,n=new URL(t);if(!(n.protocol===`http:`||n.protocol===`https:`)){IF.error(`Invalid URL protocol. Please use http:// or https://`);return}e=t}catch{IF.error(`Invalid URL format. Please enter a valid URL.`);return}}let n=C.reduce((e,t)=>(t.name&&t.value&&(e[t.name]=t.value),e),{}),r=y===`proxy`&&re.trim()?{proxyAddress:re.trim(),headers:n}:void 0,i=y===`auto`&&re.trim()?{enabled:!0,proxyAddress:re.trim()}:!1,a=sM(ie,A,ae),o={url:e,displayName:h.trim()||e,connectionMode:y,protocolNegotiation:$j(x),autoProxyFallback:i,...r?{proxyConfig:r}:{},...Object.keys(n).length>0&&!r?{headers:n}:{},...a?{oauth:a}:{}};t(e,o),bT(new Do({serverId:_.trim(),serverUrl:_.trim(),connectionType:`http`,viaProxy:!!r?.proxyAddress})).catch(()=>{}),g(``),v(``),w([]),b(`auto`),S(`auto`),k(``),j(``),oe(``),IF.success(`Server added successfully`)},[_,h,y,x,re,C,ie,A,ae,t]),le=()=>{e.forEach(e=>{i(e.id)})},ue=async e=>{try{await zj(e),IF.success(`Error message copied to clipboard`)}catch{IF.error(`Failed to copy error message`)}},de=async e=>{try{let t=dM(e,fM(e.id));await zj(JSON.stringify(t,null,2)),IF.success(`Connection configuration copied to clipboard`)}catch{IF.error(`Failed to copy connection configuration`)}},fe=(e,t)=>{e.stopPropagation(),t()},pe=(e,t)=>{let n=new URLSearchParams(u.search).get(`tunnelUrl`),r=new URLSearchParams;r.set(`server`,e.id),r.set(`tab`,t),n&&r.set(`tunnelUrl`,n),l(`/?${r.toString()}`)},me=e=>{if(e.state===`failed`)return;let t=new URLSearchParams(u.search),n=t.get(`tunnelUrl`),r=t.get(`tab`),i=new URLSearchParams;i.set(`server`,e.id),n&&i.set(`tunnelUrl`,n),r&&i.set(`tab`,r),l(`/?${i.toString()}`)},he=e=>{console.log(`[InspectorDashboard] Reconnecting server:`,e.id),e.state===`failed`&&e.retry?e.retry():c(e.id)};return(0,z.useEffect)(()=>{f(t=>{let n=new Set(t),r=!1;return t.forEach(t=>{let i=e.find(e=>e.id===t);i&&(i.state===`ready`||i.state===`failed`)&&(n.delete(t),r=!0)}),r?n:t})},[e]),(0,z.useEffect)(()=>{if(!p)return;let t=e.find(e=>e.id===p),n=(t?.tools?.length||0)>0||(t?.resources?.length||0)>0||(t?.prompts?.length||0)>0;if(t&&(t.state===`ready`||n&&t.state!==`discovering`)){m(null);let e=new URLSearchParams(u.search),n=e.get(`tunnelUrl`),r=e.get(`tab`),i=new URLSearchParams;i.set(`server`,t.id),n&&i.set(`tunnelUrl`,n),r&&i.set(`tab`,r),l(`/?${i.toString()}`)}else t&&t.state===`failed`&&!n&&t.error&&(console.warn(`[InspectorDashboard] Connection failed with no data, canceling navigation`),m(null))},[e,p,l]),(0,R.jsxs)(`div`,{className:`flex flex-col lg:flex-row items-start justify-start gap-4 h-auto lg:h-full relative`,children:[(0,R.jsxs)(`div`,{className:`w-full px-3 pt-6 sm:px-6 sm:pt-3 overflow-visible lg:overflow-auto`,children:[(0,R.jsxs)(`div`,{className:`flex mb-3 md:mb-0 flex-col sm:flex-row items-center sm:items-center gap-3 relative z-10`,children:[(0,R.jsxs)(et,{children:[(0,R.jsx)(we,{render:(0,R.jsx)(`a`,{href:`https://github.com/mcp-use/mcp-use`,target:`_blank`,rel:`noopener noreferrer`,className:`inline-block order-1 sm:order-2`,children:(0,R.jsxs)(F,{variant:`secondary`,className:`text-xs cursor-pointer hover:bg-secondary/80 transition-colors`,children:[`v`,Lo()]})}),nativeButton:!1}),(0,R.jsx)(lt,{children:(0,R.jsx)(`p`,{children:`Visit GitHub`})})]}),(0,R.jsx)(`h2`,{className:`text-2xl font-medium tracking-tight text-center sm:text-left order-2 sm:order-1`,children:`MCP Inspector`})]}),(0,R.jsx)(`p`,{className:`text-muted-foreground relative z-10 text-center sm:text-left`,children:`Inspect and debug MCP (Model Context Protocol) servers`}),(0,R.jsxs)(`div`,{className:`space-y-4 mt-4 sm:mt-8`,children:[(0,R.jsxs)(`div`,{className:`flex flex-col sm:flex-row items-center sm:items-center justify-between gap-3`,children:[(0,R.jsx)(`h3`,{className:`hidden sm:block text-base font-medium text-center sm:text-left`,children:`Connected Servers`}),(0,R.jsx)(`div`,{className:`hidden sm:flex items-center gap-3 justify-center sm:justify-start`,children:e.length>0&&(0,R.jsx)(Gt,{variant:`ghost`,size:`sm`,onClick:le,children:`Clear All`})})]}),e.length===0?(0,R.jsx)(ro,{message:`No servers connected yet. Add a server above to get started.`}):(0,R.jsx)(`div`,{className:`grid gap-3`,children:e.map(e=>(0,R.jsxs)(`div`,{"data-testid":`server-tile-${e.id}`,onClick:()=>me(e),className:`group rounded-lg bg-zinc-100 dark:bg-white/10 p-4 transition-colors ${e.state===`ready`?`hover:bg-zinc-200 dark:hover:bg-white/15 cursor-pointer`:``}`,children:[(0,R.jsxs)(`div`,{className:`flex items-center justify-between gap-3`,children:[(0,R.jsxs)(`div`,{className:`flex-1 min-w-0`,children:[(0,R.jsxs)(`div`,{className:`flex items-center gap-3`,children:[(0,R.jsx)(ZI,{server:e,size:`md`}),(0,R.jsx)(`h4`,{className:`font-semibold text-sm`,children:Xj(e)}),(0,R.jsx)(`div`,{className:`flex items-center gap-2`,children:a.has(e.id)?(0,R.jsx)(fi,{className:`w-3 h-3 animate-spin text-blue-500`}):e.error&&e.state!==`ready`?(0,R.jsxs)(et,{children:[(0,R.jsx)(we,{render:(0,R.jsx)(`button`,{type:`button`,"data-testid":`server-tile-status-${e.state}`,onClick:t=>{t.stopPropagation(),ue(e.error)},className:`w-2 h-2 rounded-full transition-colors ${(e.error.includes(`401`)||e.error.includes(`Unauthorized`))&&e.error.includes(`does not support OAuth`)?`bg-yellow-500 animate-status-pulse-yellow hover:bg-yellow-600`:`bg-rose-500 animate-status-pulse-red hover:bg-rose-600`}`,title:`Click to copy error message`,"aria-label":`Copy error message to clipboard`}),nativeButton:!0}),(0,R.jsx)(lt,{children:(0,R.jsx)(`p`,{className:`max-w-xs`,children:e.error})})]}):(0,R.jsx)(`div`,{"data-testid":`server-tile-status-${e.state}`,className:`w-2 h-2 rounded-full ${e.state===`ready`?`bg-emerald-600 animate-status-pulse`:e.state===`failed`?`bg-rose-600 animate-status-pulse-red`:`bg-yellow-500 animate-status-pulse-yellow`}`})})]}),(0,R.jsxs)(`div`,{className:`flex items-center gap-2 mt-1`,children:[(0,R.jsx)(`p`,{className:`text-xs text-muted-foreground dark:text-zinc-400 font-mono`,children:e.url}),(0,R.jsxs)(et,{children:[(0,R.jsx)(we,{render:(0,R.jsx)(`button`,{type:`button`,onClick:async t=>{t.stopPropagation();try{await zj(e.url??``),IF.success(`URL copied to clipboard`)}catch{IF.error(`Failed to copy URL`)}},className:`opacity-0 group-hover:opacity-100 transition-opacity p-1 hover:bg-white/10 rounded`,title:`Copy URL`,children:(0,R.jsx)(Wr,{className:`w-3 h-3 text-muted-foreground`})}),nativeButton:!0}),(0,R.jsx)(lt,{children:(0,R.jsx)(`p`,{children:`Copy URL`})})]})]})]}),(0,R.jsxs)(`div`,{className:`hidden lg:flex items-center gap-1 flex-shrink-0`,children:[(0,R.jsxs)(et,{children:[(0,R.jsx)(we,{render:(0,R.jsx)(Gt,{"data-testid":`server-tile-copy-config`,variant:`secondary`,size:`sm`,onClick:t=>fe(t,()=>de(e)),className:`h-8 w-8 p-0`,children:(0,R.jsx)(Wr,{className:`w-4 h-4`})}),nativeButton:!0}),(0,R.jsx)(lt,{children:(0,R.jsx)(`p`,{children:`Copy connection config`})})]}),(0,R.jsxs)(et,{children:[(0,R.jsx)(we,{render:(0,R.jsx)(Gt,{"data-testid":`server-tile-info`,variant:`secondary`,size:`sm`,onClick:t=>fe(t,()=>pe(e,`server-metadata`)),className:`h-8 w-8 p-0`,children:(0,R.jsx)(si,{className:`w-4 h-4`})}),nativeButton:!0}),(0,R.jsx)(lt,{children:(0,R.jsx)(`p`,{children:`View server info`})})]}),(0,R.jsxs)(et,{children:[(0,R.jsx)(we,{render:(0,R.jsx)(Gt,{"data-testid":`server-tile-settings`,variant:`secondary`,size:`sm`,onClick:t=>fe(t,()=>pe(e,`connection-settings`)),className:`h-8 w-8 p-0`,children:(0,R.jsx)(Ii,{className:`w-4 h-4`})}),nativeButton:!0}),(0,R.jsx)(lt,{children:(0,R.jsx)(`p`,{children:`Edit connection settings`})})]}),(0,R.jsxs)(et,{children:[(0,R.jsx)(we,{render:(0,R.jsx)(Gt,{"data-testid":`server-tile-remove`,variant:`secondary`,size:`sm`,onClick:t=>fe(t,()=>i(e.id)),className:`h-8 w-8 p-0`,children:(0,R.jsx)(Rr,{className:`w-4 h-4`})}),nativeButton:!0}),(0,R.jsx)(lt,{children:(0,R.jsx)(`p`,{children:`Remove connection`})})]}),(e.state===`ready`||e.state===`failed`||e.state===`discovering`)&&(0,R.jsxs)(et,{children:[(0,R.jsx)(we,{render:(0,R.jsx)(Gt,{"data-testid":`server-tile-reconnect`,variant:`secondary`,size:`sm`,onClick:t=>fe(t,()=>he(e)),className:`h-8 w-8 p-0`,children:(0,R.jsx)(Ni,{className:`w-4 h-4`})}),nativeButton:!0}),(0,R.jsx)(lt,{children:(0,R.jsx)(`p`,{children:e.state===`failed`?`Retry connection`:e.state===`discovering`?`Reconnect`:`Resync connection`})})]})]}),(0,R.jsx)(`div`,{className:`lg:hidden flex-shrink-0`,children:(0,R.jsxs)(Ya,{children:[(0,R.jsx)(Xa,{render:(0,R.jsx)(Gt,{variant:`ghost`,size:`sm`,className:`h-8 w-8 p-0`,onClick:e=>e.stopPropagation(),children:(0,R.jsx)(Jr,{className:`h-4 w-4`})}),nativeButton:!0}),(0,R.jsxs)(Za,{align:`end`,children:[(0,R.jsxs)($a,{onClick:t=>{t.stopPropagation(),de(e)},children:[(0,R.jsx)(Wr,{className:`h-4 w-4 mr-2`}),`Copy connection config`]}),(0,R.jsxs)($a,{onClick:t=>{t.stopPropagation(),pe(e,`server-metadata`)},children:[(0,R.jsx)(si,{className:`h-4 w-4 mr-2`}),`View server info`]}),(0,R.jsxs)($a,{onClick:t=>{t.stopPropagation(),pe(e,`connection-settings`)},children:[(0,R.jsx)(Ii,{className:`h-4 w-4 mr-2`}),`Edit connection settings`]}),(e.state===`ready`||e.state===`failed`||e.state===`discovering`)&&(0,R.jsxs)($a,{onClick:t=>{t.stopPropagation(),he(e)},children:[(0,R.jsx)(Ni,{className:`h-4 w-4 mr-2`}),e.state===`failed`?`Retry connection`:e.state===`discovering`?`Reconnect`:`Resync connection`]}),(0,R.jsxs)($a,{onClick:t=>{t.stopPropagation(),i(e.id)},className:`text-destructive focus:text-destructive`,children:[(0,R.jsx)(Rr,{className:`h-4 w-4 mr-2`}),`Remove connection`]})]})]})})]}),(e.state===`pending_auth`||e.state===`authenticating`)&&(0,R.jsx)(`div`,{className:`text-sm text-yellow-600 dark:text-yellow-400 mt-2`,children:e.state===`authenticating`?(0,R.jsxs)(Gt,{size:`sm`,className:`bg-yellow-500/20 border-0 dark:bg-yellow-400/10 text-yellow-800 dark:text-yellow-500`,variant:`outline`,disabled:!0,children:[(0,R.jsx)(fi,{className:`mr-2 h-4 w-4 animate-spin`}),`Authenticating...`]}):e.authUrl?(0,R.jsx)(Gt,{"data-testid":`server-tile-authenticate`,size:`sm`,className:`bg-yellow-500/20 border-0 dark:bg-yellow-400/10 text-yellow-800 dark:text-yellow-500`,variant:`outline`,render:(0,R.jsx)(`a`,{href:e.authUrl,onClick:t=>{t.stopPropagation();try{sessionStorage.setItem(`__mcpUseInspectorReconnect`,JSON.stringify({url:e.url,name:e.name||`Auto-connected Server`,transportType:e.transportType||`http`,connectionMode:`auto`}))}catch{}}}),nativeButton:!1,children:`Authenticate`}):null}),e.state===`failed`&&e.error&&(e.error.includes(`401`)||e.error.includes(`Unauthorized`))&&e.error.includes(`does not support OAuth`)&&(0,R.jsx)(`div`,{className:`text-sm mt-2 p-2 bg-yellow-500/10 dark:bg-yellow-400/10 border border-yellow-500/20 dark:border-yellow-400/20 rounded text-yellow-800 dark:text-yellow-400`,children:e.error})]},e.id))})]})]}),(0,R.jsxs)(`div`,{ref:se,className:`w-full relative overflow-hidden h-auto lg:h-full py-4 px-4 sm:py-6 sm:px-6 lg:p-10 items-center justify-center flex`,children:[(0,R.jsx)(`div`,{className:`absolute inset-0 z-0 overflow-hidden dark:opacity-60 pointer-events-none`,children:(0,R.jsx)(mo,{className:`h-full w-full`,colors:QI,distortion:.8,swirl:.1,grainMixer:0,grainOverlay:.2,speed:+!ce})}),(0,R.jsx)(`div`,{className:`absolute inset-0 z-[1] pointer-events-none opacity-[0.07] mix-blend-soft-light dark:opacity-[0.06]`,"aria-hidden":!0,children:(0,R.jsx)(`div`,{className:`absolute inset-0 noise`,style:{background:`url("${oo}")`,filter:`contrast(150%) brightness(550%)`}})}),(0,R.jsx)(bo,{paused:ce,onToggle:M,className:`absolute bottom-3 right-3 sm:bottom-5 sm:right-5`}),(0,R.jsx)(`div`,{className:`relative w-full max-w-xl mx-auto z-10 flex flex-col gap-3 rounded-3xl p-4 sm:p-6 bg-black/70 dark:bg-black/90 shadow-2xl shadow-black/50 backdrop-blur-md`,children:(0,R.jsx)(JI,{alias:h,setAlias:g,url:_,setUrl:v,connectionMode:y,setConnectionMode:b,protocolMode:x,setProtocolMode:S,customHeaders:C,setCustomHeaders:w,requestTimeout:T,setRequestTimeout:E,resetTimeoutOnProgress:ee,setResetTimeoutOnProgress:D,maxTotalTimeout:te,setMaxTotalTimeout:ne,proxyAddress:re,setProxyAddress:O,clientId:ie,setClientId:k,clientSecret:A,setClientSecret:j,scope:ae,setScope:oe,onConnect:N,variant:`styled`,showConnectButton:!0,showExportButton:!0})})]})]})}var eL=(0,z.createContext)(void 0);function tL({children:e}){let t=(typeof window<`u`?window.__MANUFACT_CHAT_URL__:void 0)??void 0,[n,r]=(0,z.useState)({selectedServerId:null,activeTab:`tools`,selectedToolName:null,selectedPromptName:null,selectedResourceUri:null,selectedSamplingRequestId:null,selectedElicitationRequestId:null,tunnelUrl:null,isTunnelStarting:!1,isEmbedded:!1,embeddedConfig:t?{chatApiUrl:t,chatStreamProtocol:`data-stream`,chatEnableFreeTierUpgrade:!0}:{}}),i=(0,z.useCallback)(e=>{r(t=>({...t,selectedServerId:e}))},[]),a=(0,z.useCallback)(e=>{r(t=>({...t,activeTab:e}))},[]),o=(0,z.useCallback)(e=>{r(t=>({...t,selectedToolName:e}))},[]),s=(0,z.useCallback)(e=>{r(t=>({...t,selectedPromptName:e}))},[]),c=(0,z.useCallback)(e=>{r(t=>({...t,selectedResourceUri:e}))},[]),l=(0,z.useCallback)(e=>{r(t=>({...t,selectedSamplingRequestId:e}))},[]),u=(0,z.useCallback)(e=>{r(t=>({...t,selectedElicitationRequestId:e}))},[]),d=(0,z.useCallback)(e=>{r(t=>({...t,tunnelUrl:e}))},[]),f=(0,z.useCallback)(e=>{r(t=>({...t,isTunnelStarting:e}))},[]),p=(0,z.useCallback)((e,t={})=>{r(n=>({...n,isEmbedded:e,embeddedConfig:t}))},[]),m=(0,z.useCallback)((e,t,n)=>{console.warn(`[InspectorContext] navigateToItem called:`,{serverId:e,tab:t,itemIdentifier:n}),r(r=>({...r,selectedServerId:e,activeTab:t,selectedToolName:t===`tools`&&n||null,selectedPromptName:t===`prompts`&&n||null,selectedResourceUri:t===`resources`&&n||null,selectedSamplingRequestId:t===`sampling`&&n||null,selectedElicitationRequestId:t===`elicitation`&&n||null}))},[]),h=(0,z.useCallback)(()=>{r(e=>({...e,selectedToolName:null,selectedPromptName:null,selectedResourceUri:null,selectedSamplingRequestId:null,selectedElicitationRequestId:null}))},[]);return(0,R.jsx)(eL,{value:{...n,setSelectedServerId:i,setActiveTab:a,setSelectedToolName:o,setSelectedPromptName:s,setSelectedResourceUri:c,setSelectedSamplingRequestId:l,setSelectedElicitationRequestId:u,setTunnelUrl:d,setIsTunnelStarting:f,setEmbeddedMode:p,navigateToItem:m,clearSelection:h},children:e})}function nL(){let e=(0,z.use)(eL);if(!e)throw Error(`useInspector must be used within InspectorProvider`);return e}function rL(e){(0,z.useEffect)(()=>{let t=t=>{let n=t.target,r=n.tagName===`INPUT`||n.tagName===`TEXTAREA`||n.contentEditable===`true`;if((t.metaKey||t.ctrlKey)&&t.key===`k`){t.preventDefault(),e.onCommandPalette?.();return}if((t.metaKey||t.ctrlKey)&&t.key===`o`&&e.onNewChat){t.preventDefault(),e.onNewChat();return}if(t.key===`Escape`){t.preventDefault(),document.activeElement instanceof HTMLElement&&document.activeElement.blur(),e.onBlurSearch?.();return}if(!r&&!(t.metaKey||t.ctrlKey||t.altKey||t.shiftKey))switch(t.key.toLowerCase()){case`t`:t.preventDefault(),e.onToolsTab?.();break;case`p`:t.preventDefault(),e.onPromptsTab?.();break;case`r`:t.preventDefault(),e.onResourcesTab?.();break;case`c`:t.preventDefault(),e.onChatTab?.();break;case`h`:t.preventDefault(),e.onHome?.();break;case`f`:t.preventDefault(),e.onFocusSearch?.();break;default:break}};return document.addEventListener(`keydown`,t),()=>document.removeEventListener(`keydown`,t)},[e])}var iL=`mcp-inspector-saved-requests`;function aL(){let[e,t]=(0,z.useState)([]);return(0,z.useEffect)(()=>{try{let e=localStorage.getItem(iL);e&&t(JSON.parse(e))}catch(e){console.error(`[useSavedRequests] Failed to load saved requests:`,e)}},[]),(0,z.useEffect)(()=>{let e=e=>{if(e.key===iL&&e.newValue)try{t(JSON.parse(e.newValue))}catch(e){console.error(`[useSavedRequests] Failed to parse saved requests:`,e)}};return window.addEventListener(`storage`,e),()=>window.removeEventListener(`storage`,e)},[]),{savedRequests:e,saveSavedRequests:(0,z.useCallback)(e=>{try{localStorage.setItem(iL,JSON.stringify(e)),t(e)}catch(e){console.error(`[useSavedRequests] Failed to save requests:`,e)}},[])}}function oL(e){return e.replace(/[^a-zA-Z0-9-_]/g,`_`).toLowerCase()}function sL(e){return`'${e.replace(/'/g,`'\\''`)}'`}function cL(e){return e.replace(/[^a-zA-Z0-9]/g,`_`).toUpperCase().replace(/^_+|_+$/g,``)}function lL(e,t,n){let r={url:e};if(n&&Object.keys(n).length>0){let e={};for(let[t]of Object.entries(n))e[t]=`{{${cL(t)}}}`;r.headers=e}let i=JSON.stringify(r);return`cursor://anysphere.cursor-deeplink/mcp/install?config=${btoa(i)}&name=${encodeURIComponent(oL(t))}`}function uL(e,t,n){let r={url:e,name:oL(t),type:`http`};if(n&&Object.keys(n).length>0){let e={};for(let[t]of Object.entries(n))e[t]=`your-${cL(t)}-value`;r.headers=e}let i=JSON.stringify(r);return`vscode:mcp/install?${encodeURIComponent(i)}`}function dL(e,t,n){let r={url:e,name:oL(t),type:`http`};if(n&&Object.keys(n).length>0){let e={};for(let[t]of Object.entries(n))e[t]=`your-${cL(t)}-value`;r.headers=e}let i=JSON.stringify(r);return`vscode-insiders:mcp/install?${encodeURIComponent(i)}`}function fL(e,t,n){let r={url:e,name:oL(t)};if(n&&Object.keys(n).length>0){let e={};for(let[t]of Object.entries(n))e[t]=`your-${cL(t)}-value`;r.headers=e}return r}function pL(e,t,n){try{let r=fL(e,t,n),i=JSON.stringify(r,null,2),a=globalThis.Blob,o=new a([i],{type:`application/json`}),s=URL.createObjectURL(o),c=document.createElement(`a`);c.href=s,c.download=`${oL(t)}.mcpb`,document.body.appendChild(c),c.click(),document.body.removeChild(c),URL.revokeObjectURL(s)}catch(e){throw console.error(`Failed to download .mcpb file:`,e),e}}function mL(e,t,n){let r=`claude mcp add --transport http "${oL(t)}" \\\n ${sL(e)}`,i=[];if(n&&Object.keys(n).length>0)for(let[e]of Object.entries(n)){let t=cL(e);r+=` \\\n --header ${sL(`${e}:\${${t}}`)}`,i.push({name:t,header:e})}return{command:r,envVars:i}}function hL(e,t,n){let r=`gemini mcp add --transport http "${oL(t)}" ${sL(e)}`,i=[];if(n&&Object.keys(n).length>0)for(let[e]of Object.entries(n)){let t=cL(e);r+=` \\\n --header ${sL(`${e}:\${${t}}`)}`,i.push({name:t,header:e})}return{command:r,envVars:i}}function gL(e,t,n){let r=`[mcp_servers.${oL(t)}]\nurl = "${e}"`,i=[];if(n&&Object.keys(n).length>0){let e=[];for(let[t]of Object.entries(n)){let n=cL(t);e.push(`"${t}" = "your-${n}-value"`),i.push({name:n,header:t})}if(r+=`\nhttp_headers = { ${e.join(`, `)} }`,i.length>0){r+=`
|
|
495
495
|
|
|
496
496
|
# (optional) Use environment variables instead:
|
|
497
|
-
# env_http_headers = { `;let e=i.map(({name:e,header:t})=>`"${t}" = "${e}"`);r+=e.join(`, `),r+=` }`}}return{config:r,envVars:i}}function
|
|
497
|
+
# env_http_headers = { `;let e=i.map(({name:e,header:t})=>`"${t}" = "${e}"`);r+=e.join(`, `),r+=` }`}}return{config:r,envVars:i}}function _L(e){if(e.length===0)return``;let t=`Set these environment variables in your shell:
|
|
498
498
|
|
|
499
|
-
`;for(let{name:n}of e)t+=`export ${n}="your-${n}-value"\n`;return t}function HL({className:e,size:t=`md`}){return(0,R.jsxs)(`svg`,{viewBox:`0 0 500 500`,className:L(`text-current`,{sm:`h-4 w-4`,md:`h-5 w-5`,lg:`h-6 w-6`}[t],e),fill:`currentColor`,fillRule:`nonzero`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,R.jsx)(`path`,{d:`M105.933 0C164.437 0.000116002 211.865 47.607 211.865 106.333C211.865 131.829 210.493 158.403 221.068 181.602L228.975 198.947C243.584 230.997 269.265 256.7 301.303 271.336L316.155 278.121C340.142 289.079 367.694 287.335 394.066 287.335C452.571 287.335 499.999 334.942 499.999 393.668C499.999 452.394 452.571 500.001 394.066 500.001C335.562 500.001 288.134 452.394 288.134 393.668C288.134 368.974 289.24 343.275 278.992 320.807L270.586 302.38C255.948 270.29 230.214 244.565 198.118 229.939L180.164 221.758C157.282 211.331 131.078 212.666 105.933 212.666C47.4278 212.666 4.86252e-05 165.059 0 106.333C0 47.607 47.4278 0 105.933 0Z`}),(0,R.jsx)(`circle`,{cx:`100.426`,cy:`399.575`,r:`100.426`}),(0,R.jsx)(`path`,{d:`M500 100.426C500 155.889 455.037 200.851 399.574 200.851C344.11 200.851 299.148 155.889 299.148 100.426C299.148 44.962 344.11 0 399.574 0C455.037 0 500 44.962 500 100.426Z`})]})}function UL({className:e}){return(0,R.jsx)(`svg`,{viewBox:`0 0 24 24`,className:e,fill:`currentColor`,xmlns:`http://www.w3.org/2000/svg`,children:(0,R.jsx)(`path`,{d:`M23.15 2.587L18.21.21a1.494 1.494 0 0 0-1.705.29l-9.46 8.63-4.12-3.128a.999.999 0 0 0-1.276.057L.327 7.261A1 1 0 0 0 .326 8.74L3.899 12 .326 15.26a1 1 0 0 0 .001 1.479L1.65 17.94a.999.999 0 0 0 1.276.057l4.12-3.128 9.46 8.63a1.492 1.492 0 0 0 1.704.29l4.942-2.377A1.5 1.5 0 0 0 24 20.06V3.939a1.5 1.5 0 0 0-.85-1.352zm-5.146 14.861L10.826 12l7.178-5.448v10.896z`})})}function WL({className:e}){return(0,R.jsxs)(`svg`,{fill:`currentColor`,fillRule:`evenodd`,viewBox:`0 0 24 24`,className:e,xmlns:`http://www.w3.org/2000/svg`,"aria-label":`ModelContextProtocol`,children:[(0,R.jsx)(`path`,{d:`M15.688 2.343a2.588 2.588 0 00-3.61 0l-9.626 9.44a.863.863 0 01-1.203 0 .823.823 0 010-1.18l9.626-9.44a4.313 4.313 0 016.016 0 4.116 4.116 0 011.204 3.54 4.3 4.3 0 013.609 1.18l.05.05a4.115 4.115 0 010 5.9l-8.706 8.537a.274.274 0 000 .393l1.788 1.754a.823.823 0 010 1.18.863.863 0 01-1.203 0l-1.788-1.753a1.92 1.92 0 010-2.754l8.706-8.538a2.47 2.47 0 000-3.54l-.05-.049a2.588 2.588 0 00-3.607-.003l-7.172 7.034-.002.002-.098.097a.863.863 0 01-1.204 0 .823.823 0 010-1.18l7.273-7.133a2.47 2.47 0 00-.003-3.537z`}),(0,R.jsx)(`path`,{d:`M14.485 4.703a.823.823 0 000-1.18.863.863 0 00-1.204 0l-7.119 6.982a4.115 4.115 0 000 5.9 4.314 4.314 0 006.016 0l7.12-6.982a.823.823 0 000-1.18.863.863 0 00-1.204 0l-7.119 6.982a2.588 2.588 0 01-3.61 0 2.47 2.47 0 010-3.54l7.12-6.982z`})]})}function GL({className:e}){return(0,R.jsx)(`svg`,{viewBox:`0 -28.5 256 256`,className:e,fill:`currentColor`,xmlns:`http://www.w3.org/2000/svg`,children:(0,R.jsx)(`path`,{d:`M216.856339,16.5966031 C200.285002,8.84328665 182.566144,3.2084988 164.041564,0 C161.766523,4.11318106 159.108624,9.64549908 157.276099,14.0464379 C137.583995,11.0849896 118.072967,11.0849896 98.7430163,14.0464379 C96.9108417,9.64549908 94.1925838,4.11318106 91.8971895,0 C73.3526068,3.2084988 55.6133949,8.86399117 39.0420583,16.6376612 C5.61752293,67.146514 -3.4433191,116.400813 1.08711069,164.955721 C23.2560196,181.510915 44.7403634,191.567697 65.8621325,198.148576 C71.0772151,190.971126 75.7283628,183.341335 79.7352139,175.300261 C72.104019,172.400575 64.7949724,168.822202 57.8887866,164.667963 C59.7209612,163.310589 61.5131304,161.891452 63.2445898,160.431257 C105.36741,180.133187 151.134928,180.133187 192.754523,160.431257 C194.506336,161.891452 196.298154,163.310589 198.110326,164.667963 C191.183787,168.842556 183.854737,172.420929 176.223542,175.320965 C180.230393,183.341335 184.861538,190.991831 190.096624,198.16893 C211.238746,191.588051 232.743023,181.531619 254.911949,164.955721 C260.227747,108.668201 245.831087,59.8662432 216.856339,16.5966031 Z M85.4738752,135.09489 C72.8290281,135.09489 62.4592217,123.290155 62.4592217,108.914901 C62.4592217,94.5396472 72.607595,82.7145587 85.4738752,82.7145587 C98.3405064,82.7145587 108.709962,94.5189427 108.488529,108.914901 C108.508531,123.290155 98.3405064,135.09489 85.4738752,135.09489 Z M170.525237,135.09489 C157.88039,135.09489 147.510584,123.290155 147.510584,108.914901 C147.510584,94.5396472 157.658606,82.7145587 170.525237,82.7145587 C183.391518,82.7145587 193.761324,94.5189427 193.539891,108.914901 C193.539891,123.290155 183.391518,135.09489 170.525237,135.09489 Z`,fillRule:`nonzero`})})}function KL({isOpen:e,onOpenChange:t,tools:n,prompts:r,resources:i,savedRequests:a,connections:o,selectedServer:s,tunnelUrl:c,onNavigate:l,onServerSelect:u}){let[d,f]=(0,z.useState)(``),[p,m]=(0,z.useState)(0),h=(0,z.useRef)(null),g=(0,z.useRef)(null),_=sP(),y=kt.pill,{activeIndex:b,itemRects:x,sessionRef:S,handlers:C,registerItem:w,measureItems:T}=_n(h),E=s?c?`${c}/mcp`:s.url:null,ee=s?.name||`MCP Server`,D=s?MM(s):void 0,te=s?[{id:`open-in-cursor`,name:`Open in Cursor`,description:`Add this server to Cursor`,type:`global`,category:`Open in Client`,action:()=>{try{let e=NL(E,ee,D);window.location.href=e,oI.success(`Opening in Cursor...`),t(!1)}catch{oI.error(`Failed to open in Cursor`)}}},{id:`open-in-claude-code`,name:`Open in Claude Code`,description:`Add this server to Claude Code CLI`,type:`global`,category:`Open in Client`,action:()=>{let{command:e}=RL(E,ee,D);lM(e),oI.success(`Command copied to clipboard`),t(!1)}},{id:`open-in-claude-desktop`,name:`Open in Claude Desktop`,description:`Download .mcpb configuration file`,type:`global`,category:`Open in Client`,action:()=>{try{LL(E,ee,D),oI.success(`Downloaded .mcpb file`),t(!1)}catch{oI.error(`Failed to download configuration file`)}}},{id:`open-in-vscode`,name:`Open in VS Code`,description:`Add this server to VS Code`,type:`global`,category:`Open in Client`,action:()=>{try{let e=PL(E,ee,D);window.location.href=e,oI.success(`Opening in VS Code...`),t(!1)}catch{oI.error(`Failed to open in VS Code`)}}},{id:`open-in-vscode-insiders`,name:`Open in VS Code Insiders`,description:`Add this server to VS Code Insiders`,type:`global`,category:`Open in Client`,action:()=>{try{let e=FL(E,ee,D);window.location.href=e,oI.success(`Opening in VS Code Insiders...`),t(!1)}catch{oI.error(`Failed to open in VS Code Insiders`)}}},{id:`open-in-gemini`,name:`Open in Gemini CLI`,description:`Add this server to Gemini CLI`,type:`global`,category:`Open in Client`,action:()=>{let{command:e}=zL(E,ee,D);lM(e),oI.success(`Command copied to clipboard`),t(!1)}},{id:`open-in-codex`,name:`Open in Codex CLI`,description:`Add this server to Codex CLI`,type:`global`,category:`Open in Client`,action:()=>{let{config:e}=BL(E,ee,D);lM(e),oI.success(`Config copied to clipboard`),t(!1)}}]:[],ne=[{id:`connect-server`,name:`Connect Server`,description:`Add a new MCP server connection`,type:`global`,category:`Navigation`,action:()=>_(`/`)},{id:`mcp-use-website`,name:`MCP Use Website`,description:`Visit mcp-use.com for tools and resources`,type:`global`,category:`Documentation`,action:()=>window.open(`https://mcp-use.com`,`_blank`)},{id:`mcp-use-docs`,name:`How to Create an MCP Server`,description:`Step-by-step guide to building MCP servers`,type:`global`,category:`Documentation`,action:()=>window.open(`https://mcp-use.com/docs`,`_blank`)},{id:`mcp-docs`,name:`MCP Official Documentation`,description:`Learn about the Model Context Protocol`,type:`global`,category:`Documentation`,action:()=>window.open(`https://modelcontextprotocol.io/docs/getting-started/intro`,`_blank`)},{id:`discord`,name:`Join Discord Community`,description:`Connect with the MCP community`,type:`global`,category:`Community`,action:()=>window.open(`https://discord.gg/XkNkSkMz3V`,`_blank`)},{id:`clear-localstorage`,name:`Clear localStorage & Reload`,description:`Having trouble connecting? Clear stored auth data and refresh`,type:`global`,category:`Troubleshooting`,action:()=>{let e=[];for(let t=0;t<localStorage.length;t++){let n=localStorage.key(t);n&&(n.startsWith(`mcp:auth`)||n.startsWith(`mcp-inspector`))&&e.push(n)}e.forEach(e=>localStorage.removeItem(e)),oI.success(`Cleared ${e.length} localStorage item(s). Refreshing page...`,{duration:2e3}),setTimeout(()=>{window.location.reload()},500),t(!1)}}],re=o.map(e=>({id:`server-${e.id}`,name:bM(e),description:`Connected server (${e.state})`,type:`global`,category:`Connected Servers`,metadata:{serverId:e.id,state:e.state},action:()=>u(e.id)})),O=[...ne,...te,...re,...n.map(e=>({id:`tool-${e.name}`,name:e.name,description:e.description,type:`tool`,category:e._serverName?`Tools - ${e._serverName}`:`Tools`,metadata:{inputSchema:e.inputSchema,serverId:e._serverId,serverName:e._serverName}})),...r.map(e=>({id:`prompt-${e.name}`,name:e.name,description:e.description,type:`prompt`,category:e._serverName?`Prompts - ${e._serverName}`:`Prompts`,metadata:{arguments:e.arguments,serverId:e._serverId,serverName:e._serverName}})),...i.map(e=>({id:`resource-${e.uri}`,name:e.name,description:e.description,type:`resource`,category:e._serverName?`Resources - ${e._serverName}`:`Resources`,metadata:{uri:e.uri,mimeType:e.mimeType,serverId:e._serverId,serverName:e._serverName}})),...a.map(e=>({id:`saved-${e.id}`,name:e.name,description:`Saved request for ${e.toolName}`,type:`saved-request`,category:`Saved Requests`,metadata:{toolName:e.toolName,args:e.args,savedAt:e.savedAt,serverId:e.serverId,serverName:e.serverName}}))].filter(e=>d.trim()?`${e.name} ${e.description||``} ${e.category}`.toLowerCase().includes(d.trim().toLowerCase()):!0),ie=(0,z.useCallback)(e=>{if(console.warn(`[CommandPalette] Item selected:`,{itemType:e.type,itemName:e.name,itemId:e.id,metadata:e.metadata}),e.action)console.warn(`[CommandPalette] Executing action for global item`),e.action(),t(!1);else if(e.type===`global`)e.metadata?.serverId&&(console.warn(`[CommandPalette] Selecting server:`,e.metadata.serverId),u(e.metadata.serverId),t(!1));else{let n=e.type===`resource`?e.metadata?.uri:e.name,r=e.type===`tool`?`tools`:e.type===`prompt`?`prompts`:e.type===`saved-request`?`tools`:`resources`;console.warn(`[CommandPalette] Navigating to item:`,{tab:r,itemIdentifier:n,serverId:e.metadata?.serverId}),l(r,n,e.metadata?.serverId),t(!1)}},[l,t,u]),k=(e,t,n)=>{switch(e){case`tool`:return(0,R.jsx)(`div`,{className:`bg-blue-500/20 rounded-full p-2 flex items-center justify-center shrink-0`,children:(0,R.jsx)(Yi,{className:`h-4 w-4 text-blue-500`})});case`prompt`:return(0,R.jsx)(`div`,{className:`bg-purple-500/20 rounded-full p-2 flex items-center justify-center shrink-0`,children:(0,R.jsx)(yi,{className:`h-4 w-4 text-purple-500`})});case`resource`:return(0,R.jsx)(`div`,{className:`bg-green-500/20 rounded-full p-2 flex items-center justify-center shrink-0`,children:(0,R.jsx)(Qr,{className:`h-4 w-4 text-green-500`})});case`saved-request`:return(0,R.jsx)(`div`,{className:`bg-orange-500/20 rounded-full p-2 flex items-center justify-center shrink-0`,children:(0,R.jsx)(ri,{className:`h-4 w-4 text-orange-500`})});case`global`:if(t===`Navigation`)return(0,R.jsx)(`div`,{className:`bg-gray-500/20 rounded-full p-2 flex items-center justify-center shrink-0`,children:(0,R.jsx)(Ai,{className:`h-4 w-4 text-gray-600 dark:text-gray-300`})});if(t===`Open in Client`){if(n?.includes(`Cursor`))return(0,R.jsx)(`div`,{className:`bg-gray-200 dark:bg-gray-800 rounded-full p-2 flex items-center justify-center shrink-0`,children:(0,R.jsx)(`img`,{src:`https://cdn.simpleicons.org/cursor`,alt:`Cursor`,className:`h-4 w-4`})});if(n?.includes(`Claude Code`)||n?.includes(`Claude Desktop`))return(0,R.jsx)(`div`,{className:`bg-orange-500/20 rounded-full p-2 flex items-center justify-center shrink-0`,children:(0,R.jsx)(`img`,{src:`https://cdn.simpleicons.org/claude`,alt:`Claude`,className:`h-4 w-4`})});if(n?.includes(`VS Code`))return(0,R.jsx)(`div`,{className:`bg-blue-600/20 rounded-full p-2 flex items-center justify-center shrink-0`,children:(0,R.jsx)(UL,{className:`h-4 w-4 text-blue-600`})});if(n?.includes(`Gemini`))return(0,R.jsx)(`div`,{className:`bg-purple-500/20 rounded-full p-2 flex items-center justify-center shrink-0`,children:(0,R.jsx)(`img`,{src:`https://cdn.simpleicons.org/googlegemini`,alt:`Gemini`,className:`h-4 w-4`})});if(n?.includes(`Codex`))return(0,R.jsx)(`div`,{className:`bg-green-500/20 rounded-full p-2 flex items-center justify-center shrink-0`,children:(0,R.jsx)(`img`,{src:`https://inspector-cdn.mcp-use.com/providers/openai.png`,alt:`Codex`,className:`h-4 w-4`})})}return t===`Documentation`?n?.includes(`MCP Use`)||n?.includes(`mcp-use`)?(0,R.jsx)(`div`,{className:`bg-black/10 dark:bg-white/10 rounded-full p-2 flex items-center justify-center shrink-0`,children:(0,R.jsx)(HL,{className:`h-4 w-4 text-black dark:text-white`,size:`sm`})}):(0,R.jsx)(`div`,{className:`bg-orange-500/20 rounded-full p-2 flex items-center justify-center shrink-0`,children:(0,R.jsx)(Yr,{className:`h-4 w-4 text-orange-500`})}):t===`Community`?(0,R.jsx)(`div`,{className:`bg-purple-500/20 rounded-full p-2 flex items-center justify-center shrink-0`,children:(0,R.jsx)(GL,{className:`h-4 w-4 text-purple-500`})}):t===`Troubleshooting`?(0,R.jsx)(`div`,{className:`bg-yellow-500/20 rounded-full p-2 flex items-center justify-center shrink-0`,children:(0,R.jsx)(Pr,{className:`h-4 w-4 text-yellow-500`})}):t===`Connected Servers`?(0,R.jsx)(`div`,{className:`bg-cyan-500/20 rounded-full p-2 flex items-center justify-center shrink-0`,children:(0,R.jsx)(Fi,{className:`h-4 w-4 text-cyan-500`})}):(0,R.jsx)(`div`,{className:`bg-gray-500/20 rounded-full p-2 flex items-center justify-center shrink-0`,children:(0,R.jsx)(Yr,{className:`h-4 w-4 text-gray-500`})});default:return(0,R.jsx)(`div`,{className:`bg-gray-500/20 rounded-full p-2 flex items-center justify-center shrink-0`,children:(0,R.jsx)(v,{className:`h-4 w-4 text-gray-500`})})}};(0,z.useEffect)(()=>{e&&(f(``),m(0),requestAnimationFrame(()=>g.current?.focus()))},[e]),(0,z.useEffect)(()=>{h.current&&(h.current.scrollTop=0),m(0)},[d]),(0,z.useEffect)(()=>{p>=O.length&&m(Math.max(0,O.length-1))},[p,O.length]),(0,z.useLayoutEffect)(()=>{e&&T()},[e,T,O]);let A=x[p]??null,j=b===null?null:x[b],ae=b!==null&&b!==p;return e?(0,R.jsxs)(R.Fragment,{children:[(0,R.jsx)(`button`,{type:`button`,className:`fixed inset-0 z-50 bg-black/40 backdrop-blur-sm`,"aria-label":`Close command palette`,onClick:()=>t(!1)}),(0,R.jsxs)(`div`,{role:`dialog`,"aria-label":`Command Palette`,"data-testid":`command-palette-dialog`,className:`fixed left-1/2 top-1/2 -translate-x-1/2 -translate-y-1/2 z-[51] max-w-[640px] w-[calc(100vw-2rem)] sm:w-full p-2 bg-white dark:bg-zinc-900/90 backdrop-blur-xl rounded-xl overflow-hidden border border-border shadow-[var(--cmdk-shadow)] transition-transform duration-100 ease-out outline-none`,onKeyDown:e=>{e.key===`ArrowDown`?(e.preventDefault(),m(e=>Math.min(e+1,O.length-1))):e.key===`ArrowUp`?(e.preventDefault(),m(e=>Math.max(e-1,0))):e.key===`Enter`&&O[p]?(e.preventDefault(),ie(O[p])):e.key===`Escape`&&(e.preventDefault(),t(!1))},children:[(0,R.jsx)(`input`,{ref:g,placeholder:`What do you need?`,value:d,onChange:e=>f(e.target.value),className:`border-none w-full text-[17px] px-4 pt-2 pb-4 outline-none bg-transparent text-foreground border-b border-border mb-0 rounded-none placeholder:text-muted-foreground`,"data-testid":`command-palette-input`}),(0,R.jsxs)(`div`,{ref:h,onMouseEnter:C.onMouseEnter,onMouseMove:C.onMouseMove,onMouseLeave:C.onMouseLeave,className:`relative isolate min-h-[200px] sm:min-h-[330px] max-h-[400px] overflow-auto overscroll-contain transition-[height] duration-100 ease-out px-1`,"data-testid":`command-palette-list`,children:[(0,R.jsx)(en,{children:A&&(0,R.jsx)(Pe.div,{"aria-hidden":!0,className:L(`pointer-events-none absolute bg-active`,y.bg),initial:!1,animate:{top:A.top,left:A.left,width:A.width,height:A.height,opacity:ae?.8:1},exit:{opacity:0,transition:pt.moderate.exit},transition:{...pt.moderate,opacity:{duration:.08}}})}),(0,R.jsx)(en,{children:j&&(0,R.jsx)(Pe.div,{"aria-hidden":!0,className:L(`pointer-events-none absolute bg-hover`,y.bg),initial:{opacity:0,top:A?.top??j.top,left:A?.left??j.left,width:A?.width??j.width,height:A?.height??j.height},animate:{opacity:1,top:j.top,left:j.left,width:j.width,height:j.height},exit:{opacity:0,transition:pt.fast.exit},transition:{...pt.fast,opacity:{duration:.08}}},S.current)}),O.length===0?(0,R.jsx)(`div`,{className:`text-sm flex items-center justify-center h-12 whitespace-pre-wrap text-muted-foreground`,children:`No results found.`}):O.map((e,t)=>(0,R.jsxs)(`button`,{ref:e=>w(t,e),type:`button`,"data-testid":`command-palette-item-${e.id}`,"data-proximity-index":t,onClick:()=>ie(e),className:`[content-visibility:auto] relative z-10 cursor-pointer h-12 text-sm flex items-center gap-3 px-3 text-foreground select-none w-full text-left mt-1 first:mt-0`,children:[k(e.type,e.category,e.name),(0,R.jsx)(`span`,{className:`font-medium truncate flex-1 min-w-0`,children:e.name}),(()=>{let t=e.metadata?.serverId;if(!t||e.category===`Connected Servers`)return null;let n=o.find(e=>e.id===t);return n?(0,R.jsxs)(`div`,{className:`flex items-center gap-1 shrink-0 text-muted-foreground`,children:[(0,R.jsx)(xL,{server:n,size:`xs`}),(0,R.jsx)(`span`,{className:`text-xs truncate max-w-[9rem]`,children:bM(n)})]}):null})()]},e.id))]}),(0,R.jsxs)(`div`,{className:`border-t border-border px-4 py-3 pb-1 flex items-center justify-between text-xs text-muted-foreground `,children:[(0,R.jsxs)(`div`,{className:`flex items-center gap-3`,children:[(0,R.jsxs)(`div`,{className:`flex items-center gap-1.5`,children:[(0,R.jsx)(`span`,{className:`inline-flex items-center justify-center w-5 h-5 font-mono font-medium rounded shadow-sm bg-white dark:bg-zinc-800 border border-zinc-200 dark:border-zinc-700 text-foreground leading-none`,children:`t`}),(0,R.jsx)(`span`,{children:`Tools`})]}),(0,R.jsxs)(`div`,{className:`flex items-center gap-1.5`,children:[(0,R.jsx)(`span`,{className:`inline-flex items-center justify-center w-5 h-5 font-mono font-medium rounded shadow-sm bg-white dark:bg-zinc-800 border border-zinc-200 dark:border-zinc-700 text-foreground leading-none`,children:`p`}),(0,R.jsx)(`span`,{children:`Prompts`})]}),(0,R.jsxs)(`div`,{className:`flex items-center gap-1.5`,children:[(0,R.jsx)(`span`,{className:`inline-flex items-center justify-center w-5 h-5 font-mono font-medium rounded shadow-sm bg-white dark:bg-zinc-800 border border-zinc-200 dark:border-zinc-700 text-foreground leading-none`,children:`r`}),(0,R.jsx)(`span`,{children:`Resources`})]}),(0,R.jsxs)(`div`,{className:`flex items-center gap-1.5`,children:[(0,R.jsx)(`span`,{className:`inline-flex items-center justify-center w-5 h-5 font-mono font-medium rounded shadow-sm bg-white dark:bg-zinc-800 border border-zinc-200 dark:border-zinc-700 text-foreground leading-none`,children:`c`}),(0,R.jsx)(`span`,{children:`Chat`})]})]}),(0,R.jsxs)(`div`,{className:`flex items-center gap-3`,children:[(0,R.jsxs)(`div`,{className:`flex items-center gap-1.5`,children:[(0,R.jsx)(`span`,{className:`inline-flex items-center justify-center w-5 h-5 font-mono font-medium rounded shadow-sm bg-white dark:bg-zinc-800 border border-zinc-200 dark:border-zinc-700 text-foreground leading-none`,children:`h`}),(0,R.jsx)(`span`,{children:`Home`})]}),(0,R.jsxs)(`div`,{className:`flex items-center gap-1.5`,children:[(0,R.jsx)(`span`,{className:`inline-flex items-center justify-center px-2 h-5 font-mono text-[10px] font-medium rounded shadow-sm bg-white dark:bg-zinc-800 border border-zinc-200 dark:border-zinc-700 text-foreground leading-none`,children:`esc`}),(0,R.jsx)(`span`,{children:`Close`})]})]})]})]})]}):null}var qL=`openid profile email offline_access`,JL=`mcp-inspector:manufact-auth`,YL=`manufact:session-changed`,XL={loaded:!0,authorizing:!1,accessToken:null,user:null,mode:null},ZL=new Map,QL=new Set,$L=new Map,eR=new Map,tR=null,nR=!1;typeof window<`u`&&window.addEventListener(`message`,e=>{if(e.data?.type!==`manufact:invalidate-oauth-client`)return;for(let e of ZL.keys())iR()?.removeItem(uR(e,`client`));let t=tR;!t||nR||(nR=!0,MR(t,{isRetry:!0}).finally(()=>{nR=!1}))});function rR(e){let t=ZL.get(e);if(t)return t;let n={...XL,loaded:!1};return ZL.set(e,n),n}function iR(){return typeof window>`u`?null:window.localStorage}function aR(e){return new URL(e).origin}function oR(e,t){let n=new URL(e),r=new URL(t),i=new Set([`localhost`,`127.0.0.1`]);return i.has(n.hostname)&&i.has(r.hostname)?n.origin===r.origin:(n.hostname===`manufact.com`||n.hostname.endsWith(`.manufact.com`))&&(r.hostname===`manufact.com`||r.hostname.endsWith(`.manufact.com`))}function sR(e){let t=window.__MANUFACT_LOGIN_URL__;if(t)return new URL(t).origin;let n=new URL(e);return n.hostname===`localhost`||n.hostname===`127.0.0.1`?`${n.protocol}//${n.hostname}:3000`:`${n.protocol}//manufact.com`}function cR(e){return`${sR(e)}/login`}function lR(e){return`${sR(e)}/auth/embedded-sign-out`}function uR(e,t){return`${JL}:${t}:${e}`}function dR(e){return iR()?.getItem(uR(e,`skip-session`))===`1`}function fR(e,t){let n=uR(e,`skip-session`);t?iR()?.setItem(n,`1`):iR()?.removeItem(n)}function pR(e){return`${JL}:state:${e}`}function mR(e){let t=iR()?.getItem(e);if(!t)return null;try{return JSON.parse(t)}catch{return iR()?.removeItem(e),null}}function hR(e,t){iR()?.setItem(e,JSON.stringify(t))}function gR(e,t){ZL.set(e,{...ZL.get(e)??XL,...t}),QL.forEach(e=>e()),window.dispatchEvent(new CustomEvent(YL))}function _R(e){let t=``;return e.forEach(e=>{t+=String.fromCharCode(e)}),btoa(t).replace(/\+/g,`-`).replace(/\//g,`_`).replace(/=+$/,``)}function vR(e=32){let t=new Uint8Array(e);return crypto.getRandomValues(t),_R(t)}async function yR(e){let t=await crypto.subtle.digest(`SHA-256`,new TextEncoder().encode(e));return _R(new Uint8Array(t))}async function bR(e){let t=await fetch(`${e}/api/auth/.well-known/openid-configuration`);if(!t.ok)throw Error(`Manufact OAuth discovery failed`);return await t.json()}function xR(){return`${window.location.origin}${mM()}/auth/callback`}function SR(e){return e===`localhost`||e===`127.0.0.1`}function CR(e){try{let t=new URL(e).hostname,n=typeof window<`u`?new URL(window.location.href).hostname:``;return SR(t)&&SR(n)}catch{return!1}}async function wR(e,t,n){let r=new URL(`${e}/api/auth/oauth2/authorize`);r.searchParams.set(`response_type`,`code`),r.searchParams.set(`client_id`,t),r.searchParams.set(`redirect_uri`,n),r.searchParams.set(`scope`,qL),r.searchParams.set(`code_challenge`,await yR(vR(32))),r.searchParams.set(`code_challenge_method`,`S256`),r.searchParams.set(`state`,`client-probe`),r.searchParams.set(`prompt`,`none`);try{let e=await fetch(r.toString(),{method:`GET`,redirect:`manual`,credentials:`include`}),t=e.headers.get(`location`)??``;return t.includes(`/auth/error`)&&t.includes(`invalid_client`)?!1:e.status>=300&&e.status<400||e.type===`opaqueredirect`?!!t&&!t.includes(`/auth/error`):!0}catch{return!1}}async function TR(e,t){let n=xR(),r=uR(e,`client`),i=mR(r),a=CR(e);if(!a&&i?.client_id&&i.redirect_uri===n){if(await wR(e,i.client_id,n))return i;iR()?.removeItem(r)}else a&&i?.client_id&&iR()?.removeItem(r);if(!t.registration_endpoint)throw Error(`Manufact OAuth registration is unavailable`);let o=await fetch(t.registration_endpoint,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({client_name:`mcp-use Inspector`,redirect_uris:[n],grant_types:[`authorization_code`,`refresh_token`],response_types:[`code`],token_endpoint_auth_method:`none`,scope:qL})});if(!o.ok)throw Error(`Could not register Inspector with Manufact`);let s=await o.json();if(!s.client_id)throw Error(`Manufact returned no OAuth client ID`);let c={...s,redirect_uri:n};return hR(r,c),c}async function ER(e,t){let n=await fetch(e,{method:`POST`,headers:{"Content-Type":`application/x-www-form-urlencoded`},body:new URLSearchParams(t)}),r=await n.json().catch(()=>({}));if(!n.ok||!r.access_token)throw Error(r.error_description??`Manufact token exchange failed`);return{access_token:r.access_token,refresh_token:r.refresh_token,token_type:r.token_type,expires_at:Date.now()+(r.expires_in??3600)*1e3}}async function DR(e,t){if(!t.refresh_token)return null;let n=eR.get(e);if(n)return n;let r=(async()=>{try{let n=await bR(e),r=mR(uR(e,`client`));if(!r?.client_id)return null;let i=await ER(n.token_endpoint,{grant_type:`refresh_token`,refresh_token:t.refresh_token,client_id:r.client_id}),a={...i,refresh_token:i.refresh_token??t.refresh_token};return hR(uR(e,`tokens`),a),a}catch{return iR()?.removeItem(uR(e,`tokens`)),null}finally{eR.delete(e)}})();return eR.set(e,r),r}async function OR(e){let t=mR(uR(e,`tokens`));return t?.access_token?t.expires_at>Date.now()+3e4?t:DR(e,t):null}async function kR(e,t){let n=await bR(e);if(!n.userinfo_endpoint)return null;let r=await fetch(n.userinfo_endpoint,{headers:{Authorization:`Bearer ${t}`}});if(!r.ok)return null;let i=await r.json();return i.sub?{id:i.sub,name:i.name,email:i.email,image:i.picture}:null}async function AR(e){try{let t=await fetch(`${e}/api/auth/get-session`,{credentials:`include`});return t.ok?(await t.json())?.user??null:null}catch{return null}}async function jR(e){let t=$L.get(e);if(t)return t;ZL.set(e,{...ZL.get(e)??XL,loaded:!1});let n=(async()=>{try{let t=oR(typeof window<`u`?window.location.href:e,e),n=dR(e),r=await OR(e),i=r?await kR(e,r.access_token):null;if(i&&r){fR(e,!1),gR(e,{loaded:!0,accessToken:r.access_token,user:i,mode:`oauth`});return}r&&!i&&iR()?.removeItem(uR(e,`tokens`));let a=t&&!n?await AR(e):null;if(a){gR(e,{loaded:!0,accessToken:null,user:a,mode:`session`});return}gR(e,{loaded:!0,accessToken:null,user:null,mode:null})}catch{gR(e,{loaded:!0,accessToken:null,user:null,mode:null})}})().finally(()=>$L.delete(e));return $L.set(e,n),n}async function MR(e,t){let n=aR(e);tR=e,fR(n,!1);let r=window.open(``,`manufact-oauth`,`width=600,height=700,resizable=yes,scrollbars=yes`);if(!r)throw Error(`Allow popups to sign in with Manufact`);if(gR(n,{authorizing:!0}),oR(window.location.href,n)){r.location.href=cR(n);let e=window.setInterval(async()=>{if(r.closed){window.clearInterval(e),gR(n,{authorizing:!1});return}let t=await AR(n);t&&(window.clearInterval(e),r.close(),gR(n,{loaded:!0,authorizing:!1,accessToken:null,user:t,mode:`session`}))},1e3);return}try{let e=await bR(n),t=await TR(n,e),i=vR(64),a=vR(),o=xR();hR(pR(a),{authOrigin:n,clientId:t.client_id,redirectUri:o,codeVerifier:i,expiresAt:Date.now()+600*1e3});let s=new URL(e.authorization_endpoint);s.searchParams.set(`response_type`,`code`),s.searchParams.set(`client_id`,t.client_id),s.searchParams.set(`redirect_uri`,o),s.searchParams.set(`scope`,qL),s.searchParams.set(`state`,a),s.searchParams.set(`code_challenge`,await yR(i)),s.searchParams.set(`code_challenge_method`,`S256`),s.searchParams.set(`prompt`,`consent`),r.location.href=s.toString();let c=window.setInterval(()=>{r.closed&&(window.clearInterval(c),jR(n).finally(()=>gR(n,{authorizing:!1})))},500)}catch(e){throw r.close(),gR(n,{authorizing:!1}),e}}async function NR(e=new URL(window.location.href)){let t=e.searchParams.get(`state`),n=e.searchParams.get(`code`),r=e.searchParams.get(`error_description`)??e.searchParams.get(`error`);if(r)throw Error(r);if(!t||!n)throw Error(`Missing OAuth code or state`);let i=pR(t),a=mR(i);if(iR()?.removeItem(i),!a||a.expiresAt<Date.now())throw Error(`OAuth state is invalid or expired`);let o=await ER((await bR(a.authOrigin)).token_endpoint,{grant_type:`authorization_code`,code:n,redirect_uri:a.redirectUri,client_id:a.clientId,code_verifier:a.codeVerifier});hR(uR(a.authOrigin,`tokens`),o),fR(a.authOrigin,!1);let s=await kR(a.authOrigin,o.access_token);gR(a.authOrigin,{loaded:!0,authorizing:!1,accessToken:o.access_token,user:s,mode:`oauth`}),window.opener?.postMessage({type:`manufact:oauth-complete`,authOrigin:a.authOrigin},window.location.origin)}function PR(e){let t=aR(e);iR()?.removeItem(uR(t,`tokens`)),gR(t,{loaded:!0,authorizing:!1,accessToken:null,user:null,mode:null})}async function FR(e){let t=mR(uR(e,`tokens`)),n=mR(uR(e,`client`)),r=t?.refresh_token??t?.access_token;if(!n?.client_id||!r)return null;try{let i=(await bR(e)).revocation_endpoint??`${e}/api/auth/oauth2/revoke`;return(await fetch(i,{method:`POST`,headers:{"Content-Type":`application/x-www-form-urlencoded`},body:new URLSearchParams({client_id:n.client_id,token:r,token_type_hint:t?.refresh_token?`refresh_token`:`access_token`})})).status}catch{return-1}}async function IR(e){let t=sR(e),n=window.open(lR(e),`manufact-sign-out`,`width=420,height=320`);return n?new Promise(r=>{let i=!1,a=e=>{i||(i=!0,window.clearTimeout(o),window.clearInterval(c),window.removeEventListener(`message`,s),r(e))},o=window.setTimeout(()=>{a({attempted:!0,signOutOk:!1,signOutStatus:null})},3e4),s=e=>{e.origin===t&&e.data?.type===`manufact:sign-out-complete`&&a({attempted:!0,signOutOk:!0,signOutStatus:200})},c=window.setInterval(()=>{n.closed&&AR(e).then(e=>{a({attempted:!0,signOutOk:!e,signOutStatus:e?401:200})})},500);window.addEventListener(`message`,s)}):{attempted:!0,signOutOk:!1,signOutStatus:null}}async function LR(e,t){let n=aR(e),r=!!mR(uR(n,`tokens`))?.access_token;t===`oauth`||r?(await FR(n),fR(n,!0)):t===`session`&&(await IR(n),fR(n,!1)),PR(e)}function RR(e){let t=e?aR(e):null,n=(0,z.useSyncExternalStore)((0,z.useCallback)(e=>(QL.add(e),()=>QL.delete(e)),[]),(0,z.useCallback)(()=>t?rR(t):XL,[t]),()=>XL);return(0,z.useEffect)(()=>{if(!t)return;jR(t);let e=e=>{e.origin===window.location.origin&&e.data?.type===`manufact:oauth-complete`&&e.data.authOrigin===t&&jR(t).finally(()=>gR(t,{authorizing:!1}))},n=e=>{e.key!==uR(t,`tokens`)||!e.newValue||jR(t).finally(()=>gR(t,{authorizing:!1}))};return window.addEventListener(`message`,e),window.addEventListener(`storage`,n),()=>{window.removeEventListener(`message`,e),window.removeEventListener(`storage`,n)}},[t]),{...n,authorize:(0,z.useCallback)(async()=>{e&&await MR(e)},[e]),logout:(0,z.useCallback)(async()=>{e&&await LR(e,n.mode)},[e,n.mode])}}var zR=(0,z.lazy)(()=>lS(()=>import(`./ChatTab-DxD-KLW_.js`).then(e=>({default:e.ChatTab})),__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19]))),BR=(0,z.lazy)(()=>lS(()=>import(`./ToolsTab-BSSwvp4Q.js`).then(e=>({default:e.ToolsTab})),__vite__mapDeps([20,1,2,3,5,6,4,7,8,21,22,23,13,19,18,24,25,26,10,27,28,29,16,17]))),VR=(0,z.lazy)(()=>lS(()=>import(`./PromptsTab-CLwWFf6d.js`).then(e=>({default:e.PromptsTab})),__vite__mapDeps([30,1,2,3,5,6,4,7,8,24,26,10,27,28,29,11,12,19]))),HR=(0,z.lazy)(()=>lS(()=>import(`./ResourcesTab-B8cnuq-m.js`).then(e=>({default:e.ResourcesTab})),__vite__mapDeps([31,1,2,3,5,7,21,6,4,8,22,23,13,19,18,32,24,25,26,10,27,28,14,17]))),UR=(0,z.lazy)(()=>lS(()=>import(`./SamplingTab-BjYHYRHX.js`).then(e=>({default:e.SamplingTab})),__vite__mapDeps([33,1,2,3,5,6,4,7,8,26,10,27,22,23,13,14,19]))),WR=(0,z.lazy)(()=>lS(()=>import(`./ElicitationTab-o5_z6gqe.js`).then(e=>({default:e.ElicitationTab})),__vite__mapDeps([34,1,2,3,5,8,26,10,27,22,15,12,19]))),GR=(0,z.lazy)(()=>lS(()=>import(`./NotificationsTab-CkJ5E_sR.js`).then(e=>({default:e.NotificationsTab})),__vite__mapDeps([35,1,2,3,32,25,26,5,10,27,28]))),KR=(0,z.lazy)(()=>lS(()=>import(`./ServerMetadataTab-CPlclbb7.js`).then(e=>({default:e.ServerMetadataTab})),__vite__mapDeps([36,1,5,2,3,9,7,8,27,10,37]))),qR=(0,z.lazy)(()=>lS(()=>import(`./ConnectionSettingsTab-pO6p0U0f.js`).then(e=>({default:e.ConnectionSettingsTab})),__vite__mapDeps([38,1,2,3,5,27,10,37])));function JR({children:e}){return(0,R.jsx)(z.Suspense,{fallback:(0,R.jsx)(`div`,{className:`flex h-full items-center justify-center`,children:(0,R.jsx)(bL,{className:`size-6`})}),children:e})}var YR=`anthropic/claude-sonnet-4.6`;function XR({isLoopback:e,chatApiUrl:t}){return e&&!!t}function ZR(e,t,n=!1,r){let i=e.replace(/\/chat\/stream\/?$/,`/llm`);return{provider:`openai-compatible`,model:r??`anthropic/claude-sonnet-4.6`,apiKey:t??`server-managed`,baseUrl:i,...n?{credentials:`include`}:{}}}function QR(e){return e?{Authorization:`Bearer ${e}`}:void 0}var $R=`mcp-inspector:managed-model`;function ez(e){return`${$R}:${e}`}function tz(e){try{return localStorage.getItem(ez(e))}catch{return null}}function nz(e,t,n,r){let i=e?new URL(e).origin:null,[a,o]=(0,z.useState)([]),[s,c]=(0,z.useState)(YR),[l,u]=(0,z.useState)(()=>i?tz(i)??`anthropic/claude-sonnet-4.6`:YR),[d,f]=(0,z.useState)(!1),p=(0,z.useCallback)(e=>{if(u(e),i)try{localStorage.setItem(ez(i),e)}catch{}},[i]);return(0,z.useEffect)(()=>{if(!r||!i)return;let e=!1;return f(!0),(async()=>{try{let r=QR(t),a=await fetch(`${i}/api/v1/models`,{headers:r,credentials:n===`session`?`include`:`same-origin`});if(!a.ok)return;let s=await a.json();if(e)return;let l=s.models??[];o(l);let d=s.defaultModelId??`anthropic/claude-sonnet-4.6`;c(d);let f=new Set(l.map(e=>e.id)),p=tz(i);p&&f.has(p)?u(p):f.has(d)?u(d):l[0]&&u(l[0].id)}finally{e||f(!1)}})(),()=>{e=!0}},[r,i,t,n]),{models:a,selectedModelId:l,setSelectedModelId:p,isLoading:d,selectedModel:a.find(e=>e.id===l)??null,defaultModelId:s}}var rz=[`tools`,`prompts`,`resources`,`chat`,`sampling`,`elicitation`,`notifications`,`server-metadata`,`connection-settings`];function iz(e){return rz.includes(e)?e:`tools`}function az({selectedServer:e,activeTab:t,toolsSearchRef:n,promptsSearchRef:r,resourcesSearchRef:i,onUpdateConnection:a,children:o}){let{embeddedConfig:s}=EL(),c=iz(t),[l,u]=(0,z.useState)(()=>new Set([c]));(0,z.useEffect)(()=>{let e=iz(t);u(t=>t.has(e)?t:new Set(t).add(e))},[t]);let{accessToken:d,mode:f,user:p}=RR(s.chatApiUrl),m=QR(d),h=f===`session`?`include`:void 0,g=p!=null,_=s.chatApiUrl,v=!!e?.url&&_M(e.url),y=e?XR({isLoopback:v,chatApiUrl:s.chatApiUrl,enableFreeTierUpgrade:s.chatEnableFreeTierUpgrade}):!1,b=nz(_,d,f,!!e&&!!_&&g),x=y?ZR(_,d,f===`session`,g?b.selectedModelId:void 0):s.managedLlmConfig??(_&&!v?{provider:`anthropic`,model:`claude-haiku-4-5`,apiKey:`server-managed`}:void 0);if(!e&&s.forceConnected)return s.chatApiUrl?(0,R.jsx)(JR,{children:(0,R.jsx)(zR,{connection:{id:`force-connected`,url:``,displayName:``,name:``,state:`ready`,tools:[],prompts:[],resources:[]},isConnected:!0,prompts:[],serverId:`force-connected`,callPrompt:async()=>({messages:[]}),readResource:async()=>({contents:[]}),useClientSide:!1,chatApiUrl:s.chatApiUrl,extraHeaders:m,credentials:h,managedLlmConfig:s.managedLlmConfig??{provider:`anthropic`,model:`claude-haiku-4-5`,apiKey:`server-managed`},enableFreeTierUpgrade:s.chatEnableFreeTierUpgrade,hideTitle:s.chatHideTitle,hideModelBadge:s.chatHideModelBadge??!0,hideServerUrl:s.chatHideServerUrl??!0,clearButtonLabel:s.chatClearButtonLabel,clearButtonHideIcon:s.chatClearButtonHideIcon,clearButtonHideShortcut:s.chatClearButtonHideShortcut,clearButtonVariant:s.chatClearButtonVariant,chatQuickQuestions:s.chatQuickQuestions,chatFollowups:s.chatFollowups,hideClearButton:s.chatHideClearButton,hideToolSelector:s.chatHideToolSelector,enableKeyboardShortcuts:!1},`chat-force-connected`)}):(0,R.jsx)(R.Fragment,{children:o});if(!e)return(0,R.jsx)(R.Fragment,{children:o});let S=e=>s.visibleTabs?s.visibleTabs.includes(e):!0,C=rz;return(0,R.jsxs)(JR,{children:[S(`tools`)&&l.has(`tools`)&&(0,R.jsx)(`div`,{style:{display:t===`tools`?`block`:`none`},className:`h-full`,children:(0,R.jsx)(BR,{ref:n,tools:e.tools,callTool:e.callTool,readResource:e.readResource,serverId:e.id,isConnected:e.state===`ready`,refreshTools:e.refreshTools},`tools-${e.id}`)}),S(`prompts`)&&l.has(`prompts`)&&(0,R.jsx)(`div`,{style:{display:t===`prompts`?`block`:`none`},className:`h-full`,children:(0,R.jsx)(VR,{ref:r,prompts:e.prompts,callPrompt:(t,n)=>e.getPrompt(t,n?Object.fromEntries(Object.entries(n).map(([e,t])=>[e,typeof t==`string`?t:String(t??``)])):void 0),serverId:e.id,isConnected:e.state===`ready`,refreshPrompts:e.refreshPrompts},`prompts-${e.id}`)}),S(`resources`)&&l.has(`resources`)&&(0,R.jsx)(`div`,{style:{display:t===`resources`?`block`:`none`},className:`h-full`,children:(0,R.jsx)(HR,{ref:i,resources:e.resources,readResource:e.readResource,serverId:e.id,isConnected:e.state===`ready`,mcpServerUrl:e.url||``,refreshResources:e.refreshResources},`resources-${e.id}`)}),S(`chat`)&&l.has(`chat`)&&(0,R.jsx)(`div`,{style:{display:t===`chat`?`block`:`none`},className:`h-full`,children:(0,R.jsx)(zR,{connection:e,isConnected:s.forceConnected||e.state===`ready`,prompts:e.prompts,serverId:e.id,callPrompt:(t,n)=>e.getPrompt(t,n?Object.fromEntries(Object.entries(n).map(([e,t])=>[e,typeof t==`string`?t:String(t??``)])):void 0),readResource:e.readResource,useClientSide:y||!_,chatApiUrl:_,extraHeaders:m,credentials:s.chatCredentials??h,managedLlmConfig:x,managedCloudModel:b,enableFreeTierUpgrade:s.chatEnableFreeTierUpgrade,hideTitle:s.chatHideTitle,hideModelBadge:s.chatHideModelBadge??!1,hideServerUrl:s.chatHideServerUrl??!!_,clearButtonLabel:s.chatClearButtonLabel,clearButtonHideIcon:s.chatClearButtonHideIcon,clearButtonHideShortcut:s.chatClearButtonHideShortcut,clearButtonVariant:s.chatClearButtonVariant,chatQuickQuestions:s.chatQuickQuestions,chatFollowups:s.chatFollowups,hideClearButton:s.chatHideClearButton,hideToolSelector:s.chatHideToolSelector,streamProtocol:s.chatStreamProtocol},`chat-${e.id}`)}),S(`sampling`)&&l.has(`sampling`)&&(0,R.jsx)(`div`,{style:{display:t===`sampling`?`block`:`none`},className:`h-full`,children:(0,R.jsx)(UR,{pendingRequests:e.pendingSamplingRequests,onApprove:e.approveSampling,onReject:e.rejectSampling,serverId:e.id,isConnected:e.state===`ready`,mcpServerUrl:e.url??``},`sampling-${e.id}`)}),S(`elicitation`)&&l.has(`elicitation`)&&(0,R.jsx)(`div`,{style:{display:t===`elicitation`?`block`:`none`},className:`h-full`,children:(0,R.jsx)(WR,{pendingRequests:e.pendingElicitationRequests,onApprove:e.approveElicitation,onReject:e.rejectElicitation,serverId:e.id,isConnected:e.state===`ready`},`elicitation-${e.id}`)}),S(`notifications`)&&l.has(`notifications`)&&(0,R.jsx)(`div`,{style:{display:t===`notifications`?`block`:`none`},className:`h-full`,children:(0,R.jsx)(GR,{notifications:e.notifications,unreadCount:e.unreadNotificationCount,markNotificationRead:e.markNotificationRead,markAllNotificationsRead:e.markAllNotificationsRead,clearNotifications:e.clearNotifications,serverId:e.id,isConnected:e.state===`ready`},`notifications-${e.id}`)}),S(`server-metadata`)&&l.has(`server-metadata`)&&(0,R.jsx)(`div`,{style:{display:t===`server-metadata`?`block`:`none`},className:`h-full`,children:(0,R.jsx)(KR,{connection:e},`server-metadata-${e.id}`)}),S(`connection-settings`)&&l.has(`connection-settings`)&&a&&(0,R.jsx)(`div`,{style:{display:t===`connection-settings`?`block`:`none`},className:`h-full`,children:(0,R.jsx)(qR,{connection:e,onSave:a},`connection-settings-${e.id}`)}),!C.includes(t)&&(0,R.jsx)(R.Fragment,{children:o})]})}var oz=z.createContext(void 0);function sz(){let e=z.use(oz);if(!e)throw Error(`useTabs must be used within a TabsProvider`);return e}var cz=z.createContext(void 0);function lz(){return z.use(cz)}function uz({ref:e,children:t,defaultValue:n,value:r,onValueChange:i,className:a,collapsed:o,onCollapsedChange:s,...c}){let[l,u]=z.useState(n||``),d=r!==void 0,f=o!==void 0,[p,m]=z.useState(!1),h=z.useCallback(e=>{d||u(e),i?.(e)},[d,i]);return(0,R.jsx)(oz,{value:{activeValue:d?r:l,handleValueChange:h,collapsed:f?o:p,handleCollapsedChange:z.useCallback(e=>{f||m(e),s?.(e)},[f,s])},children:(0,R.jsx)(`div`,{ref:e,className:L(`flex flex-col gap-2`,a),...c,children:t})})}uz.displayName=`Tabs`;function dz({ref:e,children:t,className:n,variant:r=`default`,collapsible:i=!1,...a}){let{activeValue:o,collapsed:s,handleCollapsedChange:c}=sz(),[l,u]=z.useState({width:0,left:0}),d=z.useRef(null),f=z.useRef(null),p=z.useRef(null),m=z.useCallback(()=>{let e=d.current;if(!e)return;let t=e.querySelector(`div:first-child`);if(!t)return;let n=t.querySelector(`button[data-tab-value="${o}"]`);if(n&&o){let e=t.getBoundingClientRect(),r=n.getBoundingClientRect();u({width:r.width,left:r.left-e.left})}else u({width:0,left:0})},[o]),h=z.useCallback(()=>{p.current&&clearTimeout(p.current),p.current=setTimeout(m,16)},[m]);z.useEffect(()=>{let e=setTimeout(m,10);return()=>clearTimeout(e)},[m,s]),z.useEffect(()=>{let e=d.current;if(!e)return;f.current=new ResizeObserver(()=>{h()}),f.current.observe(e);let t=e.querySelector(`div:first-child`);return t&&t.querySelectorAll(`button[data-tab-value]`).forEach(e=>{f.current&&f.current.observe(e)}),()=>{f.current&&f.current.disconnect(),p.current&&clearTimeout(p.current)}},[h]),z.useEffect(()=>{let e=()=>{h()};return window.addEventListener(`resize`,e),()=>window.removeEventListener(`resize`,e)},[h]);let g=z.useRef(null);return z.useEffect(()=>{g.current&&(g.current.style.width=`${l.width}px`,g.current.style.left=`${l.left}px`)},[l]),(0,R.jsx)(cz,{value:{variant:r,collapsed:s,handleCollapsedChange:c},children:(0,R.jsx)(`div`,{ref:d,className:L(`relative flex items-center bg-none gap-1`,r==="default"&&`p-1 rounded-full border border-zinc-300 dark:border-zinc-600`,r===`underline`&&`border-b border-zinc-200 dark:border-zinc-700`,n),...a,children:(0,R.jsxs)(`div`,{role:`tablist`,className:`flex-1 flex items-center relative`,children:[t,(0,R.jsx)(`span`,{ref:g,className:L(`absolute transition-all duration-[250ms] ease-in-out z-0`,r==="default"&&`bg-white dark:bg-zinc-700 rounded-full h-[calc(100%)] top-0 border border-zinc-300 dark:border-zinc-600`,r===`underline`&&`bottom-0 h-0.5 bg-black dark:bg-white`)})]})})})}dz.displayName=`TabsList`;var fz=({children:e,title:t,collapsed:n})=>!t||!n?e:(0,R.jsx)(Ve,{children:(0,R.jsxs)(et,{children:[(0,R.jsx)(we,{render:(0,R.jsx)(`span`,{className:`contents`,children:e}),nativeButton:!1}),(0,R.jsx)(lt,{children:t})]})}),pz=z.forwardRef(({children:e,value:t,className:n,disabled:r,icon:i,title:a,showDot:o=!1,alwaysExpanded:s=!1,iconOnly:c=!1,badge:l,...u},d)=>{let{activeValue:f,handleValueChange:p,collapsed:m}=sz(),h=lz()?.variant||`default`,g=f===t,_=!c&&(!m||g||s),v=c||m&&!_;return(0,R.jsx)(fz,{title:a,collapsed:m&&!_,children:(0,R.jsxs)(`button`,{ref:d,disabled:r,onClick:()=>p(t),"data-tab-value":t,"data-tab-active":g,role:`tab`,"aria-selected":g?`true`:`false`,title:m&&!_&&a?a:void 0,className:L(`relative z-10 inline-flex items-center justify-center whitespace-nowrap text-sm font-medium ring-offset-background transition-all duration-[250ms] ease-in-out focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 cursor-pointer`,c?`size-9 shrink-0 flex-none rounded-full p-0`:`flex-1`,h==="default"&&!c&&`py-2.5`,h==="default"&&!c&&`rounded-md px-4`,h===`underline`&&`px-6 py-3 border-b-2 border-transparent`,g&&`text-foreground`,!g&&`text-muted-foreground hover:text-foreground`,n),...u,children:[i&&(0,R.jsxs)(`span`,{className:L(`relative inline-flex shrink-0 items-center justify-center`,c?`size-5`:_&&`mr-2`),children:[(0,R.jsx)(i,{className:L(`h-4 w-4 shrink-0 transition-all duration-[250ms] ease-in-out`,!_&&!c&&`mr-0!`)}),l&&v?l:null]}),o&&(0,R.jsx)(`span`,{className:`absolute top-1.5 right-1.5 w-2 h-2 bg-orange-500 dark:bg-orange-400 border-2 border-white dark:border-zinc-900 rounded-full transition-opacity duration-300 z-10 animate-status-pulse-orange`}),(0,R.jsx)(`span`,{className:L(`min-w-0 transition-all duration-[250ms] ease-in-out overflow-hidden`,_?`w-auto opacity-100`:`w-0 opacity-0`),children:e}),l&&!v?l:null]})})});pz.displayName=`TabsTrigger`;function mz(e){return RR(e)}var hz=z.createContext(void 0);function gz(){let e=z.useContext(hz);if(e===void 0)throw Error(Vt(13));return e}var _z={imageLoadingStatus:()=>null},vz=z.forwardRef(function(e,t){let{className:n,render:r,style:i,...a}=e,[o,s]=z.useState(`idle`),c={imageLoadingStatus:o},l=z.useMemo(()=>({imageLoadingStatus:o,setImageLoadingStatus:s}),[o,s]),u=Ft(`span`,e,{state:c,ref:t,props:a,stateAttributesMapping:_z});return(0,R.jsx)(hz.Provider,{value:l,children:u})});function yz(e,{referrerPolicy:t,crossOrigin:n,sizes:r,srcSet:i}){let[a,o]=z.useState(`idle`);return Rt(()=>{if(!e&&!i)return o(`error`),It;let a=!0,s=new window.Image,c=e=>()=>{a&&o(e)};return o(`loading`),s.onload=c(`loaded`),s.onerror=c(`error`),t&&(s.referrerPolicy=t),s.crossOrigin=n??null,r&&(s.sizes=r),i&&(s.srcset=i),e&&(s.src=e),s.complete&&o(s.naturalWidth>0?`loaded`:`error`),()=>{a=!1}},[e,i,r,n,t]),a}var bz={..._z,...it},xz=z.forwardRef(function(e,t){let{className:n,render:r,onLoadingStatusChange:i,style:a,...o}=e,{setImageLoadingStatus:s}=gz(),c=yz(o.src,o),l=c===`loaded`,{mounted:u,transitionStatus:d,setMounted:f}=Je(l),p=z.useRef(null),m=Pt(e=>{i?.(e),s(e)});Rt(()=>{c!==`idle`&&m(c)},[c,m]),Rt(()=>()=>s(`idle`),[s]),g({open:l,ref:p,onComplete(){l||f(!1)}});let h=Ft(`img`,e,{state:{imageLoadingStatus:c,transitionStatus:d},ref:[t,p],props:o,stateAttributesMapping:bz,enabled:u});return u?h:null}),Sz=z.forwardRef(function(e,t){let{className:n,render:r,delay:i,style:a,...o}=e,{imageLoadingStatus:s}=gz(),[c,l]=z.useState(i===void 0),u=fe();return z.useEffect(()=>(i===void 0?l(!0):u.start(i,()=>l(!0)),u.clear),[u,i]),Ft(`span`,e,{state:{imageLoadingStatus:s},ref:t,props:o,stateAttributesMapping:_z,enabled:s!==`loaded`&&(i===void 0||c)})});function Cz({className:e,size:t=`default`,...n}){return(0,R.jsx)(vz,{"data-slot":`avatar`,"data-size":t,className:L(`group/avatar relative flex size-8 shrink-0 rounded-full select-none after:absolute after:inset-0 after:rounded-full after:border after:border-border after:mix-blend-darken data-[size=lg]:size-10 data-[size=sm]:size-6 dark:after:mix-blend-lighten`,e),...n})}function wz({className:e,...t}){return(0,R.jsx)(xz,{"data-slot":`avatar-image`,className:L(`aspect-square size-full rounded-full object-cover`,e),...t})}function Tz({className:e,...t}){return(0,R.jsx)(Sz,{"data-slot":`avatar-fallback`,className:L(`flex size-full items-center justify-center rounded-full bg-muted text-sm text-muted-foreground group-data-[size=sm]/avatar:text-xs`,e),...t})}function Ez(e,t){return e?.[0]?e[0].toUpperCase():t?.[0]?t[0].toUpperCase():`U`}function Dz({chatApiUrl:e,dashboardUrl:t=`https://manufact.com/cloud`,fallback:n=null,onUserResolved:r,compact:i=!1}){let{user:a,loaded:o,authorizing:s,authorize:c,logout:l,mode:u}=mz(e),d=(0,z.useRef)(void 0);if((0,z.useEffect)(()=>{if(!o)return;let e=a?.id??null;d.current!==e&&(d.current=e,r?.(a))},[o,a,r]),!o)return null;if(!a)return(0,R.jsxs)(R.Fragment,{children:[n,(0,R.jsx)(Gt,{variant:`ghost`,size:`sm`,className:L(`shrink-0 rounded-full text-[13px]`,i?`px-2.5 text-xs`:`px-4`),disabled:s,onClick:()=>{c().catch(e=>oI.error(e instanceof Error?e.message:`Authorization failed`))},children:s?`Authorizing…`:`Sign in`})]});let f=Ez(a.name,a.email),p=a.name??a.email??`User`;return(0,R.jsxs)(Ya,{children:[(0,R.jsx)(Xa,{render:(0,R.jsx)(Gt,{variant:`ghost`,className:`relative h-8 w-8 shrink-0 rounded-full p-0 mr-2`,"aria-label":`User menu`,children:(0,R.jsxs)(Cz,{className:`h-8 w-8 border border-zinc-300 dark:border-zinc-600`,children:[(0,R.jsx)(wz,{src:a.image??``,alt:p}),(0,R.jsx)(Tz,{className:`text-sm`,children:f})]})}),nativeButton:!0}),(0,R.jsxs)(Za,{className:`w-56`,align:`end`,forceMount:!0,children:[(0,R.jsx)(Qa,{className:`font-normal`,children:(0,R.jsxs)(`div`,{className:`flex flex-col space-y-1`,children:[(0,R.jsx)(`p`,{className:`text-sm font-medium leading-none truncate`,children:p}),a.email&&a.email!==p&&(0,R.jsx)(`p`,{className:`text-xs leading-none text-muted-foreground truncate`,children:a.email})]})}),(0,R.jsx)(no,{}),(0,R.jsx)($a,{render:(0,R.jsxs)(`a`,{href:t,target:`_blank`,rel:`noopener noreferrer`,children:[(0,R.jsx)(li,{className:`mr-2 h-4 w-4`}),`Go to dashboard`]})}),(0,R.jsx)(no,{}),(0,R.jsxs)($a,{onClick:()=>{l().catch(()=>oI.error(`Sign out failed`))},children:[(0,R.jsx)(hi,{className:`mr-2 h-4 w-4`}),u===`session`?`Sign out of Manufact`:`Disconnect Inspector`]})]})]})}function Oz({count:e,isActive:t,size:n=`md`,overlay:r=!1}){return e<=0?null:(0,R.jsx)(`span`,{className:L(t?`dark:bg-black`:`dark:bg-zinc-700`,`shrink-0 bg-zinc-200 text-zinc-700 dark:text-zinc-300 rounded-full font-medium`,r&&`absolute -bottom-1 -right-1.5 z-10 flex h-3.5 min-w-3.5 items-center justify-center border border-background px-0.5 text-[9px] leading-none`,!r&&`ml-1`,!r&&n===`sm`&&`text-[10px] px-1.5 py-0.5`,!r&&n===`md`&&`text-xs px-2 py-0.5`),children:e})}var kz=`flex h-10 items-center gap-2`;function Az({serverConfig:e,additionalItems:t=[],showClients:n={cursor:!0,vsCode:!0,vsCodeInsiders:!0,claudeDesktop:!0,claudeCode:!0,geminiCli:!0,codexCli:!0},className:r=``,onSuccess:i,onError:a,trigger:o}){let[s,c]=(0,z.useState)(!1),[l,u]=(0,z.useState)(null),[d,f]=(0,z.useState)(!1),{url:p,name:m,headers:h}=e,g=e=>{try{PT(new Fo({client:e})).catch(()=>{})}catch{}},_=()=>{g(`cursor`);try{let e=NL(p,m,h);window.location.href=e,i?.(`Cursor`)}catch(e){console.error(`Failed to generate Cursor deep link:`,e),a?.(e)}},v=()=>{g(`vscode`);try{let e=PL(p,m,h);window.location.href=e,i?.(`VS Code`)}catch(e){console.error(`Failed to generate VS Code deep link:`,e),a?.(e)}},y=()=>{g(`vscode-insiders`);try{let e=FL(p,m,h);window.location.href=e,i?.(`VS Code Insiders`)}catch(e){console.error(`Failed to generate VS Code Insiders deep link:`,e),a?.(e)}},b=()=>{g(`claude-desktop`);try{LL(p,m,h),i?.(`Claude Desktop`)}catch(e){console.error(`Failed to download .mcpb file:`,e),a?.(e)}},x=()=>{g(`claude-code`),u(`claude-code`),c(!0)},S=()=>{g(`gemini-cli`),u(`gemini-cli`),c(!0)},C=()=>{g(`codex-cli`),u(`codex-cli`),c(!0)},w=async e=>{try{await lM(e),f(!0),setTimeout(()=>f(!1),2e3)}catch(e){console.error(`Failed to copy:`,e),a?.(e)}},T=()=>{if(l===`claude-code`){let{command:e,envVars:t}=RL(p,m,h),n=VL(t);return(0,R.jsxs)(R.Fragment,{children:[(0,R.jsxs)(dL,{children:[(0,R.jsx)(hL,{children:`Add to Claude Code`}),(0,R.jsx)(gL,{children:`Execute the following command in your shell to add this server to Claude Code.`})]}),(0,R.jsxs)(fL,{className:`space-y-4`,children:[(0,R.jsxs)(`div`,{children:[(0,R.jsx)(`h5`,{className:`font-semibold text-sm mb-2`,children:`Instructions`}),(0,R.jsxs)(`ol`,{className:`space-y-2 text-xs text-muted-foreground`,children:[(0,R.jsxs)(`li`,{className:`flex gap-2`,children:[(0,R.jsx)(`span`,{className:`font-semibold text-foreground`,children:`1.`}),(0,R.jsx)(`span`,{children:`Ensure the Claude Code executable is available in your path`})]}),(0,R.jsxs)(`li`,{className:`flex gap-2`,children:[(0,R.jsx)(`span`,{className:`font-semibold text-foreground`,children:`2.`}),(0,R.jsx)(`span`,{children:`Execute the following snippet in your shell:`})]})]})]}),(0,R.jsxs)(`div`,{className:`relative`,children:[(0,R.jsx)(`div`,{className:`absolute top-2 right-2 z-10`,children:(0,R.jsx)(Gt,{variant:`ghost`,size:`sm`,className:`h-7 px-2 bg-background hover:bg-accent border border-border`,onClick:()=>w(e),children:d?(0,R.jsx)(Fr,{className:`size-3.5 text-green-600`}):(0,R.jsx)(Wr,{className:`size-3.5`})})}),(0,R.jsx)(`pre`,{className:`bg-muted p-3 pr-14 rounded-md text-xs overflow-x-auto`,children:(0,R.jsx)(`code`,{children:e})})]}),n&&(0,R.jsxs)(`div`,{children:[(0,R.jsx)(`h5`,{className:`font-semibold text-sm mb-2`,children:`Environment Variables`}),(0,R.jsx)(`p`,{className:`text-xs text-muted-foreground mb-2`,children:`After installation, set these environment variables in your shell:`}),(0,R.jsx)(`pre`,{className:`bg-muted p-3 rounded-md text-xs overflow-x-auto`,children:(0,R.jsx)(`code`,{children:n})})]}),(0,R.jsxs)(`p`,{className:`text-xs text-muted-foreground`,children:[`The MCP configuration supports environment variable expansion using `,(0,R.jsx)(`code`,{className:`text-foreground`,children:"${VAR}"}),` `,`syntax.`]})]})]})}if(l===`gemini-cli`){let{command:e,envVars:t}=zL(p,m,h),n=VL(t);return(0,R.jsxs)(R.Fragment,{children:[(0,R.jsxs)(dL,{children:[(0,R.jsx)(hL,{children:`Add to Gemini CLI`}),(0,R.jsx)(gL,{children:`Execute the following command in your shell to add this server to Gemini CLI.`})]}),(0,R.jsxs)(fL,{className:`space-y-4`,children:[(0,R.jsxs)(`div`,{children:[(0,R.jsx)(`h5`,{className:`font-semibold text-sm mb-2`,children:`Instructions`}),(0,R.jsxs)(`ol`,{className:`space-y-2 text-xs text-muted-foreground`,children:[(0,R.jsxs)(`li`,{className:`flex gap-2`,children:[(0,R.jsx)(`span`,{className:`font-semibold text-foreground`,children:`1.`}),(0,R.jsx)(`span`,{children:`Ensure the Gemini CLI executable is available in your path`})]}),n&&(0,R.jsxs)(`li`,{className:`flex gap-2`,children:[(0,R.jsx)(`span`,{className:`font-semibold text-foreground`,children:`2.`}),(0,R.jsx)(`span`,{children:`Set these environment variables in your shell before running the command:`})]}),(0,R.jsxs)(`li`,{className:`flex gap-2`,children:[(0,R.jsx)(`span`,{className:`font-semibold text-foreground`,children:n?`3.`:`2.`}),(0,R.jsx)(`span`,{children:`Execute the following snippet in your shell:`})]})]})]}),n&&(0,R.jsxs)(`div`,{children:[(0,R.jsx)(`h5`,{className:`font-semibold text-sm mb-2`,children:`Environment Variables`}),(0,R.jsx)(`pre`,{className:`bg-muted p-3 rounded-md text-xs overflow-x-auto`,children:(0,R.jsx)(`code`,{children:n})})]}),(0,R.jsxs)(`div`,{className:`relative`,children:[(0,R.jsx)(`div`,{className:`absolute top-2 right-2 z-10`,children:(0,R.jsx)(Gt,{variant:`ghost`,size:`sm`,className:`h-7 px-2 bg-background hover:bg-accent border border-border`,onClick:()=>w(e),children:d?(0,R.jsx)(Fr,{className:`size-3.5 text-green-600`}):(0,R.jsx)(Wr,{className:`size-3.5`})})}),(0,R.jsx)(`pre`,{className:`bg-muted p-3 pr-14 rounded-md text-xs overflow-x-auto`,children:(0,R.jsx)(`code`,{children:e})})]}),(0,R.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Restart Gemini CLI to load the new configuration.`})]})]})}if(l===`codex-cli`){let{config:e,envVars:t}=BL(p,m,h);return(0,R.jsxs)(R.Fragment,{children:[(0,R.jsxs)(dL,{children:[(0,R.jsx)(hL,{children:`Add to Codex CLI`}),(0,R.jsxs)(gL,{children:[`Add this configuration to your`,` `,(0,R.jsx)(`code`,{className:`text-foreground`,children:`~/.codex/config.toml`}),` `,`file.`]})]}),(0,R.jsxs)(fL,{className:`space-y-4`,children:[(0,R.jsxs)(`div`,{children:[(0,R.jsx)(`h5`,{className:`font-semibold text-sm mb-2`,children:`Instructions`}),(0,R.jsxs)(`p`,{className:`text-xs text-muted-foreground`,children:[`Add this configuration to your`,` `,(0,R.jsx)(`code`,{className:`text-foreground`,children:`~/.codex/config.toml`}),`:`]})]}),(0,R.jsxs)(`div`,{className:`relative`,children:[(0,R.jsx)(`div`,{className:`absolute top-2 right-2 z-10`,children:(0,R.jsx)(Gt,{variant:`ghost`,size:`sm`,className:`h-7 px-2 bg-background hover:bg-accent border border-border`,onClick:()=>w(e),children:d?(0,R.jsx)(Fr,{className:`size-3.5 text-green-600`}):(0,R.jsx)(Wr,{className:`size-3.5`})})}),(0,R.jsx)(`pre`,{className:`bg-muted p-3 pr-14 rounded-md text-xs overflow-x-auto`,children:(0,R.jsx)(`code`,{children:e})})]}),t.length>0&&(0,R.jsx)(`div`,{children:(0,R.jsxs)(`p`,{className:`text-xs text-muted-foreground`,children:[`(optional) If you would rather use variables from your system's environment, replace the`,` `,(0,R.jsx)(`code`,{className:`text-foreground`,children:`http_headers`}),` key with the `,(0,R.jsx)(`code`,{className:`text-foreground`,children:`env_http_headers`}),` `,`key as shown in the commented section above.`]})}),(0,R.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Restart Codex CLI to load the new configuration.`})]})]})}return null},E=(0,R.jsxs)(Gt,{variant:`ghost`,className:`bg-zinc-200 dark:bg-zinc-800 hover:bg-zinc-300 dark:hover:bg-zinc-700 rounded-full transition-colors px-3 flex items-center justify-center ${r}`,children:[(0,R.jsxs)(`span`,{className:`xl:hidden hidden sm:flex items-center gap-1`,children:[(0,R.jsx)(Ai,{className:`size-3`}),`Client`]}),(0,R.jsxs)(`span`,{className:`hidden xl:flex items-center gap-1`,children:[`Add to Client`,(0,R.jsx)(Ir,{className:`size-3`})]})]}),ee=o?typeof o==`function`?o({isOpen:!1,onClick:()=>{}}):o:E;return(0,R.jsxs)(R.Fragment,{children:[(0,R.jsxs)(Ya,{children:[(0,R.jsx)(Xa,{render:(0,z.isValidElement)(ee)?ee:E,nativeButton:!0}),(0,R.jsxs)(Za,{align:`end`,className:`w-auto min-w-[300px]`,children:[t.map(e=>(0,R.jsxs)($a,{onClick:async()=>{await e.onClick()},className:kz,children:[e.icon,(0,R.jsx)(`span`,{className:`min-w-0 max-w-full whitespace-nowrap`,children:e.label})]},e.id)),t.length>0&&(0,R.jsx)(no,{}),n.cursor&&(0,R.jsxs)($a,{onClick:_,className:kz,children:[(0,R.jsx)(`img`,{src:`https://cdn.simpleicons.org/cursor`,alt:`Cursor`,className:`h-4 w-4`}),(0,R.jsx)(`span`,{className:`min-w-0 max-w-full whitespace-nowrap`,children:`Cursor`})]}),n.claudeCode&&(0,R.jsxs)($a,{onClick:x,className:kz,children:[(0,R.jsx)(`img`,{src:`https://cdn.simpleicons.org/claude`,alt:`Claude`,className:`h-4 w-4`}),(0,R.jsx)(`span`,{className:`min-w-0 max-w-full whitespace-nowrap`,children:`Claude Code`})]}),n.claudeDesktop&&(0,R.jsxs)($a,{onClick:b,className:kz,children:[(0,R.jsx)(`img`,{src:`https://cdn.simpleicons.org/claude`,alt:`Claude`,className:`h-4 w-4`}),(0,R.jsx)(`span`,{className:`min-w-0 max-w-full whitespace-nowrap`,children:`Claude Desktop`})]}),n.vsCode&&(0,R.jsxs)($a,{onClick:v,className:kz,children:[(0,R.jsx)(UL,{className:`h-4 w-4 text-blue-500`}),(0,R.jsx)(`span`,{className:`min-w-0 max-w-full whitespace-nowrap`,children:`VS Code`})]}),n.vsCodeInsiders&&(0,R.jsxs)($a,{onClick:y,className:kz,children:[(0,R.jsx)(UL,{className:`h-4 w-4 text-teal-400`}),(0,R.jsx)(`span`,{className:`min-w-0 max-w-full whitespace-nowrap`,children:`VS Code Insiders`})]}),n.geminiCli&&(0,R.jsxs)($a,{onClick:S,className:kz,children:[(0,R.jsx)(`img`,{src:`https://cdn.simpleicons.org/googlegemini`,alt:`Gemini`,className:`h-4 w-4`}),(0,R.jsx)(`span`,{className:`min-w-0 max-w-full whitespace-nowrap`,children:`Gemini CLI`})]}),n.codexCli&&(0,R.jsxs)($a,{onClick:C,className:kz,children:[(0,R.jsx)(`img`,{src:`https://inspector-cdn.mcp-use.com/providers/openai.png`,alt:`Codex`,className:`h-4 w-4`}),(0,R.jsx)(`span`,{className:`min-w-0 max-w-full whitespace-nowrap`,children:`Codex CLI`})]})]})]}),(0,R.jsx)(cL,{open:s,onOpenChange:c,children:(0,R.jsx)(uL,{scrollable:!0,className:`max-w-3xl max-h-[80vh]`,children:T()})})]})}function jz({className:e,state:t=`collapsed`,to:n=`/`,showLabel:r=t===`expanded`,labelParts:i=`full`,pinSymbolInIconColumn:a=!1,size:o}){let[s,c]=(0,z.useState)(!1),l=1.5,u=.2/l,d=.8999999999999999/l,f=r&&(t===`expanded`||i===`inspector`),p=o??(a?20:t===`expanded`?40:20),m=(0,R.jsx)(`div`,{className:`relative`,children:(0,R.jsxs)(Pe.svg,{viewBox:`0 0 500 500`,initial:`rest`,animate:s?`hover`:`rest`,className:`text-foreground`,style:{width:p,height:p},children:[(0,R.jsxs)(Pe.g,{variants:{rest:{opacity:1},hover:{opacity:[1,0,0,1],transition:{duration:l,times:[0,u,d,1],ease:`easeInOut`}}},fill:`currentColor`,fillRule:`nonzero`,stroke:`currentColor`,strokeWidth:4,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,R.jsx)(`path`,{d:`M105.933 0C164.437 0.000116002 211.865 47.607 211.865 106.333C211.865 131.829 210.493 158.403 221.068 181.602L228.975 198.947C243.584 230.997 269.265 256.7 301.303 271.336L316.155 278.121C340.142 289.079 367.694 287.335 394.066 287.335C452.571 287.335 499.999 334.942 499.999 393.668C499.999 452.394 452.571 500.001 394.066 500.001C335.562 500.001 288.134 452.394 288.134 393.668C288.134 368.974 289.24 343.275 278.992 320.807L270.586 302.38C255.948 270.29 230.214 244.565 198.118 229.939L180.164 221.758C157.282 211.331 131.078 212.666 105.933 212.666C47.4278 212.666 4.86252e-05 165.059 0 106.333C0 47.607 47.4278 0 105.933 0Z`}),(0,R.jsx)(`circle`,{cx:`100.426`,cy:`399.575`,r:`100.426`}),(0,R.jsx)(`path`,{d:`M500 100.426C500 155.889 455.037 200.851 399.574 200.851C344.11 200.851 299.148 155.889 299.148 100.426C299.148 44.962 344.11 0 399.574 0C455.037 0 500 44.962 500 100.426Z`})]}),(0,R.jsxs)(`g`,{fill:`none`,stroke:`currentColor`,strokeWidth:4,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,R.jsx)(Mz,{d:`M105.933 0C164.437 0.000116002 211.865 47.607 211.865 106.333C211.865 131.829 210.493 158.403 221.068 181.602L228.975 198.947C243.584 230.997 269.265 256.7 301.303 271.336L316.155 278.121C340.142 289.079 367.694 287.335 394.066 287.335C452.571 287.335 499.999 334.942 499.999 393.668C499.999 452.394 452.571 500.001 394.066 500.001C335.562 500.001 288.134 452.394 288.134 393.668C288.134 368.974 289.24 343.275 278.992 320.807L270.586 302.38C255.948 270.29 230.214 244.565 198.118 229.939L180.164 221.758C157.282 211.331 131.078 212.666 105.933 212.666C47.4278 212.666 4.86252e-05 165.059 0 106.333C0 47.607 47.4278 0 105.933 0Z`,times:{T0:0,T1:u,T2:d,T3:1},total:l}),(0,R.jsx)(Nz,{cx:100.426,cy:399.575,r:100.426,times:{T0:0,T1:u,T2:d,T3:1},total:l}),(0,R.jsx)(Mz,{d:`M500 100.426C500 155.889 455.037 200.851 399.574 200.851C344.11 200.851 299.148 155.889 299.148 100.426C299.148 44.962 344.11 0 399.574 0C455.037 0 500 44.962 500 100.426Z`,times:{T0:0,T1:u,T2:d,T3:1},total:l})]})]})}),h=r?(0,R.jsx)(`span`,{className:L(`font-ubuntu flex items-center gap-2 whitespace-nowrap`,a?L(`pl-(--sidebar-nav-text-pl-absolute)`,f?`relative opacity-100 blur-0`:`pointer-events-none absolute left-0 top-1/2 w-0 -translate-y-1/2 overflow-hidden opacity-0 blur-[3px]`):i===`inspector`?`mr-0`:`mr-3`),children:i===`full`?(0,R.jsxs)(R.Fragment,{children:[(0,R.jsx)(`span`,{className:`text-xl font-bold leading-none text-foreground [text-box:trim-both_cap_alphabetic]`,children:`mcp-use`}),(0,R.jsx)(`span`,{className:`text-lg font-sans font-light leading-none tracking-wide text-muted-foreground [text-box:trim-both_cap_alphabetic]`,children:`Inspector`})]}):(0,R.jsx)(`span`,{className:`text-base font-medium leading-none text-foreground [text-box:trim-both_cap_alphabetic]`,children:`Inspector`})}):null,g=a?(0,R.jsxs)(`div`,{className:L(`relative flex shrink-0 items-center`,f?`min-w-(--sidebar-width-icon)`:`w-(--sidebar-width-icon)`),children:[(0,R.jsx)(`div`,{className:`pointer-events-none absolute inset-y-0 left-0 flex w-(--sidebar-width-icon) items-center justify-center`,children:(0,R.jsx)(`div`,{className:`pointer-events-auto`,children:m})}),h]}):i===`inspector`?(0,R.jsxs)(`span`,{className:`flex items-center gap-2.5`,children:[m,h]}):(0,R.jsxs)(R.Fragment,{children:[m,h]});return(0,R.jsx)(DF,{to:n,className:L(`flex items-center transition-opacity`,!a&&i!==`inspector`&&`-my-3`,e),onMouseEnter:()=>c(!0),onMouseLeave:()=>c(!1),children:g})}function Mz({d:e,times:t,total:n}){let{T0:r,T1:i,T2:a,T3:o}=t;return(0,R.jsx)(Pe.path,{d:e,variants:{rest:{pathLength:0,opacity:0},hover:{pathLength:[0,0,1,1],opacity:[0,0,1,1],transition:{duration:n,times:[r,i,a,o],ease:`easeInOut`}}}})}function Nz({cx:e,cy:t,r:n,times:r,total:i}){let{T0:a,T1:o,T2:s,T3:c}=r;return(0,R.jsx)(Pe.circle,{cx:e,cy:t,r:n,variants:{rest:{pathLength:0,opacity:0},hover:{pathLength:[0,0,1,1],opacity:[0,0,1,1],transition:{duration:i,times:[a,o,s,c],ease:`easeInOut`}}}})}var Pz=(0,z.createContext)(void 0);function Fz(){let e=(0,z.use)(Pz);if(e===void 0)throw Error(`useTheme must be used within a ThemeProvider`);return e}function Iz({children:e,defaultTheme:t=`system`,storageKey:n=`theme`,forcedTheme:r}){let[i,a]=(0,z.useState)(r||t),[o,s]=(0,z.useState)(!1),c=()=>typeof window>`u`?`light`:window.matchMedia(`(prefers-color-scheme: dark)`).matches?`dark`:`light`,l=i===`system`?c():i,u=e=>{let t=document.documentElement,i=e===`system`?c():e;t.classList.remove(`light`,`dark`),t.classList.add(i),r||localStorage.setItem(n,e)};return(0,z.useEffect)(()=>{s(!0);let e=localStorage.getItem(n),i=r||e||t;a(i),u(i)},[t,n,r]),(0,z.useEffect)(()=>{if(i!==`system`)return;let e=window.matchMedia(`(prefers-color-scheme: dark)`),t=()=>{u(`system`)};return e.addEventListener(`change`,t),()=>e.removeEventListener(`change`,t)},[i]),(0,z.useEffect)(()=>{o&&u(i)},[i,o]),(0,R.jsx)(Pz,{value:{theme:i,setTheme:e=>{if(r){console.warn(`[ThemeProvider] Theme is forced via URL parameter, ignoring setTheme call`);return}a(e)},resolvedTheme:l},children:e})}function Lz({ref:e,shimmerColor:t,shimmerSize:n=`0.05em`,shimmerDuration:r=`3s`,borderRadius:i=`100px`,background:a,className:o,children:s,...c}){let{theme:l}=Fz();return(0,R.jsxs)(`button`,{style:{"--spread":`90deg`,"--shimmer-color":t||(l===`dark`?`#000000`:`#ffffff`),"--radius":i,"--speed":r,"--cut":n,"--bg":a||(l===`dark`?`rgba(255, 255, 255, 1)`:`rgba(0, 0, 0, 1)`)},className:L(`group relative z-0 flex cursor-pointer items-center justify-center overflow-hidden [border-radius:var(--radius)] border px-6 py-3 whitespace-nowrap [background:var(--bg)]`,`transform-gpu transition-transform duration-300 ease-in-out active:translate-y-px`,`dark:text-white text-black dark:border-white/10 border-black/10`,o),ref:e,...c,children:[(0,R.jsx)(`div`,{className:L(`-z-30 blur-[2px]`,`@container-[size] absolute inset-0 overflow-visible`),children:(0,R.jsx)(`div`,{className:`animate-shimmer-slide absolute inset-0 aspect-[1] h-[100cqh] rounded-none mask-none`,children:(0,R.jsx)(`div`,{className:`animate-spin-around absolute -inset-full w-auto [translate:0_0] rotate-0 [background:conic-gradient(from_calc(270deg-(var(--spread)*0.5)),transparent_0,var(--shimmer-color)_var(--spread),transparent_var(--spread))]`})})}),s,(0,R.jsx)(`div`,{className:L(`absolute inset-0 size-full`,`rounded-2xl px-4 py-1.5 text-sm font-medium`,`transform-gpu transition-all duration-300 ease-in-out`,`dark:shadow-[inset_0_-8px_10px_#0000001f] dark:group-hover:shadow-[inset_0_-6px_10px_#0000003f] dark:group-active:shadow-[inset_0_-10px_10px_#0000003f] shadow-[inset_0_-8px_10px_#ffffff1f] group-hover:shadow-[inset_0_-6px_10px_#ffffff3f] group-active:shadow-[inset_0_-10px_10px_#ffffff3f]`)}),(0,R.jsx)(`div`,{className:L(`absolute [inset:var(--cut)] -z-20 [border-radius:var(--radius)] bg-black dark:bg-white`)})]})}Lz.displayName=`ShimmerButton`;function Rz(e){switch(e){case`ready`:return`bg-emerald-600 animate-status-pulse`;case`failed`:return`bg-rose-600 animate-status-pulse-red`;default:return`bg-yellow-500 animate-status-pulse-yellow`}}function zz(e){switch(e){case`ready`:return`Connected`;case`failed`:return`Failed`;default:return e}}function Bz({status:e,className:t}){return(0,R.jsxs)(et,{children:[(0,R.jsx)(we,{render:(0,R.jsx)(`div`,{className:L(`w-2 h-2 rounded-full shrink-0`,Rz(e),t)}),nativeButton:!1}),(0,R.jsx)(lt,{children:(0,R.jsx)(`p`,{children:zz(e)})})]})}var Vz=`h-6 px-2 text-xs bg-yellow-500/20 border-0 dark:bg-yellow-400/10 text-yellow-800 dark:text-yellow-500 shrink-0`;function Hz(e){try{sessionStorage.setItem(SI,JSON.stringify({url:e.url,name:e.name||`Auto-connected Server`,transportType:e.transportType||`http`,connectionMode:`auto`}))}catch{}}function Uz({server:e,className:t}){let{state:n,authUrl:r,authenticate:i}=e;return n!==`pending_auth`&&n!==`authenticating`?null:n===`authenticating`?(0,R.jsxs)(Gt,{size:`sm`,variant:`outline`,disabled:!0,className:L(Vz,t),children:[(0,R.jsx)(fi,{className:`h-3 w-3 animate-spin mr-1`}),`Authenticating`]}):i?(0,R.jsx)(Gt,{"data-testid":`server-header-authenticate`,size:`sm`,variant:`outline`,className:L(Vz,t),onClick:t=>{t.stopPropagation(),Hz(e),i()},children:`Authenticate`}):r?(0,R.jsx)(Gt,{size:`sm`,variant:`outline`,className:L(Vz,t),render:(0,R.jsx)(`a`,{href:r,"data-testid":`server-header-authenticate`,onClick:t=>{t.stopPropagation(),Hz(e)}}),nativeButton:!1,children:`Authenticate`}):null}function Wz({connections:e,selectedServer:t,onServerSelect:n,mobileMode:r=!1,variant:i=`default`,compactHeader:a=!1}){let o=sP(),s=t=>{e.some(e=>e.id===t)&&n(t)},c=(0,R.jsxs)(Za,{className:`w-[calc(100vw-2rem)] sm:w-[300px]`,align:`start`,children:[(0,R.jsx)(Qa,{className:`cursor-pointer hover:bg-zinc-100 dark:hover:bg-zinc-800`,onClick:()=>o(`/`),children:`MCP Servers`}),(0,R.jsx)(no,{}),e.length===0?(0,R.jsx)(`div`,{className:`px-2 py-4 text-sm text-muted-foreground dark:text-zinc-400 text-center`,children:`No servers connected. Go to the dashboard to add one.`}):e.map(e=>(0,R.jsxs)($a,{onClick:()=>s(e.id),className:`flex items-center gap-3`,children:[(0,R.jsx)(xL,{server:e,size:`sm`}),(0,R.jsxs)(`div`,{className:`flex items-center gap-2 flex-1`,children:[(0,R.jsx)(`div`,{className:`font-medium`,children:bM(e)}),(0,R.jsx)(Bz,{status:e.state})]})]},e.id)),(0,R.jsx)(no,{}),(0,R.jsx)($a,{onClick:()=>o(`/`),children:(0,R.jsx)(`span`,{className:`text-blue-600 dark:text-blue-400`,children:`+ Add new server`})})]});return r?(0,R.jsx)(`div`,{className:`flex items-center gap-2`,children:(0,R.jsx)(`div`,{className:`relative`,children:(0,R.jsxs)(Ya,{children:[(0,R.jsx)(Xa,{render:(0,R.jsxs)(Gt,{variant:`ghost`,className:`h-11 px-2 bg-black dark:bg-white text-white dark:text-black border-black dark:border-white hover:bg-gray-800 dark:hover:bg-zinc-100 hover:border-gray-800 dark:hover:border-zinc-200 flex items-center gap-1.5`,children:[t?(0,R.jsx)(xL,{server:t,size:`md`}):(0,R.jsx)(Fi,{className:`h-5 w-5`}),(0,R.jsx)(Ir,{className:`h-4 w-4`})]}),nativeButton:!0}),c]})})}):i===`header`?(0,R.jsx)(`div`,{className:`flex min-w-0 items-center gap-2`,children:(0,R.jsxs)(Ya,{children:[(0,R.jsx)(Xa,{render:(0,R.jsxs)(`button`,{type:`button`,className:`inline-flex max-w-full min-w-0 items-center gap-1.5 border-0 bg-transparent p-0 cursor-pointer text-foreground transition-opacity hover:opacity-80`,children:[t&&(0,R.jsx)(xL,{server:t,size:`sm`,className:`!size-5 shrink-0`}),(0,R.jsx)(`span`,{className:`truncate text-sm`,children:t?bM(t):`Select server`}),t&&(0,R.jsxs)(R.Fragment,{children:[(0,R.jsx)(Bz,{status:t.state}),!a&&(0,R.jsx)(Uz,{server:t})]}),(0,R.jsx)(Ir,{className:`size-3.5 shrink-0 text-muted-foreground`})]}),nativeButton:!0}),c]})}):(0,R.jsx)(`div`,{className:`flex items-center gap-2`,children:(0,R.jsx)(`div`,{className:`relative`,children:(0,R.jsxs)(Ya,{children:[(0,R.jsx)(Xa,{render:(0,R.jsxs)(Lz,{className:L(`min-w-0 sm:min-w-[200px] p-0 px-1 text-sm h-11 justify-start text-white dark:text-black border-black dark:border-white hover:bg-gray-800 dark:hover:bg-zinc-100 hover:border-gray-800 dark:hover:border-zinc-200`,!t&&`pl-4`),children:[t&&(0,R.jsx)(xL,{server:t,size:`md`,className:`mr-2`}),(0,R.jsxs)(`div`,{className:`flex items-center gap-2 flex-1`,children:[(0,R.jsx)(`span`,{className:`truncate lg:max-w-[120px] xl:max-w-none`,children:t?bM(t):`Select server to inspect`}),t&&(0,R.jsx)(`div`,{className:`flex items-center gap-2`,children:t.error&&t.state!==`ready`?(0,R.jsxs)(et,{children:[(0,R.jsx)(we,{render:(0,R.jsx)(`button`,{onClick:e=>{e.stopPropagation()},className:`w-2 h-2 rounded-full bg-rose-500 animate-status-pulse-red hover:bg-rose-600 transition-colors`,title:`Click to copy error message`,"aria-label":`Copy error message to clipboard`}),nativeButton:!0}),(0,R.jsx)(lt,{children:(0,R.jsx)(`p`,{className:`max-w-xs`,children:t.error})})]}):(0,R.jsx)(`div`,{className:`w-2 h-2 rounded-full ${t.state===`ready`?`bg-emerald-600 animate-status-pulse`:t.state===`failed`?`bg-rose-600 animate-status-pulse-red`:`bg-yellow-500 animate-status-pulse-yellow`}`})})]})]}),nativeButton:!0}),c]})})})}function Gz(e){if(!e)return null;try{let t=new URL(e);if(t.protocol===`https:`)return t.origin}catch{}return null}function Kz(e,t){return e===`tools`?t.tools.length:e===`prompts`?t.prompts.length:e===`resources`?t.resources.length:e===`sampling`?t.pendingSamplingRequests?.length||0:e===`elicitation`?t.pendingElicitationRequests?.length||0:e===`notifications`?t.unreadNotificationCount:0}function qz(e,t,n){return n&&t>0&&[`sampling`,`elicitation`,`notifications`].includes(e)}var Jz=[{id:`server-metadata`,label:`Server Metadata`,icon:si},{id:`separator`},{id:`chat`,label:`Chat`,icon:vi,alwaysExpanded:!0},{id:`separator`},{id:`tools`,label:`Tools`,icon:Yi},{id:`prompts`,label:`Prompts`,icon:yi},{id:`resources`,label:`Resources`,icon:$r},{id:`sampling`,label:`Sampling`,icon:ti},{id:`elicitation`,label:`Elicitation`,icon:zi},{id:`notifications`,label:`Notifications`,icon:Mr},{id:`separator`},{id:`connection-settings`,label:`Connection Settings`,icon:Ii}],Yz=z.createContext(void 0);function Xz(e){let t=z.useContext(Yz);if(t===void 0&&!e)throw Error(Vt(47));return t}function Zz(){return{...ft(),disabled:!1,modal:!1,focusManagerModal:!1,instantType:void 0,openMethod:null,openChangeReason:null,titleElementId:void 0,descriptionElementId:void 0,stickIfOpen:!0,nested:!1,openOnHover:!1,closeDelay:0,hasViewport:!1}}var Qz={...De,disabled:St(e=>e.disabled),instantType:St(e=>e.instantType),openMethod:St(e=>e.openMethod),openChangeReason:St(e=>e.openChangeReason),modal:St(e=>e.modal),focusManagerModal:St(e=>e.focusManagerModal),stickIfOpen:St(e=>e.stickIfOpen),titleElementId:St(e=>e.titleElementId),descriptionElementId:St(e=>e.descriptionElementId),openOnHover:St(e=>e.openOnHover),closeDelay:St(e=>e.closeDelay),hasViewport:St(e=>e.hasViewport)},$z=class e extends Tt{constructor(e,t,n=!1){let r={...Zz(),...e},i=new at;r.open&&e?.mounted===void 0&&(r.mounted=!0),r.floatingRootContext=We(i,t,n),super(r,{popupRef:z.createRef(),backdropRef:z.createRef(),internalBackdropRef:z.createRef(),onOpenChange:void 0,onOpenChangeComplete:void 0,triggerFocusTargetRef:z.createRef(),beforeContentFocusGuardRef:z.createRef(),stickIfOpenTimeout:new xt,triggerElements:i},Qz)}setOpen=(e,t)=>{let n=t.reason===o,r=t.reason===`trigger-press`&&t.event.detail===0,i=!e&&(t.reason===`escape-key`||t.reason==null),a=je(t),s=this.select(`activeTriggerId`);if(!e&&t.reason===`close-press`&&t.trigger==null&&s!=null&&(t.trigger=this.context.triggerElements.getById(s)??this.select(`activeTriggerElement`)??void 0),this.context.onOpenChange?.(e,t),t.isCanceled)return;this.state.floatingRootContext.dispatchOpenChange(e,t);let c=()=>{let n={open:e,openChangeReason:t.reason};_t(n,e,t.trigger,a()),this.update(n)};n?(this.set(`stickIfOpen`,!0),this.context.stickIfOpenTimeout.start(500,()=>{this.set(`stickIfOpen`,!1)}),br.flushSync(c)):c(),r||i?this.set(`instantType`,r?`click`:`dismiss`):t.reason===`focus-out`?this.set(`instantType`,`focus`):this.set(`instantType`,void 0)};static useStore(t,n){let{store:r,internalStore:i}=Le(t,(t,r)=>new e(n,t,r));return z.useEffect(()=>i?.disposeEffect(),[i]),r}disposeEffect=()=>this.context.stickIfOpenTimeout.disposeEffect()};function eB({props:e}){let{children:t,open:n,defaultOpen:r=!1,onOpenChange:i,onOpenChangeComplete:a,modal:o=!1,handle:s,triggerId:c,defaultTriggerId:l=null}=e,u=$z.useStore(s?.store,{modal:o,open:r,openProp:n,activeTriggerId:l,triggerIdProp:c});Fe(u,n,r,l),u.useControlledProp(`openProp`,n),u.useControlledProp(`triggerIdProp`,c);let d=u.useState(`open`),f=u.useState(`mounted`),p=u.useState(`payload`),m=Ke()!=null;u.useContextCallback(`onOpenChange`,i),u.useContextCallback(`onOpenChangeComplete`,a),Be(u,d),Me(u);let{forceUnmount:h}=ot(d,u,()=>{u.update({stickIfOpen:!0,openChangeReason:null})});u.useSyncedValues({modal:o,nested:m}),z.useEffect(()=>{d||u.context.stickIfOpenTimeout.clear()},[u,d]);let g=z.useCallback(()=>{u.setOpen(!1,te(_e))},[u]);z.useImperativeHandle(e.actionsRef,()=>({unmount:h,close:g}),[h,g]);let _=d||f,v=z.useMemo(()=>({store:u}),[u]);return(0,R.jsxs)(Yz.Provider,{value:v,children:[_&&(0,R.jsx)(nB,{store:u,modal:o}),typeof t==`function`?t({payload:p}):t]})}function tB(e){return Xz(!0)?(0,R.jsx)(eB,{props:e}):(0,R.jsx)(Ye,{children:(0,R.jsx)(eB,{props:e})})}function nB({store:e,modal:t}){let n=m(e.useState(`floatingRootContext`),{outsidePressEvent:{mouse:t===`trap-focus`?`sloppy`:`intentional`,touch:`sloppy`}});return $e(e,{activeTriggerProps:n.reference??Wt,inactiveTriggerProps:n.trigger??Wt,popupProps:z.useMemo(()=>zt(mt,n.floating),[n.floating])}),null}var rB=z.forwardRef(function(e,t){let{render:n,className:r,style:i,disabled:o=!1,nativeButton:s=!0,handle:c,payload:l,openOnHover:u=!1,delay:d=300,closeDelay:f=0,id:p,...m}=e,h=Xz(!0),g=c?.store??h?.store;if(!g)throw Error(Vt(74));let _=O(p),v=g.useState(`isTriggerActive`,_),y=g.useState(`floatingRootContext`),b=g.useState(`isOpenedByTrigger`,_),S=g.useState(`triggerPopupId`,_),C=z.useRef(null),{registerTrigger:w,isMountedByThisTrigger:T}=Ce(_,C,g,{payload:l,disabled:o,openOnHover:u,closeDelay:f}),E=g.useState(`openChangeReason`),ee=g.useState(`stickIfOpen`),D=g.useState(`openMethod`),te=g.useState(`focusManagerModal`),ne=a(y,{enabled:!o&&y!=null&&u&&(D!==`touch`||E!==`trigger-press`),mouseOnly:!0,move:!1,handleClose:se(),restMs:d,delay:{close:f},triggerElementRef:C,isActiveTrigger:v,isClosing:()=>g.select(`transitionStatus`)===`ending`}),re=Sn(y,{enabled:y!=null,stickIfOpen:ee}),ie=dn(()=>g.select(`open`),e=>{g.set(`openMethod`,e)}),k=g.useState(`triggerProps`,T),{getButtonProps:A,buttonRef:j}=Lt({disabled:o,native:s}),ae={open(e){return e&&E===`trigger-press`?Ue.open(e):Ee.open(e)}},{preFocusGuardRef:oe,handlePreFocusGuardFocus:ce,handleFocusTargetFocus:M}=xr(g,C),N=Ft(`button`,e,{state:{disabled:o,open:b},ref:[j,t,w,C],props:[re.reference,ne,k,ie,{[x]:``,id:_,"aria-haspopup":`dialog`,"aria-expanded":b,"aria-controls":S},m,A],stateAttributesMapping:ae});return T&&!te?(0,R.jsxs)(z.Fragment,{children:[(0,R.jsx)(ut,{ref:oe,onFocus:ce}),(0,R.jsx)(z.Fragment,{children:N},_),(0,R.jsx)(ut,{ref:g.context.triggerFocusTargetRef,onFocus:M})]}):(0,R.jsx)(z.Fragment,{children:N},_)}),iB=z.createContext(void 0);function aB(){let e=z.useContext(iB);if(e===void 0)throw Error(Vt(45));return e}var oB=z.forwardRef(function(e,t){let{keepMounted:n=!1,...r}=e,{store:i}=Xz();return i.useState(`mounted`)||n?(0,R.jsx)(iB.Provider,{value:n,children:(0,R.jsx)(oe,{ref:t,...r})}):null}),sB=z.createContext(void 0);function cB(){let e=z.useContext(sB);if(!e)throw Error(Vt(46));return e}var lB=z.forwardRef(function(e,t){let{render:n,className:r,style:i,anchor:a,positionMethod:o=`absolute`,side:s=`bottom`,align:l=`center`,sideOffset:u=0,alignOffset:d=0,collisionBoundary:f=`clipping-ancestors`,collisionPadding:m=5,arrowPadding:h=5,sticky:g=!1,disableAnchorTracking:_=!1,collisionAvoidance:v=N,...y}=e,{store:b}=Xz(),x=aB(),C=c(),w=b.useState(`floatingRootContext`),T=b.useState(`mounted`),E=b.useState(`open`),ee=b.useState(`openChangeReason`),D=b.useState(`activeTriggerElement`),te=b.useState(`modal`),ne=b.useState(`openMethod`),re=b.useState(`positionerElement`),O=b.useState(`instantType`),ie=b.useState(`transitionStatus`),k=b.useState(`hasViewport`),j=z.useRef(null),ae=p(re,!1,!1),oe=S({anchor:a,floatingRootContext:w,positionMethod:o,mounted:T,side:s,sideOffset:u,align:l,alignOffset:d,arrowPadding:h,collisionBoundary:f,collisionPadding:m,sticky:g,disableAnchorTracking:_,keepMounted:x,nodeId:C,collisionAvoidance:v,adaptiveOrigin:k?ye:void 0}),se=w.useState(`domReferenceElement`);Rt(()=>{let e=se,t=j.current;if(e&&(j.current=e),t&&e&&e!==t){b.set(`instantType`,void 0);let e=new AbortController;return ae(()=>{b.set(`instantType`,`trigger-change`)},e.signal),()=>{e.abort()}}},[se,ae,b]),an(E&&te===!0&&ee!==`trigger-hover`,ne===`touch`,re,D);let ce=z.useCallback(e=>{b.set(`positionerElement`,e)},[b]),M=st(e,{open:E,side:oe.side,align:oe.align,anchorHidden:oe.anchorHidden,instant:O},{styles:oe.positionerStyles,transitionStatus:ie,props:y,refs:[t,ce],hidden:!T,inert:!E});return(0,R.jsxs)(sB.Provider,{value:oe,children:[T&&te===!0&&ee!==`trigger-hover`&&(0,R.jsx)(wn,{ref:b.context.internalBackdropRef,inert:sn(!E),cutout:D}),(0,R.jsx)(A,{id:C,children:M})]})}),uB=z.createContext(void 0);function dB(){let[e,t]=z.useState(0),n=Pt(()=>(t(e=>e+1),()=>{t(e=>Math.max(0,e-1))}));return{context:z.useMemo(()=>({register:n}),[n]),hasClosePart:e>0}}function fB(e){let{value:t,children:n}=e;return(0,R.jsx)(uB.Provider,{value:t,children:n})}var pB={...dt,...it},mB=z.forwardRef(function(e,t){let{render:n,className:r,style:i,initialFocus:a,finalFocus:o,...s}=e,{store:c}=Xz(),l=cB(),u=Cn(!0)!=null,{context:d,hasClosePart:f}=dB(),p=c.useState(`open`),m=c.useState(`openMethod`),h=c.useState(`instantType`),_=c.useState(`transitionStatus`),v=c.useState(`popupProps`),y=c.useState(`titleElementId`),b=c.useState(`descriptionElementId`),x=c.useState(`modal`),S=c.useState(`mounted`),C=c.useState(`openChangeReason`),w=c.useState(`activeTriggerElement`),T=c.useState(`floatingRootContext`),E=T.useState(`floatingId`),ee=c.useState(`disabled`),D=c.useState(`openOnHover`),te=c.useState(`closeDelay`),ne=s.id??E;g({open:p,ref:c.context.popupRef,onComplete(){p&&c.context.onOpenChangeComplete?.(!0)}}),Ne(T,{enabled:D&&!ee,closeDelay:te});let re=a===void 0?Xe(c.context.popupRef):a,O=x!==!1&&f;c.useSyncedValue(`focusManagerModal`,O);let ie=z.useCallback(e=>{c.set(`popupElement`,e)},[c]),k=Ft(`div`,e,{state:{open:p,side:l.side,align:l.align,instant:h,transitionStatus:_},ref:[t,c.context.popupRef,ie],props:[v,{id:ne,role:`dialog`,...mt,"aria-labelledby":y,"aria-describedby":b,onKeyDown(e){u&&Qt.has(e.key)&&e.stopPropagation()}},xe(_),s],stateAttributesMapping:pB});return(0,R.jsx)(rn,{context:T,openInteractionType:m,modal:O,disabled:!S||C===`trigger-hover`,initialFocus:re,returnFocus:o,restoreFocus:`popup`,previousFocusableElement:Bt(w)?w:void 0,nextFocusableElement:c.context.triggerFocusTargetRef,beforeContentFocusGuardRef:c.context.beforeContentFocusGuardRef,children:(0,R.jsx)(fB,{value:d,children:k})})});function hB({...e}){return(0,R.jsx)(tB,{"data-slot":`popover`,...e})}function gB(e){return(0,R.jsx)(rB,{"data-slot":`popover-trigger`,...e})}function _B({className:e,align:t=`center`,alignOffset:n=0,side:r=`bottom`,sideOffset:i=4,...a}){return(0,R.jsx)(oB,{children:(0,R.jsx)(lB,{align:t,alignOffset:n,side:r,sideOffset:i,className:`isolate z-50`,children:(0,R.jsx)(mB,{"data-slot":`popover-content`,className:L(`z-50 flex w-72 origin-(--transform-origin) flex-col gap-4 rounded-md bg-popover p-4 text-sm text-popover-foreground shadow-md ring-1 ring-foreground/10 outline-hidden duration-100 data-[side=bottom]:slide-in-from-top-2 data-[side=inline-end]:slide-in-from-left-2 data-[side=inline-start]:slide-in-from-right-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95`,e),...a})})})}var vB={success:`border-emerald-700/20 bg-emerald-700/10 text-emerald-700 dark:border-emerald-400/30 dark:bg-emerald-400/10 dark:text-emerald-400`,failed:`border-red-500/20 bg-red-500/10 text-red-500 dark:border-red-400/30 dark:bg-red-400/10 dark:text-red-400`,warning:`border-amber-700/20 bg-amber-700/10 text-amber-700 dark:border-amber-400/30 dark:bg-amber-400/10 dark:text-amber-400`,loading:`border-purple-500/20 bg-purple-500/10 text-purple-500 dark:border-purple-400/30 dark:bg-purple-400/10 dark:text-purple-400 animate-spin`},yB=`size-4 shrink-0 rounded-full border p-0.5`;function bB({state:e,className:t}){let n=L(yB,vB[e],t);switch(e){case`success`:return(0,R.jsx)(Fr,{className:n,"aria-hidden":!0});case`failed`:return(0,R.jsx)(zr,{className:n,"aria-hidden":!0});case`warning`:return(0,R.jsx)(Ki,{className:n,"aria-hidden":!0});case`loading`:return(0,R.jsx)(fi,{className:n,"aria-hidden":!0});default:return null}}function xB(){return`text-emerald-700 dark:text-emerald-400`}function SB({onStop:e,showCopiedBanner:t=!1}){return(0,R.jsxs)(R.Fragment,{children:[t&&(0,R.jsxs)(`div`,{className:L(`flex items-center gap-2 text-sm -mt-1`,xB()),children:[(0,R.jsx)(bB,{state:`success`}),(0,R.jsx)(`span`,{children:`URL copied to clipboard`})]}),(0,R.jsxs)(`div`,{className:`flex items-center justify-between`,children:[(0,R.jsx)(`h4`,{className:`font-semibold text-sm`,children:`Tunnel URL`}),(0,R.jsxs)(`a`,{href:`https://manufact.com/docs/tunneling`,target:`_blank`,rel:`noopener noreferrer`,className:`flex items-center gap-1 text-xs text-muted-foreground hover:text-foreground transition-colors`,children:[`Docs`,(0,R.jsx)(Ar,{className:`size-3`})]})]}),(0,R.jsxs)(`div`,{children:[(0,R.jsx)(`h5`,{className:`font-semibold text-sm mb-2`,children:`Use in ChatGPT & Claude`}),(0,R.jsxs)(`ol`,{className:`space-y-2 text-xs text-muted-foreground`,children:[(0,R.jsxs)(`li`,{className:`flex gap-2`,children:[(0,R.jsx)(`span`,{className:`font-semibold text-foreground`,children:`1.`}),(0,R.jsxs)(`span`,{children:[`Enable`,` `,(0,R.jsx)(`a`,{href:`https://chatgpt.com/plugins#settings/Security`,target:`_blank`,rel:`noopener noreferrer`,className:`font-medium text-foreground underline underline-offset-2 hover:text-purple-600 dark:hover:text-purple-400`,children:`dev mode`}),` `,`from settings`]})]}),(0,R.jsxs)(`li`,{className:`flex gap-2`,children:[(0,R.jsx)(`span`,{className:`font-semibold text-foreground`,children:`2.`}),(0,R.jsxs)(`span`,{children:[(0,R.jsx)(`a`,{href:`https://chatgpt.com/plugins#settings/Connectors?create-connector=true&redirectAfter=%2Fplugins`,target:`_blank`,rel:`noopener noreferrer`,className:`font-medium text-foreground underline underline-offset-2 hover:text-purple-600 dark:hover:text-purple-400`,children:`Add a connector`}),` `,`in App & Connectors`]})]}),(0,R.jsxs)(`li`,{className:`flex gap-2`,children:[(0,R.jsx)(`span`,{className:`font-semibold text-foreground`,children:`3.`}),(0,R.jsx)(`span`,{children:`Use the tunnel URL in the input`})]})]})]}),(0,R.jsxs)(`button`,{type:`button`,onClick:()=>void e(),className:`flex items-center gap-1.5 text-xs text-red-600 dark:text-red-400 hover:text-red-700 dark:hover:text-red-300 transition-colors cursor-pointer`,children:[(0,R.jsx)(Vi,{className:`size-3 fill-current`}),`Stop Tunnel`]})]})}function CB(e){try{let t=new URL(e),n=t.pathname+t.search;return t.host+(n&&n!==`/`?n:``)}catch{return e}}function wB({copied:e,onCopy:t,className:n}){return(0,R.jsx)(`button`,{type:`button`,onClick:e=>{e.stopPropagation(),t()},"aria-label":e?`URL copied`:`Copy URL`,className:L(`shrink-0 cursor-pointer p-0.5 rounded-sm text-muted-foreground hover:text-foreground transition-opacity opacity-0 group-hover:opacity-100`,n),children:e?(0,R.jsx)(bB,{state:`success`,className:`size-3.5`}):(0,R.jsx)(Wr,{className:`size-3.5`})})}function TB({url:e,className:t,tunnelPopover:n}){let[r,i]=(0,z.useState)(!1),[a,o]=(0,z.useState)(!1);if(!e)return null;let s=CB(e),c=n?.mcpUrl??e,l=!!n,u=async()=>{try{await lM(c),i(!0),setTimeout(()=>i(!1),2e3)}catch{oI.error(`Failed to copy URL`)}};(0,z.useEffect)(()=>{if(!n?.autoCopyOnOpen){o(!1);return}o(!0),i(!0);let e=setTimeout(()=>i(!1),2e3);return()=>clearTimeout(e)},[n?.autoCopyOnOpen]);let d=(0,R.jsxs)(R.Fragment,{children:[l?(0,R.jsx)(Lr,{className:`size-3.5 shrink-0`}):(0,R.jsx)(ei,{className:`size-3.5 shrink-0`}),(0,R.jsx)(`span`,{className:`truncate max-w-[min(24rem,30vw)]`,children:s})]}),f=L(`flex items-center gap-1 min-w-0 truncate text-left text-sm cursor-pointer`,l?`text-purple-600 dark:text-purple-400`:`text-blue-500`);return(0,R.jsxs)(`div`,{className:L(`group flex items-center gap-1.5 min-w-0`,t),children:[l?(0,R.jsxs)(hB,{open:n.open,onOpenChange:n.onOpenChange,children:[(0,R.jsx)(gB,{render:(0,R.jsx)(`button`,{type:`button`,className:L(f,`hover:opacity-80`),children:d}),nativeButton:!0}),(0,R.jsx)(_B,{className:`w-[calc(100vw-2rem)] sm:w-96`,align:`start`,sideOffset:4,children:(0,R.jsx)(SB,{showCopiedBanner:a,onStop:async()=>{n.onOpenChange(!1),await n.onStop()}})})]}):(0,R.jsx)(`span`,{className:f,children:d}),(0,R.jsx)(wB,{copied:r,onCopy:()=>void u()})]})}function EB({devFromCli:e,isTunnelStarting:t,waitTicks:n,onStart:r}){if(t)return(0,R.jsxs)(`button`,{disabled:!0,className:`flex items-center gap-1 h-6 px-2 bg-violet-50 dark:bg-violet-950/40 border border-violet-200 dark:border-violet-800 rounded-full opacity-75 cursor-wait shrink-0`,children:[(0,R.jsx)(fi,{className:`size-3 text-violet-500 dark:text-violet-400 animate-spin`}),(0,R.jsxs)(`span`,{className:`text-xs font-medium text-violet-600 dark:text-violet-300 hidden lg:inline`,children:[`Start Tunnel `,(0,R.jsxs)(`span`,{className:`tabular-nums`,children:[n,`s`]})]})]});let i=e===!0,a=e===null;return(0,R.jsxs)(`button`,{type:`button`,onClick:()=>void r(),disabled:!i||a,title:e===!1?"Run `mcp-use dev` from your project to enable tunneling.":a?`Checking dev server…`:void 0,className:L(`flex items-center gap-1 h-6 px-2 border rounded-full transition-colors shrink-0`,i&&!a?`bg-violet-50 dark:bg-violet-950/40 border-violet-200 dark:border-violet-800 hover:bg-violet-100 dark:hover:bg-violet-900/50 cursor-pointer`:`bg-violet-50/60 dark:bg-violet-950/20 border-violet-200 dark:border-violet-800 cursor-not-allowed opacity-70`),children:[a?(0,R.jsx)(fi,{className:`size-3 text-violet-500 dark:text-violet-400 animate-spin`}):(0,R.jsx)(Lr,{className:`size-3 text-violet-500 dark:text-violet-400`}),(0,R.jsx)(`span`,{className:`text-xs font-medium text-violet-600 dark:text-violet-300 hidden lg:inline`,children:`Start Tunnel`})]})}function DB(){return typeof window>`u`?!1:window.__MCP_DEV_CLI__===!0}async function OB(){try{let e=await fetch(hM(`dev/info`));return e.ok?await e.json():null}catch{return null}}function kB({tunnelUrl:e,setTunnelUrl:t,isTunnelStarting:n,setIsTunnelStarting:r,onTunnelStarted:i}){let[a,o]=(0,z.useState)(null),[s,c]=(0,z.useState)(null),[l,u]=(0,z.useState)(0),d=(0,z.useCallback)((e,n)=>{let r=n?.syncTunnel??!1;if(o(!!e.fromCli),e.mcpUrl&&c(e.mcpUrl),!r)return;if(e.tunnelUrl){t(new URL(e.tunnelUrl).origin);return}let i=Gz(e.mcpUrl??null);if(i){t(i);return}t(null)},[t]);return(0,z.useEffect)(()=>{if(!n){u(20);return}u(20);let e=setInterval(()=>u(e=>e>0?e-1:0),1e3);return()=>clearInterval(e)},[n]),(0,z.useEffect)(()=>{let e=!1;if(!DB()){o(!1);return}return(async()=>{let t=await OB();e||(t?d(t,{syncTunnel:!0}):o(!1))})(),()=>{e=!0}},[d]),{devFromCli:a,mcpUrl:s,waitTicks:l,handleStartTunnel:(0,z.useCallback)(async()=>{if(a===!1){oI.error("Start Tunnel requires `mcp-use dev` from your project directory.");return}r(!0);let e=!1;try{let t=await fetch(hM(`dev/start-tunnel`),{method:`POST`});if(!t.ok){let e=await t.json().catch(()=>({}));oI.error(e.error||`Failed to start tunnel`);return}let n=await OB();if(n?.tunnelUrl||n?.mcpUrl){d(n,{syncTunnel:!0});let e=n.mcpUrl??(n.tunnelUrl?`${n.tunnelUrl.replace(/\/+$/,``)}/mcp`:null);e&&cM(e),i?.()}e=!0}catch{oI.error(`Failed to start tunnel`)}finally{r(!1)}try{PT(new jo({action:`start`,success:e})).catch(()=>{})}catch{}},[d,a,i,r]),handleStopTunnel:(0,z.useCallback)(async()=>{r(!0);let n=!1;try{let e=await fetch(hM(`dev/stop-tunnel`),{method:`POST`});if(!e.ok){let t=await e.json().catch(()=>({}));oI.error(t.error||`Failed to stop tunnel`);return}t(null),c(null),oI.success(`Tunnel stopped`),n=!0}catch{oI.error(`Failed to stop tunnel`)}finally{r(!1)}try{PT(new jo({action:`stop`,success:n,tunnelUrl:e})).catch(()=>{})}catch{}},[r,t,e])}}function AB(e){let t=window.matchMedia(`(min-width: 1024px)`);return t.addEventListener(`change`,e),()=>t.removeEventListener(`change`,e)}function jB(){return window.matchMedia(`(min-width: 1024px)`).matches}function MB(){return!0}function NB(){return(0,z.useSyncExternalStore)(AB,jB,MB)}function PB(e){let[t,n]=(0,z.useState)(!1),[r,i]=(0,z.useState)(!1),a=NB(),o=(0,z.useCallback)(()=>{n(!0),i(!0)},[]);return(0,z.useEffect)(()=>{e||(n(!1),i(!1))},[e]),(0,z.useEffect)(()=>{if(!e)return;let t=new URLSearchParams(window.location.search);if(!t.has(`openTunnelPopover`))return;n(!0),i(!0),t.delete(`openTunnelPopover`);let r=t.toString();window.history.replaceState({},``,`${window.location.pathname}${r?`?${r}`:``}`)},[e]),{open:t,onOpenChange:(0,z.useCallback)(e=>{n(e),e||i(!1)},[]),isLgUp:a,autoCopyOnOpen:r,openWithAutoCopy:o}}function FB({connections:e,selectedServer:t,activeTab:n,onServerSelect:r,onTabChange:i,embedded:a=!1,sidebarCollapsed:o=!1}){let{tunnelUrl:s,isTunnelStarting:c,setTunnelUrl:l,setIsTunnelStarting:u,embeddedConfig:d}=EL(),[f,p]=(0,z.useState)(!1),[m]=(0,z.useState)(!0),h=PB(s),g=kB({tunnelUrl:s,setTunnelUrl:l,isTunnelStarting:c,setIsTunnelStarting:u,onTunnelStarted:h.openWithAutoCopy});if(d.singleTab)return null;let _=d.visibleTabs?Jz.filter(e=>e.id===`separator`||d.visibleTabs.includes(e.id)):Jz,v=!!t,y=!!t&&(_M(t.url??``)||vM(t.url??``)||!!s),b=t?s?`${s.replace(/\/+$/,``)}${pM()}`:t.url??``:``,x=g.mcpUrl??(s?`${s.replace(/\/+$/,``)}${pM()}`:null),S=(e,n)=>{if(!t||!b)return null;let r=e===`desktop`?h.isLgUp:!h.isLgUp;return(0,R.jsxs)(`div`,{className:`flex items-center gap-1 min-w-0`,children:[(0,R.jsx)(TB,{url:b,className:n,tunnelPopover:s&&x&&r?{mcpUrl:x,onStop:g.handleStopTunnel,open:h.open,onOpenChange:h.onOpenChange,autoCopyOnOpen:h.autoCopyOnOpen}:void 0}),y&&!s&&(0,R.jsx)(EB,{devFromCli:g.devFromCli,isTunnelStarting:c,waitTicks:g.waitTicks,onStart:g.handleStartTunnel})]})},C=()=>a?null:(0,R.jsxs)(`div`,{className:`flex items-center gap-2 sm:gap-3 flex-shrink-0`,children:[t&&(0,R.jsx)(R.Fragment,{children:(0,R.jsx)(Az,{serverConfig:{url:b,name:bM(t),headers:MM(t),serverId:t.id},onSuccess:e=>oI.success(`Opening in ${e}...`),onError:e=>oI.error(`Failed: ${e.message}`),trigger:(0,R.jsxs)(Gt,{variant:`ghost`,className:`bg-zinc-200 dark:bg-zinc-800 hover:bg-zinc-300 dark:hover:bg-zinc-700 rounded-full transition-colors px-3 flex items-center justify-center`,"aria-label":`Add to Client`,children:[(0,R.jsxs)(`span`,{className:`xl:hidden hidden sm:flex items-center gap-1`,children:[(0,R.jsx)(Ai,{className:`size-3`}),`Client`]}),(0,R.jsxs)(`span`,{className:`hidden xl:flex items-center gap-1`,children:[`Add to Client`,(0,R.jsx)(Ir,{className:`size-3`})]})]})})}),(0,R.jsx)(`a`,{href:f?`https://manufact.com/cloud?ref=mcp-use-inspector`:`https://manufact.com/signup?ref=mcp-use-inspector`,target:`_blank`,rel:`noopener noreferrer`,onClick:()=>{try{PT(new Mo({referrer:`mcp-use-inspector`})).catch(()=>{})}catch{}},className:`inline-flex h-8 items-center justify-center rounded-full border border-blue-500/25 bg-blue-500/10 px-4 text-[13px] text-blue-500 outline-none cursor-pointer transition-colors hover:bg-blue-500/15 dark:border-blue-400/30 dark:bg-blue-400/10 dark:text-blue-400 dark:hover:bg-blue-400/15 focus-visible:ring-1 focus-visible:ring-ring`,children:(0,R.jsx)(`span`,{className:`[text-box:trim-both_cap_alphabetic]`,children:`Deploy`})}),w()]}),w=(e=!1)=>d.chatApiUrl?(0,R.jsx)(Dz,{chatApiUrl:d.chatApiUrl,onUserResolved:e=>p(!!e),compact:e}):null;return(0,R.jsxs)(`header`,{className:`w-full min-w-0 shrink-0 overflow-hidden`,children:[(0,R.jsxs)(`div`,{className:`hidden lg:flex h-(--header-height) items-center justify-between gap-3 px-4 md:pl-0 md:pr-6`,children:[(0,R.jsx)(`div`,{className:`flex items-center gap-3 min-w-0 flex-1`,children:!a&&(0,R.jsxs)(R.Fragment,{children:[(0,R.jsx)(`div`,{className:L(`hidden lg:block shrink-0`,v&&o&&`-mr-[calc(var(--sidebar-width-icon)/2-0.625rem)]`),children:(0,R.jsx)(jz,{pinSymbolInIconColumn:!0,showLabel:!v||!o,state:v&&o?`collapsed`:`expanded`})}),(0,R.jsx)(`span`,{className:`text-sm text-muted-foreground/60 shrink-0 [text-box:trim-both_cap_alphabetic]`,children:`/`}),(0,R.jsx)(Wz,{connections:e,selectedServer:t,onServerSelect:r,variant:`header`}),S(`desktop`)]})}),C()]}),(0,R.jsxs)(`div`,{className:`flex lg:hidden min-w-0 w-full flex-col overflow-hidden pt-(--mobile-chrome-gap)`,children:[(0,R.jsx)(`div`,{className:`flex min-h-0 items-center gap-2 pb-(--mobile-chrome-gap)`,children:!a&&(0,R.jsxs)(R.Fragment,{children:[(0,R.jsxs)(`div`,{className:`flex min-w-0 flex-1 items-center gap-2.5 overflow-hidden`,children:[(0,R.jsx)(jz,{state:`collapsed`,showLabel:!0,labelParts:`inspector`,className:`shrink-0`}),(0,R.jsx)(`span`,{className:`shrink-0 px-0.5 text-sm text-muted-foreground/60 [text-box:trim-both_cap_alphabetic]`,children:`/`}),(0,R.jsx)(`div`,{className:`min-w-0 flex-1`,children:(0,R.jsx)(Wz,{connections:e,selectedServer:t,onServerSelect:r,variant:`header`,compactHeader:!0})})]}),(0,R.jsx)(`div`,{className:`shrink-0`,children:w(!0)})]})}),t&&(0,R.jsx)(`div`,{className:`w-full min-w-0 pb-(--mobile-chrome-gap) lg:hidden`,children:(0,R.jsx)(uz,{value:n,onValueChange:e=>i(e),collapsed:m,className:`w-full`,children:(0,R.jsx)(dz,{className:`w-full gap-0 border-0 bg-transparent p-0 [&_[role=tablist]]:justify-between`,children:_.filter(e=>e.id!==`separator`).map(e=>{let r=Kz(e.id,t);return(0,R.jsx)(pz,{value:e.id,"data-testid":`tab-${e.id}`,icon:e.icon,iconOnly:!0,title:e.label,badge:r>0?(0,R.jsx)(Oz,{count:r,isActive:n===e.id,overlay:!0}):void 0,className:`size-9 shrink-0 rounded-full p-0`,children:(0,R.jsx)(`span`,{className:`sr-only`,children:e.label})},e.id)})})})})]})]})}function IB({collapsed:e,onToggle:t}){let n=e?`Expand sidebar`:`Collapse sidebar`;return(0,R.jsxs)(et,{children:[(0,R.jsx)(we,{render:(0,R.jsxs)(Gt,{type:`button`,variant:`ghost`,size:`icon-sm`,tabIndex:-1,"aria-label":n,onClick:t,className:L(`border-border absolute top-1/2 right-0 z-30 hidden size-7 min-h-7 min-w-7 -translate-y-1/2 translate-x-1/2 rounded-full border bg-background lg:flex`,`opacity-0 transition-opacity duration-200 group-hover/sidebar:opacity-100 focus-visible:opacity-100`),children:[(0,R.jsx)(wi,{className:`size-4`}),(0,R.jsx)(`span`,{className:`sr-only`,children:n})]}),nativeButton:!0}),(0,R.jsx)(lt,{side:`right`,children:n})]})}function LB({className:e}){return(0,R.jsxs)(`svg`,{xmlns:`http://www.w3.org/2000/svg`,width:`24`,height:`24`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentcolor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,className:e,children:[(0,R.jsx)(`path`,{d:`M15 22v-4a4.8 4.8 0 0 0-1-3.5c3 0 6-2 6-5.5.08-1.25-.27-2.48-1-3.5.28-1.15.28-2.35 0-3.5 0 0-1 0-3 1.5-2.64-.5-5.36-.5-8 0C6 2 5 2 5 2c-.3 1.15-.3 2.35 0 3.5A5.403 5.403 0 0 0 4 9c0 3.5 3 5.5 6 5.5-.39.49-.68 1.05-.85 1.65-.17.6-.22 1.23-.15 1.85v4`}),(0,R.jsx)(`path`,{d:`M9 18c-4.51 2-5-2-7-2`})]})}var RB=z.createContext(void 0);function zB(){let e=z.useContext(RB);if(e===void 0)throw Error(Vt(63));return e}var BB=function(e){return e.checked=`data-checked`,e.unchecked=`data-unchecked`,e.disabled=`data-disabled`,e.readonly=`data-readonly`,e.required=`data-required`,e.valid=`data-valid`,e.invalid=`data-invalid`,e.touched=`data-touched`,e.dirty=`data-dirty`,e.filled=`data-filled`,e.focused=`data-focused`,e}({}),VB={...Tn,checked(e){return e?{[BB.checked]:``}:{[BB.unchecked]:``}}};function HB(e,t,n,r=!0,i){let[a,o]=z.useState(),s=O(i?`${i}-label`:void 0),c=e??t??a;return Rt(()=>{let i=e||t||!r?void 0:UB(n.current,s);a!==i&&o(i)}),c}function UB(e,t){let n=WB(e);if(n)return!n.id&&t&&(n.id=t),n.id||void 0}function WB(e){if(!e)return;let t=e.parentElement;if(t&&t.tagName===`LABEL`)return t;let n=e.id;if(n){let t=e.nextElementSibling;if(t&&t.htmlFor===n)return t}let r=e.labels;return r&&r[0]}var GB=z.forwardRef(function(e,t){let{checked:n,className:r,defaultChecked:i,"aria-labelledby":a,form:o,id:s,inputRef:c,name:l,nativeButton:u=!1,onCheckedChange:d,readOnly:f=!1,required:p=!1,disabled:m=!1,render:h,uncheckedValue:g,value:_,style:v,...y}=e,{clearErrors:b}=An(),{state:x,setTouched:S,setDirty:C,validityData:w,setFilled:T,setFocused:E,validationMode:ee,disabled:D,name:ne,validation:re}=On(),{labelId:ie}=kn(),k=D||m,A=ne??l,j=z.useRef(null),ae=Kt(j,c,re.inputRef),oe=z.useRef(null),se=O(),ce=cn({id:s,implicit:!1,controlRef:oe}),M=u?void 0:ce,[N,le]=Yt({controlled:n,default:!!i,name:`Switch`,state:`checked`});En(oe,se,N,void 0,!k,l),Rt(()=>{j.current&&T(j.current.checked)},[j,T]),Dn(N,()=>{b(A),C(N!==w.initialValue),T(N),re.change(N)});let{getButtonProps:ue,buttonRef:de}=Lt({disabled:k,native:u}),fe=HB(a,ie,j,!u,M),pe={id:u?ce:se,role:`switch`,"aria-checked":N,"aria-readonly":f||void 0,"aria-required":p||void 0,"aria-labelledby":fe,onFocus(){k||E(!0)},onBlur(){let e=j.current;!e||k||(S(!0),E(!1),ee===`onBlur`&&re.commit(e.checked))},onClick(e){if(f||k)return;e.preventDefault();let t=j.current;t&&t.dispatchEvent(new(Mt(t)).PointerEvent(`click`,{bubbles:!0,shiftKey:e.shiftKey,ctrlKey:e.ctrlKey,altKey:e.altKey,metaKey:e.metaKey}))}},me=zt({checked:N,disabled:k,form:o,id:M,name:A,required:p,style:A?Te:He,tabIndex:-1,type:`checkbox`,"aria-hidden":!0,ref:ae,onChange(e){if(e.nativeEvent.defaultPrevented)return;if(f){e.preventDefault();return}let t=e.currentTarget.checked,n=te(be,e.nativeEvent);d?.(t,n),!n.isCanceled&&le(t)},onFocus(){oe.current?.focus()}},e=>re.getValidationProps(k,e),_===void 0?Wt:{value:_}),he=z.useMemo(()=>({...x,checked:N,disabled:k,readOnly:f,required:p}),[x,N,k,f,p]),ge=Ft(`span`,e,{state:he,ref:[t,oe,de],props:[pe,y,ue,e=>re.getValidationProps(k,e)],stateAttributesMapping:VB});return(0,R.jsxs)(RB.Provider,{value:he,children:[ge,!N&&A&&g!==void 0&&(0,R.jsx)(`input`,{type:`hidden`,form:o,name:A,value:g,disabled:k}),(0,R.jsx)(`input`,{...me,suppressHydrationWarning:!0})]})}),KB=z.forwardRef(function(e,t){let{render:n,className:r,style:i,...a}=e;return Ft(`span`,e,{state:zB(),ref:t,stateAttributesMapping:VB,props:a})}),qB=34,JB=20,YB=16,XB=2,ZB=4,QB=2;function $B(e){return`label`in e&&typeof e.label==`string`}var eV=(0,z.forwardRef)(({label:e,checked:t,onToggle:n,disabled:r=!1,thumbTransition:i,uncheckedTrackColor:a,uncheckedTrackColorHovered:o,className:s,...c},l)=>{let u=(0,z.useId)(),d=(0,z.useRef)(!1),[f,p]=(0,z.useState)(!1),[m,h]=(0,z.useState)(!1),g=(0,z.useRef)(!1),_=(0,z.useRef)(!1),v=(0,z.useRef)(null),y=ia(t?16:XB);(0,z.useEffect)(()=>{d.current=!0},[]);let b=m?20:f?18:YB,x=m?YB-ZB:YB,S=m?4:XB,C=b-YB,w=t?16-C:XB;(0,z.useEffect)(()=>{g.current||(d.current?ka(y,w,i??pt.moderate):y.set(w))},[w,y,i]);let T=(0,z.useCallback)(e=>{r||e.pointerType===`mouse`&&e.button!==0||(h(!0),g.current=!1,_.current=!1,v.current={clientX:e.clientX,originX:y.get()},e.currentTarget.setPointerCapture(e.pointerId))},[r,y]),E=(0,z.useCallback)(e=>{if(!v.current)return;let t=e.clientX-v.current.clientX;if(!g.current){if(Math.abs(t)<QB)return;g.current=!0}let n=XB,r=qB-XB-20,i=v.current.originX+t;y.set(Math.max(n,Math.min(r,i)))},[y]),ee=(0,z.useCallback)(e=>{v.current&&=(h(!1),g.current&&(_.current=!0,g.current=!1,e&&(y.get()>14/2===t?ka(y,t?16:XB,i??pt.moderate):n()),requestAnimationFrame(()=>{_.current=!1})),null)},[t,n,y,i]);return(0,R.jsxs)(`div`,{ref:l,className:L(`relative z-10 flex items-center gap-2.5 px-3 py-2 cursor-pointer select-none touch-none`,r&&`opacity-50 pointer-events-none`,s),onPointerEnter:e=>{e.pointerType===`mouse`&&p(!0)},onPointerLeave:()=>p(!1),onPointerDown:T,onPointerMove:E,onPointerUp:()=>ee(!0),onPointerCancel:()=>{v.current&&=(h(!1),g.current&&(g.current=!1,ka(y,t?16:XB,i??pt.moderate)),null)},onClick:()=>{r||_.current||n()},...c,children:[(0,R.jsx)(GB,{checked:t,"aria-labelledby":u,onCheckedChange:()=>{_.current||n()},disabled:r,tabIndex:0,className:L(`relative shrink-0 rounded-full outline-none cursor-pointer`,`transition-colors duration-80`,`focus-visible:ring-1 focus-visible:ring-[color:var(--focus-ring,#6B97FF)] focus-visible:ring-offset-2 focus-visible:ring-offset-background`),style:{width:qB,height:JB,backgroundColor:t?f?`color-mix(in oklab, var(--primary) 88%, black)`:`var(--primary)`:f?o??`color-mix(in oklab, var(--accent), rgb(var(--overlay)) 10%)`:a??`var(--accent)`},onClick:e=>e.stopPropagation(),children:(0,R.jsx)(KB,{render:e=>{let{style:t,onDrag:n,onDragStart:r,onDragEnd:a,onAnimationStart:o,onAnimationEnd:s,onAnimationIteration:c,...l}=e;return(0,R.jsx)(Pe.span,{...l,className:`absolute top-0 left-0 block rounded-full bg-white shadow-sm`,initial:!1,style:{...t,x:y},animate:{y:S,width:b,height:x},transition:d.current?i??pt.moderate:{duration:0}})}})}),(0,R.jsx)(`span`,{id:u,className:L(`text-[13px] [text-box:trim-both_cap_alphabetic] transition-[color] duration-80`,t?`text-foreground`:`text-muted-foreground`),children:e})]})});eV.displayName=`FluidSwitch`;var tV=(0,z.forwardRef)(({checked:e,defaultChecked:t=!1,onCheckedChange:n,disabled:r=!1,className:i},a)=>{let[o,s]=(0,z.useState)(t),c=e??o;return(0,R.jsx)(GB,{ref:a,checked:c,disabled:r,onCheckedChange:t=>{e===void 0&&s(t),n?.(t)},className:L(`peer inline-flex h-5 w-9 shrink-0 cursor-pointer items-center rounded-full border-2 border-transparent shadow-xs transition-colors duration-80`,`focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-[color:var(--focus-ring,#6B97FF)]`,`disabled:cursor-not-allowed disabled:opacity-50`,`data-checked:bg-primary data-unchecked:bg-input`,i),children:(0,R.jsx)(KB,{className:L(`pointer-events-none block size-4 rounded-full bg-background shadow-sm ring-0 transition-transform duration-80`,`data-checked:translate-x-4 data-unchecked:translate-x-0`)})})});tV.displayName=`ShadcnSwitch`;var nV=(0,z.forwardRef)((e,t)=>$B(e)?(0,R.jsx)(eV,{ref:t,...e}):(0,R.jsx)(tV,{ref:t,...e}));nV.displayName=`Switch`;function rV({className:e}){return(0,R.jsx)(`svg`,{viewBox:`0 -28.5 256 256`,className:e,fill:`currentColor`,xmlns:`http://www.w3.org/2000/svg`,"aria-hidden":!0,children:(0,R.jsx)(`path`,{d:`M216.856339,16.5966031 C200.285002,8.84328665 182.566144,3.2084988 164.041564,0 C161.766523,4.11318106 159.108624,9.64549908 157.276099,14.0464379 C137.583995,11.0849896 118.072967,11.0849896 98.7430163,14.0464379 C96.9108417,9.64549908 94.1925838,4.11318106 91.8971895,0 C73.3526068,3.2084988 55.6133949,8.86399117 39.0420583,16.6376612 C5.61752293,67.146514 -3.4433191,116.400813 1.08711069,164.955721 C23.2560196,181.510915 44.7403634,191.567697 65.8621325,198.148576 C71.0772151,190.971126 75.7283628,183.341335 79.7352139,175.300261 C72.104019,172.400575 64.7949724,168.822202 57.8887866,164.667963 C59.7209612,163.310589 61.5131304,161.891452 63.2445898,160.431257 C105.36741,180.133187 151.134928,180.133187 192.754523,160.431257 C194.506336,161.891452 196.298154,163.310589 198.110326,164.667963 C191.183787,168.842556 183.854737,172.420929 176.223542,175.320965 C180.230393,183.341335 184.861538,190.991831 190.096624,198.16893 C211.238746,191.588051 232.743023,181.531619 254.911949,164.955721 C260.227747,108.668201 245.831087,59.8662432 216.856339,16.5966031 Z M85.4738752,135.09489 C72.8290281,135.09489 62.4592217,123.290155 62.4592217,108.914901 C62.4592217,94.5396472 72.607595,82.7145587 85.4738752,82.7145587 C98.3405064,82.7145587 108.709962,94.5189427 108.488529,108.914901 C108.508531,123.290155 98.3405064,135.09489 85.4738752,135.09489 Z M170.525237,135.09489 C157.88039,135.09489 147.510584,123.290155 147.510584,108.914901 C147.510584,94.5396472 157.658606,82.7145587 170.525237,82.7145587 C183.391518,82.7145587 193.761324,94.5189427 193.539891,108.914901 C193.539891,123.290155 183.391518,135.09489 170.525237,135.09489 Z`,fillRule:`nonzero`})})}var iV=`flex size-8 items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-sidebar-accent hover:text-sidebar-accent-foreground`,aV=`color-mix(in oklab, var(--sidebar-foreground) 22%, var(--sidebar))`,oV=`color-mix(in oklab, var(--sidebar-foreground) 30%, var(--sidebar))`,sV=`data-unchecked:!bg-zinc-300 dark:data-unchecked:!bg-zinc-600`;function cV({collapsed:e,rpcLoggerOpen:t,onRpcLoggerOpenChange:n,onCommandPaletteOpen:r}){let{embeddedConfig:i}=EL(),{theme:a,setTheme:o}=Fz(),{user:s}=mz(i.chatApiUrl),c=s?`https://manufact.com/cloud?ref=mcp-use-inspector`:`https://manufact.com/signup?ref=mcp-use-inspector`,l=()=>{try{PT(new Mo({referrer:`mcp-use-inspector-sidebar`})).catch(()=>{})}catch{}};return(0,R.jsx)(`footer`,{className:`mt-auto shrink-0`,children:(0,R.jsxs)(`div`,{className:L(`flex flex-col`,e?`items-center gap-2 px-2 py-3`:`gap-3 px-(--sidebar-nav-inset-x) py-4`),children:[e?(0,R.jsxs)(et,{children:[(0,R.jsx)(we,{render:(0,R.jsx)(`div`,{className:`flex size-8 items-center justify-center`,children:(0,R.jsx)(nV,{checked:t,onCheckedChange:n,"aria-label":`RPC Panel`,className:L(`scale-75`,sV)})}),nativeButton:!1}),(0,R.jsx)(lt,{side:`right`,children:`RPC Panel`})]}):(0,R.jsx)(nV,{label:`RPC Panel`,checked:t,onToggle:()=>n(!t),uncheckedTrackColor:aV,uncheckedTrackColorHovered:oV,className:`w-full flex-row-reverse justify-between`}),e?(0,R.jsxs)(et,{children:[(0,R.jsx)(we,{render:(0,R.jsx)(`a`,{href:c,target:`_blank`,rel:`noopener noreferrer`,onClick:l,className:iV,"aria-label":`Deploying your MCP Server? Try manufact.com`,children:(0,R.jsx)(Ar,{className:`size-4`})}),nativeButton:!1}),(0,R.jsx)(lt,{side:`right`,children:`Deploying your MCP Server? Try manufact.com`})]}):(0,R.jsxs)(`a`,{href:c,target:`_blank`,rel:`noopener noreferrer`,onClick:l,className:`relative block rounded-xl border border-sidebar-border bg-white p-3 transition-colors hover:bg-sidebar-accent/50 dark:bg-black`,children:[(0,R.jsx)(Ar,{className:`absolute top-2.5 right-2.5 size-3.5 text-muted-foreground`,"aria-hidden":!0}),(0,R.jsx)(`p`,{className:`pr-5 text-xs leading-snug text-muted-foreground`,children:`Deploying your MCP Server?`}),(0,R.jsxs)(`p`,{className:`mt-0.5 text-xs leading-snug`,children:[`Try`,` `,(0,R.jsx)(`span`,{className:`font-medium underline underline-offset-2`,children:`manufact.com`})]})]}),(0,R.jsxs)(`div`,{className:L(`flex`,e?`flex-col items-center gap-1`:`flex-row items-center gap-2`),children:[(0,R.jsxs)(et,{children:[(0,R.jsx)(we,{render:(0,R.jsx)(`a`,{href:`https://github.com/mcp-use/mcp-use`,target:`_blank`,rel:`noopener noreferrer`,className:iV,"aria-label":`GitHub`,children:(0,R.jsx)(LB,{className:`size-4`})}),nativeButton:!1}),(0,R.jsx)(lt,{side:e?`right`:`top`,children:`GitHub`})]}),(0,R.jsxs)(et,{children:[(0,R.jsx)(we,{render:(0,R.jsx)(`a`,{href:`https://discord.gg/XkNkSkMz3V`,target:`_blank`,rel:`noopener noreferrer`,className:iV,"aria-label":`Discord`,children:(0,R.jsx)(rV,{className:`size-4`})}),nativeButton:!1}),(0,R.jsx)(lt,{side:e?`right`:`top`,children:`Discord`})]}),(0,R.jsxs)(Ya,{children:[(0,R.jsxs)(et,{children:[(0,R.jsx)(we,{render:(0,R.jsx)(Xa,{render:(0,R.jsx)(`button`,{type:`button`,className:iV,"aria-label":`Theme`,children:a===`light`?(0,R.jsx)(Ui,{className:`size-4`}):a===`dark`?(0,R.jsx)(xi,{className:`size-4`}):(0,R.jsx)(bi,{className:`size-4`})}),nativeButton:!0}),nativeButton:!0}),(0,R.jsx)(lt,{side:e?`right`:`top`,children:`Theme`})]}),(0,R.jsx)(Za,{side:e?`right`:`top`,align:e?`start`:`center`,className:`w-40`,children:(0,R.jsxs)(eo,{value:a,onValueChange:e=>o(e),children:[(0,R.jsxs)(to,{value:`light`,children:[(0,R.jsx)(Ui,{className:`size-4 mr-2`}),`Light`]}),(0,R.jsxs)(to,{value:`dark`,children:[(0,R.jsx)(xi,{className:`size-4 mr-2`}),`Dark`]}),(0,R.jsxs)(to,{value:`system`,children:[(0,R.jsx)(bi,{className:`size-4 mr-2`}),`System`]})]})})]}),(0,R.jsxs)(et,{children:[(0,R.jsx)(we,{render:(0,R.jsx)(`button`,{type:`button`,onClick:r,className:iV,"aria-label":`Command Palette`,"data-testid":`command-palette-trigger-button`,children:(0,R.jsx)(Ur,{className:`size-4`})}),nativeButton:!0}),(0,R.jsxs)(lt,{side:e?`right`:`top`,children:[`Command Palette (`,`⌘`,`K)`]})]})]})]})})}function lV(e,t){let n=0,r=0,i=e;for(;i&&i!==t;)n+=i.offsetTop,r+=i.offsetLeft,i=i.offsetParent;if(i!==t){let n=t.getBoundingClientRect(),r=e.getBoundingClientRect();return{top:r.top-n.top,left:r.left-n.left,width:r.width,height:r.height}}return{top:n,left:r,width:e.offsetWidth,height:e.offsetHeight}}function uV(e,t){let n=Object.keys(e),r=Object.keys(t);if(n.length!==r.length)return!1;for(let r of n){let n=e[r],i=t[r];if(!n||!i||n.top!==i.top||n.left!==i.left||n.width!==i.width||n.height!==i.height)return!1}return!0}function dV(e,t={}){let{axis:n=`y`}=t,r=(0,z.useRef)(new Map),[i,a]=(0,z.useState)(null),[o,s]=(0,z.useState)({}),c=(0,z.useRef)({}),l=(0,z.useRef)(0),u=(0,z.useRef)(null),d=(0,z.useRef)(null),f=(0,z.useCallback)(()=>{let t=e.current;if(!t)return;let n={};r.current.forEach((e,r)=>{n[r]=lV(e,t)}),!uV(c.current,n)&&(c.current=n,s(n))},[e]),p=(0,z.useCallback)((e,t)=>{t?r.current.set(e,t):r.current.delete(e),d.current!==null&&cancelAnimationFrame(d.current),d.current=requestAnimationFrame(()=>{d.current=null,f()})},[f]),m=(0,z.useCallback)(t=>{let r=t.clientX,i=t.clientY;u.current!==null&&cancelAnimationFrame(u.current),u.current=requestAnimationFrame(()=>{u.current=null;let t=e.current;if(!t)return;let o=t.getBoundingClientRect(),s=n===`x`?r:i,l=null,d=1/0,f=null,p=c.current,m=n===`x`?t.scrollLeft:t.scrollTop,h=n===`x`?t.clientLeft:t.clientTop,g=n===`x`?o.left:o.top,_=n===`x`?t.offsetWidth:t.offsetHeight,v=n===`x`?o.width:o.height,y=_>0?v/_:1;for(let[e,t]of Object.entries(p)){let r=g+(h+(n===`x`?t.left:t.top)-m)*y,i=(n===`x`?t.width:t.height)*y,a=r+i;s>=r&&s<=a&&(f=e);let o=r+i/2,c=Math.abs(s-o);c<d&&(d=c,l=e)}a(f??l)})},[n,e]),h=(0,z.useCallback)(()=>{l.current+=1},[]),g=(0,z.useCallback)(()=>{u.current!==null&&(cancelAnimationFrame(u.current),u.current=null),a(null)},[]);return(0,z.useEffect)(()=>{let t=e.current;if(!t||typeof ResizeObserver>`u`)return;let n=new ResizeObserver(()=>{d.current!==null&&cancelAnimationFrame(d.current),d.current=requestAnimationFrame(()=>{d.current=null,f()})});return n.observe(t),()=>n.disconnect()},[e,f]),(0,z.useEffect)(()=>()=>{u.current!==null&&cancelAnimationFrame(u.current),d.current!==null&&cancelAnimationFrame(d.current)},[]),{activeKey:i,itemRects:o,sessionRef:l,handlers:{onMouseMove:m,onMouseEnter:h,onMouseLeave:g},registerItem:p,measureItems:f}}function fV(e){if(!e)return{left:0,right:0};let t=getComputedStyle(e),n=Number.parseFloat(t.getPropertyValue(`--sidebar-nav-pill-bleed`))||0,r=Number.parseFloat(t.getPropertyValue(`--sidebar-nav-scrollbar-width`))||0,i=Number.parseFloat(t.getPropertyValue(`--sidebar-nav-pill-outer-trim-right`))||0;return{left:n,right:n+r+i}}function pV(e,t){return{...e,left:e.left-t.left,width:e.width+t.left+t.right}}var mV=(0,z.createContext)(null);function hV(){let e=(0,z.useContext)(mV),t=(0,z.useRef)(e?.registerItem);t.current=e?.registerItem;let n=(0,z.useRef)(new Map);return(0,z.useCallback)(e=>{let r=n.current,i=r.get(e);return i||(i=n=>t.current?.(e,n),r.set(e,i)),i},[])}function gV({children:e,isActiveKey:t,className:n}){let r=(0,z.useRef)(null),{activeKey:i,itemRects:a,sessionRef:o,handlers:s,registerItem:c,measureItems:l}=dV(r),u=(0,z.useMemo)(()=>({registerItem:c}),[c]),d=Object.keys(a).find(e=>t(e))??null;(0,z.useLayoutEffect)(()=>{l()},[l,e,d]);let f=fV(r.current),p=i?a[i]:null,m=d?a[d]:null,h=p?pV(p,f):null,g=m?pV(m,f):null,_=i!==null&&i!==d;return(0,R.jsx)(mV.Provider,{value:u,children:(0,R.jsxs)(`div`,{ref:r,onMouseEnter:s.onMouseEnter,onMouseMove:s.onMouseMove,onMouseLeave:s.onMouseLeave,className:L(`relative isolate`,n),children:[(0,R.jsx)(en,{initial:!1,children:g&&d?(0,R.jsx)(Pe.div,{"aria-hidden":!0,className:`pointer-events-none absolute -z-20 rounded-full bg-sidebar-accent`,initial:{opacity:0,top:g.top,left:g.left,width:g.width,height:g.height},animate:{opacity:_?.85:1,top:g.top,left:g.left,width:g.width,height:g.height},exit:{opacity:0,transition:pt.fast.exit},transition:{opacity:{duration:.08},top:{duration:0},left:{duration:0},width:{duration:0},height:{duration:0}}},d):null}),(0,R.jsx)(en,{children:h?(0,R.jsx)(Pe.div,{"aria-hidden":!0,className:`pointer-events-none absolute -z-10 rounded-full bg-sidebar-accent`,initial:{opacity:0,top:g?.top??h.top,left:g?.left??h.left,width:g?.width??h.width,height:g?.height??h.height},animate:{opacity:1,top:h.top,left:h.left,width:h.width,height:h.height},exit:{opacity:0,transition:pt.fast.exit},transition:{...pt.fast,opacity:{duration:.08}}},o.current):null}),e]})})}var _V=L(`pointer-events-auto absolute right-(--sidebar-nav-trailing-right) top-1/2 z-10 flex h-(--sidebar-nav-trailing-size) min-w-(--sidebar-nav-trailing-size) -translate-y-1/2 items-center justify-center`,L(`transition-[opacity,filter] duration-200 ease-out`,`opacity-100 blur-0`,`group-data-[collapsible=icon]:opacity-0 group-data-[collapsible=icon]:blur-[3px] group-data-[collapsible=icon]:pointer-events-none`,`group-data-[collapsed=true]:opacity-0 group-data-[collapsed=true]:blur-[3px] group-data-[collapsed=true]:pointer-events-none`)),vV=L(`truncate transition-[opacity,filter,margin] duration-200 ease-out`,`group-data-[collapsible=icon]:hidden`,`group-data-[collapsed=true]:hidden`),yV=L(`peer/menu-button flex cursor-pointer items-center gap-2 overflow-hidden rounded-full py-2 text-left text-sm outline-hidden ring-sidebar-ring hover:text-sidebar-accent-foreground group-hover/menu-item:text-sidebar-accent-foreground focus-visible:ring-2 active:text-sidebar-accent-foreground disabled:pointer-events-none disabled:opacity-50 aria-disabled:pointer-events-none aria-disabled:opacity-50 data-active:font-medium data-active:text-sidebar-accent-foreground [&>span:last-child]:truncate [&>svg]:size-4 [&>svg]:shrink-0`,`transition-[width,max-width,height,padding,border-radius] duration-200 ease-out`,`h-8 text-sm`);function bV({count:e}){return(0,R.jsx)(`span`,{className:L(`inline-flex h-5 shrink-0 items-center justify-center border border-border bg-zinc-200 px-1 text-[10px] font-medium tabular-nums leading-none text-foreground dark:bg-zinc-700`,String(e).length>=3?`min-w-5 rounded-md`:`size-5 min-w-5 rounded-full`),children:e})}function xV(e){return e.id!==`separator`}function SV({activeTab:e,onTabChange:t,selectedServer:n,visibleTabs:r,collapsed:i}){let a=hV();return(0,R.jsx)(`ul`,{className:`flex w-full min-w-0 flex-col gap-1 px-(--sidebar-nav-inset-x) group`,"data-collapsed":i,"aria-label":`Inspector tabs`,children:(r?Jz.filter(e=>xV(e)&&r.includes(e.id)):Jz.filter(xV)).map((r,o)=>{let s=Kz(r.id,n),c=qz(r.id,s,i),l=r.icon,u=e===r.id,d=s>0||c,f=(0,R.jsxs)(`button`,{ref:a(r.id),type:`button`,"data-testid":`tab-${r.id}`,"data-active":u?!0:void 0,onClick:()=>t(r.id),className:L(yV,i?`size-8! w-8! max-w-8! shrink-0 justify-center gap-0 p-0!`:`w-full max-w-full sidebar-nav-pill-bleed-x pl-(--sidebar-nav-icon-pl-bleed) pr-(--sidebar-nav-pr-bleed)`,d&&!i&&`pr-[calc(var(--sidebar-nav-trailing-right)+var(--sidebar-nav-trailing-size))]`),children:[(0,R.jsx)(l,{className:`size-4 shrink-0`}),(0,R.jsx)(`span`,{className:vV,children:r.label})]});return(0,R.jsxs)(`li`,{className:L(`group/menu-item relative`,o===0&&`mt-4`),children:[i?(0,R.jsxs)(et,{delayDuration:0,children:[(0,R.jsx)(we,{render:f,nativeButton:!0}),(0,R.jsx)(lt,{side:`right`,children:s>0?`${r.label} (${s})`:r.label})]}):f,d&&!i?(0,R.jsx)(`div`,{className:_V,children:s>0?(0,R.jsx)(bV,{count:s}):c?(0,R.jsx)(`span`,{className:`inline-flex h-2 w-2 shrink-0 rounded-full bg-yellow-500 animate-status-pulse-yellow`}):null}):null]},r.id)})})}function CV({activeTab:e,onTabChange:t,selectedServer:n,visibleTabs:r,collapsed:i,onCollapsedChange:a,rpcLoggerOpen:o,onRpcLoggerOpenChange:s,onCommandPaletteOpen:c}){return(0,R.jsxs)(`aside`,{className:L(`group/sidebar relative hidden lg:flex flex-col shrink-0 text-sidebar-foreground transition-[width] duration-200 ease-out @container/sidebar`,i?`w-(--sidebar-width-icon)`:`w-(--sidebar-width)`),"data-collapsed":i,"data-collapsible":i?`icon`:`expanded`,children:[(0,R.jsx)(`div`,{className:`sidebar-nav-scroll flex-1 overflow-y-auto overflow-x-hidden min-h-0`,children:(0,R.jsx)(gV,{isActiveKey:t=>t===e,className:`pb-2`,children:(0,R.jsx)(SV,{activeTab:e,onTabChange:t,selectedServer:n,visibleTabs:r,collapsed:i})})}),(0,R.jsx)(cV,{collapsed:i,rpcLoggerOpen:o,onRpcLoggerOpenChange:s,onCommandPaletteOpen:c}),(0,R.jsx)(IB,{collapsed:i,onToggle:()=>a(!i)})]})}function wV(e){if(e===0)return`0 Bytes`;let t=1024,n=[`Bytes`,`KB`,`MB`,`GB`],r=Math.floor(Math.log(e)/Math.log(t));return Math.round(e/t**r*100)/100+` `+n[r]}function TV(e){if(e===0)return`0 B`;let t=1024,n=[`B`,`KB`,`MB`],r=Math.floor(Math.log(e)/Math.log(t));return`${parseFloat((e/t**r).toFixed(1))} ${n[r]}`}var EV=100*1024,DV=1024*20;function OV(e,t){if(e==null)return e;if(typeof e==`string`)return e.length>t?e.substring(0,t)+`... (truncated)`:e;if(Array.isArray(e))return e.map(e=>OV(e,t));if(typeof e==`object`){let n={};for(let r in e)Object.prototype.hasOwnProperty.call(e,r)&&(n[r]=OV(e[r],t));return n}return e}function kV(e){let t=JSON.stringify(e,null,2);return new TextEncoder().encode(t).length>EV?OV(e,DV):e}function AV(e){let t=JSON.stringify(e,null,2),n=new TextEncoder().encode(t).length,r=n>EV,i;if(r){let t=OV(e,DV);i=JSON.stringify(t,null,2)}else i=t;return{isLarge:r,size:n,sizeFormatted:wV(n),preview:i,full:t}}function jV(e,t){try{let n=JSON.stringify(e,null,2),r=globalThis.Blob,i=new r([n],{type:`application/json`}),a=URL.createObjectURL(i),o=document.createElement(`a`);o.href=a,o.download=t||`data-${Date.now()}.json`,document.body.appendChild(o),o.click(),document.body.removeChild(o),URL.revokeObjectURL(a)}catch(e){throw console.error(`Failed to download JSON:`,e),e}}var MV={key:`text-sky-600 dark:text-sky-400`,string:`text-emerald-600 dark:text-emerald-400`,number:`text-amber-600 dark:text-amber-400`,boolean:`text-violet-600 dark:text-violet-400`,null:`text-zinc-500 dark:text-zinc-400`,punctuation:`text-muted-foreground`};function NV(e){let t=[],n=0,r=(e,n)=>{n&&t.push({kind:e,text:n})};for(;n<e.length;){let t=e[n];if(t===`"`){let t=n;for(n++;n<e.length;){if(e[n]===`\\`){n+=2;continue}if(e[n]===`"`){n++;break}n++}let i=e.slice(t,n),a=n;for(;a<e.length&&/[ \t]/.test(e[a]);)a++;r(e[a]===`:`?`key`:`string`,i);continue}if(/[0-9-]/.test(t)){let t=n;for(e[n]===`-`&&n++;n<e.length&&/[0-9.eE+-]/.test(e[n]);)n++;r(`number`,e.slice(t,n));continue}if(e.startsWith(`true`,n)||e.startsWith(`false`,n)){let t=e.startsWith(`true`,n)?`true`:`false`;r(`boolean`,t),n+=t.length;continue}if(e.startsWith(`null`,n)){r(`null`,`null`),n+=4;continue}if(/[{}[\],:]/.test(t)){r(`punctuation`,t),n++;continue}r(`punctuation`,t),n++}return t}function PV(e){return NV(e).map((e,t)=>(0,R.jsx)(`span`,{className:MV[e.kind],children:e.text},t))}var FV={string:`text-emerald-600 dark:text-emerald-400`,number:`text-amber-600 dark:text-amber-400`,boolean:`text-violet-600 dark:text-violet-400`,null:`text-zinc-500 dark:text-zinc-400`,key:`text-sky-600 dark:text-sky-400`,punctuation:`text-muted-foreground`};function IV(e){return e===null?(0,R.jsx)(`span`,{className:FV.null,children:`null`}):typeof e==`string`?(0,R.jsx)(`span`,{className:FV.string,children:JSON.stringify(e)}):typeof e==`number`?(0,R.jsx)(`span`,{className:FV.number,children:String(e)}):typeof e==`boolean`?(0,R.jsx)(`span`,{className:FV.boolean,children:String(e)}):(0,R.jsx)(`span`,{className:FV.string,children:JSON.stringify(e)})}function LV(e){return Array.isArray(e)?`[${e.length}]`:`{${Object.keys(e).length}}`}function RV({label:e,value:t,depth:n,defaultExpanded:r}){let i=typeof t==`object`&&t&&!Array.isArray(t)?Object.keys(t).length>0:Array.isArray(t)?t.length>0:!1,[a,o]=(0,z.useState)(i&&(r||n===0));if(!i){let r=Array.isArray(t)?`[]`:`{}`;return typeof t==`object`&&t?(0,R.jsxs)(`div`,{className:`font-mono text-[0.8rem] leading-relaxed`,style:{paddingLeft:n*12},children:[e!=null&&(0,R.jsxs)(R.Fragment,{children:[(0,R.jsx)(`span`,{className:FV.key,children:JSON.stringify(e)}),(0,R.jsx)(`span`,{className:FV.punctuation,children:`: `})]}),(0,R.jsx)(`span`,{className:FV.punctuation,children:r})]}):(0,R.jsxs)(`div`,{className:`font-mono text-[0.8rem] leading-relaxed`,style:{paddingLeft:n*12},children:[e!=null&&(0,R.jsxs)(R.Fragment,{children:[(0,R.jsx)(`span`,{className:FV.key,children:JSON.stringify(e)}),(0,R.jsx)(`span`,{className:FV.punctuation,children:`: `})]}),IV(t)]})}let s=Array.isArray(t)?t.map((e,t)=>[String(t),e]):Object.entries(t),c=Array.isArray(t),l=c?`[`:`{`,u=c?`]`:`}`;return(0,R.jsxs)(`div`,{className:`font-mono text-[0.8rem] leading-relaxed`,children:[(0,R.jsxs)(`div`,{className:`flex items-start gap-0.5`,style:{paddingLeft:n*12},children:[(0,R.jsx)(`button`,{type:`button`,"aria-expanded":a,onClick:()=>o(e=>!e),className:`mt-0.5 inline-flex shrink-0 items-center justify-center rounded-sm text-muted-foreground hover:text-foreground`,children:(0,R.jsx)(C,{className:L(`h-3.5 w-3.5 transition-transform`,a&&`rotate-90`)})}),(0,R.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[e!=null&&(0,R.jsxs)(R.Fragment,{children:[(0,R.jsx)(`span`,{className:FV.key,children:JSON.stringify(e)}),(0,R.jsx)(`span`,{className:FV.punctuation,children:`: `})]}),(0,R.jsx)(`span`,{className:FV.punctuation,children:l}),!a&&(0,R.jsxs)(R.Fragment,{children:[(0,R.jsx)(`button`,{type:`button`,onClick:()=>o(!0),className:`mx-1 text-xs text-muted-foreground hover:text-foreground`,children:LV(t)}),(0,R.jsx)(`span`,{className:FV.punctuation,children:u})]})]})]}),a&&(0,R.jsxs)(`div`,{children:[s.map(([e,t])=>(0,R.jsx)(RV,{label:e,value:t,depth:n+1,defaultExpanded:r},`${n}-${e}`)),(0,R.jsx)(`div`,{style:{paddingLeft:n*12},children:(0,R.jsx)(`span`,{className:FV.punctuation,children:u})})]})]})}function zV({data:e,defaultExpanded:t=!0,className:n}){return(0,R.jsx)(`div`,{className:L(`text-gray-900 dark:text-gray-100 [overflow-wrap:anywhere]`,n),"data-testid":`collapsible-json`,children:(0,R.jsx)(RV,{value:e,depth:0,defaultExpanded:t})})}var BV=`font-mono text-[0.8rem] text-gray-900 dark:text-gray-100 whitespace-pre-wrap break-words [overflow-wrap:anywhere]`;function VV({data:e,filename:t,className:n,collapsible:r=!1,defaultExpanded:i=!0,...a}){let o=AV(e),s=kV(e),c=o.isLarge?(0,R.jsx)(`div`,{className:`mb-3 p-3 bg-yellow-50 dark:bg-yellow-900/20 border border-yellow-200 dark:border-yellow-800 rounded-lg`,children:(0,R.jsxs)(`div`,{className:`flex items-center justify-between gap-2`,children:[(0,R.jsxs)(`div`,{className:`flex-1`,children:[(0,R.jsxs)(`p`,{className:`text-sm font-medium text-yellow-800 dark:text-yellow-300 mb-1`,children:[`JSON is too large (`,o.sizeFormatted,`)`]}),(0,R.jsx)(`p`,{className:`text-xs text-yellow-700 dark:text-yellow-400`,children:`Showing full structure with truncated values. Download the full JSON file to see complete values.`})]}),(0,R.jsxs)(Gt,{variant:`outline`,size:`sm`,onClick:()=>{jV(e,t)},className:`shrink-0`,children:[(0,R.jsx)(qr,{className:`h-4 w-4 mr-1`}),`Download`]})]})}):null;return r?(0,R.jsxs)(`div`,{className:n,...a,children:[c,(0,R.jsx)(zV,{data:s,defaultExpanded:i})]}):o.isLarge?(0,R.jsxs)(`div`,{className:n,...a,children:[c,(0,R.jsx)(`pre`,{className:BV,children:(0,R.jsx)(`code`,{children:PV(o.preview)})})]}):(0,R.jsx)(`div`,{className:n,...a,children:(0,R.jsx)(`pre`,{className:BV,children:(0,R.jsx)(`code`,{children:PV(o.preview)})})})}function HV(e){if(!e)return null;for(let t of e.elements){let e=t.tagName;if(e===`BUTTON`||e===`INPUT`){let e=t;if(e.type===`submit`)return e}}return null}var UV=function(e){return e.checked=`data-checked`,e.unchecked=`data-unchecked`,e.indeterminate=`data-indeterminate`,e.disabled=`data-disabled`,e.readonly=`data-readonly`,e.required=`data-required`,e.valid=`data-valid`,e.invalid=`data-invalid`,e.touched=`data-touched`,e.dirty=`data-dirty`,e.filled=`data-filled`,e.focused=`data-focused`,e}({});function WV(e){return z.useMemo(()=>({checked(t){return e.indeterminate?{}:t?{[UV.checked]:``}:{[UV.unchecked]:``}},...Tn}),[e.indeterminate])}var GV=z.createContext({disabled:!1});function KV(){return z.useContext(GV)}var qV=z.createContext(void 0);function JV(e=!0){let t=z.useContext(qV);if(t===void 0&&!e)throw Error(Vt(3));return t}var YV=z.createContext(void 0);function XV(){let e=z.useContext(YV);if(e===void 0)throw Error(Vt(14));return e}var ZV=`data-parent`,QV=z.forwardRef(function(e,t){let{checked:n,className:r,defaultChecked:i=!1,"aria-labelledby":a,disabled:o=!1,form:s,id:c,indeterminate:l=!1,inputRef:u,name:d,onCheckedChange:f,parent:p=!1,readOnly:m=!1,render:h,required:g=!1,uncheckedValue:_,value:v,nativeButton:y=!1,style:b,...x}=e,{clearErrors:S}=An(),{disabled:C,name:w,setDirty:T,setFilled:E,setFocused:ee,setTouched:D,state:ne,validationMode:re,validityData:ie,validation:k}=On(),A=KV(),{labelId:j,controlId:ae,registerControlId:oe,getDescriptionProps:se}=kn(),ce=JV(),M=ce?.parent,N=M&&ce.allValues,le=C||A.disabled||ce?.disabled||o,ue=w??d,de=v??ue,fe=O(),pe=O(),me=ae;N?me=p?pe:`${M.id}-${de}`:c&&(me=c);let he={};N&&(p?he=ce.parent.getParentProps():de&&(he=ce.parent.getChildProps(de)));let{checked:ge=n,indeterminate:_e=l,onCheckedChange:ve,...ye}=he,xe=ce?.value,P=ce?.setValue,Se=ce?.defaultValue,Ce=z.useRef(null),we=qt(()=>Symbol(`checkbox-control`)),Ee=z.useRef(!1),{getButtonProps:De,buttonRef:Oe}=Lt({disabled:le,native:y}),ke=ce?.validation??k,[Ae,je]=Yt({controlled:de&&xe&&!p?xe.includes(de):ge,default:de&&Se&&!p?Se.includes(de):i,name:`Checkbox`,state:`checked`}),Me=N?!!ge:Ae,Ne=N&&_e||l;Rt(()=>{oe!==It&&(Ee.current=!0,oe(we.current,me))},[me,oe,we]),z.useEffect(()=>{let e=we.current;return()=>{!Ee.current||oe===It||(Ee.current=!1,oe(e,void 0))}},[oe,we]),En(Ce,fe,Ae,void 0,!ce&&!le,d);let Pe=z.useRef(null),Fe=Kt(u,Pe,ke.inputRef,ke.registerInput),Ie=HB(a,j,Pe,!y,me??void 0);Rt(()=>{Pe.current&&(Pe.current.indeterminate=Ne,Ae&&E(!0))},[Ae,Ne,E]),Dn(Ae,()=>{ce||(S(ue),E(Ae),T(Ae!==ie.initialValue),ke.change(Ae))});let Le=zt({checked:Ae,disabled:le,form:s,name:p?void 0:ue,id:y?void 0:me??void 0,required:g,ref:Fe,style:ue?Te:He,tabIndex:-1,type:`checkbox`,"aria-hidden":!0,onChange(e){if(e.nativeEvent.defaultPrevented)return;if(m){e.preventDefault();return}let t=e.currentTarget.checked,n=te(be,e.nativeEvent);f?.(t,n),!n.isCanceled&&(ve?.(t,n),!n.isCanceled&&(je(t),de&&xe&&P&&!p&&!N&&P(t?[...xe,de]:xe.filter(e=>e!==de),n)))},onFocus(){Ce.current?.focus()}},v===void 0?Wt:{value:(ce?Ae&&v:v)||``},se,e=>ke.getValidationProps(le,e));z.useEffect(()=>{if(!M||!de)return;let e=M.disabledStatesRef.current;return e.set(de,le),()=>{e.delete(de)}},[M,le,de]);let Re=z.useMemo(()=>({...ne,checked:Me,disabled:le,readOnly:m,required:g,indeterminate:Ne}),[ne,Me,le,m,g,Ne]),ze=WV(Re),Be=Ft(`span`,e,{state:Re,ref:[Oe,Ce,t,ce?.registerControlRef],props:[{id:y?me??void 0:fe,role:`checkbox`,"aria-checked":Ne?`mixed`:Me,"aria-readonly":m||void 0,"aria-required":g||void 0,"aria-labelledby":Ie,[ZV]:p?``:void 0,onFocus(){le||ee(!0)},onBlur(){let e=Pe.current;e&&(D(!0),ee(!1),re===`onBlur`&&ke.commit(ce?xe:e.checked))},onKeyDown(e){if(e.key!==`Enter`||(e.preventBaseUIHandler(),e.defaultPrevented))return;let t=Pe.current?.form??null,n=e.currentTarget,r=e.nativeEvent,i=e.preventDefault,a=r.preventDefault,o=!1;e.preventDefault=()=>{o=!0,i.call(e)},r.preventDefault=()=>{o=!0,a.call(r)},a.call(r),Mt(n).queueMicrotask(()=>{e.preventDefault=i,r.preventDefault=a,o||HV(t)?.click()})},onClick(e){if(m||le)return;e.preventDefault();let t=Pe.current;t&&t.dispatchEvent(new(Mt(t)).PointerEvent(`click`,{bubbles:!0,shiftKey:e.shiftKey,ctrlKey:e.ctrlKey,altKey:e.altKey,metaKey:e.metaKey}))}},x,ye,De,se,e=>ke.getValidationProps(le,e)],stateAttributesMapping:ze});return(0,R.jsxs)(YV.Provider,{value:Re,children:[Be,!Ae&&!ce&&ue&&!p&&_!==void 0&&(0,R.jsx)(`input`,{type:`hidden`,form:s,name:ue,value:_,disabled:le}),(0,R.jsx)(`input`,{...Le,suppressHydrationWarning:!0})]})}),$V=z.forwardRef(function(e,t){let{render:n,className:r,style:i,keepMounted:a=!1,...o}=e,s=XV(),c=s.checked||s.indeterminate,{mounted:l,transitionStatus:u,setMounted:d}=Je(c),f=z.useRef(null),p={...s,transitionStatus:u};g({open:c,ref:f,onComplete(){c||d(!1)}});let m={...WV(s),...it,...Tn},h=a||l,_=Ft(`span`,e,{ref:[t,f],state:p,stateAttributesMapping:m,props:o});return h?_:null}),eH=(0,z.createContext)(null);function tH(){let e=(0,z.useContext)(eH);if(!e)throw Error(`useCheckboxGroup must be used within a CheckboxGroup`);return e}var nH=(0,z.forwardRef)(({children:e,checkedIndices:t,orientation:n=`vertical`,className:r,...i},a)=>{let o=(0,z.useRef)(null),s=n===`horizontal`,{activeIndex:c,setActiveIndex:l,handlers:u,registerItem:d,measureItems:f}=_n(o,{axis:s?`x`:`y`});(0,z.useEffect)(()=>{f()},[f,e]);let p=s?`ArrowLeft`:`ArrowUp`,m=s?`ArrowRight`:`ArrowDown`;return(0,R.jsx)(eH.Provider,{value:{registerItem:d,activeIndex:c},children:(0,R.jsx)(`div`,{ref:e=>{o.current=e,typeof a==`function`?a(e):a&&(a.current=e)},onMouseEnter:u.onMouseEnter,onMouseMove:u.onMouseMove,onMouseLeave:u.onMouseLeave,onFocus:e=>{let t=e.target.closest(`[data-proximity-index]`)?.getAttribute(`data-proximity-index`);t!=null&&l(Number(t))},onBlur:e=>{o.current?.contains(e.relatedTarget)||l(null)},onKeyDown:e=>{let t=Array.from(o.current?.querySelectorAll(`[data-proximity-index]`)??[]),n=t.indexOf(e.target);n!==-1&&([p,m].includes(e.key)?(e.preventDefault(),t[e.key===m?(n+1)%t.length:(n-1+t.length)%t.length]?.focus()):e.key===`Home`?(e.preventDefault(),t[0]?.focus()):e.key===`End`&&(e.preventDefault(),t[t.length-1]?.focus()))},role:`group`,className:L(`relative flex max-w-full select-none`,s?`w-auto flex-row`:`w-72 flex-col`,r),...i,children:e})})});nH.displayName=`CheckboxGroup`;var rH=(0,z.forwardRef)(({label:e,index:t,checked:n,onToggle:r,size:i=`default`,className:a,...o},s)=>{let c=(0,z.useRef)(null),l=(0,z.useRef)(!1),{registerItem:u,activeIndex:d}=tH();(0,z.useEffect)(()=>(u(t,c.current),()=>u(t,null)),[t,u]),(0,z.useEffect)(()=>{l.current=!0},[]);let f=d===t,p=!l.current,m=Nt(),h=i===`sm`;return(0,R.jsxs)(`div`,{ref:e=>{c.current=e,typeof s==`function`?s(e):s&&(s.current=e)},"data-proximity-index":t,tabIndex:0,role:`checkbox`,"aria-checked":n,"aria-label":e,onClick:r,onMouseDown:e=>{let t=e.target.closest(`button:not([tabindex="-1"]), a[href], input, select, textarea, [tabindex]:not([tabindex="-1"])`);t&&t!==e.currentTarget||(e.preventDefault(),e.currentTarget.focus())},onKeyDown:e=>{(e.key===` `||e.key===`Enter`)&&(e.preventDefault(),r())},className:L(`relative z-10 flex items-center cursor-pointer outline-none`,h?`h-7 gap-1.5 px-2`:`h-8 gap-2.5 px-3`,m.item,`focus-visible:ring-1 focus-visible:ring-[color:var(--focus-ring,#6B97FF)]`,a),...o,children:[(0,R.jsxs)(QV,{checked:n,tabIndex:-1,"aria-hidden":!0,className:L(`pointer-events-none relative shrink-0 appearance-none bg-transparent p-0 border-0 outline-none`,h?`size-[13px]`:`size-[15px]`),children:[(0,R.jsx)(`div`,{className:L(`absolute inset-0 rounded-[5px] border-solid transition-all duration-80 border-[1.5px]`,n?`border-border`:f?`border-neutral-400 dark:border-neutral-500`:`border-border`)}),(0,R.jsx)(en,{children:n&&(0,R.jsx)($V,{keepMounted:!0,render:e=>{let{style:t,onDrag:n,onDragStart:r,onDragEnd:i,onAnimationStart:a,onAnimationEnd:o,onAnimationIteration:s,...c}=e;return(0,R.jsx)(Pe.svg,{...c,width:h?14:18,height:h?14:18,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:2,strokeLinecap:`round`,strokeLinejoin:`round`,className:`absolute left-1/2 top-1/2 -translate-x-1/2 -translate-y-1/2 text-foreground`,initial:{opacity:1},animate:{opacity:1},exit:{opacity:1},children:(0,R.jsx)(Pe.path,{d:`M6 12L10 16L18 8`,initial:{pathLength:+!!p},animate:{pathLength:1,transition:{duration:.08,ease:`easeOut`}},exit:{pathLength:0,transition:{duration:.04,ease:`easeIn`}}})})}})})]}),(0,R.jsxs)(`span`,{className:`inline-grid items-center self-center leading-none`,children:[(0,R.jsx)(`span`,{className:`col-start-1 row-start-1 invisible leading-none`,style:{fontVariationSettings:ke.semibold},"aria-hidden":`true`,children:e}),(0,R.jsx)(`span`,{className:L(`col-start-1 row-start-1 leading-none transition-[color,font-variation-settings] duration-80`,h?`text-[11px]`:`text-[13px]`,n||f?`text-foreground`:`text-muted-foreground`),style:{fontVariationSettings:n?ke.semibold:ke.normal},children:e})]})]})});rH.displayName=`CheckboxItem`;var iH=36,aH=188,oH=6;function sH(e,t,n){let[r,i]=(0,z.useState)(0),[a,o]=(0,z.useState)(0),s=(0,z.useMemo)(()=>{let n=[],r=[],i=0;for(let a of e){n.push(i);let e=iH+(t.has(a.id)?aH:0);r.push(e),i+=e}return{offsets:n,heights:r,totalHeight:i}},[t,e]),c=(0,z.useMemo)(()=>{if(e.length===0)return{totalHeight:0,visibleItems:[]};let{offsets:t,heights:n,totalHeight:i}=s,o=r+a,c=0;for(;c<e.length&&t[c]+n[c]<r;)c++;c=Math.max(0,c-oH);let l=c;for(;l<e.length&&t[l]<o;)l++;l=Math.min(e.length,l+oH);let u=[];for(let r=c;r<l;r++)u.push({index:r,item:e[r],top:t[r],height:n[r]});return{totalHeight:i,visibleItems:u}},[e,s,r,a]),l=(0,z.useCallback)(()=>{let e=n.current;e&&i(e.scrollTop)},[n]);return(0,z.useEffect)(()=>{let e=n.current;if(!e)return;let t=()=>{o(e.clientHeight),i(e.scrollTop)};t();let r=new ResizeObserver(t);return r.observe(e),e.addEventListener(`scroll`,l,{passive:!0}),()=>{r.disconnect(),e.removeEventListener(`scroll`,l)}},[l,n,e.length]),c}var cH=300,lH=/(?:^|\/)notifications\//;function uH(e){let t=e;return typeof t?.method==`string`?t.method:null}function dH(e){let t=e.message;if(t?.id!==void 0&&t.id!==null||t?.result!==void 0||t?.error!==void 0)return null;let n=uH(e.message);return!n||!lH.test(n)?null:[e.source,e.serverId,e.widgetId??``,e.direction,n].join(`|`)}function fH(e,t,n=Date.now()){let r=dH(e),i=dH(t);if(!r||r!==i)return!1;let a=Date.parse(e.timestamp);return Number.isNaN(a)?!1:n-a<=cH}function pH(e,t){return{...e,timestamp:t.timestamp,message:t.message,repeatCount:(e.repeatCount??1)+1}}var mH=new class{maxEntries;entries=[];listeners=new Set;nextId=0;emitFrame=null;constructor(e=1e3){this.maxEntries=e}publish(e){let t=this.entries[this.entries.length-1];if(t&&fH(t,e,Date.parse(e.timestamp))){this.entries[this.entries.length-1]=pH(t,e),this.scheduleEmit();return}this.entries.push({...e,id:`rpc-${++this.nextId}`}),this.entries.length>this.maxEntries&&this.entries.splice(0,this.entries.length-this.maxEntries),this.scheduleEmit()}getSnapshot=()=>this.entries;subscribe=e=>(this.listeners.add(e),()=>this.listeners.delete(e));clear(e={}){let t=new Set(e.serverIds??[]),n=new Set(e.sources??[]);t.size===0&&n.size===0?this.entries=[]:this.entries=this.entries.filter(e=>!((t.size===0||t.has(e.serverId))&&(n.size===0||n.has(e.source)))),this.scheduleEmit()}peekCoalesceKey(e){return dH(e)}scheduleEmit(){if(this.emitFrame===null){if(typeof requestAnimationFrame>`u`){this.emit();return}this.emitFrame=requestAnimationFrame(()=>{this.emitFrame=null,this.emit()})}}emit(){this.listeners.forEach(e=>e())}},hH;function gH(e){mH.publish({source:`mcp`,serverId:e.serverId,direction:e.direction,timestamp:e.timestamp,message:e.message})}function _H(){hH||=(dk().forEach(gH),fk(gH))}_H();function vH({serverIds:e,onCountChange:t,onClearRef:n,onExportRef:r}={}){let i=(0,z.useRef)(null),[a,o]=(0,z.useState)(new Set),[s,c]=(0,z.useState)(``),[l,u]=(0,z.useState)(!1),[d,f]=(0,z.useState)(()=>new Set([`mcp`,`widget`])),p=(0,z.useSyncExternalStore)(mH.subscribe,mH.getSnapshot,mH.getSnapshot),m=async e=>{try{await lM(JSON.stringify(e,null,2)),oI.success(`Message copied to clipboard`)}catch(e){console.error(`Failed to copy message:`,e),oI.error(`Failed to copy to clipboard`)}},h=(0,z.useMemo)(()=>{if(!e?.length)return p;let t=new Set(e);return p.filter(e=>t.has(e.serverId))},[p,e]),g=(0,z.useMemo)(()=>{let e=new Set;return d.has(`mcp`)&&e.add(0),d.has(`widget`)&&e.add(1),e},[d]),_=(0,z.useCallback)(e=>{f(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})},[]),y=(0,z.useMemo)(()=>{let e=h;d.size>0&&(e=e.filter(e=>d.has(e.source)));let t=s.trim().toLowerCase();return t&&(e=e.filter(e=>{let n=bH(e);return e.serverId.toLowerCase().includes(t)||e.widgetId?.toLowerCase().includes(t)||e.source.includes(t)||n.toLowerCase().includes(t)||e.direction.toLowerCase().includes(t)||JSON.stringify(e.message).toLowerCase().includes(t)})),[...e].reverse()},[h,s,d]),{totalHeight:b,visibleItems:x}=sH(y,a,i),S=(0,z.useCallback)(e=>{o(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})},[]),C=(0,z.useCallback)(async()=>{let t=d.size===0||d.size===2?void 0:[...d];(!t||t.includes(`mcp`))&&(e?.length?e.forEach(e=>pk(e)):pk()),mH.clear({serverIds:e,sources:t}),o(new Set)},[e,d]),w=(0,z.useCallback)(async()=>{try{await lM(JSON.stringify(y,null,2)),oI.success(`Copied ${y.length} messages`)}catch(e){console.error(`Failed to copy messages:`,e),oI.error(`Failed to copy to clipboard`)}},[y]),T=(0,z.useCallback)(()=>{let e=new Blob([JSON.stringify(y,null,2)],{type:`application/json`}),t=URL.createObjectURL(e),n=document.createElement(`a`);n.href=t,n.download=`mcp-rpc-traffic-${new Date().toISOString().replaceAll(`:`,`-`)}.json`,n.click(),URL.revokeObjectURL(t)},[y]);return(0,z.useEffect)(()=>{t?.(y.length)},[y.length,t]),(0,z.useEffect)(()=>(n&&(n.current=C),()=>{n&&(n.current=null)}),[C,n]),(0,z.useEffect)(()=>(r&&(r.current=w),()=>{r&&(r.current=null)}),[w,r]),(0,R.jsxs)(`div`,{className:`flex h-full min-h-0 flex-col overflow-hidden`,children:[(0,R.jsxs)(`div`,{className:`flex shrink-0 items-center justify-between gap-2 pr-2 pt-2 pl-1`,children:[(0,R.jsx)(`h2`,{className:`text-xs font-medium text-foreground`,children:`RPC Logs`}),(0,R.jsxs)(`div`,{className:`flex items-center gap-0.5`,children:[(0,R.jsx)(Gt,{variant:`ghost`,size:`sm`,className:`size-7 p-0`,onClick:w,disabled:y.length===0,"aria-label":`Copy filtered RPC traffic`,title:`Copy filtered`,children:(0,R.jsx)(Wr,{className:`size-3.5`})}),(0,R.jsx)(Gt,{variant:`ghost`,size:`sm`,className:`size-7 p-0`,onClick:T,disabled:y.length===0,"aria-label":`Download filtered RPC traffic as JSON`,title:`Download JSON`,children:(0,R.jsx)(qr,{className:`size-3.5`})}),(0,R.jsx)(Gt,{variant:`ghost`,size:`sm`,className:`size-7 p-0`,onClick:C,disabled:p.length===0,"aria-label":`Clear RPC traffic`,title:`Clear`,children:(0,R.jsx)(Gi,{className:`size-3.5`})})]})]}),(0,R.jsxs)(`div`,{className:`flex shrink-0 items-center pr-2 pb-2 pt-1 pl-1`,children:[(0,R.jsxs)(`div`,{className:`relative min-w-0 flex-1 transition-[flex-grow] duration-200 ease-out`,children:[(0,R.jsx)(v,{className:`pointer-events-none absolute left-2 top-1/2 size-3.5 -translate-y-1/2 text-muted-foreground`}),(0,R.jsx)(ht,{value:s,onChange:e=>c(e.target.value),onFocus:()=>u(!0),onBlur:()=>u(!1),placeholder:`Search`,"aria-label":`Search RPC traffic`,className:`h-8 w-full pl-7 text-xs shadow-none transition-[width] duration-200 ease-out`})]}),(0,R.jsx)(`div`,{"aria-hidden":l,className:L(`shrink-0 overflow-hidden transition-[max-width,opacity,margin] duration-200 ease-out`,l?`pointer-events-none ml-0 max-w-0 opacity-0`:`ml-2 max-w-32 opacity-100`),children:(0,R.jsxs)(nH,{checkedIndices:g,orientation:`horizontal`,"aria-label":`Filter RPC traffic by source`,className:`w-auto shrink-0`,children:[(0,R.jsx)(rH,{index:0,label:`MCP`,size:`sm`,checked:d.has(`mcp`),onToggle:()=>_(`mcp`)}),(0,R.jsx)(rH,{index:1,label:`UI`,size:`sm`,checked:d.has(`widget`),onToggle:()=>_(`widget`)})]})})]}),(0,R.jsx)(`div`,{ref:i,className:`min-h-0 flex-1 overflow-y-auto pb-10`,style:{maskImage:`linear-gradient(to bottom, black 0, black calc(100% - 3rem), transparent 100%)`,WebkitMaskImage:`linear-gradient(to bottom, black 0, black calc(100% - 3rem), transparent 100%)`},children:y.length===0?(0,R.jsxs)(`div`,{className:`text-center py-8`,children:[(0,R.jsx)(`div`,{className:`text-xs text-muted-foreground`,children:`No messages yet`}),(0,R.jsx)(`div`,{className:`text-[10px] text-muted-foreground mt-1`,children:`JSON-RPC messages will appear here`})]}):(0,R.jsx)(`div`,{className:`relative w-full`,style:{height:b},children:x.map(({item:e,top:t,height:n})=>(0,R.jsx)(yH,{item:e,top:t,height:n,expanded:a.has(e.id),onToggle:()=>S(e.id),onCopy:()=>m(e.message)},e.id))})})]})}function yH({item:e,top:t,height:n,expanded:r,onToggle:i,onCopy:a}){let o=bH(e),s=xH(e),c=e.repeatCount&&e.repeatCount>1?` ×${e.repeatCount}`:``;return(0,R.jsxs)(`div`,{className:`absolute inset-x-0 overflow-hidden`,style:{top:t,height:n},"data-testid":`rpc-message-${o.replace(/\//g,`-`)}`,children:[(0,R.jsxs)(`button`,{type:`button`,"aria-expanded":r,onClick:i,className:`flex h-9 w-full cursor-pointer items-center gap-2 py-2 pr-3 pl-1 text-left text-muted-foreground transition-colors hover:text-foreground`,children:[(0,R.jsxs)(et,{children:[(0,R.jsx)(we,{render:(0,R.jsx)(`span`,{className:`flex size-4 shrink-0 items-center justify-center`,children:e.direction===`receive`?(0,R.jsx)(Dr,{className:`size-3.5 text-blue-500`}):(0,R.jsx)(Ar,{className:`size-3.5 text-emerald-500`})}),nativeButton:!1}),(0,R.jsx)(lt,{side:`left`,children:s})]}),(0,R.jsxs)(et,{children:[(0,R.jsx)(we,{render:(0,R.jsx)(`span`,{className:`flex size-3.5 shrink-0 items-center justify-center`,children:e.source===`mcp`?(0,R.jsx)(WL,{className:`size-3`}):(0,R.jsx)(Ti,{className:`size-3`})}),nativeButton:!1}),(0,R.jsx)(lt,{side:`left`,children:e.source===`mcp`?`MCP server`:`UI widget`})]}),(0,R.jsxs)(`span`,{className:`min-w-0 flex-1 truncate font-mono text-xs text-foreground`,children:[o,c?(0,R.jsx)(`span`,{className:`text-muted-foreground`,children:c}):null]}),(0,R.jsxs)(et,{children:[(0,R.jsx)(we,{render:(0,R.jsx)(`time`,{dateTime:e.timestamp,className:`shrink-0 cursor-default font-mono text-[10px] tabular-nums text-muted-foreground underline decoration-dotted underline-offset-2`,children:new Date(e.timestamp).toLocaleTimeString()}),nativeButton:!1}),(0,R.jsx)(lt,{side:`left`,children:new Date(e.timestamp).toLocaleString()})]})]}),r?(0,R.jsxs)(`div`,{className:`relative mx-3 mb-2 max-h-44 overflow-auto rounded-lg p-2 pr-8`,children:[(0,R.jsx)(VV,{data:e.message,className:`[&_pre]:!text-[10px] [&_pre]:!leading-4`}),(0,R.jsx)(Gt,{variant:`secondary`,size:`icon-sm`,onClick:a,className:`absolute right-1 top-1 size-6 rounded-full p-0`,title:`Copy message`,"aria-label":`Copy message`,children:(0,R.jsx)(Wr,{className:`size-3`})})]}):null]})}function bH(e){let t=uH(e.message);if(t)return t;let n=e.message;return n?.result===void 0?n?.error===void 0?`unknown`:`error`:`result`}function xH(e){return e.source===`widget`?e.direction===`send`?`Host → Widget`:`Widget → Host`:e.direction===`send`?`Inspector → MCP`:`MCP → Inspector`}function SH({serverId:e,open:t}){return(0,R.jsx)(`aside`,{"aria-label":`RPC Panel`,"aria-hidden":!t,className:L(`relative hidden min-h-0 shrink-0 flex-col overflow-hidden transition-[width,margin] duration-200 ease-out lg:flex`,t?`w-(--rpc-panel-width) lg:mr-[18px]`:`w-0 lg:mr-0`),children:(0,R.jsx)(`div`,{className:L(`flex h-full min-h-0 w-(--rpc-panel-width) flex-col transition-opacity duration-200 ease-out`,t?`opacity-100`:`pointer-events-none opacity-0`),children:(0,R.jsx)(vH,{serverIds:[e]})})})}function CH({...e}){return(0,R.jsx)(tL,{"data-slot":`sheet`,...e})}function wH(e){return(0,R.jsx)(rL,{"data-slot":`sheet-trigger`,...e})}function TH({...e}){return(0,R.jsx)(JI,{"data-slot":`sheet-portal`,...e})}function EH({className:e,container:t,...n}){return(0,R.jsx)(zI,{"data-slot":`sheet-overlay`,className:L(`inset-0 z-50 bg-black/50 transition-opacity duration-150 data-ending-style:opacity-0 data-starting-style:opacity-0`,t?`absolute`:`fixed`,e),...n})}function DH({className:e,children:t,side:n=`right`,showCloseButton:r=!0,container:i,...a}){return(0,R.jsxs)(TH,{container:i??void 0,children:[(0,R.jsx)(EH,{container:i}),(0,R.jsxs)(qI,{"data-slot":`sheet-content`,"data-side":n,className:L(`z-50 flex flex-col gap-4 bg-popover bg-clip-padding text-sm text-popover-foreground shadow-lg transition duration-200 ease-in-out data-ending-style:opacity-0 data-starting-style:opacity-0 data-[side=bottom]:inset-x-0 data-[side=bottom]:bottom-0 data-[side=bottom]:h-auto data-[side=bottom]:border-t data-[side=bottom]:data-ending-style:translate-y-[2.5rem] data-[side=bottom]:data-starting-style:translate-y-[2.5rem] data-[side=left]:inset-y-0 data-[side=left]:left-0 data-[side=left]:h-full data-[side=left]:w-3/4 data-[side=left]:border-r data-[side=left]:data-ending-style:translate-x-[-2.5rem] data-[side=left]:data-starting-style:translate-x-[-2.5rem] data-[side=right]:inset-y-0 data-[side=right]:right-0 data-[side=right]:h-full data-[side=right]:w-3/4 data-[side=right]:border-l data-[side=right]:data-ending-style:translate-x-[2.5rem] data-[side=right]:data-starting-style:translate-x-[2.5rem] data-[side=top]:inset-x-0 data-[side=top]:top-0 data-[side=top]:h-auto data-[side=top]:border-b data-[side=top]:data-ending-style:translate-y-[-2.5rem] data-[side=top]:data-starting-style:translate-y-[-2.5rem] data-[side=left]:sm:max-w-sm data-[side=right]:sm:max-w-sm`,i?`absolute`:`fixed`,e),...a,children:[t,r&&(0,R.jsxs)(BI,{"data-slot":`sheet-close`,render:(0,R.jsx)(Gt,{variant:`ghost`,className:`absolute top-4 right-4`,size:`icon-sm`}),children:[(0,R.jsx)(Xi,{}),(0,R.jsx)(`span`,{className:`sr-only`,children:`Close`})]})]})]})}function OH({className:e,...t}){return(0,R.jsx)(`div`,{"data-slot":`sheet-header`,className:L(`flex flex-col gap-1.5 p-4`,e),...t})}function kH({className:e,...t}){return(0,R.jsx)(nL,{"data-slot":`sheet-title`,className:L(`font-medium text-foreground`,e),...t})}function AH({className:e,...t}){return(0,R.jsx)(VI,{"data-slot":`sheet-description`,className:L(`text-sm text-muted-foreground`,e),...t})}var jH=`https://cdn.mcp-use.com/mcpuse_logo_circle_dark.svg`;function MH({symbolSize:e=14,className:t,textClassName:n}){return(0,R.jsxs)(`span`,{className:L(`inline-flex items-center gap-1.5`,t),children:[(0,R.jsx)(NH,{size:e}),(0,R.jsx)(`span`,{className:L(`font-medium leading-none text-black [font-family:var(--font-family-outfit)]`,n),children:`Manufact`})]})}function NH({size:e=14,className:t}){return(0,R.jsxs)(`svg`,{width:e,height:e,viewBox:`0 0 480 480`,"aria-hidden":!0,className:L(`block shrink-0`,t),children:[(0,R.jsx)(`path`,{d:`M101.7 0 C157.9 0 203.4 45.7 203.4 102.1 C203.4 126.6 202.1 152.1 212.2 174.3 L219.8 191 C233.8 221.8 258.5 246.4 289.2 260.5 L303.5 267 C326.5 277.5 353 275.8 378.3 275.8 C434.5 275.8 480 321.5 480 377.9 C480 434.3 434.5 480 378.3 480 C322.1 480 276.6 434.3 276.6 377.9 C276.6 354.2 277.7 329.6 267.8 308 L259.8 290.3 C245.7 259.5 221 234.8 190.2 220.7 L173 212.9 C151 202.9 125.8 204.2 101.7 204.2 C45.5 204.2 0 158.5 0 102.1 C0 45.7 45.5 0 101.7 0 Z`,fill:`currentColor`}),(0,R.jsx)(`circle`,{cx:`96.4`,cy:`383.6`,r:`96.4`,fill:`currentColor`}),(0,R.jsx)(`circle`,{cx:`383.6`,cy:`96.4`,r:`96.4`,fill:`currentColor`})]})}var PH=`data:image/svg+xml,%3Csvg%20width%3D%22512%22%20height%3D%22512%22%20viewBox%3D%220%200%20512%20512%22%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20fill%3D%22%2394A3B8%22%20stroke%3D%22%2394A3B8%22%3E%3Cg%3E%3Cpath%20fill%3D%22none%22%20d%3D%22M3%20248.945C18%20248.945%2076%20236%20106%20219C136%20202%20136%20202%20198%20158C276.497%20102.293%20332%20120.945%20423%20120.945%22%20stroke-width%3D%2290%22%2F%3E%3Cpath%20d%3D%22M511%20121.5L357.25%20210.268L357.25%2032.7324L511%20121.5Z%22%2F%3E%3Cpath%20fill%3D%22none%22%20d%3D%22M0%20249C15%20249%2073%20261.945%20103%20278.945C133%20295.945%20133%20295.945%20195%20339.945C273.497%20395.652%20329%20377%20420%20377%22%20stroke-width%3D%2290%22%2F%3E%3Cpath%20d%3D%22M508%20376.445L354.25%20287.678L354.25%20465.213L508%20376.445Z%22%2F%3E%3C%2Fg%3E%3C%2Fsvg%3E`,FH={openai:`OpenAI`,anthropic:`Anthropic`,google:`Google`};function IH(e){let t=e.split(`/`)[0]?.toLowerCase();return t===`openai`||t===`anthropic`||t===`google`?t:`openrouter`}function LH(e,t){let n=e.trim(),r=FH[t];if(r){let e=r.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`),t=RegExp(`^${e}\\s*:\\s*`,`i`),i=n.replace(t,``).trim();if(i.length>0)return i}let i=n.indexOf(`: `);return i>0&&i<48?n.slice(i+2).trim():n}function RH({provider:e,model:t,displayName:n,mode:r=`byok`,className:i,...a}){let o=n??t,s=r===`managed`&&e===`openai-compatible`?IH(t):e;return(0,R.jsxs)(`button`,{type:`button`,className:L(`inline-flex items-center gap-1.5 min-w-0 border-0 bg-transparent p-1`,`font-mono text-[11px] text-muted-foreground cursor-pointer`,`hover:text-foreground transition-colors`,`rounded-md outline-none focus-visible:ring-1 focus-visible:ring-ring`,i),...a,children:[r===`managed`?(0,R.jsx)(`img`,{src:jH,alt:`Manufact`,className:`h-3.5 w-3.5 shrink-0 rounded-full object-cover`}):(0,R.jsx)(ci,{className:`size-3 shrink-0 opacity-70`,"aria-hidden":!0}),(0,R.jsx)(VH,{provider:s,className:`shrink-0`}),(0,R.jsx)(`span`,{className:`whitespace-nowrap`,children:o}),(0,R.jsx)(Ir,{className:`size-3 shrink-0 opacity-60`,"aria-hidden":!0})]})}function zH(e){switch(e){case`openai`:return`OpenAI`;case`openai-compatible`:return`OpenAI Compatible`;case`anthropic`:return`Anthropic`;case`google`:return`Google`;case`openrouter`:return`OpenRouter`;case`ollama`:return`Ollama`;default:return e}}function BH(e,t){switch(e){case`openai`:case`anthropic`:case`google`:return`https://inspector-cdn.mcp-use.com/providers/${e}.png`;case`ollama`:return`https://inspector-cdn.mcp-use.com/providers/${t===`dark`?`ollama_dark`:`ollama_light`}.png`;case`openrouter`:return PH;case`openai-compatible`:return null;default:return null}}function VH({provider:e,className:t}){let{resolvedTheme:n}=Fz();if(e===`openai-compatible`)return null;let r=BH(e,n);if(r){let n=e===`ollama`?`h-3.5 w-3.5 object-contain`:`h-4 w-4 rounded-full object-cover`;return(0,R.jsx)(`img`,{src:r,alt:zH(e),className:L(n,t)})}return(0,R.jsx)(`div`,{"aria-label":zH(e),className:L(`flex h-4 w-4 items-center justify-center rounded-full bg-neutral-900 text-[9px] font-semibold text-white dark:bg-neutral-100 dark:text-neutral-900`,t),children:zH(e).charAt(0)})}function HH({className:e}){return(0,R.jsx)(`svg`,{viewBox:`0 -28.5 256 256`,className:e,fill:`currentColor`,xmlns:`http://www.w3.org/2000/svg`,"aria-hidden":!0,children:(0,R.jsx)(`path`,{d:`M216.856339,16.5966031 C200.285002,8.84328665 182.566144,3.2084988 164.041564,0 C161.766523,4.11318106 159.108624,9.64549908 157.276099,14.0464379 C137.583995,11.0849896 118.072967,11.0849896 98.7430163,14.0464379 C96.9108417,9.64549908 94.1925838,4.11318106 91.8971895,0 C73.3526068,3.2084988 55.6133949,8.86399117 39.0420583,16.6376612 C5.61752293,67.146514 -3.4433191,116.400813 1.08711069,164.955721 C23.2560196,181.510915 44.7403634,191.567697 65.8621325,198.148576 C71.0772151,190.971126 75.7283628,183.341335 79.7352139,175.300261 C72.104019,172.400575 64.7949724,168.822202 57.8887866,164.667963 C59.7209612,163.310589 61.5131304,161.891452 63.2445898,160.431257 C105.36741,180.133187 151.134928,180.133187 192.754523,160.431257 C194.506336,161.891452 196.298154,163.310589 198.110326,164.667963 C191.183787,168.842556 183.854737,172.420929 176.223542,175.320965 C180.230393,183.341335 184.861538,190.991831 190.096624,198.16893 C211.238746,191.588051 232.743023,181.531619 254.911949,164.955721 C260.227747,108.668201 245.831087,59.8662432 216.856339,16.5966031 Z M85.4738752,135.09489 C72.8290281,135.09489 62.4592217,123.290155 62.4592217,108.914901 C62.4592217,94.5396472 72.607595,82.7145587 85.4738752,82.7145587 C98.3405064,82.7145587 108.709962,94.5189427 108.488529,108.914901 C108.508531,123.290155 98.3405064,135.09489 85.4738752,135.09489 Z M170.525237,135.09489 C157.88039,135.09489 147.510584,123.290155 147.510584,108.914901 C147.510584,94.5396472 157.658606,82.7145587 170.525237,82.7145587 C183.391518,82.7145587 193.761324,94.5189427 193.539891,108.914901 C193.539891,123.290155 183.391518,135.09489 170.525237,135.09489 Z`,fillRule:`nonzero`})})}var UH=`flex flex-1 items-center justify-center text-muted-foreground transition-colors hover:text-foreground active:text-foreground`;function WH({serverId:e,rpcLoggerOpen:t,onRpcLoggerOpenChange:n}){let r=NB(),{embeddedConfig:i}=EL(),{user:a}=mz(i.chatApiUrl),o=a?`https://manufact.com/cloud?ref=mcp-use-inspector`:`https://manufact.com/signup?ref=mcp-use-inspector`;return(0,R.jsxs)(R.Fragment,{children:[typeof document<`u`&&(0,br.createPortal)((0,R.jsxs)(`nav`,{"aria-label":`Inspector shortcuts`,className:`fixed inset-x-0 bottom-0 z-[100] flex items-center bg-transparent px-4 pt-(--mobile-chrome-gap) pb-[calc(var(--mobile-chrome-gap)+env(safe-area-inset-bottom))] lg:hidden`,children:[(0,R.jsx)(`button`,{type:`button`,onClick:()=>n(!t),className:L(UH,t&&`text-foreground`),"aria-label":`RPC logs`,"aria-pressed":t,children:(0,R.jsx)(Pi,{className:`size-4 shrink-0`})}),(0,R.jsx)(`a`,{href:`https://github.com/mcp-use/mcp-use`,target:`_blank`,rel:`noopener noreferrer`,className:UH,"aria-label":`GitHub`,children:(0,R.jsx)(LB,{className:`size-4 shrink-0`})}),(0,R.jsx)(`a`,{href:`https://discord.gg/XkNkSkMz3V`,target:`_blank`,rel:`noopener noreferrer`,className:UH,"aria-label":`Discord`,children:(0,R.jsx)(HH,{className:`size-4 shrink-0`})}),(0,R.jsx)(`a`,{href:o,target:`_blank`,rel:`noopener noreferrer`,onClick:()=>{try{PT(new Mo({referrer:`mcp-use-inspector-mobile-toolbar`})).catch(()=>{})}catch{}},className:UH,"aria-label":`manufact.com`,children:(0,R.jsx)(NH,{size:16})})]}),document.body),!r&&(0,R.jsx)(CH,{open:t,onOpenChange:n,children:(0,R.jsxs)(DH,{side:`bottom`,className:`z-[101] flex h-[min(85dvh,720px)] flex-col gap-0 rounded-t-2xl border-zinc-200 p-0 dark:border-zinc-700`,children:[(0,R.jsx)(OH,{className:`sr-only`,children:(0,R.jsx)(kH,{children:`RPC logs`})}),(0,R.jsx)(`div`,{className:`flex min-h-0 flex-1 flex-col px-2 pb-2 pt-1`,children:(0,R.jsx)(vH,{serverIds:e?[e]:void 0})})]})})]})}function GH(e){return`${e.replace(/\/+$/,``)}${pM()}`}function KH({tunnelUrl:e,tunnelMcpUrl:t,selectedServerId:n,selectedServer:r,configLoaded:i,removeConnection:a,updateConnection:o,connections:s}){let c=(0,z.useRef)(null),l=(0,z.useRef)(!1),u=(0,z.useRef)(null),[d,f]=(0,z.useState)(!1);return(0,z.useEffect)(()=>{!d||r?.url!==u.current||r.state!==`ready`&&r.state!==`failed`||(f(!1),l.current=!1,u.current=null)},[d,r]),(0,z.useEffect)(()=>{n&&_M(n)?c.current=n:r?.url&&_M(r.url)&&(c.current=r.url)},[r?.url,n]),(0,z.useEffect)(()=>{if(!i||!n||!r||l.current)return;let d=r.url??``,p=_M(d),m=vM(d),h=t??(e?GH(e):null),g=null;e&&h&&p?g=h:!e&&m&&c.current&&(g=c.current),!(!g||g===d)&&(l.current=!0,u.current=g,f(!0),(async()=>{try{g!==n&&s.some(e=>e.id===g)&&await a(g),await o(n,PM({...IM(n)??FM(r),url:g}))}catch{f(!1),u.current=null,l.current=!1}})())},[i,s,a,r,n,t,e,o]),(0,z.useEffect)(()=>{d||(l.current=!1)},[d]),d}function qH({children:e}){let t=sP(),n=iP(),{servers:r,addServer:i,removeServer:a,updateServerMetadata:o,updateServer:s,storageLoaded:c}=Aj(),l=(0,z.useCallback)(async(e,t)=>{try{await s(e,PM(t)),AM(e,t)}catch(t){console.error(`[Layout] Failed to update connection ${e}:`,t)}},[s]),u=(0,z.useCallback)(async(e,t)=>{try{await o(e,t)}catch(t){console.error(`[Layout] Failed to update connection metadata for ${e}:`,t)}},[o]),{selectedServerId:d,setSelectedServerId:f,activeTab:p,setActiveTab:m,navigateToItem:h,setTunnelUrl:g,tunnelUrl:_,isEmbedded:v,embeddedConfig:y,setEmbeddedMode:b}=EL(),[x,S]=(0,z.useState)(!1),[C,w]=(0,z.useState)(()=>{try{return localStorage.getItem(`inspector-sidebar-collapsed`)===`true`}catch{return!1}}),[T,E]=(0,z.useState)(()=>{try{return localStorage.getItem(`inspector-rpc-logger-open`)===`true`}catch{return!1}});(0,z.useEffect)(()=>{try{localStorage.setItem(`inspector-sidebar-collapsed`,C?`true`:`false`)}catch{}},[C]),(0,z.useEffect)(()=>{try{localStorage.setItem(`inspector-rpc-logger-open`,String(T))}catch{}},[T]);let{savedRequests:ee}=kL();(0,z.useEffect)(()=>{let e=new URLSearchParams(n.search),t=e.get(`embedded`)===`true`,r=e.get(`embeddedConfig`);if(t){let e={};if(r)try{e=JSON.parse(r)}catch(e){console.error(`Failed to parse embeddedConfig:`,e)}b(!0,e),e.defaultTab&&m(e.defaultTab)}},[]),(0,z.useEffect)(()=>{let e=new URLSearchParams(n.search).get(`tunnelUrl`);e!==null&&g(e)},[n.search,g]),(0,z.useEffect)(()=>{let e=new URLSearchParams(n.search).get(`tab`);e&&[`tools`,`prompts`,`resources`,`chat`,`sampling`,`elicitation`,`notifications`,`server-metadata`,`connection-settings`].includes(e)&&m(e)},[n.search,m]);let D=(0,z.useRef)(null),te=(0,z.useRef)(Date.now()),ne=(0,z.useRef)(new Set),re=(0,z.useRef)(0);(0,z.useEffect)(()=>{let e=()=>{re.current++};return window.addEventListener(`mcp-tool-executed`,e),()=>window.removeEventListener(`mcp-tool-executed`,e)},[]),(0,z.useEffect)(()=>{let e=()=>{try{PT(new Io({durationSeconds:Math.round((Date.now()-te.current)/1e3),tabsVisited:ne.current.size,toolsExecuted:re.current})).catch(()=>{})}catch{}};return window.addEventListener(`beforeunload`,e),()=>window.removeEventListener(`beforeunload`,e)},[]);let O=(0,z.useCallback)(e=>{try{PT(new Po({tab:e,previousTab:D.current})).catch(()=>{})}catch{}D.current=e,ne.current.add(e),m(e);let r=new URLSearchParams(n.search);r.set(`tab`,e),t(`/?${r.toString()}`,{replace:!0})},[m,t,n.search]);(0,z.useEffect)(()=>{let e=e=>{let t=e.detail.requestId;d&&h(d,`sampling`,t)},t=e=>{let t=e.detail.requestId;d&&h(d,`elicitation`,t)},n=e=>{let t=e.detail.toolName;d&&t?h(d,`tools`,t):d&&O(`tools`)};return window.addEventListener(`navigate-to-sampling`,e),window.addEventListener(`navigate-to-elicitation`,t),window.addEventListener(`navigate-to-tool-result`,n),()=>{window.removeEventListener(`navigate-to-sampling`,e),window.removeEventListener(`navigate-to-elicitation`,t),window.removeEventListener(`navigate-to-tool-result`,n)}},[d,O,h]);let ie=(0,z.useRef)(null),k=(0,z.useRef)(null),A=(0,z.useRef)(null),{isAutoConnecting:j}=EI({connections:r,addServer:i,removeConnection:a,configLoaded:c,embedded:v});(0,z.useEffect)(()=>{let e=()=>{let e=document.documentElement.classList.contains(`dark`)?`#000000`:`#f3f3f3`;document.documentElement.style.backgroundColor=e,document.body.style.backgroundColor=e};e();let t=new MutationObserver(e);return t.observe(document.documentElement,{attributes:!0,attributeFilter:[`class`]}),()=>t.disconnect()},[]);let ae=(0,z.useCallback)(e=>{PT(new ko({trigger:e})).catch(()=>{}),S(!0)},[]),oe=e=>{if(!r.find(t=>t.id===e))return;f(e);let i=new URLSearchParams(n.search),a=i.get(`tunnelUrl`),o=i.get(`tab`),s=new URLSearchParams;s.set(`server`,e),a&&s.set(`tunnelUrl`,a),o&&s.set(`tab`,o),t(`/?${s.toString()}`)},se=(0,z.useCallback)(e=>{if(!d)return;let t=IM(d)||r.find(e=>e.id===d);e.url===d?t&&zM(t,e)?(u(d,{name:e.name||e.url}),AM(d,e)):l(d,e):(a(d),i(e.url,PM(e))),oI.success(`Connection settings updated`)},[d,r,a,i,u,l]),ce=(e,i,a)=>{if(console.warn(`[Layout] handleCommandPaletteNavigate called:`,{tab:e,itemName:i,serverId:a}),a){let o=r.find(e=>e.id===a);if(console.warn(`[Layout] Server lookup:`,{serverId:a,serverFound:!!o,serverState:o?.state}),!o||o.state!==`ready`){console.warn(`[Layout] Server not ready, showing error`),oI.error(`Server is not connected and cannot be inspected`);return}console.warn(`[Layout] Calling navigateToItem:`,{serverId:a,tab:e,itemName:i}),h(a,e,i);let s=new URLSearchParams(n.search),c=s.get(`tunnelUrl`),l=s.get(`tab`),u=new URLSearchParams;u.set(`server`,a),c&&u.set(`tunnelUrl`,c),e?u.set(`tab`,e):l&&u.set(`tab`,l);let d=`/?${u.toString()}`;console.warn(`[Layout] Navigating to:`,d),t(d)}else console.warn(`[Layout] No serverId, just updating tab to:`,e),O(e)},M=r.find(e=>e.id===d),N=KH({tunnelUrl:_,selectedServerId:d,selectedServer:M,configLoaded:c,removeConnection:a,updateConnection:s,connections:r}),le=M?M.tools.map(e=>({...e,_serverId:M.id})):r.flatMap(e=>e.state===`ready`?e.tools.map(t=>({...t,_serverId:e.id,_serverName:bM(e)})):[]),ue=M?M.prompts.map(e=>({...e,_serverId:M.id})):r.flatMap(e=>e.state===`ready`?e.prompts.map(t=>({...t,_serverId:e.id,_serverName:bM(e)})):[]),de=M?M.resources.map(e=>({...e,_serverId:M.id})):r.flatMap(e=>e.state===`ready`?e.resources.map(t=>({...t,_serverId:e.id,_serverName:bM(e)})):[]);(0,z.useEffect)(()=>{if(N)return;let e=new URLSearchParams(n.search),i=e.get(`server`);if(i&&(i.startsWith(`http://`)||i.startsWith(`https://`))&&!r.find(e=>e.id===i)){let n=new URLSearchParams(e);n.delete(`server`),n.set(`autoConnect`,i),t(`/?${n.toString()}`,{replace:!0});return}i!==d&&f(i)},[n.search,d,f,r,t,N]),(0,z.useEffect)(()=>{if(N)return;let e=new URLSearchParams(n.search).get(`server`);if(e&&!r.find(t=>t.id===e)){let e=setTimeout(()=>t(`/`),3e3);return()=>clearTimeout(e)}},[n.search,t,r,N]),(0,z.useEffect)(()=>{if(!v)return;let e=e=>{if(!e.data||typeof e.data!=`object`||e.data.type!==`mcp-inspector:connect_servers`)return;let t=e.data.servers;if(!Array.isArray(t)||t.length===0)return;let n=null;for(let e of t){if(!e.url||typeof e.url!=`string`)continue;let t=e.url,a=e.name??`Server`,o={...e.headers??{}};if(e.auth?.access_token){let t=e.auth.token_type||`bearer`;o.Authorization=`${t.charAt(0).toUpperCase()+t.slice(1)} ${e.auth.access_token}`}let s=typeof e.proxyConfig?.proxyAddress==`string`?e.proxyConfig.proxyAddress.trim():``,c=``;try{new URL(t).origin!==window.location.origin&&(c=TM())}catch{c=TM()}let l=s||c,u=EM(e.connectionMode,e.connectionType,!!s),d=PM({url:t,name:a,transportType:`http`,connectionMode:u,protocolNegotiation:CM(wM(e.protocolNegotiation)),connectionType:u===`proxy`?`Via Proxy`:`Direct`,proxyConfig:u===`proxy`&&l?{proxyAddress:l,...Object.keys(o).length>0?{headers:o}:{}}:void 0,headers:o,autoProxyFallback:u===`auto`&&l?{enabled:!0,proxyAddress:l}:!1});r.find(e=>e.url===t)||i(t,d),n||=t}window.parent!==window&&window.parent.postMessage({type:`mcp-inspector:servers_connected`,count:t.length},`*`)};return window.addEventListener(`message`,e),()=>window.removeEventListener(`message`,e)},[v,r,i]);let fe=(0,z.useRef)(!1);(0,z.useEffect)(()=>{if(!v||fe.current||d)return;let e=r.find(e=>e.state===`ready`);if(e){fe.current=!0,f(e.id);let r=new URLSearchParams(n.search);r.set(`server`,e.id),t(`/?${r.toString()}`,{replace:!0})}},[v,r,d,f,t,n.search]),DL({onCommandPalette:()=>ae(`keyboard`),onToolsTab:()=>{M&&O(`tools`)},onPromptsTab:()=>{M&&O(`prompts`)},onResourcesTab:()=>{M&&O(`resources`)},onChatTab:()=>{M&&O(`chat`)},onHome:()=>{t(`/`)},onFocusSearch:()=>{p===`tools`&&ie.current?ie.current.focusSearch():p===`prompts`&&k.current?k.current.focusSearch():p===`resources`&&A.current&&A.current.focusSearch()},onBlurSearch:()=>{p===`tools`&&ie.current?ie.current.blurSearch():p===`prompts`&&k.current?k.current.blurSearch():p===`resources`&&A.current&&A.current.blurSearch()}});let pe=new URLSearchParams(n.search).get(`server`),me=!c&&!!pe&&!pe.startsWith(`http://`)&&!pe.startsWith(`https://`),he=j||me||N,ge=M?.id??`home`,_e=he?`boot`:ge,[ve,ye]=(0,z.useState)(_e);(0,z.useLayoutEffect)(()=>{if(_e===ve)return;let e=()=>(0,br.flushSync)(()=>ye(_e));typeof document.startViewTransition==`function`?document.startViewTransition(e):e()},[_e,ve]);let be=ve===`boot`,xe=be||ve===`home`?void 0:r.find(e=>e.id===ve),P=v&&y.singleTab,Se=v?{backgroundColor:y.backgroundColor||`#f3f3f3`,padding:P?`0`:y.padding||`0.5rem`}:{},Ce=v?P?`h-screen flex flex-col`:`h-screen flex flex-col gap-2 sm:gap-4`:`h-screen bg-[#f3f3f3] dark:bg-black flex flex-col overflow-x-hidden px-4 lg:px-0 pb-[calc(var(--mobile-toolbar-height)+env(safe-area-inset-bottom))] lg:pb-4`,we=P?`flex-1 w-full bg-white dark:bg-black p-0 overflow-auto`:L(`flex-1 min-h-0 min-w-0 max-w-full w-full bg-white dark:bg-black rounded-2xl border border-zinc-200 dark:border-zinc-700 overflow-x-hidden overflow-y-auto`,!xe&&`lg:mx-4`,xe&&`lg:mr-4`);return(0,R.jsxs)(Ve,{children:[(0,R.jsx)(`div`,{className:`inspector-view-transition h-screen overflow-x-hidden bg-[#f3f3f3] dark:bg-black`,children:be?(0,R.jsx)(`div`,{className:`flex h-full items-center justify-center bg-[#f3f3f3] dark:bg-black`,children:(0,R.jsxs)(`div`,{className:`flex flex-col items-center gap-4`,children:[(0,R.jsx)(bL,{className:`h-8 w-8 text-zinc-600 dark:text-zinc-400`}),(0,R.jsx)(`p`,{className:`text-sm text-zinc-600 dark:text-zinc-400`,children:`Connecting to MCP server...`})]})}):(0,R.jsxs)(`div`,{className:Ce,style:Se,children:[!P&&(0,R.jsx)(FB,{connections:r,selectedServer:xe,activeTab:p,onServerSelect:oe,onTabChange:O,embedded:v,sidebarCollapsed:C}),(0,R.jsxs)(`div`,{className:P?`flex-1 min-h-0`:`flex min-w-0 flex-1 min-h-0 overflow-hidden`,children:[xe&&!P&&(0,R.jsx)(CV,{activeTab:p,onTabChange:O,selectedServer:xe,visibleTabs:y.visibleTabs,collapsed:C,onCollapsedChange:w,rpcLoggerOpen:T,onRpcLoggerOpenChange:E,onCommandPaletteOpen:()=>ae(`button`)}),(0,R.jsx)(`main`,{className:we,children:(0,R.jsx)(az,{selectedServer:xe,activeTab:p,toolsSearchRef:ie,promptsSearchRef:k,resourcesSearchRef:A,onUpdateConnection:se,children:e})}),xe&&!P&&(0,R.jsx)(SH,{serverId:xe.id,open:T})]})]})}),!P&&!be&&(0,R.jsx)(WH,{serverId:xe?.id,rpcLoggerOpen:T,onRpcLoggerOpenChange:E}),(0,R.jsx)(KL,{isOpen:x,onOpenChange:S,tools:le,prompts:ue,resources:de,savedRequests:ee,connections:r,selectedServer:M,tunnelUrl:_,onNavigate:ce,onServerSelect:oe})]})}function JH({...e}){let{resolvedTheme:t}=Fz();return(0,R.jsx)(xI,{theme:t,className:`toaster group`,style:{"--normal-bg":`var(--popover)`,"--normal-text":`var(--popover-foreground)`,"--normal-border":`var(--border)`},...e})}var YH=(0,z.createContext)(void 0),XH={deviceType:`desktop`,customViewport:{width:768,height:1024},cspMode:`permissive`,displayModeOverride:null,capabilities:{hover:!0,touch:!1},safeAreaInsets:{top:0,right:0,bottom:0,left:0},locale:`en-US`,timeZone:Intl.DateTimeFormat().resolvedOptions().timeZone||`UTC`};function ZH({children:e}){let[t,n]=(0,z.useState)({activeWidgetId:null,widgets:new Map,playground:XH}),r=(0,z.useCallback)(e=>{n(t=>({...t,activeWidgetId:e}))},[]),i=(0,z.useCallback)((e,t)=>{n(n=>{if(n.widgets.has(e))return n;let r=new Map(n.widgets);return r.set(e,{...t,cspViolations:[]}),{...n,widgets:r}})},[]),a=(0,z.useCallback)(e=>{n(t=>{let n=new Map(t.widgets);return n.delete(e),{...t,widgets:n,activeWidgetId:t.activeWidgetId===e?null:t.activeWidgetId}})},[]),o=(0,z.useRef)(t);o.current=t;let s=(0,z.useCallback)(e=>o.current.widgets.get(e),[]),c=(0,z.useCallback)((e,t)=>{n(n=>{let r=n.widgets.get(e);if(!r)return n;let i={cspViolations:[...r.cspViolations,t]};t.originalPolicy&&r.effectivePolicy===void 0&&(i.effectivePolicy=t.originalPolicy);let a=new Map(n.widgets);return a.set(e,{...r,...i}),{...n,widgets:a}})},[]),l=(0,z.useCallback)(e=>{n(t=>{let n=t.widgets.get(e);if(!n)return t;let r=new Map(t.widgets);return r.set(e,{...n,cspViolations:[]}),{...t,widgets:r}})},[]),u=(0,z.useCallback)((e,t)=>{n(n=>{let r=n.widgets.get(e);if(!r)return n;let i=new Map(n.widgets);return i.set(e,{...r,modelContext:t}),{...n,widgets:i}})},[]),d=(0,z.useCallback)((e,t)=>{n(n=>{let r=n.widgets.get(e);if(!r)return n;let i=new Map(n.widgets);return i.set(e,{...r,widgetState:t}),{...n,widgets:i}})},[]),f=(0,z.useCallback)((e,t,r)=>{n(n=>{let i=n.widgets.get(e);if(!i)return n;let a=new Map(n.widgets);return a.set(e,{...i,declaredCsp:t,...r!==void 0&&{effectivePolicy:r}}),{...n,widgets:a}})},[]),p=(0,z.useCallback)(e=>{n(t=>({...t,playground:{...t.playground,...e}}))},[]),m=(0,z.useCallback)(()=>{n(e=>({...e,widgets:new Map,activeWidgetId:null}))},[]),h=(0,z.useCallback)(()=>{let e=new Map;for(let[n,r]of t.widgets)r.modelContext&&e.set(n,r.modelContext);return e},[t.widgets]);return(0,R.jsx)(YH,{value:(0,z.useMemo)(()=>({...t,setActiveWidget:r,addWidget:i,removeWidget:a,getWidget:s,addCspViolation:c,clearCspViolations:l,setWidgetModelContext:u,setWidgetState:d,setWidgetDeclaredCsp:f,updatePlaygroundSettings:p,clearAllWidgets:m,getAllModelContexts:h}),[t,r,i,a,s,c,l,u,d,f,p,m,h]),children:e})}function QH(){let e=(0,z.use)(YH);if(!e)throw Error(`useWidgetDebug must be used within WidgetDebugProvider`);return e}var $H={mobile:{width:390,height:844,name:`iPhone 14`},desktop:{width:1440,height:900,name:`Desktop`}},eU=(0,z.lazy)(()=>lS(()=>import(`./OAuthCallback-Dv_mFcua.js`).then(e=>({default:e.OAuthCallback})),__vite__mapDeps([39,1,3]))),tU=(0,z.lazy)(()=>lS(()=>import(`./ManufactOAuthCallback-BnWhf5bW.js`).then(e=>({default:e.ManufactOAuthCallback})),__vite__mapDeps([40,1,3]))),nU=(0,z.lazy)(()=>lS(()=>import(`./ViewPreview-C_LJdgt9.js`).then(e=>({default:e.ViewPreview})),__vite__mapDeps([41,1,3,18,2])));function rU({activeTabRef:e}){let{activeTab:t}=EL();return(0,z.useEffect)(()=>{e.current=t},[t,e]),null}function iU(){let e=(0,z.useRef)(`tools`),t=new URLSearchParams(window.location.search),n=t.get(`embedded`)===`true`,r=t.get(`theme`),i=(0,z.useMemo)(()=>n?void 0:new BM(`mcp-inspector-connections`),[n]),a=TM(),o=a?.replace(/\/proxy\/?$/,`/oauth`),s=mM();return(0,z.useEffect)(()=>{MT()},[]),(0,z.useEffect)(()=>{let e=t.get(`auth_error`);if(!e)return;let n=t.get(`auth_error_description`);oI.error(`OAuth authentication failed: ${n||e}`,{duration:1/0,closeButton:!0});let r=new URLSearchParams(t);r.delete(`auth_error`),r.delete(`auth_error_description`);let i=r.toString();window.history.replaceState({},``,`${window.location.pathname}${i?`?${i}`:``}`)},[]),(0,R.jsx)(Iz,{forcedTheme:r||void 0,children:(0,R.jsx)(Jt,{defaultShape:`pill`,children:(0,R.jsx)(ZH,{children:(0,R.jsx)(kj,{storageProvider:i,enableRpcLogging:!0,defaultCallbackUrl:`${window.location.origin}${s}/oauth/callback`,defaultOAuthProxyUrl:o,defaultAutoProxyFallback:a?{enabled:!0,proxyAddress:a}:!1,defaultServerConfig:{preventAutoAuth:!0,useRedirectFlow:!0},clientInfo:{name:`mcp-use Inspector`,version:Lo(),websiteUrl:`https://mcp-use.com`,icons:[{src:`https://mcp-use.com/logo.png`}],capabilities:{extensions:{"io.modelcontextprotocol/ui":{mimeTypes:[`text/html;profile=mcp-app`]}}}},onServerAdded:(e,t)=>{console.log(`[Inspector] Server added:`,e,t.state)},onServerRemoved:e=>{console.log(`[Inspector] Server removed:`,e)},onServerStateChange:(e,t)=>{console.log(`[Inspector] Server state changed:`,e,t)},onSamplingRequest:(e,t,n,r,i)=>{let a=oI((0,R.jsx)(Fn,{title:`Sampling Request Received`,description:`New request from ${n}`,actions:[{label:`View Details`,testId:`sampling-toast-view-details`,onClick:()=>{let t=new CustomEvent(`navigate-to-sampling`,{detail:{requestId:e.id}});window.dispatchEvent(t),oI.dismiss(a)}},{label:`Approve`,testId:`sampling-toast-approve`,onClick:()=>{r(e.id,In),oI.success(`Sampling request approved`),oI.dismiss(a)}},{label:`Deny`,testId:`sampling-toast-deny`,onClick:()=>{i(e.id,`User denied from toast`),oI.dismiss(a)}}]}),{duration:1/0})},onElicitationRequest:(t,n,r,i,a)=>{if(e.current===`chat`)return;let o=t.request.mode||`form`,s=t.request.message,c=o===`url`&&`url`in t.request?t.request.url:void 0,l=oI((0,R.jsx)(Fn,{title:`Elicitation Request Received`,description:`From ${r}: ${s}`,extra:o===`url`&&c?(0,R.jsx)(`p`,{className:`text-xs text-muted-foreground mt-1 font-mono`,children:c}):void 0,actions:[{label:`View Details`,testId:`elicitation-toast-view-details`,onClick:()=>{let e=new CustomEvent(`navigate-to-elicitation`,{detail:{requestId:t.id}});window.dispatchEvent(e),oI.dismiss(l)}},...o===`url`&&c?[{label:`Open URL`,testId:`elicitation-toast-open-url`,onClick:()=>{window.open(c,`_blank`),oI.dismiss(l)}}]:[],{label:`Cancel`,testId:`elicitation-toast-cancel`,onClick:()=>{a(t.id,`User cancelled from toast`),oI.dismiss(l)}}]}),{duration:1/0})},children:(0,R.jsxs)(TL,{children:[(0,R.jsx)(rU,{activeTabRef:e}),(0,R.jsx)(wF,{basename:s,children:(0,R.jsxs)(FP,{children:[(0,R.jsx)(NP,{path:`/oauth/callback`,element:(0,R.jsx)(JR,{children:(0,R.jsx)(eU,{})})}),(0,R.jsx)(NP,{path:`/auth/callback`,element:(0,R.jsx)(JR,{children:(0,R.jsx)(tU,{})})}),(0,R.jsx)(NP,{path:`/preview/:view`,element:(0,R.jsx)(JR,{children:(0,R.jsx)(nU,{})})}),(0,R.jsx)(NP,{path:`/`,element:(0,R.jsx)(qH,{children:(0,R.jsx)(CL,{})})})]})}),(0,R.jsx)(JH,{position:`top-center`})]})})})})})}var aU=document.getElementById(`root`);aU?Pn.createRoot(aU).render((0,R.jsx)(iU,{})):console.error(`[inspector] Root element not found`);export{zI as $,Wi as $t,mz as A,Q as At,uL as B,go as Bt,TV as C,Mr as Cn,qj as Ct,_B as D,Aj as Dt,hB as E,_r as En,gj as Et,bL as F,Eo as Ft,hL as G,Ya as Gt,mL as H,vo as Ht,yL as I,wo as It,eL as J,Xa as Jt,lL as K,Za as Kt,vL as L,Co as Lt,kL as M,Bb as Mt,DL as N,Cf as Nt,gB as O,PT as Ot,EL as P,No as Pt,BI as Q,Gi as Qt,cL as R,So as Rt,jV as S,Fr as Sn,oM as St,HB as T,vr as Tn,Jj as Tt,dL as U,mo as Ut,gL as V,bo as Vt,pL as W,ro as Wt,qI as X,Xi as Xt,JI as Y,Ia as Yt,VI as Z,Yi as Zt,ZV as _,Yr as _n,xM as _t,VH as a,xi as an,kI as at,VV as b,Vr as bn,lM as bt,CH as c,fi as cn,FF as ct,OH as d,ai as dn,IM as dt,zi as en,PI as et,kH as f,ri as fn,wM as ft,QV as g,Xr as gn,bM as gt,$V as h,Zr as hn,yM as ht,RH as i,Ti as in,OI as it,NR as j,lS as jt,Fz as k,KC as kt,DH as l,ci as ln,jM as lt,mH as m,$r as mn,FM as mt,QH as n,Ai as nn,jI as nt,LH as o,bi as on,oI as ot,wH as p,ti as pn,CM as pt,nL as q,$a as qt,MH as r,ki as rn,AI as rt,zH as s,yi as sn,lP as st,$H as t,Ii as tn,DI as tt,AH as u,si as un,TM as ut,qV as v,qr as vn,pM as vt,nV as w,jr as wn,Yj as wt,AV as x,Ir as xn,uM as xt,KV as y,Wr as yn,hM as yt,fL as z,Ao as zt};
|
|
499
|
+
`;for(let{name:n}of e)t+=`export ${n}="your-${n}-value"\n`;return t}function vL({className:e,size:t=`md`}){return(0,R.jsxs)(`svg`,{viewBox:`0 0 500 500`,className:L(`text-current`,{sm:`h-4 w-4`,md:`h-5 w-5`,lg:`h-6 w-6`}[t],e),fill:`currentColor`,fillRule:`nonzero`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,R.jsx)(`path`,{d:`M105.933 0C164.437 0.000116002 211.865 47.607 211.865 106.333C211.865 131.829 210.493 158.403 221.068 181.602L228.975 198.947C243.584 230.997 269.265 256.7 301.303 271.336L316.155 278.121C340.142 289.079 367.694 287.335 394.066 287.335C452.571 287.335 499.999 334.942 499.999 393.668C499.999 452.394 452.571 500.001 394.066 500.001C335.562 500.001 288.134 452.394 288.134 393.668C288.134 368.974 289.24 343.275 278.992 320.807L270.586 302.38C255.948 270.29 230.214 244.565 198.118 229.939L180.164 221.758C157.282 211.331 131.078 212.666 105.933 212.666C47.4278 212.666 4.86252e-05 165.059 0 106.333C0 47.607 47.4278 0 105.933 0Z`}),(0,R.jsx)(`circle`,{cx:`100.426`,cy:`399.575`,r:`100.426`}),(0,R.jsx)(`path`,{d:`M500 100.426C500 155.889 455.037 200.851 399.574 200.851C344.11 200.851 299.148 155.889 299.148 100.426C299.148 44.962 344.11 0 399.574 0C455.037 0 500 44.962 500 100.426Z`})]})}function yL({className:e}){return(0,R.jsx)(`svg`,{viewBox:`0 0 24 24`,className:e,fill:`currentColor`,xmlns:`http://www.w3.org/2000/svg`,children:(0,R.jsx)(`path`,{d:`M23.15 2.587L18.21.21a1.494 1.494 0 0 0-1.705.29l-9.46 8.63-4.12-3.128a.999.999 0 0 0-1.276.057L.327 7.261A1 1 0 0 0 .326 8.74L3.899 12 .326 15.26a1 1 0 0 0 .001 1.479L1.65 17.94a.999.999 0 0 0 1.276.057l4.12-3.128 9.46 8.63a1.492 1.492 0 0 0 1.704.29l4.942-2.377A1.5 1.5 0 0 0 24 20.06V3.939a1.5 1.5 0 0 0-.85-1.352zm-5.146 14.861L10.826 12l7.178-5.448v10.896z`})})}function bL({className:e}){return(0,R.jsxs)(`svg`,{fill:`currentColor`,fillRule:`evenodd`,viewBox:`0 0 24 24`,className:e,xmlns:`http://www.w3.org/2000/svg`,"aria-label":`ModelContextProtocol`,children:[(0,R.jsx)(`path`,{d:`M15.688 2.343a2.588 2.588 0 00-3.61 0l-9.626 9.44a.863.863 0 01-1.203 0 .823.823 0 010-1.18l9.626-9.44a4.313 4.313 0 016.016 0 4.116 4.116 0 011.204 3.54 4.3 4.3 0 013.609 1.18l.05.05a4.115 4.115 0 010 5.9l-8.706 8.537a.274.274 0 000 .393l1.788 1.754a.823.823 0 010 1.18.863.863 0 01-1.203 0l-1.788-1.753a1.92 1.92 0 010-2.754l8.706-8.538a2.47 2.47 0 000-3.54l-.05-.049a2.588 2.588 0 00-3.607-.003l-7.172 7.034-.002.002-.098.097a.863.863 0 01-1.204 0 .823.823 0 010-1.18l7.273-7.133a2.47 2.47 0 00-.003-3.537z`}),(0,R.jsx)(`path`,{d:`M14.485 4.703a.823.823 0 000-1.18.863.863 0 00-1.204 0l-7.119 6.982a4.115 4.115 0 000 5.9 4.314 4.314 0 006.016 0l7.12-6.982a.823.823 0 000-1.18.863.863 0 00-1.204 0l-7.119 6.982a2.588 2.588 0 01-3.61 0 2.47 2.47 0 010-3.54l7.12-6.982z`})]})}function xL({className:e}){return(0,R.jsx)(`svg`,{viewBox:`0 -28.5 256 256`,className:e,fill:`currentColor`,xmlns:`http://www.w3.org/2000/svg`,children:(0,R.jsx)(`path`,{d:`M216.856339,16.5966031 C200.285002,8.84328665 182.566144,3.2084988 164.041564,0 C161.766523,4.11318106 159.108624,9.64549908 157.276099,14.0464379 C137.583995,11.0849896 118.072967,11.0849896 98.7430163,14.0464379 C96.9108417,9.64549908 94.1925838,4.11318106 91.8971895,0 C73.3526068,3.2084988 55.6133949,8.86399117 39.0420583,16.6376612 C5.61752293,67.146514 -3.4433191,116.400813 1.08711069,164.955721 C23.2560196,181.510915 44.7403634,191.567697 65.8621325,198.148576 C71.0772151,190.971126 75.7283628,183.341335 79.7352139,175.300261 C72.104019,172.400575 64.7949724,168.822202 57.8887866,164.667963 C59.7209612,163.310589 61.5131304,161.891452 63.2445898,160.431257 C105.36741,180.133187 151.134928,180.133187 192.754523,160.431257 C194.506336,161.891452 196.298154,163.310589 198.110326,164.667963 C191.183787,168.842556 183.854737,172.420929 176.223542,175.320965 C180.230393,183.341335 184.861538,190.991831 190.096624,198.16893 C211.238746,191.588051 232.743023,181.531619 254.911949,164.955721 C260.227747,108.668201 245.831087,59.8662432 216.856339,16.5966031 Z M85.4738752,135.09489 C72.8290281,135.09489 62.4592217,123.290155 62.4592217,108.914901 C62.4592217,94.5396472 72.607595,82.7145587 85.4738752,82.7145587 C98.3405064,82.7145587 108.709962,94.5189427 108.488529,108.914901 C108.508531,123.290155 98.3405064,135.09489 85.4738752,135.09489 Z M170.525237,135.09489 C157.88039,135.09489 147.510584,123.290155 147.510584,108.914901 C147.510584,94.5396472 157.658606,82.7145587 170.525237,82.7145587 C183.391518,82.7145587 193.761324,94.5189427 193.539891,108.914901 C193.539891,123.290155 183.391518,135.09489 170.525237,135.09489 Z`,fillRule:`nonzero`})})}function SL({isOpen:e,onOpenChange:t,tools:n,prompts:r,resources:i,savedRequests:a,connections:o,selectedServer:s,tunnelUrl:c,onNavigate:l,onServerSelect:u}){let[d,f]=(0,z.useState)(``),[p,m]=(0,z.useState)(0),h=(0,z.useRef)(null),g=(0,z.useRef)(null),_=LN(),y=kt.pill,{activeIndex:b,itemRects:x,sessionRef:S,handlers:C,registerItem:w,measureItems:T}=_n(h),E=s?c?`${c}/mcp`:s.url:null,ee=s?.name||`MCP Server`,D=s?cM(s):void 0,te=s?[{id:`open-in-cursor`,name:`Open in Cursor`,description:`Add this server to Cursor`,type:`global`,category:`Open in Client`,action:()=>{try{let e=lL(E,ee,D);window.location.href=e,IF.success(`Opening in Cursor...`),t(!1)}catch{IF.error(`Failed to open in Cursor`)}}},{id:`open-in-claude-code`,name:`Open in Claude Code`,description:`Add this server to Claude Code CLI`,type:`global`,category:`Open in Client`,action:()=>{let{command:e}=mL(E,ee,D);zj(e),IF.success(`Command copied to clipboard`),t(!1)}},{id:`open-in-claude-desktop`,name:`Open in Claude Desktop`,description:`Download .mcpb configuration file`,type:`global`,category:`Open in Client`,action:()=>{try{pL(E,ee,D),IF.success(`Downloaded .mcpb file`),t(!1)}catch{IF.error(`Failed to download configuration file`)}}},{id:`open-in-vscode`,name:`Open in VS Code`,description:`Add this server to VS Code`,type:`global`,category:`Open in Client`,action:()=>{try{let e=uL(E,ee,D);window.location.href=e,IF.success(`Opening in VS Code...`),t(!1)}catch{IF.error(`Failed to open in VS Code`)}}},{id:`open-in-vscode-insiders`,name:`Open in VS Code Insiders`,description:`Add this server to VS Code Insiders`,type:`global`,category:`Open in Client`,action:()=>{try{let e=dL(E,ee,D);window.location.href=e,IF.success(`Opening in VS Code Insiders...`),t(!1)}catch{IF.error(`Failed to open in VS Code Insiders`)}}},{id:`open-in-gemini`,name:`Open in Gemini CLI`,description:`Add this server to Gemini CLI`,type:`global`,category:`Open in Client`,action:()=>{let{command:e}=hL(E,ee,D);zj(e),IF.success(`Command copied to clipboard`),t(!1)}},{id:`open-in-codex`,name:`Open in Codex CLI`,description:`Add this server to Codex CLI`,type:`global`,category:`Open in Client`,action:()=>{let{config:e}=gL(E,ee,D);zj(e),IF.success(`Config copied to clipboard`),t(!1)}}]:[],ne=[{id:`connect-server`,name:`Connect Server`,description:`Add a new MCP server connection`,type:`global`,category:`Navigation`,action:()=>_(`/`)},{id:`mcp-use-website`,name:`MCP Use Website`,description:`Visit mcp-use.com for tools and resources`,type:`global`,category:`Documentation`,action:()=>window.open(`https://mcp-use.com`,`_blank`)},{id:`mcp-use-docs`,name:`How to Create an MCP Server`,description:`Step-by-step guide to building MCP servers`,type:`global`,category:`Documentation`,action:()=>window.open(`https://mcp-use.com/docs`,`_blank`)},{id:`mcp-docs`,name:`MCP Official Documentation`,description:`Learn about the Model Context Protocol`,type:`global`,category:`Documentation`,action:()=>window.open(`https://modelcontextprotocol.io/docs/getting-started/intro`,`_blank`)},{id:`discord`,name:`Join Discord Community`,description:`Connect with the MCP community`,type:`global`,category:`Community`,action:()=>window.open(`https://discord.gg/XkNkSkMz3V`,`_blank`)},{id:`clear-localstorage`,name:`Clear localStorage & Reload`,description:`Having trouble connecting? Clear stored auth data and refresh`,type:`global`,category:`Troubleshooting`,action:()=>{let e=[];for(let t=0;t<localStorage.length;t++){let n=localStorage.key(t);n&&(n.startsWith(`mcp:auth`)||n.startsWith(`mcp-inspector`))&&e.push(n)}e.forEach(e=>localStorage.removeItem(e)),IF.success(`Cleared ${e.length} localStorage item(s). Refreshing page...`,{duration:2e3}),setTimeout(()=>{window.location.reload()},500),t(!1)}}],re=o.map(e=>({id:`server-${e.id}`,name:Xj(e),description:`Connected server (${e.state})`,type:`global`,category:`Connected Servers`,metadata:{serverId:e.id,state:e.state},action:()=>u(e.id)})),O=[...ne,...te,...re,...n.map(e=>({id:`tool-${e.name}`,name:e.name,description:e.description,type:`tool`,category:e._serverName?`Tools - ${e._serverName}`:`Tools`,metadata:{inputSchema:e.inputSchema,serverId:e._serverId,serverName:e._serverName}})),...r.map(e=>({id:`prompt-${e.name}`,name:e.name,description:e.description,type:`prompt`,category:e._serverName?`Prompts - ${e._serverName}`:`Prompts`,metadata:{arguments:e.arguments,serverId:e._serverId,serverName:e._serverName}})),...i.map(e=>({id:`resource-${e.uri}`,name:e.name,description:e.description,type:`resource`,category:e._serverName?`Resources - ${e._serverName}`:`Resources`,metadata:{uri:e.uri,mimeType:e.mimeType,serverId:e._serverId,serverName:e._serverName}})),...a.map(e=>({id:`saved-${e.id}`,name:e.name,description:`Saved request for ${e.toolName}`,type:`saved-request`,category:`Saved Requests`,metadata:{toolName:e.toolName,args:e.args,savedAt:e.savedAt,serverId:e.serverId,serverName:e.serverName}}))].filter(e=>d.trim()?`${e.name} ${e.description||``} ${e.category}`.toLowerCase().includes(d.trim().toLowerCase()):!0),ie=(0,z.useCallback)(e=>{if(console.warn(`[CommandPalette] Item selected:`,{itemType:e.type,itemName:e.name,itemId:e.id,metadata:e.metadata}),e.action)console.warn(`[CommandPalette] Executing action for global item`),e.action(),t(!1);else if(e.type===`global`)e.metadata?.serverId&&(console.warn(`[CommandPalette] Selecting server:`,e.metadata.serverId),u(e.metadata.serverId),t(!1));else{let n=e.type===`resource`?e.metadata?.uri:e.name,r=e.type===`tool`?`tools`:e.type===`prompt`?`prompts`:e.type===`saved-request`?`tools`:`resources`;console.warn(`[CommandPalette] Navigating to item:`,{tab:r,itemIdentifier:n,serverId:e.metadata?.serverId}),l(r,n,e.metadata?.serverId),t(!1)}},[l,t,u]),k=(e,t,n)=>{switch(e){case`tool`:return(0,R.jsx)(`div`,{className:`bg-blue-500/20 rounded-full p-2 flex items-center justify-center shrink-0`,children:(0,R.jsx)(Yi,{className:`h-4 w-4 text-blue-500`})});case`prompt`:return(0,R.jsx)(`div`,{className:`bg-purple-500/20 rounded-full p-2 flex items-center justify-center shrink-0`,children:(0,R.jsx)(yi,{className:`h-4 w-4 text-purple-500`})});case`resource`:return(0,R.jsx)(`div`,{className:`bg-green-500/20 rounded-full p-2 flex items-center justify-center shrink-0`,children:(0,R.jsx)(Qr,{className:`h-4 w-4 text-green-500`})});case`saved-request`:return(0,R.jsx)(`div`,{className:`bg-orange-500/20 rounded-full p-2 flex items-center justify-center shrink-0`,children:(0,R.jsx)(ri,{className:`h-4 w-4 text-orange-500`})});case`global`:if(t===`Navigation`)return(0,R.jsx)(`div`,{className:`bg-gray-500/20 rounded-full p-2 flex items-center justify-center shrink-0`,children:(0,R.jsx)(Ai,{className:`h-4 w-4 text-gray-600 dark:text-gray-300`})});if(t===`Open in Client`){if(n?.includes(`Cursor`))return(0,R.jsx)(`div`,{className:`bg-gray-200 dark:bg-gray-800 rounded-full p-2 flex items-center justify-center shrink-0`,children:(0,R.jsx)(`img`,{src:`https://cdn.simpleicons.org/cursor`,alt:`Cursor`,className:`h-4 w-4`})});if(n?.includes(`Claude Code`)||n?.includes(`Claude Desktop`))return(0,R.jsx)(`div`,{className:`bg-orange-500/20 rounded-full p-2 flex items-center justify-center shrink-0`,children:(0,R.jsx)(`img`,{src:`https://cdn.simpleicons.org/claude`,alt:`Claude`,className:`h-4 w-4`})});if(n?.includes(`VS Code`))return(0,R.jsx)(`div`,{className:`bg-blue-600/20 rounded-full p-2 flex items-center justify-center shrink-0`,children:(0,R.jsx)(yL,{className:`h-4 w-4 text-blue-600`})});if(n?.includes(`Gemini`))return(0,R.jsx)(`div`,{className:`bg-purple-500/20 rounded-full p-2 flex items-center justify-center shrink-0`,children:(0,R.jsx)(`img`,{src:`https://cdn.simpleicons.org/googlegemini`,alt:`Gemini`,className:`h-4 w-4`})});if(n?.includes(`Codex`))return(0,R.jsx)(`div`,{className:`bg-green-500/20 rounded-full p-2 flex items-center justify-center shrink-0`,children:(0,R.jsx)(`img`,{src:`https://inspector-cdn.mcp-use.com/providers/openai.png`,alt:`Codex`,className:`h-4 w-4`})})}return t===`Documentation`?n?.includes(`MCP Use`)||n?.includes(`mcp-use`)?(0,R.jsx)(`div`,{className:`bg-black/10 dark:bg-white/10 rounded-full p-2 flex items-center justify-center shrink-0`,children:(0,R.jsx)(vL,{className:`h-4 w-4 text-black dark:text-white`,size:`sm`})}):(0,R.jsx)(`div`,{className:`bg-orange-500/20 rounded-full p-2 flex items-center justify-center shrink-0`,children:(0,R.jsx)(Yr,{className:`h-4 w-4 text-orange-500`})}):t===`Community`?(0,R.jsx)(`div`,{className:`bg-purple-500/20 rounded-full p-2 flex items-center justify-center shrink-0`,children:(0,R.jsx)(xL,{className:`h-4 w-4 text-purple-500`})}):t===`Troubleshooting`?(0,R.jsx)(`div`,{className:`bg-yellow-500/20 rounded-full p-2 flex items-center justify-center shrink-0`,children:(0,R.jsx)(Pr,{className:`h-4 w-4 text-yellow-500`})}):t===`Connected Servers`?(0,R.jsx)(`div`,{className:`bg-cyan-500/20 rounded-full p-2 flex items-center justify-center shrink-0`,children:(0,R.jsx)(Fi,{className:`h-4 w-4 text-cyan-500`})}):(0,R.jsx)(`div`,{className:`bg-gray-500/20 rounded-full p-2 flex items-center justify-center shrink-0`,children:(0,R.jsx)(Yr,{className:`h-4 w-4 text-gray-500`})});default:return(0,R.jsx)(`div`,{className:`bg-gray-500/20 rounded-full p-2 flex items-center justify-center shrink-0`,children:(0,R.jsx)(v,{className:`h-4 w-4 text-gray-500`})})}};(0,z.useEffect)(()=>{e&&(f(``),m(0),requestAnimationFrame(()=>g.current?.focus()))},[e]),(0,z.useEffect)(()=>{h.current&&(h.current.scrollTop=0),m(0)},[d]),(0,z.useEffect)(()=>{p>=O.length&&m(Math.max(0,O.length-1))},[p,O.length]),(0,z.useLayoutEffect)(()=>{e&&T()},[e,T,O]);let A=x[p]??null,j=b===null?null:x[b],ae=b!==null&&b!==p;return e?(0,R.jsxs)(R.Fragment,{children:[(0,R.jsx)(`button`,{type:`button`,className:`fixed inset-0 z-50 bg-black/40 backdrop-blur-sm`,"aria-label":`Close command palette`,onClick:()=>t(!1)}),(0,R.jsxs)(`div`,{role:`dialog`,"aria-label":`Command Palette`,"data-testid":`command-palette-dialog`,className:`fixed left-1/2 top-1/2 -translate-x-1/2 -translate-y-1/2 z-[51] max-w-[640px] w-[calc(100vw-2rem)] sm:w-full p-2 bg-white dark:bg-zinc-900/90 backdrop-blur-xl rounded-xl overflow-hidden border border-border shadow-[var(--cmdk-shadow)] transition-transform duration-100 ease-out outline-none`,onKeyDown:e=>{e.key===`ArrowDown`?(e.preventDefault(),m(e=>Math.min(e+1,O.length-1))):e.key===`ArrowUp`?(e.preventDefault(),m(e=>Math.max(e-1,0))):e.key===`Enter`&&O[p]?(e.preventDefault(),ie(O[p])):e.key===`Escape`&&(e.preventDefault(),t(!1))},children:[(0,R.jsx)(`input`,{ref:g,placeholder:`What do you need?`,value:d,onChange:e=>f(e.target.value),className:`border-none w-full text-[17px] px-4 pt-2 pb-4 outline-none bg-transparent text-foreground border-b border-border mb-0 rounded-none placeholder:text-muted-foreground`,"data-testid":`command-palette-input`}),(0,R.jsxs)(`div`,{ref:h,onMouseEnter:C.onMouseEnter,onMouseMove:C.onMouseMove,onMouseLeave:C.onMouseLeave,className:`relative isolate min-h-[200px] sm:min-h-[330px] max-h-[400px] overflow-auto overscroll-contain transition-[height] duration-100 ease-out px-1`,"data-testid":`command-palette-list`,children:[(0,R.jsx)(en,{children:A&&(0,R.jsx)(Pe.div,{"aria-hidden":!0,className:L(`pointer-events-none absolute bg-active`,y.bg),initial:!1,animate:{top:A.top,left:A.left,width:A.width,height:A.height,opacity:ae?.8:1},exit:{opacity:0,transition:pt.moderate.exit},transition:{...pt.moderate,opacity:{duration:.08}}})}),(0,R.jsx)(en,{children:j&&(0,R.jsx)(Pe.div,{"aria-hidden":!0,className:L(`pointer-events-none absolute bg-hover`,y.bg),initial:{opacity:0,top:A?.top??j.top,left:A?.left??j.left,width:A?.width??j.width,height:A?.height??j.height},animate:{opacity:1,top:j.top,left:j.left,width:j.width,height:j.height},exit:{opacity:0,transition:pt.fast.exit},transition:{...pt.fast,opacity:{duration:.08}}},S.current)}),O.length===0?(0,R.jsx)(`div`,{className:`text-sm flex items-center justify-center h-12 whitespace-pre-wrap text-muted-foreground`,children:`No results found.`}):O.map((e,t)=>(0,R.jsxs)(`button`,{ref:e=>w(t,e),type:`button`,"data-testid":`command-palette-item-${e.id}`,"data-proximity-index":t,onClick:()=>ie(e),className:`[content-visibility:auto] relative z-10 cursor-pointer h-12 text-sm flex items-center gap-3 px-3 text-foreground select-none w-full text-left mt-1 first:mt-0`,children:[k(e.type,e.category,e.name),(0,R.jsx)(`span`,{className:`font-medium truncate flex-1 min-w-0`,children:e.name}),(()=>{let t=e.metadata?.serverId;if(!t||e.category===`Connected Servers`)return null;let n=o.find(e=>e.id===t);return n?(0,R.jsxs)(`div`,{className:`flex items-center gap-1 shrink-0 text-muted-foreground`,children:[(0,R.jsx)(ZI,{server:n,size:`xs`}),(0,R.jsx)(`span`,{className:`text-xs truncate max-w-[9rem]`,children:Xj(n)})]}):null})()]},e.id))]}),(0,R.jsxs)(`div`,{className:`border-t border-border px-4 py-3 pb-1 flex items-center justify-between text-xs text-muted-foreground `,children:[(0,R.jsxs)(`div`,{className:`flex items-center gap-3`,children:[(0,R.jsxs)(`div`,{className:`flex items-center gap-1.5`,children:[(0,R.jsx)(`span`,{className:`inline-flex items-center justify-center w-5 h-5 font-mono font-medium rounded shadow-sm bg-white dark:bg-zinc-800 border border-zinc-200 dark:border-zinc-700 text-foreground leading-none`,children:`t`}),(0,R.jsx)(`span`,{children:`Tools`})]}),(0,R.jsxs)(`div`,{className:`flex items-center gap-1.5`,children:[(0,R.jsx)(`span`,{className:`inline-flex items-center justify-center w-5 h-5 font-mono font-medium rounded shadow-sm bg-white dark:bg-zinc-800 border border-zinc-200 dark:border-zinc-700 text-foreground leading-none`,children:`p`}),(0,R.jsx)(`span`,{children:`Prompts`})]}),(0,R.jsxs)(`div`,{className:`flex items-center gap-1.5`,children:[(0,R.jsx)(`span`,{className:`inline-flex items-center justify-center w-5 h-5 font-mono font-medium rounded shadow-sm bg-white dark:bg-zinc-800 border border-zinc-200 dark:border-zinc-700 text-foreground leading-none`,children:`r`}),(0,R.jsx)(`span`,{children:`Resources`})]}),(0,R.jsxs)(`div`,{className:`flex items-center gap-1.5`,children:[(0,R.jsx)(`span`,{className:`inline-flex items-center justify-center w-5 h-5 font-mono font-medium rounded shadow-sm bg-white dark:bg-zinc-800 border border-zinc-200 dark:border-zinc-700 text-foreground leading-none`,children:`c`}),(0,R.jsx)(`span`,{children:`Chat`})]})]}),(0,R.jsxs)(`div`,{className:`flex items-center gap-3`,children:[(0,R.jsxs)(`div`,{className:`flex items-center gap-1.5`,children:[(0,R.jsx)(`span`,{className:`inline-flex items-center justify-center w-5 h-5 font-mono font-medium rounded shadow-sm bg-white dark:bg-zinc-800 border border-zinc-200 dark:border-zinc-700 text-foreground leading-none`,children:`h`}),(0,R.jsx)(`span`,{children:`Home`})]}),(0,R.jsxs)(`div`,{className:`flex items-center gap-1.5`,children:[(0,R.jsx)(`span`,{className:`inline-flex items-center justify-center px-2 h-5 font-mono text-[10px] font-medium rounded shadow-sm bg-white dark:bg-zinc-800 border border-zinc-200 dark:border-zinc-700 text-foreground leading-none`,children:`esc`}),(0,R.jsx)(`span`,{children:`Close`})]})]})]})]})]}):null}var CL=`openid profile email offline_access`,wL=`mcp-inspector:manufact-auth`,TL=`manufact:session-changed`,EL={loaded:!0,authorizing:!1,accessToken:null,user:null,mode:null},DL=new Map,OL=new Set,kL=new Map,AL=new Map,jL=null,ML=!1;typeof window<`u`&&window.addEventListener(`message`,e=>{if(e.data?.type!==`manufact:invalidate-oauth-client`)return;for(let e of DL.keys())PL()?.removeItem(BL(e,`client`));let t=jL;!t||ML||(ML=!0,cR(t,{isRetry:!0}).finally(()=>{ML=!1}))});function NL(e){let t=DL.get(e);if(t)return t;let n={...EL,loaded:!1};return DL.set(e,n),n}function PL(){return typeof window>`u`?null:window.localStorage}function FL(e){return new URL(e).origin}function IL(e,t){let n=new URL(e),r=new URL(t),i=new Set([`localhost`,`127.0.0.1`]);return i.has(n.hostname)&&i.has(r.hostname)?n.origin===r.origin:(n.hostname===`manufact.com`||n.hostname.endsWith(`.manufact.com`))&&(r.hostname===`manufact.com`||r.hostname.endsWith(`.manufact.com`))}function LL(e){let t=window.__MANUFACT_LOGIN_URL__;if(t)return new URL(t).origin;let n=new URL(e);return n.hostname===`localhost`||n.hostname===`127.0.0.1`?`${n.protocol}//${n.hostname}:3000`:`${n.protocol}//manufact.com`}function RL(e){return`${LL(e)}/login`}function zL(e){return`${LL(e)}/auth/embedded-sign-out`}function BL(e,t){return`${wL}:${t}:${e}`}function VL(e){return PL()?.getItem(BL(e,`skip-session`))===`1`}function HL(e,t){let n=BL(e,`skip-session`);t?PL()?.setItem(n,`1`):PL()?.removeItem(n)}function UL(e){return`${wL}:state:${e}`}function WL(e){let t=PL()?.getItem(e);if(!t)return null;try{return JSON.parse(t)}catch{return PL()?.removeItem(e),null}}function GL(e,t){PL()?.setItem(e,JSON.stringify(t))}function KL(e,t){DL.set(e,{...DL.get(e)??EL,...t}),OL.forEach(e=>e()),window.dispatchEvent(new CustomEvent(TL))}function qL(e){let t=``;return e.forEach(e=>{t+=String.fromCharCode(e)}),btoa(t).replace(/\+/g,`-`).replace(/\//g,`_`).replace(/=+$/,``)}function JL(e=32){let t=new Uint8Array(e);return crypto.getRandomValues(t),qL(t)}async function YL(e){let t=await crypto.subtle.digest(`SHA-256`,new TextEncoder().encode(e));return qL(new Uint8Array(t))}async function XL(e){let t=await fetch(`${e}/api/auth/.well-known/openid-configuration`);if(!t.ok)throw Error(`Manufact OAuth discovery failed`);return await t.json()}function ZL(){return`${window.location.origin}${Wj()}/auth/callback`}function QL(e){return e===`localhost`||e===`127.0.0.1`}function $L(e){try{let t=new URL(e).hostname,n=typeof window<`u`?new URL(window.location.href).hostname:``;return QL(t)&&QL(n)}catch{return!1}}async function eR(e,t,n){let r=new URL(`${e}/api/auth/oauth2/authorize`);r.searchParams.set(`response_type`,`code`),r.searchParams.set(`client_id`,t),r.searchParams.set(`redirect_uri`,n),r.searchParams.set(`scope`,CL),r.searchParams.set(`code_challenge`,await YL(JL(32))),r.searchParams.set(`code_challenge_method`,`S256`),r.searchParams.set(`state`,`client-probe`),r.searchParams.set(`prompt`,`none`);try{let e=await fetch(r.toString(),{method:`GET`,redirect:`manual`,credentials:`include`}),t=e.headers.get(`location`)??``;return t.includes(`/auth/error`)&&t.includes(`invalid_client`)?!1:e.status>=300&&e.status<400||e.type===`opaqueredirect`?!!t&&!t.includes(`/auth/error`):!0}catch{return!1}}async function tR(e,t){let n=ZL(),r=BL(e,`client`),i=WL(r),a=$L(e);if(!a&&i?.client_id&&i.redirect_uri===n){if(await eR(e,i.client_id,n))return i;PL()?.removeItem(r)}else a&&i?.client_id&&PL()?.removeItem(r);if(!t.registration_endpoint)throw Error(`Manufact OAuth registration is unavailable`);let o=await fetch(t.registration_endpoint,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({client_name:`mcp-use Inspector`,redirect_uris:[n],grant_types:[`authorization_code`,`refresh_token`],response_types:[`code`],token_endpoint_auth_method:`none`,scope:CL})});if(!o.ok)throw Error(`Could not register Inspector with Manufact`);let s=await o.json();if(!s.client_id)throw Error(`Manufact returned no OAuth client ID`);let c={...s,redirect_uri:n};return GL(r,c),c}async function nR(e,t){let n=await fetch(e,{method:`POST`,headers:{"Content-Type":`application/x-www-form-urlencoded`},body:new URLSearchParams(t)}),r=await n.json().catch(()=>({}));if(!n.ok||!r.access_token)throw Error(r.error_description??`Manufact token exchange failed`);return{access_token:r.access_token,refresh_token:r.refresh_token,token_type:r.token_type,expires_at:Date.now()+(r.expires_in??3600)*1e3}}async function rR(e,t){if(!t.refresh_token)return null;let n=AL.get(e);if(n)return n;let r=(async()=>{try{let n=await XL(e),r=WL(BL(e,`client`));if(!r?.client_id)return null;let i=await nR(n.token_endpoint,{grant_type:`refresh_token`,refresh_token:t.refresh_token,client_id:r.client_id}),a={...i,refresh_token:i.refresh_token??t.refresh_token};return GL(BL(e,`tokens`),a),a}catch{return PL()?.removeItem(BL(e,`tokens`)),null}finally{AL.delete(e)}})();return AL.set(e,r),r}async function iR(e){let t=WL(BL(e,`tokens`));return t?.access_token?t.expires_at>Date.now()+3e4?t:rR(e,t):null}async function aR(e,t){let n=await XL(e);if(!n.userinfo_endpoint)return null;let r=await fetch(n.userinfo_endpoint,{headers:{Authorization:`Bearer ${t}`}});if(!r.ok)return null;let i=await r.json();return i.sub?{id:i.sub,name:i.name,email:i.email,image:i.picture}:null}async function oR(e){try{let t=await fetch(`${e}/api/auth/get-session`,{credentials:`include`});return t.ok?(await t.json())?.user??null:null}catch{return null}}async function sR(e){let t=kL.get(e);if(t)return t;DL.set(e,{...DL.get(e)??EL,loaded:!1});let n=(async()=>{try{let t=IL(typeof window<`u`?window.location.href:e,e),n=VL(e),r=await iR(e),i=r?await aR(e,r.access_token):null;if(i&&r){HL(e,!1),KL(e,{loaded:!0,accessToken:r.access_token,user:i,mode:`oauth`});return}r&&!i&&PL()?.removeItem(BL(e,`tokens`));let a=t&&!n?await oR(e):null;if(a){KL(e,{loaded:!0,accessToken:null,user:a,mode:`session`});return}KL(e,{loaded:!0,accessToken:null,user:null,mode:null})}catch{KL(e,{loaded:!0,accessToken:null,user:null,mode:null})}})().finally(()=>kL.delete(e));return kL.set(e,n),n}async function cR(e,t){let n=FL(e);jL=e,HL(n,!1);let r=window.open(``,`manufact-oauth`,`width=600,height=700,resizable=yes,scrollbars=yes`);if(!r)throw Error(`Allow popups to sign in with Manufact`);if(KL(n,{authorizing:!0}),IL(window.location.href,n)){r.location.href=RL(n);let e=window.setInterval(async()=>{if(r.closed){window.clearInterval(e),KL(n,{authorizing:!1});return}let t=await oR(n);t&&(window.clearInterval(e),r.close(),KL(n,{loaded:!0,authorizing:!1,accessToken:null,user:t,mode:`session`}))},1e3);return}try{let e=await XL(n),t=await tR(n,e),i=JL(64),a=JL(),o=ZL();GL(UL(a),{authOrigin:n,clientId:t.client_id,redirectUri:o,codeVerifier:i,expiresAt:Date.now()+600*1e3});let s=new URL(e.authorization_endpoint);s.searchParams.set(`response_type`,`code`),s.searchParams.set(`client_id`,t.client_id),s.searchParams.set(`redirect_uri`,o),s.searchParams.set(`scope`,CL),s.searchParams.set(`state`,a),s.searchParams.set(`code_challenge`,await YL(i)),s.searchParams.set(`code_challenge_method`,`S256`),s.searchParams.set(`prompt`,`consent`),r.location.href=s.toString();let c=window.setInterval(()=>{r.closed&&(window.clearInterval(c),sR(n).finally(()=>KL(n,{authorizing:!1})))},500)}catch(e){throw r.close(),KL(n,{authorizing:!1}),e}}async function lR(e=new URL(window.location.href)){let t=e.searchParams.get(`state`),n=e.searchParams.get(`code`),r=e.searchParams.get(`error_description`)??e.searchParams.get(`error`);if(r)throw Error(r);if(!t||!n)throw Error(`Missing OAuth code or state`);let i=UL(t),a=WL(i);if(PL()?.removeItem(i),!a||a.expiresAt<Date.now())throw Error(`OAuth state is invalid or expired`);let o=await nR((await XL(a.authOrigin)).token_endpoint,{grant_type:`authorization_code`,code:n,redirect_uri:a.redirectUri,client_id:a.clientId,code_verifier:a.codeVerifier});GL(BL(a.authOrigin,`tokens`),o),HL(a.authOrigin,!1);let s=await aR(a.authOrigin,o.access_token);KL(a.authOrigin,{loaded:!0,authorizing:!1,accessToken:o.access_token,user:s,mode:`oauth`}),window.opener?.postMessage({type:`manufact:oauth-complete`,authOrigin:a.authOrigin},window.location.origin)}function uR(e){let t=FL(e);PL()?.removeItem(BL(t,`tokens`)),KL(t,{loaded:!0,authorizing:!1,accessToken:null,user:null,mode:null})}async function dR(e){let t=WL(BL(e,`tokens`)),n=WL(BL(e,`client`)),r=t?.refresh_token??t?.access_token;if(!n?.client_id||!r)return null;try{let i=(await XL(e)).revocation_endpoint??`${e}/api/auth/oauth2/revoke`;return(await fetch(i,{method:`POST`,headers:{"Content-Type":`application/x-www-form-urlencoded`},body:new URLSearchParams({client_id:n.client_id,token:r,token_type_hint:t?.refresh_token?`refresh_token`:`access_token`})})).status}catch{return-1}}async function fR(e){let t=LL(e),n=window.open(zL(e),`manufact-sign-out`,`width=420,height=320`);return n?new Promise(r=>{let i=!1,a=e=>{i||(i=!0,window.clearTimeout(o),window.clearInterval(c),window.removeEventListener(`message`,s),r(e))},o=window.setTimeout(()=>{a({attempted:!0,signOutOk:!1,signOutStatus:null})},3e4),s=e=>{e.origin===t&&e.data?.type===`manufact:sign-out-complete`&&a({attempted:!0,signOutOk:!0,signOutStatus:200})},c=window.setInterval(()=>{n.closed&&oR(e).then(e=>{a({attempted:!0,signOutOk:!e,signOutStatus:e?401:200})})},500);window.addEventListener(`message`,s)}):{attempted:!0,signOutOk:!1,signOutStatus:null}}async function pR(e,t){let n=FL(e),r=!!WL(BL(n,`tokens`))?.access_token;t===`oauth`||r?(await dR(n),HL(n,!0)):t===`session`&&(await fR(n),HL(n,!1)),uR(e)}function mR(e){let t=e?FL(e):null,n=(0,z.useSyncExternalStore)((0,z.useCallback)(e=>(OL.add(e),()=>OL.delete(e)),[]),(0,z.useCallback)(()=>t?NL(t):EL,[t]),()=>EL);return(0,z.useEffect)(()=>{if(!t)return;sR(t);let e=e=>{e.origin===window.location.origin&&e.data?.type===`manufact:oauth-complete`&&e.data.authOrigin===t&&sR(t).finally(()=>KL(t,{authorizing:!1}))},n=e=>{e.key!==BL(t,`tokens`)||!e.newValue||sR(t).finally(()=>KL(t,{authorizing:!1}))};return window.addEventListener(`message`,e),window.addEventListener(`storage`,n),()=>{window.removeEventListener(`message`,e),window.removeEventListener(`storage`,n)}},[t]),{...n,authorize:(0,z.useCallback)(async()=>{e&&await cR(e)},[e]),logout:(0,z.useCallback)(async()=>{e&&await pR(e,n.mode)},[e,n.mode])}}var hR=(0,z.lazy)(()=>lS(()=>import(`./ChatTab-fclW7HPg.js`).then(e=>({default:e.ChatTab})),__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19]))),gR=(0,z.lazy)(()=>lS(()=>import(`./ToolsTab-DBHJRY9V.js`).then(e=>({default:e.ToolsTab})),__vite__mapDeps([20,1,2,3,5,6,4,7,8,21,22,23,13,19,18,24,25,26,10,27,28,29,16,17]))),_R=(0,z.lazy)(()=>lS(()=>import(`./PromptsTab-irNacYfj.js`).then(e=>({default:e.PromptsTab})),__vite__mapDeps([30,1,2,3,5,6,4,7,8,24,26,10,27,28,29,11,12,19]))),vR=(0,z.lazy)(()=>lS(()=>import(`./ResourcesTab-C-4Fd-HY.js`).then(e=>({default:e.ResourcesTab})),__vite__mapDeps([31,1,2,3,5,7,21,6,4,8,22,23,13,19,18,32,24,25,26,10,27,28,14,17]))),yR=(0,z.lazy)(()=>lS(()=>import(`./SamplingTab-B7bM9cnF.js`).then(e=>({default:e.SamplingTab})),__vite__mapDeps([33,1,2,3,5,6,4,7,8,26,10,27,22,23,13,14,19]))),bR=(0,z.lazy)(()=>lS(()=>import(`./ElicitationTab-B73XazTU.js`).then(e=>({default:e.ElicitationTab})),__vite__mapDeps([34,1,2,3,5,8,26,10,27,22,15,12,19]))),xR=(0,z.lazy)(()=>lS(()=>import(`./NotificationsTab-CV9kw9j-.js`).then(e=>({default:e.NotificationsTab})),__vite__mapDeps([35,1,2,3,32,25,26,5,10,27,28]))),SR=(0,z.lazy)(()=>lS(()=>import(`./ServerMetadataTab-CnGUw9uD.js`).then(e=>({default:e.ServerMetadataTab})),__vite__mapDeps([36,1,5,2,3,9,7,8,27,10,37]))),CR=(0,z.lazy)(()=>lS(()=>import(`./ConnectionSettingsTab-DNl63AkH.js`).then(e=>({default:e.ConnectionSettingsTab})),__vite__mapDeps([38,1,2,3,5,27,10,37])));function wR({children:e}){return(0,R.jsx)(z.Suspense,{fallback:(0,R.jsx)(`div`,{className:`flex h-full items-center justify-center`,children:(0,R.jsx)(XI,{className:`size-6`})}),children:e})}var TR=`anthropic/claude-sonnet-4.6`;function ER({isLoopback:e,chatApiUrl:t}){return e&&!!t}function DR(e,t,n=!1,r){let i=e.replace(/\/chat\/stream\/?$/,`/llm`);return{provider:`openai-compatible`,model:r??`anthropic/claude-sonnet-4.6`,apiKey:t??`server-managed`,baseUrl:i,...n?{credentials:`include`}:{}}}function OR(e){return e?{Authorization:`Bearer ${e}`}:void 0}var kR=`mcp-inspector:managed-model`;function AR(e){return`${kR}:${e}`}function jR(e){try{return localStorage.getItem(AR(e))}catch{return null}}function MR(e,t,n,r){let i=e?new URL(e).origin:null,[a,o]=(0,z.useState)([]),[s,c]=(0,z.useState)(TR),[l,u]=(0,z.useState)(()=>i?jR(i)??`anthropic/claude-sonnet-4.6`:TR),[d,f]=(0,z.useState)(!1),p=(0,z.useCallback)(e=>{if(u(e),i)try{localStorage.setItem(AR(i),e)}catch{}},[i]);return(0,z.useEffect)(()=>{if(!r||!i)return;let e=!1;return f(!0),(async()=>{try{let r=OR(t),a=await fetch(`${i}/api/v1/models`,{headers:r,credentials:n===`session`?`include`:`same-origin`});if(!a.ok)return;let s=await a.json();if(e)return;let l=s.models??[];o(l);let d=s.defaultModelId??`anthropic/claude-sonnet-4.6`;c(d);let f=new Set(l.map(e=>e.id)),p=jR(i);p&&f.has(p)?u(p):f.has(d)?u(d):l[0]&&u(l[0].id)}finally{e||f(!1)}})(),()=>{e=!0}},[r,i,t,n]),{models:a,selectedModelId:l,setSelectedModelId:p,isLoading:d,selectedModel:a.find(e=>e.id===l)??null,defaultModelId:s}}var NR=[`tools`,`prompts`,`resources`,`chat`,`sampling`,`elicitation`,`notifications`,`server-metadata`,`connection-settings`];function PR(e){return NR.includes(e)?e:`tools`}function FR({selectedServer:e,activeTab:t,toolsSearchRef:n,promptsSearchRef:r,resourcesSearchRef:i,onUpdateConnection:a,children:o}){let{embeddedConfig:s}=nL(),c=PR(t),[l,u]=(0,z.useState)(()=>new Set([c]));(0,z.useEffect)(()=>{let e=PR(t);u(t=>t.has(e)?t:new Set(t).add(e))},[t]);let{accessToken:d,mode:f,user:p}=mR(s.chatApiUrl),m=OR(d),h=f===`session`?`include`:void 0,g=p!=null,_=s.chatApiUrl,v=!!e?.url&&qj(e.url),y=e?ER({isLoopback:v,chatApiUrl:s.chatApiUrl,enableFreeTierUpgrade:s.chatEnableFreeTierUpgrade}):!1,b=MR(_,d,f,!!e&&!!_&&g),x=y?DR(_,d,f===`session`,g?b.selectedModelId:void 0):s.managedLlmConfig??(_&&!v?{provider:`anthropic`,model:`claude-haiku-4-5`,apiKey:`server-managed`}:void 0);if(!e&&s.forceConnected)return s.chatApiUrl?(0,R.jsx)(wR,{children:(0,R.jsx)(hR,{connection:{id:`force-connected`,url:``,displayName:``,name:``,state:`ready`,tools:[],prompts:[],resources:[]},isConnected:!0,prompts:[],serverId:`force-connected`,callPrompt:async()=>({messages:[]}),readResource:async()=>({contents:[]}),useClientSide:!1,chatApiUrl:s.chatApiUrl,extraHeaders:m,credentials:h,managedLlmConfig:s.managedLlmConfig??{provider:`anthropic`,model:`claude-haiku-4-5`,apiKey:`server-managed`},enableFreeTierUpgrade:s.chatEnableFreeTierUpgrade,hideTitle:s.chatHideTitle,hideModelBadge:s.chatHideModelBadge??!0,hideServerUrl:s.chatHideServerUrl??!0,clearButtonLabel:s.chatClearButtonLabel,clearButtonHideIcon:s.chatClearButtonHideIcon,clearButtonHideShortcut:s.chatClearButtonHideShortcut,clearButtonVariant:s.chatClearButtonVariant,chatQuickQuestions:s.chatQuickQuestions,chatFollowups:s.chatFollowups,hideClearButton:s.chatHideClearButton,hideToolSelector:s.chatHideToolSelector,enableKeyboardShortcuts:!1},`chat-force-connected`)}):(0,R.jsx)(R.Fragment,{children:o});if(!e)return(0,R.jsx)(R.Fragment,{children:o});let S=e=>s.visibleTabs?s.visibleTabs.includes(e):!0,C=NR;return(0,R.jsxs)(wR,{children:[S(`tools`)&&l.has(`tools`)&&(0,R.jsx)(`div`,{style:{display:t===`tools`?`block`:`none`},className:`h-full`,children:(0,R.jsx)(gR,{ref:n,tools:e.tools,callTool:e.callTool,readResource:e.readResource,serverId:e.id,isConnected:e.state===`ready`,refreshTools:e.refreshTools},`tools-${e.id}`)}),S(`prompts`)&&l.has(`prompts`)&&(0,R.jsx)(`div`,{style:{display:t===`prompts`?`block`:`none`},className:`h-full`,children:(0,R.jsx)(_R,{ref:r,prompts:e.prompts,callPrompt:(t,n)=>e.getPrompt(t,n?Object.fromEntries(Object.entries(n).map(([e,t])=>[e,typeof t==`string`?t:String(t??``)])):void 0),serverId:e.id,isConnected:e.state===`ready`,refreshPrompts:e.refreshPrompts},`prompts-${e.id}`)}),S(`resources`)&&l.has(`resources`)&&(0,R.jsx)(`div`,{style:{display:t===`resources`?`block`:`none`},className:`h-full`,children:(0,R.jsx)(vR,{ref:i,resources:e.resources,readResource:e.readResource,serverId:e.id,isConnected:e.state===`ready`,mcpServerUrl:e.url||``,refreshResources:e.refreshResources},`resources-${e.id}`)}),S(`chat`)&&l.has(`chat`)&&(0,R.jsx)(`div`,{style:{display:t===`chat`?`block`:`none`},className:`h-full`,children:(0,R.jsx)(hR,{connection:e,isConnected:s.forceConnected||e.state===`ready`,prompts:e.prompts,serverId:e.id,callPrompt:(t,n)=>e.getPrompt(t,n?Object.fromEntries(Object.entries(n).map(([e,t])=>[e,typeof t==`string`?t:String(t??``)])):void 0),readResource:e.readResource,useClientSide:y||!_,chatApiUrl:_,extraHeaders:m,credentials:s.chatCredentials??h,managedLlmConfig:x,managedCloudModel:b,enableFreeTierUpgrade:s.chatEnableFreeTierUpgrade,hideTitle:s.chatHideTitle,hideModelBadge:s.chatHideModelBadge??!1,hideServerUrl:s.chatHideServerUrl??!!_,clearButtonLabel:s.chatClearButtonLabel,clearButtonHideIcon:s.chatClearButtonHideIcon,clearButtonHideShortcut:s.chatClearButtonHideShortcut,clearButtonVariant:s.chatClearButtonVariant,chatQuickQuestions:s.chatQuickQuestions,chatFollowups:s.chatFollowups,hideClearButton:s.chatHideClearButton,hideToolSelector:s.chatHideToolSelector,streamProtocol:s.chatStreamProtocol},`chat-${e.id}`)}),S(`sampling`)&&l.has(`sampling`)&&(0,R.jsx)(`div`,{style:{display:t===`sampling`?`block`:`none`},className:`h-full`,children:(0,R.jsx)(yR,{pendingRequests:e.pendingSamplingRequests,onApprove:e.approveSampling,onReject:e.rejectSampling,serverId:e.id,isConnected:e.state===`ready`,mcpServerUrl:e.url??``},`sampling-${e.id}`)}),S(`elicitation`)&&l.has(`elicitation`)&&(0,R.jsx)(`div`,{style:{display:t===`elicitation`?`block`:`none`},className:`h-full`,children:(0,R.jsx)(bR,{pendingRequests:e.pendingElicitationRequests,onApprove:e.approveElicitation,onReject:e.rejectElicitation,serverId:e.id,isConnected:e.state===`ready`},`elicitation-${e.id}`)}),S(`notifications`)&&l.has(`notifications`)&&(0,R.jsx)(`div`,{style:{display:t===`notifications`?`block`:`none`},className:`h-full`,children:(0,R.jsx)(xR,{notifications:e.notifications,unreadCount:e.unreadNotificationCount,markNotificationRead:e.markNotificationRead,markAllNotificationsRead:e.markAllNotificationsRead,clearNotifications:e.clearNotifications,serverId:e.id,isConnected:e.state===`ready`},`notifications-${e.id}`)}),S(`server-metadata`)&&l.has(`server-metadata`)&&(0,R.jsx)(`div`,{style:{display:t===`server-metadata`?`block`:`none`},className:`h-full`,children:(0,R.jsx)(SR,{connection:e},`server-metadata-${e.id}`)}),S(`connection-settings`)&&l.has(`connection-settings`)&&a&&(0,R.jsx)(`div`,{style:{display:t===`connection-settings`?`block`:`none`},className:`h-full`,children:(0,R.jsx)(CR,{connection:e,onSave:a},`connection-settings-${e.id}`)}),!C.includes(t)&&(0,R.jsx)(R.Fragment,{children:o})]})}var IR=z.createContext(void 0);function LR(){let e=z.use(IR);if(!e)throw Error(`useTabs must be used within a TabsProvider`);return e}var RR=z.createContext(void 0);function zR(){return z.use(RR)}function BR({ref:e,children:t,defaultValue:n,value:r,onValueChange:i,className:a,collapsed:o,onCollapsedChange:s,...c}){let[l,u]=z.useState(n||``),d=r!==void 0,f=o!==void 0,[p,m]=z.useState(!1),h=z.useCallback(e=>{d||u(e),i?.(e)},[d,i]);return(0,R.jsx)(IR,{value:{activeValue:d?r:l,handleValueChange:h,collapsed:f?o:p,handleCollapsedChange:z.useCallback(e=>{f||m(e),s?.(e)},[f,s])},children:(0,R.jsx)(`div`,{ref:e,className:L(`flex flex-col gap-2`,a),...c,children:t})})}BR.displayName=`Tabs`;function VR({ref:e,children:t,className:n,variant:r=`default`,collapsible:i=!1,...a}){let{activeValue:o,collapsed:s,handleCollapsedChange:c}=LR(),[l,u]=z.useState({width:0,left:0}),d=z.useRef(null),f=z.useRef(null),p=z.useRef(null),m=z.useCallback(()=>{let e=d.current;if(!e)return;let t=e.querySelector(`div:first-child`);if(!t)return;let n=t.querySelector(`button[data-tab-value="${o}"]`);if(n&&o){let e=t.getBoundingClientRect(),r=n.getBoundingClientRect();u({width:r.width,left:r.left-e.left})}else u({width:0,left:0})},[o]),h=z.useCallback(()=>{p.current&&clearTimeout(p.current),p.current=setTimeout(m,16)},[m]);z.useEffect(()=>{let e=setTimeout(m,10);return()=>clearTimeout(e)},[m,s]),z.useEffect(()=>{let e=d.current;if(!e)return;f.current=new ResizeObserver(()=>{h()}),f.current.observe(e);let t=e.querySelector(`div:first-child`);return t&&t.querySelectorAll(`button[data-tab-value]`).forEach(e=>{f.current&&f.current.observe(e)}),()=>{f.current&&f.current.disconnect(),p.current&&clearTimeout(p.current)}},[h]),z.useEffect(()=>{let e=()=>{h()};return window.addEventListener(`resize`,e),()=>window.removeEventListener(`resize`,e)},[h]);let g=z.useRef(null);return z.useEffect(()=>{g.current&&(g.current.style.width=`${l.width}px`,g.current.style.left=`${l.left}px`)},[l]),(0,R.jsx)(RR,{value:{variant:r,collapsed:s,handleCollapsedChange:c},children:(0,R.jsx)(`div`,{ref:d,className:L(`relative flex items-center bg-none gap-1`,r==="default"&&`p-1 rounded-full border border-zinc-300 dark:border-zinc-600`,r===`underline`&&`border-b border-zinc-200 dark:border-zinc-700`,n),...a,children:(0,R.jsxs)(`div`,{role:`tablist`,className:`flex-1 flex items-center relative`,children:[t,(0,R.jsx)(`span`,{ref:g,className:L(`absolute transition-all duration-[250ms] ease-in-out z-0`,r==="default"&&`bg-white dark:bg-zinc-700 rounded-full h-[calc(100%)] top-0 border border-zinc-300 dark:border-zinc-600`,r===`underline`&&`bottom-0 h-0.5 bg-black dark:bg-white`)})]})})})}VR.displayName=`TabsList`;var HR=({children:e,title:t,collapsed:n})=>!t||!n?e:(0,R.jsx)(Ve,{children:(0,R.jsxs)(et,{children:[(0,R.jsx)(we,{render:(0,R.jsx)(`span`,{className:`contents`,children:e}),nativeButton:!1}),(0,R.jsx)(lt,{children:t})]})}),UR=z.forwardRef(({children:e,value:t,className:n,disabled:r,icon:i,title:a,showDot:o=!1,alwaysExpanded:s=!1,iconOnly:c=!1,badge:l,...u},d)=>{let{activeValue:f,handleValueChange:p,collapsed:m}=LR(),h=zR()?.variant||`default`,g=f===t,_=!c&&(!m||g||s),v=c||m&&!_;return(0,R.jsx)(HR,{title:a,collapsed:m&&!_,children:(0,R.jsxs)(`button`,{ref:d,disabled:r,onClick:()=>p(t),"data-tab-value":t,"data-tab-active":g,role:`tab`,"aria-selected":g?`true`:`false`,title:m&&!_&&a?a:void 0,className:L(`relative z-10 inline-flex items-center justify-center whitespace-nowrap text-sm font-medium ring-offset-background transition-all duration-[250ms] ease-in-out focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 cursor-pointer`,c?`size-9 shrink-0 flex-none rounded-full p-0`:`flex-1`,h==="default"&&!c&&`py-2.5`,h==="default"&&!c&&`rounded-md px-4`,h===`underline`&&`px-6 py-3 border-b-2 border-transparent`,g&&`text-foreground`,!g&&`text-muted-foreground hover:text-foreground`,n),...u,children:[i&&(0,R.jsxs)(`span`,{className:L(`relative inline-flex shrink-0 items-center justify-center`,c?`size-5`:_&&`mr-2`),children:[(0,R.jsx)(i,{className:L(`h-4 w-4 shrink-0 transition-all duration-[250ms] ease-in-out`,!_&&!c&&`mr-0!`)}),l&&v?l:null]}),o&&(0,R.jsx)(`span`,{className:`absolute top-1.5 right-1.5 w-2 h-2 bg-orange-500 dark:bg-orange-400 border-2 border-white dark:border-zinc-900 rounded-full transition-opacity duration-300 z-10 animate-status-pulse-orange`}),(0,R.jsx)(`span`,{className:L(`min-w-0 transition-all duration-[250ms] ease-in-out overflow-hidden`,_?`w-auto opacity-100`:`w-0 opacity-0`),children:e}),l&&!v?l:null]})})});UR.displayName=`TabsTrigger`;function WR(e){return mR(e)}var GR=z.createContext(void 0);function KR(){let e=z.useContext(GR);if(e===void 0)throw Error(Vt(13));return e}var qR={imageLoadingStatus:()=>null},JR=z.forwardRef(function(e,t){let{className:n,render:r,style:i,...a}=e,[o,s]=z.useState(`idle`),c={imageLoadingStatus:o},l=z.useMemo(()=>({imageLoadingStatus:o,setImageLoadingStatus:s}),[o,s]),u=Ft(`span`,e,{state:c,ref:t,props:a,stateAttributesMapping:qR});return(0,R.jsx)(GR.Provider,{value:l,children:u})});function YR(e,{referrerPolicy:t,crossOrigin:n,sizes:r,srcSet:i}){let[a,o]=z.useState(`idle`);return Rt(()=>{if(!e&&!i)return o(`error`),It;let a=!0,s=new window.Image,c=e=>()=>{a&&o(e)};return o(`loading`),s.onload=c(`loaded`),s.onerror=c(`error`),t&&(s.referrerPolicy=t),s.crossOrigin=n??null,r&&(s.sizes=r),i&&(s.srcset=i),e&&(s.src=e),s.complete&&o(s.naturalWidth>0?`loaded`:`error`),()=>{a=!1}},[e,i,r,n,t]),a}var XR={...qR,...it},ZR=z.forwardRef(function(e,t){let{className:n,render:r,onLoadingStatusChange:i,style:a,...o}=e,{setImageLoadingStatus:s}=KR(),c=YR(o.src,o),l=c===`loaded`,{mounted:u,transitionStatus:d,setMounted:f}=Je(l),p=z.useRef(null),m=Pt(e=>{i?.(e),s(e)});Rt(()=>{c!==`idle`&&m(c)},[c,m]),Rt(()=>()=>s(`idle`),[s]),g({open:l,ref:p,onComplete(){l||f(!1)}});let h=Ft(`img`,e,{state:{imageLoadingStatus:c,transitionStatus:d},ref:[t,p],props:o,stateAttributesMapping:XR,enabled:u});return u?h:null}),QR=z.forwardRef(function(e,t){let{className:n,render:r,delay:i,style:a,...o}=e,{imageLoadingStatus:s}=KR(),[c,l]=z.useState(i===void 0),u=fe();return z.useEffect(()=>(i===void 0?l(!0):u.start(i,()=>l(!0)),u.clear),[u,i]),Ft(`span`,e,{state:{imageLoadingStatus:s},ref:t,props:o,stateAttributesMapping:qR,enabled:s!==`loaded`&&(i===void 0||c)})});function $R({className:e,size:t=`default`,...n}){return(0,R.jsx)(JR,{"data-slot":`avatar`,"data-size":t,className:L(`group/avatar relative flex size-8 shrink-0 rounded-full select-none after:absolute after:inset-0 after:rounded-full after:border after:border-border after:mix-blend-darken data-[size=lg]:size-10 data-[size=sm]:size-6 dark:after:mix-blend-lighten`,e),...n})}function ez({className:e,...t}){return(0,R.jsx)(ZR,{"data-slot":`avatar-image`,className:L(`aspect-square size-full rounded-full object-cover`,e),...t})}function tz({className:e,...t}){return(0,R.jsx)(QR,{"data-slot":`avatar-fallback`,className:L(`flex size-full items-center justify-center rounded-full bg-muted text-sm text-muted-foreground group-data-[size=sm]/avatar:text-xs`,e),...t})}function nz(e,t){return e?.[0]?e[0].toUpperCase():t?.[0]?t[0].toUpperCase():`U`}function rz({chatApiUrl:e,dashboardUrl:t=`https://manufact.com/cloud`,fallback:n=null,onUserResolved:r,compact:i=!1}){let{user:a,loaded:o,authorizing:s,authorize:c,logout:l,mode:u}=WR(e),d=(0,z.useRef)(void 0);if((0,z.useEffect)(()=>{if(!o)return;let e=a?.id??null;d.current!==e&&(d.current=e,r?.(a))},[o,a,r]),!o)return null;if(!a)return(0,R.jsxs)(R.Fragment,{children:[n,(0,R.jsx)(Gt,{variant:`ghost`,size:`sm`,className:L(`shrink-0 rounded-full text-[13px]`,i?`px-2.5 text-xs`:`px-4`),disabled:s,onClick:()=>{c().catch(e=>IF.error(e instanceof Error?e.message:`Authorization failed`))},children:s?`Authorizing…`:`Sign in`})]});let f=nz(a.name,a.email),p=a.name??a.email??`User`;return(0,R.jsxs)(Ya,{children:[(0,R.jsx)(Xa,{render:(0,R.jsx)(Gt,{variant:`ghost`,className:`relative h-8 w-8 shrink-0 rounded-full p-0 mr-2`,"aria-label":`User menu`,children:(0,R.jsxs)($R,{className:`h-8 w-8 border border-zinc-300 dark:border-zinc-600`,children:[(0,R.jsx)(ez,{src:a.image??``,alt:p}),(0,R.jsx)(tz,{className:`text-sm`,children:f})]})}),nativeButton:!0}),(0,R.jsxs)(Za,{className:`w-56`,align:`end`,forceMount:!0,children:[(0,R.jsx)(Qa,{className:`font-normal`,children:(0,R.jsxs)(`div`,{className:`flex flex-col space-y-1`,children:[(0,R.jsx)(`p`,{className:`text-sm font-medium leading-none truncate`,children:p}),a.email&&a.email!==p&&(0,R.jsx)(`p`,{className:`text-xs leading-none text-muted-foreground truncate`,children:a.email})]})}),(0,R.jsx)(no,{}),(0,R.jsx)($a,{render:(0,R.jsxs)(`a`,{href:t,target:`_blank`,rel:`noopener noreferrer`,children:[(0,R.jsx)(li,{className:`mr-2 h-4 w-4`}),`Go to dashboard`]})}),(0,R.jsx)(no,{}),(0,R.jsxs)($a,{onClick:()=>{l().catch(()=>IF.error(`Sign out failed`))},children:[(0,R.jsx)(hi,{className:`mr-2 h-4 w-4`}),u===`session`?`Sign out of Manufact`:`Disconnect Inspector`]})]})]})}function iz({count:e,isActive:t,size:n=`md`,overlay:r=!1}){return e<=0?null:(0,R.jsx)(`span`,{className:L(t?`dark:bg-black`:`dark:bg-zinc-700`,`shrink-0 bg-zinc-200 text-zinc-700 dark:text-zinc-300 rounded-full font-medium`,r&&`absolute -bottom-1 -right-1.5 z-10 flex h-3.5 min-w-3.5 items-center justify-center border border-background px-0.5 text-[9px] leading-none`,!r&&`ml-1`,!r&&n===`sm`&&`text-[10px] px-1.5 py-0.5`,!r&&n===`md`&&`text-xs px-2 py-0.5`),children:e})}var az=`flex h-10 items-center gap-2`;function oz({serverConfig:e,additionalItems:t=[],showClients:n={cursor:!0,vsCode:!0,vsCodeInsiders:!0,claudeDesktop:!0,claudeCode:!0,geminiCli:!0,codexCli:!0},className:r=``,onSuccess:i,onError:a,trigger:o}){let[s,c]=(0,z.useState)(!1),[l,u]=(0,z.useState)(null),[d,f]=(0,z.useState)(!1),{url:p,name:m,headers:h}=e,g=e=>{try{bT(new Fo({client:e})).catch(()=>{})}catch{}},_=()=>{g(`cursor`);try{let e=lL(p,m,h);window.location.href=e,i?.(`Cursor`)}catch(e){console.error(`Failed to generate Cursor deep link:`,e),a?.(e)}},v=()=>{g(`vscode`);try{let e=uL(p,m,h);window.location.href=e,i?.(`VS Code`)}catch(e){console.error(`Failed to generate VS Code deep link:`,e),a?.(e)}},y=()=>{g(`vscode-insiders`);try{let e=dL(p,m,h);window.location.href=e,i?.(`VS Code Insiders`)}catch(e){console.error(`Failed to generate VS Code Insiders deep link:`,e),a?.(e)}},b=()=>{g(`claude-desktop`);try{pL(p,m,h),i?.(`Claude Desktop`)}catch(e){console.error(`Failed to download .mcpb file:`,e),a?.(e)}},x=()=>{g(`claude-code`),u(`claude-code`),c(!0)},S=()=>{g(`gemini-cli`),u(`gemini-cli`),c(!0)},C=()=>{g(`codex-cli`),u(`codex-cli`),c(!0)},w=async e=>{try{await zj(e),f(!0),setTimeout(()=>f(!1),2e3)}catch(e){console.error(`Failed to copy:`,e),a?.(e)}},T=()=>{if(l===`claude-code`){let{command:e,envVars:t}=mL(p,m,h),n=_L(t);return(0,R.jsxs)(R.Fragment,{children:[(0,R.jsxs)(VI,{children:[(0,R.jsx)(GI,{children:`Add to Claude Code`}),(0,R.jsx)(KI,{children:`Execute the following command in your shell to add this server to Claude Code.`})]}),(0,R.jsxs)(HI,{className:`space-y-4`,children:[(0,R.jsxs)(`div`,{children:[(0,R.jsx)(`h5`,{className:`font-semibold text-sm mb-2`,children:`Instructions`}),(0,R.jsxs)(`ol`,{className:`space-y-2 text-xs text-muted-foreground`,children:[(0,R.jsxs)(`li`,{className:`flex gap-2`,children:[(0,R.jsx)(`span`,{className:`font-semibold text-foreground`,children:`1.`}),(0,R.jsx)(`span`,{children:`Ensure the Claude Code executable is available in your path`})]}),(0,R.jsxs)(`li`,{className:`flex gap-2`,children:[(0,R.jsx)(`span`,{className:`font-semibold text-foreground`,children:`2.`}),(0,R.jsx)(`span`,{children:`Execute the following snippet in your shell:`})]})]})]}),(0,R.jsxs)(`div`,{className:`relative`,children:[(0,R.jsx)(`div`,{className:`absolute top-2 right-2 z-10`,children:(0,R.jsx)(Gt,{variant:`ghost`,size:`sm`,className:`h-7 px-2 bg-background hover:bg-accent border border-border`,onClick:()=>w(e),children:d?(0,R.jsx)(Fr,{className:`size-3.5 text-green-600`}):(0,R.jsx)(Wr,{className:`size-3.5`})})}),(0,R.jsx)(`pre`,{className:`bg-muted p-3 pr-14 rounded-md text-xs overflow-x-auto`,children:(0,R.jsx)(`code`,{children:e})})]}),n&&(0,R.jsxs)(`div`,{children:[(0,R.jsx)(`h5`,{className:`font-semibold text-sm mb-2`,children:`Environment Variables`}),(0,R.jsx)(`p`,{className:`text-xs text-muted-foreground mb-2`,children:`After installation, set these environment variables in your shell:`}),(0,R.jsx)(`pre`,{className:`bg-muted p-3 rounded-md text-xs overflow-x-auto`,children:(0,R.jsx)(`code`,{children:n})})]}),(0,R.jsxs)(`p`,{className:`text-xs text-muted-foreground`,children:[`The MCP configuration supports environment variable expansion using `,(0,R.jsx)(`code`,{className:`text-foreground`,children:"${VAR}"}),` `,`syntax.`]})]})]})}if(l===`gemini-cli`){let{command:e,envVars:t}=hL(p,m,h),n=_L(t);return(0,R.jsxs)(R.Fragment,{children:[(0,R.jsxs)(VI,{children:[(0,R.jsx)(GI,{children:`Add to Gemini CLI`}),(0,R.jsx)(KI,{children:`Execute the following command in your shell to add this server to Gemini CLI.`})]}),(0,R.jsxs)(HI,{className:`space-y-4`,children:[(0,R.jsxs)(`div`,{children:[(0,R.jsx)(`h5`,{className:`font-semibold text-sm mb-2`,children:`Instructions`}),(0,R.jsxs)(`ol`,{className:`space-y-2 text-xs text-muted-foreground`,children:[(0,R.jsxs)(`li`,{className:`flex gap-2`,children:[(0,R.jsx)(`span`,{className:`font-semibold text-foreground`,children:`1.`}),(0,R.jsx)(`span`,{children:`Ensure the Gemini CLI executable is available in your path`})]}),n&&(0,R.jsxs)(`li`,{className:`flex gap-2`,children:[(0,R.jsx)(`span`,{className:`font-semibold text-foreground`,children:`2.`}),(0,R.jsx)(`span`,{children:`Set these environment variables in your shell before running the command:`})]}),(0,R.jsxs)(`li`,{className:`flex gap-2`,children:[(0,R.jsx)(`span`,{className:`font-semibold text-foreground`,children:n?`3.`:`2.`}),(0,R.jsx)(`span`,{children:`Execute the following snippet in your shell:`})]})]})]}),n&&(0,R.jsxs)(`div`,{children:[(0,R.jsx)(`h5`,{className:`font-semibold text-sm mb-2`,children:`Environment Variables`}),(0,R.jsx)(`pre`,{className:`bg-muted p-3 rounded-md text-xs overflow-x-auto`,children:(0,R.jsx)(`code`,{children:n})})]}),(0,R.jsxs)(`div`,{className:`relative`,children:[(0,R.jsx)(`div`,{className:`absolute top-2 right-2 z-10`,children:(0,R.jsx)(Gt,{variant:`ghost`,size:`sm`,className:`h-7 px-2 bg-background hover:bg-accent border border-border`,onClick:()=>w(e),children:d?(0,R.jsx)(Fr,{className:`size-3.5 text-green-600`}):(0,R.jsx)(Wr,{className:`size-3.5`})})}),(0,R.jsx)(`pre`,{className:`bg-muted p-3 pr-14 rounded-md text-xs overflow-x-auto`,children:(0,R.jsx)(`code`,{children:e})})]}),(0,R.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Restart Gemini CLI to load the new configuration.`})]})]})}if(l===`codex-cli`){let{config:e,envVars:t}=gL(p,m,h);return(0,R.jsxs)(R.Fragment,{children:[(0,R.jsxs)(VI,{children:[(0,R.jsx)(GI,{children:`Add to Codex CLI`}),(0,R.jsxs)(KI,{children:[`Add this configuration to your`,` `,(0,R.jsx)(`code`,{className:`text-foreground`,children:`~/.codex/config.toml`}),` `,`file.`]})]}),(0,R.jsxs)(HI,{className:`space-y-4`,children:[(0,R.jsxs)(`div`,{children:[(0,R.jsx)(`h5`,{className:`font-semibold text-sm mb-2`,children:`Instructions`}),(0,R.jsxs)(`p`,{className:`text-xs text-muted-foreground`,children:[`Add this configuration to your`,` `,(0,R.jsx)(`code`,{className:`text-foreground`,children:`~/.codex/config.toml`}),`:`]})]}),(0,R.jsxs)(`div`,{className:`relative`,children:[(0,R.jsx)(`div`,{className:`absolute top-2 right-2 z-10`,children:(0,R.jsx)(Gt,{variant:`ghost`,size:`sm`,className:`h-7 px-2 bg-background hover:bg-accent border border-border`,onClick:()=>w(e),children:d?(0,R.jsx)(Fr,{className:`size-3.5 text-green-600`}):(0,R.jsx)(Wr,{className:`size-3.5`})})}),(0,R.jsx)(`pre`,{className:`bg-muted p-3 pr-14 rounded-md text-xs overflow-x-auto`,children:(0,R.jsx)(`code`,{children:e})})]}),t.length>0&&(0,R.jsx)(`div`,{children:(0,R.jsxs)(`p`,{className:`text-xs text-muted-foreground`,children:[`(optional) If you would rather use variables from your system's environment, replace the`,` `,(0,R.jsx)(`code`,{className:`text-foreground`,children:`http_headers`}),` key with the `,(0,R.jsx)(`code`,{className:`text-foreground`,children:`env_http_headers`}),` `,`key as shown in the commented section above.`]})}),(0,R.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Restart Codex CLI to load the new configuration.`})]})]})}return null},E=(0,R.jsxs)(Gt,{variant:`ghost`,className:`bg-zinc-200 dark:bg-zinc-800 hover:bg-zinc-300 dark:hover:bg-zinc-700 rounded-full transition-colors px-3 flex items-center justify-center ${r}`,children:[(0,R.jsxs)(`span`,{className:`xl:hidden hidden sm:flex items-center gap-1`,children:[(0,R.jsx)(Ai,{className:`size-3`}),`Client`]}),(0,R.jsxs)(`span`,{className:`hidden xl:flex items-center gap-1`,children:[`Add to Client`,(0,R.jsx)(Ir,{className:`size-3`})]})]}),ee=o?typeof o==`function`?o({isOpen:!1,onClick:()=>{}}):o:E;return(0,R.jsxs)(R.Fragment,{children:[(0,R.jsxs)(Ya,{children:[(0,R.jsx)(Xa,{render:(0,z.isValidElement)(ee)?ee:E,nativeButton:!0}),(0,R.jsxs)(Za,{align:`end`,className:`w-auto min-w-[300px]`,children:[t.map(e=>(0,R.jsxs)($a,{onClick:async()=>{await e.onClick()},className:az,children:[e.icon,(0,R.jsx)(`span`,{className:`min-w-0 max-w-full whitespace-nowrap`,children:e.label})]},e.id)),t.length>0&&(0,R.jsx)(no,{}),n.cursor&&(0,R.jsxs)($a,{onClick:_,className:az,children:[(0,R.jsx)(`img`,{src:`https://cdn.simpleicons.org/cursor`,alt:`Cursor`,className:`h-4 w-4`}),(0,R.jsx)(`span`,{className:`min-w-0 max-w-full whitespace-nowrap`,children:`Cursor`})]}),n.claudeCode&&(0,R.jsxs)($a,{onClick:x,className:az,children:[(0,R.jsx)(`img`,{src:`https://cdn.simpleicons.org/claude`,alt:`Claude`,className:`h-4 w-4`}),(0,R.jsx)(`span`,{className:`min-w-0 max-w-full whitespace-nowrap`,children:`Claude Code`})]}),n.claudeDesktop&&(0,R.jsxs)($a,{onClick:b,className:az,children:[(0,R.jsx)(`img`,{src:`https://cdn.simpleicons.org/claude`,alt:`Claude`,className:`h-4 w-4`}),(0,R.jsx)(`span`,{className:`min-w-0 max-w-full whitespace-nowrap`,children:`Claude Desktop`})]}),n.vsCode&&(0,R.jsxs)($a,{onClick:v,className:az,children:[(0,R.jsx)(yL,{className:`h-4 w-4 text-blue-500`}),(0,R.jsx)(`span`,{className:`min-w-0 max-w-full whitespace-nowrap`,children:`VS Code`})]}),n.vsCodeInsiders&&(0,R.jsxs)($a,{onClick:y,className:az,children:[(0,R.jsx)(yL,{className:`h-4 w-4 text-teal-400`}),(0,R.jsx)(`span`,{className:`min-w-0 max-w-full whitespace-nowrap`,children:`VS Code Insiders`})]}),n.geminiCli&&(0,R.jsxs)($a,{onClick:S,className:az,children:[(0,R.jsx)(`img`,{src:`https://cdn.simpleicons.org/googlegemini`,alt:`Gemini`,className:`h-4 w-4`}),(0,R.jsx)(`span`,{className:`min-w-0 max-w-full whitespace-nowrap`,children:`Gemini CLI`})]}),n.codexCli&&(0,R.jsxs)($a,{onClick:C,className:az,children:[(0,R.jsx)(`img`,{src:`https://inspector-cdn.mcp-use.com/providers/openai.png`,alt:`Codex`,className:`h-4 w-4`}),(0,R.jsx)(`span`,{className:`min-w-0 max-w-full whitespace-nowrap`,children:`Codex CLI`})]})]})]}),(0,R.jsx)(RI,{open:s,onOpenChange:c,children:(0,R.jsx)(BI,{scrollable:!0,className:`max-w-3xl max-h-[80vh]`,children:T()})})]})}function sz({className:e,state:t=`collapsed`,to:n=`/`,showLabel:r=t===`expanded`,labelParts:i=`full`,pinSymbolInIconColumn:a=!1,size:o}){let[s,c]=(0,z.useState)(!1),l=1.5,u=.2/l,d=.8999999999999999/l,f=r&&(t===`expanded`||i===`inspector`),p=o??(a?20:t===`expanded`?40:20),m=(0,R.jsx)(`div`,{className:`relative`,children:(0,R.jsxs)(Pe.svg,{viewBox:`0 0 500 500`,initial:`rest`,animate:s?`hover`:`rest`,className:`text-foreground`,style:{width:p,height:p},children:[(0,R.jsxs)(Pe.g,{variants:{rest:{opacity:1},hover:{opacity:[1,0,0,1],transition:{duration:l,times:[0,u,d,1],ease:`easeInOut`}}},fill:`currentColor`,fillRule:`nonzero`,stroke:`currentColor`,strokeWidth:4,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,R.jsx)(`path`,{d:`M105.933 0C164.437 0.000116002 211.865 47.607 211.865 106.333C211.865 131.829 210.493 158.403 221.068 181.602L228.975 198.947C243.584 230.997 269.265 256.7 301.303 271.336L316.155 278.121C340.142 289.079 367.694 287.335 394.066 287.335C452.571 287.335 499.999 334.942 499.999 393.668C499.999 452.394 452.571 500.001 394.066 500.001C335.562 500.001 288.134 452.394 288.134 393.668C288.134 368.974 289.24 343.275 278.992 320.807L270.586 302.38C255.948 270.29 230.214 244.565 198.118 229.939L180.164 221.758C157.282 211.331 131.078 212.666 105.933 212.666C47.4278 212.666 4.86252e-05 165.059 0 106.333C0 47.607 47.4278 0 105.933 0Z`}),(0,R.jsx)(`circle`,{cx:`100.426`,cy:`399.575`,r:`100.426`}),(0,R.jsx)(`path`,{d:`M500 100.426C500 155.889 455.037 200.851 399.574 200.851C344.11 200.851 299.148 155.889 299.148 100.426C299.148 44.962 344.11 0 399.574 0C455.037 0 500 44.962 500 100.426Z`})]}),(0,R.jsxs)(`g`,{fill:`none`,stroke:`currentColor`,strokeWidth:4,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,R.jsx)(cz,{d:`M105.933 0C164.437 0.000116002 211.865 47.607 211.865 106.333C211.865 131.829 210.493 158.403 221.068 181.602L228.975 198.947C243.584 230.997 269.265 256.7 301.303 271.336L316.155 278.121C340.142 289.079 367.694 287.335 394.066 287.335C452.571 287.335 499.999 334.942 499.999 393.668C499.999 452.394 452.571 500.001 394.066 500.001C335.562 500.001 288.134 452.394 288.134 393.668C288.134 368.974 289.24 343.275 278.992 320.807L270.586 302.38C255.948 270.29 230.214 244.565 198.118 229.939L180.164 221.758C157.282 211.331 131.078 212.666 105.933 212.666C47.4278 212.666 4.86252e-05 165.059 0 106.333C0 47.607 47.4278 0 105.933 0Z`,times:{T0:0,T1:u,T2:d,T3:1},total:l}),(0,R.jsx)(lz,{cx:100.426,cy:399.575,r:100.426,times:{T0:0,T1:u,T2:d,T3:1},total:l}),(0,R.jsx)(cz,{d:`M500 100.426C500 155.889 455.037 200.851 399.574 200.851C344.11 200.851 299.148 155.889 299.148 100.426C299.148 44.962 344.11 0 399.574 0C455.037 0 500 44.962 500 100.426Z`,times:{T0:0,T1:u,T2:d,T3:1},total:l})]})]})}),h=r?(0,R.jsx)(`span`,{className:L(`font-ubuntu flex items-center gap-2 whitespace-nowrap`,a?L(`pl-(--sidebar-nav-text-pl-absolute)`,f?`relative opacity-100 blur-0`:`pointer-events-none absolute left-0 top-1/2 w-0 -translate-y-1/2 overflow-hidden opacity-0 blur-[3px]`):i===`inspector`?`mr-0`:`mr-3`),children:i===`full`?(0,R.jsxs)(R.Fragment,{children:[(0,R.jsx)(`span`,{className:`text-xl font-bold leading-none text-foreground [text-box:trim-both_cap_alphabetic]`,children:`mcp-use`}),(0,R.jsx)(`span`,{className:`text-lg font-sans font-light leading-none tracking-wide text-muted-foreground [text-box:trim-both_cap_alphabetic]`,children:`Inspector`})]}):(0,R.jsx)(`span`,{className:`text-base font-medium leading-none text-foreground [text-box:trim-both_cap_alphabetic]`,children:`Inspector`})}):null,g=a?(0,R.jsxs)(`div`,{className:L(`relative flex shrink-0 items-center`,f?`min-w-(--sidebar-width-icon)`:`w-(--sidebar-width-icon)`),children:[(0,R.jsx)(`div`,{className:`pointer-events-none absolute inset-y-0 left-0 flex w-(--sidebar-width-icon) items-center justify-center`,children:(0,R.jsx)(`div`,{className:`pointer-events-auto`,children:m})}),h]}):i===`inspector`?(0,R.jsxs)(`span`,{className:`flex items-center gap-2.5`,children:[m,h]}):(0,R.jsxs)(R.Fragment,{children:[m,h]});return(0,R.jsx)(rF,{to:n,className:L(`flex items-center transition-opacity`,!a&&i!==`inspector`&&`-my-3`,e),onMouseEnter:()=>c(!0),onMouseLeave:()=>c(!1),children:g})}function cz({d:e,times:t,total:n}){let{T0:r,T1:i,T2:a,T3:o}=t;return(0,R.jsx)(Pe.path,{d:e,variants:{rest:{pathLength:0,opacity:0},hover:{pathLength:[0,0,1,1],opacity:[0,0,1,1],transition:{duration:n,times:[r,i,a,o],ease:`easeInOut`}}}})}function lz({cx:e,cy:t,r:n,times:r,total:i}){let{T0:a,T1:o,T2:s,T3:c}=r;return(0,R.jsx)(Pe.circle,{cx:e,cy:t,r:n,variants:{rest:{pathLength:0,opacity:0},hover:{pathLength:[0,0,1,1],opacity:[0,0,1,1],transition:{duration:i,times:[a,o,s,c],ease:`easeInOut`}}}})}var uz=(0,z.createContext)(void 0);function dz(){let e=(0,z.use)(uz);if(e===void 0)throw Error(`useTheme must be used within a ThemeProvider`);return e}function fz({children:e,defaultTheme:t=`system`,storageKey:n=`theme`,forcedTheme:r}){let[i,a]=(0,z.useState)(r||t),[o,s]=(0,z.useState)(!1),c=()=>typeof window>`u`?`light`:window.matchMedia(`(prefers-color-scheme: dark)`).matches?`dark`:`light`,l=i===`system`?c():i,u=e=>{let t=document.documentElement,i=e===`system`?c():e;t.classList.remove(`light`,`dark`),t.classList.add(i),r||localStorage.setItem(n,e)};return(0,z.useEffect)(()=>{s(!0);let e=localStorage.getItem(n),i=r||e||t;a(i),u(i)},[t,n,r]),(0,z.useEffect)(()=>{if(i!==`system`)return;let e=window.matchMedia(`(prefers-color-scheme: dark)`),t=()=>{u(`system`)};return e.addEventListener(`change`,t),()=>e.removeEventListener(`change`,t)},[i]),(0,z.useEffect)(()=>{o&&u(i)},[i,o]),(0,R.jsx)(uz,{value:{theme:i,setTheme:e=>{if(r){console.warn(`[ThemeProvider] Theme is forced via URL parameter, ignoring setTheme call`);return}a(e)},resolvedTheme:l},children:e})}function pz({ref:e,shimmerColor:t,shimmerSize:n=`0.05em`,shimmerDuration:r=`3s`,borderRadius:i=`100px`,background:a,className:o,children:s,...c}){let{theme:l}=dz();return(0,R.jsxs)(`button`,{style:{"--spread":`90deg`,"--shimmer-color":t||(l===`dark`?`#000000`:`#ffffff`),"--radius":i,"--speed":r,"--cut":n,"--bg":a||(l===`dark`?`rgba(255, 255, 255, 1)`:`rgba(0, 0, 0, 1)`)},className:L(`group relative z-0 flex cursor-pointer items-center justify-center overflow-hidden [border-radius:var(--radius)] border px-6 py-3 whitespace-nowrap [background:var(--bg)]`,`transform-gpu transition-transform duration-300 ease-in-out active:translate-y-px`,`dark:text-white text-black dark:border-white/10 border-black/10`,o),ref:e,...c,children:[(0,R.jsx)(`div`,{className:L(`-z-30 blur-[2px]`,`@container-[size] absolute inset-0 overflow-visible`),children:(0,R.jsx)(`div`,{className:`animate-shimmer-slide absolute inset-0 aspect-[1] h-[100cqh] rounded-none mask-none`,children:(0,R.jsx)(`div`,{className:`animate-spin-around absolute -inset-full w-auto [translate:0_0] rotate-0 [background:conic-gradient(from_calc(270deg-(var(--spread)*0.5)),transparent_0,var(--shimmer-color)_var(--spread),transparent_var(--spread))]`})})}),s,(0,R.jsx)(`div`,{className:L(`absolute inset-0 size-full`,`rounded-2xl px-4 py-1.5 text-sm font-medium`,`transform-gpu transition-all duration-300 ease-in-out`,`dark:shadow-[inset_0_-8px_10px_#0000001f] dark:group-hover:shadow-[inset_0_-6px_10px_#0000003f] dark:group-active:shadow-[inset_0_-10px_10px_#0000003f] shadow-[inset_0_-8px_10px_#ffffff1f] group-hover:shadow-[inset_0_-6px_10px_#ffffff3f] group-active:shadow-[inset_0_-10px_10px_#ffffff3f]`)}),(0,R.jsx)(`div`,{className:L(`absolute [inset:var(--cut)] -z-20 [border-radius:var(--radius)] bg-black dark:bg-white`)})]})}pz.displayName=`ShimmerButton`;function mz(e){switch(e){case`ready`:return`bg-emerald-600 animate-status-pulse`;case`failed`:return`bg-rose-600 animate-status-pulse-red`;default:return`bg-yellow-500 animate-status-pulse-yellow`}}function hz(e){switch(e){case`ready`:return`Connected`;case`failed`:return`Failed`;default:return e}}function gz({status:e,className:t}){return(0,R.jsxs)(et,{children:[(0,R.jsx)(we,{render:(0,R.jsx)(`div`,{className:L(`w-2 h-2 rounded-full shrink-0`,mz(e),t)}),nativeButton:!1}),(0,R.jsx)(lt,{children:(0,R.jsx)(`p`,{children:hz(e)})})]})}var _z=`h-6 px-2 text-xs bg-yellow-500/20 border-0 dark:bg-yellow-400/10 text-yellow-800 dark:text-yellow-500 shrink-0`;function vz(e){try{sessionStorage.setItem(QF,JSON.stringify({url:e.url,name:e.name||`Auto-connected Server`,transportType:e.transportType||`http`,connectionMode:`auto`}))}catch{}}function yz({server:e,className:t}){let{state:n,authUrl:r,authenticate:i}=e;return n!==`pending_auth`&&n!==`authenticating`?null:n===`authenticating`?(0,R.jsxs)(Gt,{size:`sm`,variant:`outline`,disabled:!0,className:L(_z,t),children:[(0,R.jsx)(fi,{className:`h-3 w-3 animate-spin mr-1`}),`Authenticating`]}):i?(0,R.jsx)(Gt,{"data-testid":`server-header-authenticate`,size:`sm`,variant:`outline`,className:L(_z,t),onClick:t=>{t.stopPropagation(),vz(e),i()},children:`Authenticate`}):r?(0,R.jsx)(Gt,{size:`sm`,variant:`outline`,className:L(_z,t),render:(0,R.jsx)(`a`,{href:r,"data-testid":`server-header-authenticate`,onClick:t=>{t.stopPropagation(),vz(e)}}),nativeButton:!1,children:`Authenticate`}):null}function bz({connections:e,selectedServer:t,onServerSelect:n,mobileMode:r=!1,variant:i=`default`,compactHeader:a=!1}){let o=LN(),s=t=>{e.some(e=>e.id===t)&&n(t)},c=(0,R.jsxs)(Za,{className:`w-[calc(100vw-2rem)] sm:w-[300px]`,align:`start`,children:[(0,R.jsx)(Qa,{className:`cursor-pointer hover:bg-zinc-100 dark:hover:bg-zinc-800`,onClick:()=>o(`/`),children:`MCP Servers`}),(0,R.jsx)(no,{}),e.length===0?(0,R.jsx)(`div`,{className:`px-2 py-4 text-sm text-muted-foreground dark:text-zinc-400 text-center`,children:`No servers connected. Go to the dashboard to add one.`}):e.map(e=>(0,R.jsxs)($a,{onClick:()=>s(e.id),className:`flex items-center gap-3`,children:[(0,R.jsx)(ZI,{server:e,size:`sm`}),(0,R.jsxs)(`div`,{className:`flex items-center gap-2 flex-1`,children:[(0,R.jsx)(`div`,{className:`font-medium`,children:Xj(e)}),(0,R.jsx)(gz,{status:e.state})]})]},e.id)),(0,R.jsx)(no,{}),(0,R.jsx)($a,{onClick:()=>o(`/`),children:(0,R.jsx)(`span`,{className:`text-blue-600 dark:text-blue-400`,children:`+ Add new server`})})]});return r?(0,R.jsx)(`div`,{className:`flex items-center gap-2`,children:(0,R.jsx)(`div`,{className:`relative`,children:(0,R.jsxs)(Ya,{children:[(0,R.jsx)(Xa,{render:(0,R.jsxs)(Gt,{variant:`ghost`,className:`h-11 px-2 bg-black dark:bg-white text-white dark:text-black border-black dark:border-white hover:bg-gray-800 dark:hover:bg-zinc-100 hover:border-gray-800 dark:hover:border-zinc-200 flex items-center gap-1.5`,children:[t?(0,R.jsx)(ZI,{server:t,size:`md`}):(0,R.jsx)(Fi,{className:`h-5 w-5`}),(0,R.jsx)(Ir,{className:`h-4 w-4`})]}),nativeButton:!0}),c]})})}):i===`header`?(0,R.jsx)(`div`,{className:`flex min-w-0 items-center gap-2`,children:(0,R.jsxs)(Ya,{children:[(0,R.jsx)(Xa,{render:(0,R.jsxs)(`button`,{type:`button`,className:`inline-flex max-w-full min-w-0 items-center gap-1.5 border-0 bg-transparent p-0 cursor-pointer text-foreground transition-opacity hover:opacity-80`,children:[t&&(0,R.jsx)(ZI,{server:t,size:`sm`,className:`!size-5 shrink-0`}),(0,R.jsx)(`span`,{className:`truncate text-sm`,children:t?Xj(t):`Select server`}),t&&(0,R.jsxs)(R.Fragment,{children:[(0,R.jsx)(gz,{status:t.state}),!a&&(0,R.jsx)(yz,{server:t})]}),(0,R.jsx)(Ir,{className:`size-3.5 shrink-0 text-muted-foreground`})]}),nativeButton:!0}),c]})}):(0,R.jsx)(`div`,{className:`flex items-center gap-2`,children:(0,R.jsx)(`div`,{className:`relative`,children:(0,R.jsxs)(Ya,{children:[(0,R.jsx)(Xa,{render:(0,R.jsxs)(pz,{className:L(`min-w-0 sm:min-w-[200px] p-0 px-1 text-sm h-11 justify-start text-white dark:text-black border-black dark:border-white hover:bg-gray-800 dark:hover:bg-zinc-100 hover:border-gray-800 dark:hover:border-zinc-200`,!t&&`pl-4`),children:[t&&(0,R.jsx)(ZI,{server:t,size:`md`,className:`mr-2`}),(0,R.jsxs)(`div`,{className:`flex items-center gap-2 flex-1`,children:[(0,R.jsx)(`span`,{className:`truncate lg:max-w-[120px] xl:max-w-none`,children:t?Xj(t):`Select server to inspect`}),t&&(0,R.jsx)(`div`,{className:`flex items-center gap-2`,children:t.error&&t.state!==`ready`?(0,R.jsxs)(et,{children:[(0,R.jsx)(we,{render:(0,R.jsx)(`button`,{onClick:e=>{e.stopPropagation()},className:`w-2 h-2 rounded-full bg-rose-500 animate-status-pulse-red hover:bg-rose-600 transition-colors`,title:`Click to copy error message`,"aria-label":`Copy error message to clipboard`}),nativeButton:!0}),(0,R.jsx)(lt,{children:(0,R.jsx)(`p`,{className:`max-w-xs`,children:t.error})})]}):(0,R.jsx)(`div`,{className:`w-2 h-2 rounded-full ${t.state===`ready`?`bg-emerald-600 animate-status-pulse`:t.state===`failed`?`bg-rose-600 animate-status-pulse-red`:`bg-yellow-500 animate-status-pulse-yellow`}`})})]})]}),nativeButton:!0}),c]})})})}function xz(e){if(!e)return null;try{let t=new URL(e);if(t.protocol===`https:`)return t.origin}catch{}return null}function Sz(e,t){return e===`tools`?t.tools.length:e===`prompts`?t.prompts.length:e===`resources`?t.resources.length:e===`sampling`?t.pendingSamplingRequests?.length||0:e===`elicitation`?t.pendingElicitationRequests?.length||0:e===`notifications`?t.unreadNotificationCount:0}function Cz(e,t,n){return n&&t>0&&[`sampling`,`elicitation`,`notifications`].includes(e)}var wz=[{id:`server-metadata`,label:`Server Metadata`,icon:si},{id:`separator`},{id:`chat`,label:`Chat`,icon:vi,alwaysExpanded:!0},{id:`separator`},{id:`tools`,label:`Tools`,icon:Yi},{id:`prompts`,label:`Prompts`,icon:yi},{id:`resources`,label:`Resources`,icon:$r},{id:`sampling`,label:`Sampling`,icon:ti},{id:`elicitation`,label:`Elicitation`,icon:zi},{id:`notifications`,label:`Notifications`,icon:Mr},{id:`separator`},{id:`connection-settings`,label:`Connection Settings`,icon:Ii}],Tz=z.createContext(void 0);function Ez(e){let t=z.useContext(Tz);if(t===void 0&&!e)throw Error(Vt(47));return t}function Dz(){return{...ft(),disabled:!1,modal:!1,focusManagerModal:!1,instantType:void 0,openMethod:null,openChangeReason:null,titleElementId:void 0,descriptionElementId:void 0,stickIfOpen:!0,nested:!1,openOnHover:!1,closeDelay:0,hasViewport:!1}}var Oz={...De,disabled:St(e=>e.disabled),instantType:St(e=>e.instantType),openMethod:St(e=>e.openMethod),openChangeReason:St(e=>e.openChangeReason),modal:St(e=>e.modal),focusManagerModal:St(e=>e.focusManagerModal),stickIfOpen:St(e=>e.stickIfOpen),titleElementId:St(e=>e.titleElementId),descriptionElementId:St(e=>e.descriptionElementId),openOnHover:St(e=>e.openOnHover),closeDelay:St(e=>e.closeDelay),hasViewport:St(e=>e.hasViewport)},kz=class e extends Tt{constructor(e,t,n=!1){let r={...Dz(),...e},i=new at;r.open&&e?.mounted===void 0&&(r.mounted=!0),r.floatingRootContext=We(i,t,n),super(r,{popupRef:z.createRef(),backdropRef:z.createRef(),internalBackdropRef:z.createRef(),onOpenChange:void 0,onOpenChangeComplete:void 0,triggerFocusTargetRef:z.createRef(),beforeContentFocusGuardRef:z.createRef(),stickIfOpenTimeout:new xt,triggerElements:i},Oz)}setOpen=(e,t)=>{let n=t.reason===o,r=t.reason===`trigger-press`&&t.event.detail===0,i=!e&&(t.reason===`escape-key`||t.reason==null),a=je(t),s=this.select(`activeTriggerId`);if(!e&&t.reason===`close-press`&&t.trigger==null&&s!=null&&(t.trigger=this.context.triggerElements.getById(s)??this.select(`activeTriggerElement`)??void 0),this.context.onOpenChange?.(e,t),t.isCanceled)return;this.state.floatingRootContext.dispatchOpenChange(e,t);let c=()=>{let n={open:e,openChangeReason:t.reason};_t(n,e,t.trigger,a()),this.update(n)};n?(this.set(`stickIfOpen`,!0),this.context.stickIfOpenTimeout.start(500,()=>{this.set(`stickIfOpen`,!1)}),br.flushSync(c)):c(),r||i?this.set(`instantType`,r?`click`:`dismiss`):t.reason===`focus-out`?this.set(`instantType`,`focus`):this.set(`instantType`,void 0)};static useStore(t,n){let{store:r,internalStore:i}=Le(t,(t,r)=>new e(n,t,r));return z.useEffect(()=>i?.disposeEffect(),[i]),r}disposeEffect=()=>this.context.stickIfOpenTimeout.disposeEffect()};function Az({props:e}){let{children:t,open:n,defaultOpen:r=!1,onOpenChange:i,onOpenChangeComplete:a,modal:o=!1,handle:s,triggerId:c,defaultTriggerId:l=null}=e,u=kz.useStore(s?.store,{modal:o,open:r,openProp:n,activeTriggerId:l,triggerIdProp:c});Fe(u,n,r,l),u.useControlledProp(`openProp`,n),u.useControlledProp(`triggerIdProp`,c);let d=u.useState(`open`),f=u.useState(`mounted`),p=u.useState(`payload`),m=Ke()!=null;u.useContextCallback(`onOpenChange`,i),u.useContextCallback(`onOpenChangeComplete`,a),Be(u,d),Me(u);let{forceUnmount:h}=ot(d,u,()=>{u.update({stickIfOpen:!0,openChangeReason:null})});u.useSyncedValues({modal:o,nested:m}),z.useEffect(()=>{d||u.context.stickIfOpenTimeout.clear()},[u,d]);let g=z.useCallback(()=>{u.setOpen(!1,te(_e))},[u]);z.useImperativeHandle(e.actionsRef,()=>({unmount:h,close:g}),[h,g]);let _=d||f,v=z.useMemo(()=>({store:u}),[u]);return(0,R.jsxs)(Tz.Provider,{value:v,children:[_&&(0,R.jsx)(Mz,{store:u,modal:o}),typeof t==`function`?t({payload:p}):t]})}function jz(e){return Ez(!0)?(0,R.jsx)(Az,{props:e}):(0,R.jsx)(Ye,{children:(0,R.jsx)(Az,{props:e})})}function Mz({store:e,modal:t}){let n=m(e.useState(`floatingRootContext`),{outsidePressEvent:{mouse:t===`trap-focus`?`sloppy`:`intentional`,touch:`sloppy`}});return $e(e,{activeTriggerProps:n.reference??Wt,inactiveTriggerProps:n.trigger??Wt,popupProps:z.useMemo(()=>zt(mt,n.floating),[n.floating])}),null}var Nz=z.forwardRef(function(e,t){let{render:n,className:r,style:i,disabled:o=!1,nativeButton:s=!0,handle:c,payload:l,openOnHover:u=!1,delay:d=300,closeDelay:f=0,id:p,...m}=e,h=Ez(!0),g=c?.store??h?.store;if(!g)throw Error(Vt(74));let _=O(p),v=g.useState(`isTriggerActive`,_),y=g.useState(`floatingRootContext`),b=g.useState(`isOpenedByTrigger`,_),S=g.useState(`triggerPopupId`,_),C=z.useRef(null),{registerTrigger:w,isMountedByThisTrigger:T}=Ce(_,C,g,{payload:l,disabled:o,openOnHover:u,closeDelay:f}),E=g.useState(`openChangeReason`),ee=g.useState(`stickIfOpen`),D=g.useState(`openMethod`),te=g.useState(`focusManagerModal`),ne=a(y,{enabled:!o&&y!=null&&u&&(D!==`touch`||E!==`trigger-press`),mouseOnly:!0,move:!1,handleClose:se(),restMs:d,delay:{close:f},triggerElementRef:C,isActiveTrigger:v,isClosing:()=>g.select(`transitionStatus`)===`ending`}),re=Sn(y,{enabled:y!=null,stickIfOpen:ee}),ie=dn(()=>g.select(`open`),e=>{g.set(`openMethod`,e)}),k=g.useState(`triggerProps`,T),{getButtonProps:A,buttonRef:j}=Lt({disabled:o,native:s}),ae={open(e){return e&&E===`trigger-press`?Ue.open(e):Ee.open(e)}},{preFocusGuardRef:oe,handlePreFocusGuardFocus:ce,handleFocusTargetFocus:M}=xr(g,C),N=Ft(`button`,e,{state:{disabled:o,open:b},ref:[j,t,w,C],props:[re.reference,ne,k,ie,{[x]:``,id:_,"aria-haspopup":`dialog`,"aria-expanded":b,"aria-controls":S},m,A],stateAttributesMapping:ae});return T&&!te?(0,R.jsxs)(z.Fragment,{children:[(0,R.jsx)(ut,{ref:oe,onFocus:ce}),(0,R.jsx)(z.Fragment,{children:N},_),(0,R.jsx)(ut,{ref:g.context.triggerFocusTargetRef,onFocus:M})]}):(0,R.jsx)(z.Fragment,{children:N},_)}),Pz=z.createContext(void 0);function Fz(){let e=z.useContext(Pz);if(e===void 0)throw Error(Vt(45));return e}var Iz=z.forwardRef(function(e,t){let{keepMounted:n=!1,...r}=e,{store:i}=Ez();return i.useState(`mounted`)||n?(0,R.jsx)(Pz.Provider,{value:n,children:(0,R.jsx)(oe,{ref:t,...r})}):null}),Lz=z.createContext(void 0);function Rz(){let e=z.useContext(Lz);if(!e)throw Error(Vt(46));return e}var zz=z.forwardRef(function(e,t){let{render:n,className:r,style:i,anchor:a,positionMethod:o=`absolute`,side:s=`bottom`,align:l=`center`,sideOffset:u=0,alignOffset:d=0,collisionBoundary:f=`clipping-ancestors`,collisionPadding:m=5,arrowPadding:h=5,sticky:g=!1,disableAnchorTracking:_=!1,collisionAvoidance:v=N,...y}=e,{store:b}=Ez(),x=Fz(),C=c(),w=b.useState(`floatingRootContext`),T=b.useState(`mounted`),E=b.useState(`open`),ee=b.useState(`openChangeReason`),D=b.useState(`activeTriggerElement`),te=b.useState(`modal`),ne=b.useState(`openMethod`),re=b.useState(`positionerElement`),O=b.useState(`instantType`),ie=b.useState(`transitionStatus`),k=b.useState(`hasViewport`),j=z.useRef(null),ae=p(re,!1,!1),oe=S({anchor:a,floatingRootContext:w,positionMethod:o,mounted:T,side:s,sideOffset:u,align:l,alignOffset:d,arrowPadding:h,collisionBoundary:f,collisionPadding:m,sticky:g,disableAnchorTracking:_,keepMounted:x,nodeId:C,collisionAvoidance:v,adaptiveOrigin:k?ye:void 0}),se=w.useState(`domReferenceElement`);Rt(()=>{let e=se,t=j.current;if(e&&(j.current=e),t&&e&&e!==t){b.set(`instantType`,void 0);let e=new AbortController;return ae(()=>{b.set(`instantType`,`trigger-change`)},e.signal),()=>{e.abort()}}},[se,ae,b]),an(E&&te===!0&&ee!==`trigger-hover`,ne===`touch`,re,D);let ce=z.useCallback(e=>{b.set(`positionerElement`,e)},[b]),M=st(e,{open:E,side:oe.side,align:oe.align,anchorHidden:oe.anchorHidden,instant:O},{styles:oe.positionerStyles,transitionStatus:ie,props:y,refs:[t,ce],hidden:!T,inert:!E});return(0,R.jsxs)(Lz.Provider,{value:oe,children:[T&&te===!0&&ee!==`trigger-hover`&&(0,R.jsx)(wn,{ref:b.context.internalBackdropRef,inert:sn(!E),cutout:D}),(0,R.jsx)(A,{id:C,children:M})]})}),Bz=z.createContext(void 0);function Vz(){let[e,t]=z.useState(0),n=Pt(()=>(t(e=>e+1),()=>{t(e=>Math.max(0,e-1))}));return{context:z.useMemo(()=>({register:n}),[n]),hasClosePart:e>0}}function Hz(e){let{value:t,children:n}=e;return(0,R.jsx)(Bz.Provider,{value:t,children:n})}var Uz={...dt,...it},Wz=z.forwardRef(function(e,t){let{render:n,className:r,style:i,initialFocus:a,finalFocus:o,...s}=e,{store:c}=Ez(),l=Rz(),u=Cn(!0)!=null,{context:d,hasClosePart:f}=Vz(),p=c.useState(`open`),m=c.useState(`openMethod`),h=c.useState(`instantType`),_=c.useState(`transitionStatus`),v=c.useState(`popupProps`),y=c.useState(`titleElementId`),b=c.useState(`descriptionElementId`),x=c.useState(`modal`),S=c.useState(`mounted`),C=c.useState(`openChangeReason`),w=c.useState(`activeTriggerElement`),T=c.useState(`floatingRootContext`),E=T.useState(`floatingId`),ee=c.useState(`disabled`),D=c.useState(`openOnHover`),te=c.useState(`closeDelay`),ne=s.id??E;g({open:p,ref:c.context.popupRef,onComplete(){p&&c.context.onOpenChangeComplete?.(!0)}}),Ne(T,{enabled:D&&!ee,closeDelay:te});let re=a===void 0?Xe(c.context.popupRef):a,O=x!==!1&&f;c.useSyncedValue(`focusManagerModal`,O);let ie=z.useCallback(e=>{c.set(`popupElement`,e)},[c]),k=Ft(`div`,e,{state:{open:p,side:l.side,align:l.align,instant:h,transitionStatus:_},ref:[t,c.context.popupRef,ie],props:[v,{id:ne,role:`dialog`,...mt,"aria-labelledby":y,"aria-describedby":b,onKeyDown(e){u&&Qt.has(e.key)&&e.stopPropagation()}},xe(_),s],stateAttributesMapping:Uz});return(0,R.jsx)(rn,{context:T,openInteractionType:m,modal:O,disabled:!S||C===`trigger-hover`,initialFocus:re,returnFocus:o,restoreFocus:`popup`,previousFocusableElement:Bt(w)?w:void 0,nextFocusableElement:c.context.triggerFocusTargetRef,beforeContentFocusGuardRef:c.context.beforeContentFocusGuardRef,children:(0,R.jsx)(Hz,{value:d,children:k})})});function Gz({...e}){return(0,R.jsx)(jz,{"data-slot":`popover`,...e})}function Kz(e){return(0,R.jsx)(Nz,{"data-slot":`popover-trigger`,...e})}function qz({className:e,align:t=`center`,alignOffset:n=0,side:r=`bottom`,sideOffset:i=4,...a}){return(0,R.jsx)(Iz,{children:(0,R.jsx)(zz,{align:t,alignOffset:n,side:r,sideOffset:i,className:`isolate z-50`,children:(0,R.jsx)(Wz,{"data-slot":`popover-content`,className:L(`z-50 flex w-72 origin-(--transform-origin) flex-col gap-4 rounded-md bg-popover p-4 text-sm text-popover-foreground shadow-md ring-1 ring-foreground/10 outline-hidden duration-100 data-[side=bottom]:slide-in-from-top-2 data-[side=inline-end]:slide-in-from-left-2 data-[side=inline-start]:slide-in-from-right-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95`,e),...a})})})}var Jz={success:`border-emerald-700/20 bg-emerald-700/10 text-emerald-700 dark:border-emerald-400/30 dark:bg-emerald-400/10 dark:text-emerald-400`,failed:`border-red-500/20 bg-red-500/10 text-red-500 dark:border-red-400/30 dark:bg-red-400/10 dark:text-red-400`,warning:`border-amber-700/20 bg-amber-700/10 text-amber-700 dark:border-amber-400/30 dark:bg-amber-400/10 dark:text-amber-400`,loading:`border-purple-500/20 bg-purple-500/10 text-purple-500 dark:border-purple-400/30 dark:bg-purple-400/10 dark:text-purple-400 animate-spin`},Yz=`size-4 shrink-0 rounded-full border p-0.5`;function Xz({state:e,className:t}){let n=L(Yz,Jz[e],t);switch(e){case`success`:return(0,R.jsx)(Fr,{className:n,"aria-hidden":!0});case`failed`:return(0,R.jsx)(zr,{className:n,"aria-hidden":!0});case`warning`:return(0,R.jsx)(Ki,{className:n,"aria-hidden":!0});case`loading`:return(0,R.jsx)(fi,{className:n,"aria-hidden":!0});default:return null}}function Zz(){return`text-emerald-700 dark:text-emerald-400`}function Qz({onStop:e,showCopiedBanner:t=!1}){return(0,R.jsxs)(R.Fragment,{children:[t&&(0,R.jsxs)(`div`,{className:L(`flex items-center gap-2 text-sm -mt-1`,Zz()),children:[(0,R.jsx)(Xz,{state:`success`}),(0,R.jsx)(`span`,{children:`URL copied to clipboard`})]}),(0,R.jsxs)(`div`,{className:`flex items-center justify-between`,children:[(0,R.jsx)(`h4`,{className:`font-semibold text-sm`,children:`Tunnel URL`}),(0,R.jsxs)(`a`,{href:`https://manufact.com/docs/tunneling`,target:`_blank`,rel:`noopener noreferrer`,className:`flex items-center gap-1 text-xs text-muted-foreground hover:text-foreground transition-colors`,children:[`Docs`,(0,R.jsx)(Ar,{className:`size-3`})]})]}),(0,R.jsxs)(`div`,{children:[(0,R.jsx)(`h5`,{className:`font-semibold text-sm mb-2`,children:`Use in ChatGPT & Claude`}),(0,R.jsxs)(`ol`,{className:`space-y-2 text-xs text-muted-foreground`,children:[(0,R.jsxs)(`li`,{className:`flex gap-2`,children:[(0,R.jsx)(`span`,{className:`font-semibold text-foreground`,children:`1.`}),(0,R.jsxs)(`span`,{children:[`Enable`,` `,(0,R.jsx)(`a`,{href:`https://chatgpt.com/plugins#settings/Security`,target:`_blank`,rel:`noopener noreferrer`,className:`font-medium text-foreground underline underline-offset-2 hover:text-purple-600 dark:hover:text-purple-400`,children:`dev mode`}),` `,`from settings`]})]}),(0,R.jsxs)(`li`,{className:`flex gap-2`,children:[(0,R.jsx)(`span`,{className:`font-semibold text-foreground`,children:`2.`}),(0,R.jsxs)(`span`,{children:[(0,R.jsx)(`a`,{href:`https://chatgpt.com/plugins#settings/Connectors?create-connector=true&redirectAfter=%2Fplugins`,target:`_blank`,rel:`noopener noreferrer`,className:`font-medium text-foreground underline underline-offset-2 hover:text-purple-600 dark:hover:text-purple-400`,children:`Add a connector`}),` `,`in App & Connectors`]})]}),(0,R.jsxs)(`li`,{className:`flex gap-2`,children:[(0,R.jsx)(`span`,{className:`font-semibold text-foreground`,children:`3.`}),(0,R.jsx)(`span`,{children:`Use the tunnel URL in the input`})]})]})]}),(0,R.jsxs)(`button`,{type:`button`,onClick:()=>void e(),className:`flex items-center gap-1.5 text-xs text-red-600 dark:text-red-400 hover:text-red-700 dark:hover:text-red-300 transition-colors cursor-pointer`,children:[(0,R.jsx)(Vi,{className:`size-3 fill-current`}),`Stop Tunnel`]})]})}function $z(e){try{let t=new URL(e),n=t.pathname+t.search;return t.host+(n&&n!==`/`?n:``)}catch{return e}}function eB({copied:e,onCopy:t,className:n}){return(0,R.jsx)(`button`,{type:`button`,onClick:e=>{e.stopPropagation(),t()},"aria-label":e?`URL copied`:`Copy URL`,className:L(`shrink-0 cursor-pointer p-0.5 rounded-sm text-muted-foreground hover:text-foreground transition-opacity opacity-0 group-hover:opacity-100`,n),children:e?(0,R.jsx)(Xz,{state:`success`,className:`size-3.5`}):(0,R.jsx)(Wr,{className:`size-3.5`})})}function tB({url:e,className:t,tunnelPopover:n}){let[r,i]=(0,z.useState)(!1),[a,o]=(0,z.useState)(!1);if(!e)return null;let s=$z(e),c=n?.mcpUrl??e,l=!!n,u=async()=>{try{await zj(c),i(!0),setTimeout(()=>i(!1),2e3)}catch{IF.error(`Failed to copy URL`)}};(0,z.useEffect)(()=>{if(!n?.autoCopyOnOpen){o(!1);return}o(!0),i(!0);let e=setTimeout(()=>i(!1),2e3);return()=>clearTimeout(e)},[n?.autoCopyOnOpen]);let d=(0,R.jsxs)(R.Fragment,{children:[l?(0,R.jsx)(Lr,{className:`size-3.5 shrink-0`}):(0,R.jsx)(ei,{className:`size-3.5 shrink-0`}),(0,R.jsx)(`span`,{className:`truncate max-w-[min(24rem,30vw)]`,children:s})]}),f=L(`flex items-center gap-1 min-w-0 truncate text-left text-sm cursor-pointer`,l?`text-purple-600 dark:text-purple-400`:`text-blue-500`);return(0,R.jsxs)(`div`,{className:L(`group flex items-center gap-1.5 min-w-0`,t),children:[l?(0,R.jsxs)(Gz,{open:n.open,onOpenChange:n.onOpenChange,children:[(0,R.jsx)(Kz,{render:(0,R.jsx)(`button`,{type:`button`,className:L(f,`hover:opacity-80`),children:d}),nativeButton:!0}),(0,R.jsx)(qz,{className:`w-[calc(100vw-2rem)] sm:w-96`,align:`start`,sideOffset:4,children:(0,R.jsx)(Qz,{showCopiedBanner:a,onStop:async()=>{n.onOpenChange(!1),await n.onStop()}})})]}):(0,R.jsx)(`span`,{className:f,children:d}),(0,R.jsx)(eB,{copied:r,onCopy:()=>void u()})]})}function nB({devFromCli:e,isTunnelStarting:t,waitTicks:n,onStart:r}){if(t)return(0,R.jsxs)(`button`,{disabled:!0,className:`flex items-center gap-1 h-6 px-2 bg-violet-50 dark:bg-violet-950/40 border border-violet-200 dark:border-violet-800 rounded-full opacity-75 cursor-wait shrink-0`,children:[(0,R.jsx)(fi,{className:`size-3 text-violet-500 dark:text-violet-400 animate-spin`}),(0,R.jsxs)(`span`,{className:`text-xs font-medium text-violet-600 dark:text-violet-300 hidden lg:inline`,children:[`Start Tunnel `,(0,R.jsxs)(`span`,{className:`tabular-nums`,children:[n,`s`]})]})]});let i=e===!0,a=e===null;return(0,R.jsxs)(`button`,{type:`button`,onClick:()=>void r(),disabled:!i||a,title:e===!1?"Run `mcp-use dev` from your project to enable tunneling.":a?`Checking dev server…`:void 0,className:L(`flex items-center gap-1 h-6 px-2 border rounded-full transition-colors shrink-0`,i&&!a?`bg-violet-50 dark:bg-violet-950/40 border-violet-200 dark:border-violet-800 hover:bg-violet-100 dark:hover:bg-violet-900/50 cursor-pointer`:`bg-violet-50/60 dark:bg-violet-950/20 border-violet-200 dark:border-violet-800 cursor-not-allowed opacity-70`),children:[a?(0,R.jsx)(fi,{className:`size-3 text-violet-500 dark:text-violet-400 animate-spin`}):(0,R.jsx)(Lr,{className:`size-3 text-violet-500 dark:text-violet-400`}),(0,R.jsx)(`span`,{className:`text-xs font-medium text-violet-600 dark:text-violet-300 hidden lg:inline`,children:`Start Tunnel`})]})}function rB(){return typeof window>`u`?!1:window.__MCP_DEV_CLI__===!0}async function iB(){try{let e=await fetch(Gj(`dev/info`));return e.ok?await e.json():null}catch{return null}}function aB({tunnelUrl:e,setTunnelUrl:t,isTunnelStarting:n,setIsTunnelStarting:r,onTunnelStarted:i}){let[a,o]=(0,z.useState)(null),[s,c]=(0,z.useState)(null),[l,u]=(0,z.useState)(0),d=(0,z.useCallback)((e,n)=>{let r=n?.syncTunnel??!1;if(o(!!e.fromCli),e.mcpUrl&&c(e.mcpUrl),!r)return;if(e.tunnelUrl){t(new URL(e.tunnelUrl).origin);return}let i=xz(e.mcpUrl??null);if(i){t(i);return}t(null)},[t]);return(0,z.useEffect)(()=>{if(!n){u(20);return}u(20);let e=setInterval(()=>u(e=>e>0?e-1:0),1e3);return()=>clearInterval(e)},[n]),(0,z.useEffect)(()=>{let e=!1;if(!rB()){o(!1);return}return(async()=>{let t=await iB();e||(t?d(t,{syncTunnel:!0}):o(!1))})(),()=>{e=!0}},[d]),{devFromCli:a,mcpUrl:s,waitTicks:l,handleStartTunnel:(0,z.useCallback)(async()=>{if(a===!1){IF.error("Start Tunnel requires `mcp-use dev` from your project directory.");return}r(!0);let e=!1;try{let t=await fetch(Gj(`dev/start-tunnel`),{method:`POST`});if(!t.ok){let e=await t.json().catch(()=>({}));IF.error(e.error||`Failed to start tunnel`);return}let n=await iB();if(n?.tunnelUrl||n?.mcpUrl){d(n,{syncTunnel:!0});let e=n.mcpUrl??(n.tunnelUrl?`${n.tunnelUrl.replace(/\/+$/,``)}/mcp`:null);e&&Rj(e),i?.()}e=!0}catch{IF.error(`Failed to start tunnel`)}finally{r(!1)}try{bT(new jo({action:`start`,success:e})).catch(()=>{})}catch{}},[d,a,i,r]),handleStopTunnel:(0,z.useCallback)(async()=>{r(!0);let n=!1;try{let e=await fetch(Gj(`dev/stop-tunnel`),{method:`POST`});if(!e.ok){let t=await e.json().catch(()=>({}));IF.error(t.error||`Failed to stop tunnel`);return}t(null),c(null),IF.success(`Tunnel stopped`),n=!0}catch{IF.error(`Failed to stop tunnel`)}finally{r(!1)}try{bT(new jo({action:`stop`,success:n,tunnelUrl:e})).catch(()=>{})}catch{}},[r,t,e])}}function oB(e){let t=window.matchMedia(`(min-width: 1024px)`);return t.addEventListener(`change`,e),()=>t.removeEventListener(`change`,e)}function sB(){return window.matchMedia(`(min-width: 1024px)`).matches}function cB(){return!0}function lB(){return(0,z.useSyncExternalStore)(oB,sB,cB)}function uB(e){let[t,n]=(0,z.useState)(!1),[r,i]=(0,z.useState)(!1),a=lB(),o=(0,z.useCallback)(()=>{n(!0),i(!0)},[]);return(0,z.useEffect)(()=>{e||(n(!1),i(!1))},[e]),(0,z.useEffect)(()=>{if(!e)return;let t=new URLSearchParams(window.location.search);if(!t.has(`openTunnelPopover`))return;n(!0),i(!0),t.delete(`openTunnelPopover`);let r=t.toString();window.history.replaceState({},``,`${window.location.pathname}${r?`?${r}`:``}`)},[e]),{open:t,onOpenChange:(0,z.useCallback)(e=>{n(e),e||i(!1)},[]),isLgUp:a,autoCopyOnOpen:r,openWithAutoCopy:o}}function dB({connections:e,selectedServer:t,activeTab:n,onServerSelect:r,onTabChange:i,embedded:a=!1,sidebarCollapsed:o=!1}){let{tunnelUrl:s,isTunnelStarting:c,setTunnelUrl:l,setIsTunnelStarting:u,embeddedConfig:d}=nL(),[f,p]=(0,z.useState)(!1),[m]=(0,z.useState)(!0),h=uB(s),g=aB({tunnelUrl:s,setTunnelUrl:l,isTunnelStarting:c,setIsTunnelStarting:u,onTunnelStarted:h.openWithAutoCopy});if(d.singleTab)return null;let _=d.visibleTabs?wz.filter(e=>e.id===`separator`||d.visibleTabs.includes(e.id)):wz,v=!!t,y=!!t&&(qj(t.url??``)||Jj(t.url??``)||!!s),b=t?s?`${s.replace(/\/+$/,``)}${Uj()}`:t.url??``:``,x=g.mcpUrl??(s?`${s.replace(/\/+$/,``)}${Uj()}`:null),S=(e,n)=>{if(!t||!b)return null;let r=e===`desktop`?h.isLgUp:!h.isLgUp;return(0,R.jsxs)(`div`,{className:`flex items-center gap-1 min-w-0`,children:[(0,R.jsx)(tB,{url:b,className:n,tunnelPopover:s&&x&&r?{mcpUrl:x,onStop:g.handleStopTunnel,open:h.open,onOpenChange:h.onOpenChange,autoCopyOnOpen:h.autoCopyOnOpen}:void 0}),y&&!s&&(0,R.jsx)(nB,{devFromCli:g.devFromCli,isTunnelStarting:c,waitTicks:g.waitTicks,onStart:g.handleStartTunnel})]})},C=()=>a?null:(0,R.jsxs)(`div`,{className:`flex items-center gap-2 sm:gap-3 flex-shrink-0`,children:[t&&(0,R.jsx)(R.Fragment,{children:(0,R.jsx)(oz,{serverConfig:{url:b,name:Xj(t),headers:cM(t),serverId:t.id},onSuccess:e=>IF.success(`Opening in ${e}...`),onError:e=>IF.error(`Failed: ${e.message}`),trigger:(0,R.jsxs)(Gt,{variant:`ghost`,className:`bg-zinc-200 dark:bg-zinc-800 hover:bg-zinc-300 dark:hover:bg-zinc-700 rounded-full transition-colors px-3 flex items-center justify-center`,"aria-label":`Add to Client`,children:[(0,R.jsxs)(`span`,{className:`xl:hidden hidden sm:flex items-center gap-1`,children:[(0,R.jsx)(Ai,{className:`size-3`}),`Client`]}),(0,R.jsxs)(`span`,{className:`hidden xl:flex items-center gap-1`,children:[`Add to Client`,(0,R.jsx)(Ir,{className:`size-3`})]})]})})}),(0,R.jsx)(`a`,{href:f?`https://manufact.com/cloud?ref=mcp-use-inspector`:`https://manufact.com/signup?ref=mcp-use-inspector`,target:`_blank`,rel:`noopener noreferrer`,onClick:()=>{try{bT(new Mo({referrer:`mcp-use-inspector`})).catch(()=>{})}catch{}},className:`inline-flex h-8 items-center justify-center rounded-full border border-blue-500/25 bg-blue-500/10 px-4 text-[13px] text-blue-500 outline-none cursor-pointer transition-colors hover:bg-blue-500/15 dark:border-blue-400/30 dark:bg-blue-400/10 dark:text-blue-400 dark:hover:bg-blue-400/15 focus-visible:ring-1 focus-visible:ring-ring`,children:(0,R.jsx)(`span`,{className:`[text-box:trim-both_cap_alphabetic]`,children:`Deploy`})}),w()]}),w=(e=!1)=>d.chatApiUrl?(0,R.jsx)(rz,{chatApiUrl:d.chatApiUrl,onUserResolved:e=>p(!!e),compact:e}):null;return(0,R.jsxs)(`header`,{className:`w-full min-w-0 shrink-0 overflow-hidden`,children:[(0,R.jsxs)(`div`,{className:`hidden lg:flex h-(--header-height) items-center justify-between gap-3 px-4 md:pl-0 md:pr-6`,children:[(0,R.jsx)(`div`,{className:`flex items-center gap-3 min-w-0 flex-1`,children:!a&&(0,R.jsxs)(R.Fragment,{children:[(0,R.jsx)(`div`,{className:L(`hidden lg:block shrink-0`,v&&o&&`-mr-[calc(var(--sidebar-width-icon)/2-0.625rem)]`),children:(0,R.jsx)(sz,{pinSymbolInIconColumn:!0,showLabel:!v||!o,state:v&&o?`collapsed`:`expanded`})}),(0,R.jsx)(`span`,{className:`text-sm text-muted-foreground/60 shrink-0 [text-box:trim-both_cap_alphabetic]`,children:`/`}),(0,R.jsx)(bz,{connections:e,selectedServer:t,onServerSelect:r,variant:`header`}),S(`desktop`)]})}),C()]}),(0,R.jsxs)(`div`,{className:`flex lg:hidden min-w-0 w-full flex-col overflow-hidden pt-(--mobile-chrome-gap)`,children:[(0,R.jsx)(`div`,{className:`flex min-h-0 items-center gap-2 pb-(--mobile-chrome-gap)`,children:!a&&(0,R.jsxs)(R.Fragment,{children:[(0,R.jsxs)(`div`,{className:`flex min-w-0 flex-1 items-center gap-2.5 overflow-hidden`,children:[(0,R.jsx)(sz,{state:`collapsed`,showLabel:!0,labelParts:`inspector`,className:`shrink-0`}),(0,R.jsx)(`span`,{className:`shrink-0 px-0.5 text-sm text-muted-foreground/60 [text-box:trim-both_cap_alphabetic]`,children:`/`}),(0,R.jsx)(`div`,{className:`min-w-0 flex-1`,children:(0,R.jsx)(bz,{connections:e,selectedServer:t,onServerSelect:r,variant:`header`,compactHeader:!0})})]}),(0,R.jsx)(`div`,{className:`shrink-0`,children:w(!0)})]})}),t&&(0,R.jsx)(`div`,{className:`w-full min-w-0 pb-(--mobile-chrome-gap) lg:hidden`,children:(0,R.jsx)(BR,{value:n,onValueChange:e=>i(e),collapsed:m,className:`w-full`,children:(0,R.jsx)(VR,{className:`w-full gap-0 border-0 bg-transparent p-0 [&_[role=tablist]]:justify-between`,children:_.filter(e=>e.id!==`separator`).map(e=>{let r=Sz(e.id,t);return(0,R.jsx)(UR,{value:e.id,"data-testid":`tab-${e.id}`,icon:e.icon,iconOnly:!0,title:e.label,badge:r>0?(0,R.jsx)(iz,{count:r,isActive:n===e.id,overlay:!0}):void 0,className:`size-9 shrink-0 rounded-full p-0`,children:(0,R.jsx)(`span`,{className:`sr-only`,children:e.label})},e.id)})})})})]})]})}function fB({collapsed:e,onToggle:t}){let n=e?`Expand sidebar`:`Collapse sidebar`;return(0,R.jsxs)(et,{children:[(0,R.jsx)(we,{render:(0,R.jsxs)(Gt,{type:`button`,variant:`ghost`,size:`icon-sm`,tabIndex:-1,"aria-label":n,onClick:t,className:L(`border-border absolute top-1/2 right-0 z-30 hidden size-7 min-h-7 min-w-7 -translate-y-1/2 translate-x-1/2 rounded-full border bg-background lg:flex`,`opacity-0 transition-opacity duration-200 group-hover/sidebar:opacity-100 focus-visible:opacity-100`),children:[(0,R.jsx)(wi,{className:`size-4`}),(0,R.jsx)(`span`,{className:`sr-only`,children:n})]}),nativeButton:!0}),(0,R.jsx)(lt,{side:`right`,children:n})]})}function pB({className:e}){return(0,R.jsxs)(`svg`,{xmlns:`http://www.w3.org/2000/svg`,width:`24`,height:`24`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentcolor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,className:e,children:[(0,R.jsx)(`path`,{d:`M15 22v-4a4.8 4.8 0 0 0-1-3.5c3 0 6-2 6-5.5.08-1.25-.27-2.48-1-3.5.28-1.15.28-2.35 0-3.5 0 0-1 0-3 1.5-2.64-.5-5.36-.5-8 0C6 2 5 2 5 2c-.3 1.15-.3 2.35 0 3.5A5.403 5.403 0 0 0 4 9c0 3.5 3 5.5 6 5.5-.39.49-.68 1.05-.85 1.65-.17.6-.22 1.23-.15 1.85v4`}),(0,R.jsx)(`path`,{d:`M9 18c-4.51 2-5-2-7-2`})]})}var mB=z.createContext(void 0);function hB(){let e=z.useContext(mB);if(e===void 0)throw Error(Vt(63));return e}var gB=function(e){return e.checked=`data-checked`,e.unchecked=`data-unchecked`,e.disabled=`data-disabled`,e.readonly=`data-readonly`,e.required=`data-required`,e.valid=`data-valid`,e.invalid=`data-invalid`,e.touched=`data-touched`,e.dirty=`data-dirty`,e.filled=`data-filled`,e.focused=`data-focused`,e}({}),_B={...Tn,checked(e){return e?{[gB.checked]:``}:{[gB.unchecked]:``}}};function vB(e,t,n,r=!0,i){let[a,o]=z.useState(),s=O(i?`${i}-label`:void 0),c=e??t??a;return Rt(()=>{let i=e||t||!r?void 0:yB(n.current,s);a!==i&&o(i)}),c}function yB(e,t){let n=bB(e);if(n)return!n.id&&t&&(n.id=t),n.id||void 0}function bB(e){if(!e)return;let t=e.parentElement;if(t&&t.tagName===`LABEL`)return t;let n=e.id;if(n){let t=e.nextElementSibling;if(t&&t.htmlFor===n)return t}let r=e.labels;return r&&r[0]}var xB=z.forwardRef(function(e,t){let{checked:n,className:r,defaultChecked:i,"aria-labelledby":a,form:o,id:s,inputRef:c,name:l,nativeButton:u=!1,onCheckedChange:d,readOnly:f=!1,required:p=!1,disabled:m=!1,render:h,uncheckedValue:g,value:_,style:v,...y}=e,{clearErrors:b}=An(),{state:x,setTouched:S,setDirty:C,validityData:w,setFilled:T,setFocused:E,validationMode:ee,disabled:D,name:ne,validation:re}=On(),{labelId:ie}=kn(),k=D||m,A=ne??l,j=z.useRef(null),ae=Kt(j,c,re.inputRef),oe=z.useRef(null),se=O(),ce=cn({id:s,implicit:!1,controlRef:oe}),M=u?void 0:ce,[N,le]=Yt({controlled:n,default:!!i,name:`Switch`,state:`checked`});En(oe,se,N,void 0,!k,l),Rt(()=>{j.current&&T(j.current.checked)},[j,T]),Dn(N,()=>{b(A),C(N!==w.initialValue),T(N),re.change(N)});let{getButtonProps:ue,buttonRef:de}=Lt({disabled:k,native:u}),fe=vB(a,ie,j,!u,M),pe={id:u?ce:se,role:`switch`,"aria-checked":N,"aria-readonly":f||void 0,"aria-required":p||void 0,"aria-labelledby":fe,onFocus(){k||E(!0)},onBlur(){let e=j.current;!e||k||(S(!0),E(!1),ee===`onBlur`&&re.commit(e.checked))},onClick(e){if(f||k)return;e.preventDefault();let t=j.current;t&&t.dispatchEvent(new(Mt(t)).PointerEvent(`click`,{bubbles:!0,shiftKey:e.shiftKey,ctrlKey:e.ctrlKey,altKey:e.altKey,metaKey:e.metaKey}))}},me=zt({checked:N,disabled:k,form:o,id:M,name:A,required:p,style:A?Te:He,tabIndex:-1,type:`checkbox`,"aria-hidden":!0,ref:ae,onChange(e){if(e.nativeEvent.defaultPrevented)return;if(f){e.preventDefault();return}let t=e.currentTarget.checked,n=te(be,e.nativeEvent);d?.(t,n),!n.isCanceled&&le(t)},onFocus(){oe.current?.focus()}},e=>re.getValidationProps(k,e),_===void 0?Wt:{value:_}),he=z.useMemo(()=>({...x,checked:N,disabled:k,readOnly:f,required:p}),[x,N,k,f,p]),ge=Ft(`span`,e,{state:he,ref:[t,oe,de],props:[pe,y,ue,e=>re.getValidationProps(k,e)],stateAttributesMapping:_B});return(0,R.jsxs)(mB.Provider,{value:he,children:[ge,!N&&A&&g!==void 0&&(0,R.jsx)(`input`,{type:`hidden`,form:o,name:A,value:g,disabled:k}),(0,R.jsx)(`input`,{...me,suppressHydrationWarning:!0})]})}),SB=z.forwardRef(function(e,t){let{render:n,className:r,style:i,...a}=e;return Ft(`span`,e,{state:hB(),ref:t,stateAttributesMapping:_B,props:a})}),CB=34,wB=20,TB=16,EB=2,DB=4,OB=2;function kB(e){return`label`in e&&typeof e.label==`string`}var AB=(0,z.forwardRef)(({label:e,checked:t,onToggle:n,disabled:r=!1,thumbTransition:i,uncheckedTrackColor:a,uncheckedTrackColorHovered:o,className:s,...c},l)=>{let u=(0,z.useId)(),d=(0,z.useRef)(!1),[f,p]=(0,z.useState)(!1),[m,h]=(0,z.useState)(!1),g=(0,z.useRef)(!1),_=(0,z.useRef)(!1),v=(0,z.useRef)(null),y=ia(t?16:EB);(0,z.useEffect)(()=>{d.current=!0},[]);let b=m?20:f?18:TB,x=m?TB-DB:TB,S=m?4:EB,C=b-TB,w=t?16-C:EB;(0,z.useEffect)(()=>{g.current||(d.current?ka(y,w,i??pt.moderate):y.set(w))},[w,y,i]);let T=(0,z.useCallback)(e=>{r||e.pointerType===`mouse`&&e.button!==0||(h(!0),g.current=!1,_.current=!1,v.current={clientX:e.clientX,originX:y.get()},e.currentTarget.setPointerCapture(e.pointerId))},[r,y]),E=(0,z.useCallback)(e=>{if(!v.current)return;let t=e.clientX-v.current.clientX;if(!g.current){if(Math.abs(t)<OB)return;g.current=!0}let n=EB,r=CB-EB-20,i=v.current.originX+t;y.set(Math.max(n,Math.min(r,i)))},[y]),ee=(0,z.useCallback)(e=>{v.current&&=(h(!1),g.current&&(_.current=!0,g.current=!1,e&&(y.get()>14/2===t?ka(y,t?16:EB,i??pt.moderate):n()),requestAnimationFrame(()=>{_.current=!1})),null)},[t,n,y,i]);return(0,R.jsxs)(`div`,{ref:l,className:L(`relative z-10 flex items-center gap-2.5 px-3 py-2 cursor-pointer select-none touch-none`,r&&`opacity-50 pointer-events-none`,s),onPointerEnter:e=>{e.pointerType===`mouse`&&p(!0)},onPointerLeave:()=>p(!1),onPointerDown:T,onPointerMove:E,onPointerUp:()=>ee(!0),onPointerCancel:()=>{v.current&&=(h(!1),g.current&&(g.current=!1,ka(y,t?16:EB,i??pt.moderate)),null)},onClick:()=>{r||_.current||n()},...c,children:[(0,R.jsx)(xB,{checked:t,"aria-labelledby":u,onCheckedChange:()=>{_.current||n()},disabled:r,tabIndex:0,className:L(`relative shrink-0 rounded-full outline-none cursor-pointer`,`transition-colors duration-80`,`focus-visible:ring-1 focus-visible:ring-[color:var(--focus-ring,#6B97FF)] focus-visible:ring-offset-2 focus-visible:ring-offset-background`),style:{width:CB,height:wB,backgroundColor:t?f?`color-mix(in oklab, var(--primary) 88%, black)`:`var(--primary)`:f?o??`color-mix(in oklab, var(--accent), rgb(var(--overlay)) 10%)`:a??`var(--accent)`},onClick:e=>e.stopPropagation(),children:(0,R.jsx)(SB,{render:e=>{let{style:t,onDrag:n,onDragStart:r,onDragEnd:a,onAnimationStart:o,onAnimationEnd:s,onAnimationIteration:c,...l}=e;return(0,R.jsx)(Pe.span,{...l,className:`absolute top-0 left-0 block rounded-full bg-white shadow-sm`,initial:!1,style:{...t,x:y},animate:{y:S,width:b,height:x},transition:d.current?i??pt.moderate:{duration:0}})}})}),(0,R.jsx)(`span`,{id:u,className:L(`text-[13px] [text-box:trim-both_cap_alphabetic] transition-[color] duration-80`,t?`text-foreground`:`text-muted-foreground`),children:e})]})});AB.displayName=`FluidSwitch`;var jB=(0,z.forwardRef)(({checked:e,defaultChecked:t=!1,onCheckedChange:n,disabled:r=!1,className:i},a)=>{let[o,s]=(0,z.useState)(t),c=e??o;return(0,R.jsx)(xB,{ref:a,checked:c,disabled:r,onCheckedChange:t=>{e===void 0&&s(t),n?.(t)},className:L(`peer inline-flex h-5 w-9 shrink-0 cursor-pointer items-center rounded-full border-2 border-transparent shadow-xs transition-colors duration-80`,`focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-[color:var(--focus-ring,#6B97FF)]`,`disabled:cursor-not-allowed disabled:opacity-50`,`data-checked:bg-primary data-unchecked:bg-input`,i),children:(0,R.jsx)(SB,{className:L(`pointer-events-none block size-4 rounded-full bg-background shadow-sm ring-0 transition-transform duration-80`,`data-checked:translate-x-4 data-unchecked:translate-x-0`)})})});jB.displayName=`ShadcnSwitch`;var MB=(0,z.forwardRef)((e,t)=>kB(e)?(0,R.jsx)(AB,{ref:t,...e}):(0,R.jsx)(jB,{ref:t,...e}));MB.displayName=`Switch`;function NB({className:e}){return(0,R.jsx)(`svg`,{viewBox:`0 -28.5 256 256`,className:e,fill:`currentColor`,xmlns:`http://www.w3.org/2000/svg`,"aria-hidden":!0,children:(0,R.jsx)(`path`,{d:`M216.856339,16.5966031 C200.285002,8.84328665 182.566144,3.2084988 164.041564,0 C161.766523,4.11318106 159.108624,9.64549908 157.276099,14.0464379 C137.583995,11.0849896 118.072967,11.0849896 98.7430163,14.0464379 C96.9108417,9.64549908 94.1925838,4.11318106 91.8971895,0 C73.3526068,3.2084988 55.6133949,8.86399117 39.0420583,16.6376612 C5.61752293,67.146514 -3.4433191,116.400813 1.08711069,164.955721 C23.2560196,181.510915 44.7403634,191.567697 65.8621325,198.148576 C71.0772151,190.971126 75.7283628,183.341335 79.7352139,175.300261 C72.104019,172.400575 64.7949724,168.822202 57.8887866,164.667963 C59.7209612,163.310589 61.5131304,161.891452 63.2445898,160.431257 C105.36741,180.133187 151.134928,180.133187 192.754523,160.431257 C194.506336,161.891452 196.298154,163.310589 198.110326,164.667963 C191.183787,168.842556 183.854737,172.420929 176.223542,175.320965 C180.230393,183.341335 184.861538,190.991831 190.096624,198.16893 C211.238746,191.588051 232.743023,181.531619 254.911949,164.955721 C260.227747,108.668201 245.831087,59.8662432 216.856339,16.5966031 Z M85.4738752,135.09489 C72.8290281,135.09489 62.4592217,123.290155 62.4592217,108.914901 C62.4592217,94.5396472 72.607595,82.7145587 85.4738752,82.7145587 C98.3405064,82.7145587 108.709962,94.5189427 108.488529,108.914901 C108.508531,123.290155 98.3405064,135.09489 85.4738752,135.09489 Z M170.525237,135.09489 C157.88039,135.09489 147.510584,123.290155 147.510584,108.914901 C147.510584,94.5396472 157.658606,82.7145587 170.525237,82.7145587 C183.391518,82.7145587 193.761324,94.5189427 193.539891,108.914901 C193.539891,123.290155 183.391518,135.09489 170.525237,135.09489 Z`,fillRule:`nonzero`})})}var PB=`flex size-8 items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-sidebar-accent hover:text-sidebar-accent-foreground`,FB=`color-mix(in oklab, var(--sidebar-foreground) 22%, var(--sidebar))`,IB=`color-mix(in oklab, var(--sidebar-foreground) 30%, var(--sidebar))`,LB=`data-unchecked:!bg-zinc-300 dark:data-unchecked:!bg-zinc-600`;function RB({collapsed:e,rpcLoggerOpen:t,onRpcLoggerOpenChange:n,onCommandPaletteOpen:r}){let{embeddedConfig:i}=nL(),{theme:a,setTheme:o}=dz(),{user:s}=WR(i.chatApiUrl),c=s?`https://manufact.com/cloud?ref=mcp-use-inspector`:`https://manufact.com/signup?ref=mcp-use-inspector`,l=()=>{try{bT(new Mo({referrer:`mcp-use-inspector-sidebar`})).catch(()=>{})}catch{}};return(0,R.jsx)(`footer`,{className:`mt-auto shrink-0`,children:(0,R.jsxs)(`div`,{className:L(`flex flex-col`,e?`items-center gap-2 px-2 py-3`:`gap-3 px-(--sidebar-nav-inset-x) py-4`),children:[e?(0,R.jsxs)(et,{children:[(0,R.jsx)(we,{render:(0,R.jsx)(`div`,{className:`flex size-8 items-center justify-center`,children:(0,R.jsx)(MB,{checked:t,onCheckedChange:n,"aria-label":`RPC Panel`,className:L(`scale-75`,LB)})}),nativeButton:!1}),(0,R.jsx)(lt,{side:`right`,children:`RPC Panel`})]}):(0,R.jsx)(MB,{label:`RPC Panel`,checked:t,onToggle:()=>n(!t),uncheckedTrackColor:FB,uncheckedTrackColorHovered:IB,className:`w-full flex-row-reverse justify-between`}),e?(0,R.jsxs)(et,{children:[(0,R.jsx)(we,{render:(0,R.jsx)(`a`,{href:c,target:`_blank`,rel:`noopener noreferrer`,onClick:l,className:PB,"aria-label":`Deploying your MCP Server? Try manufact.com`,children:(0,R.jsx)(Ar,{className:`size-4`})}),nativeButton:!1}),(0,R.jsx)(lt,{side:`right`,children:`Deploying your MCP Server? Try manufact.com`})]}):(0,R.jsxs)(`a`,{href:c,target:`_blank`,rel:`noopener noreferrer`,onClick:l,className:`relative block rounded-xl border border-sidebar-border bg-white p-3 transition-colors hover:bg-sidebar-accent/50 dark:bg-black`,children:[(0,R.jsx)(Ar,{className:`absolute top-2.5 right-2.5 size-3.5 text-muted-foreground`,"aria-hidden":!0}),(0,R.jsx)(`p`,{className:`pr-5 text-xs leading-snug text-muted-foreground`,children:`Deploying your MCP Server?`}),(0,R.jsxs)(`p`,{className:`mt-0.5 text-xs leading-snug`,children:[`Try`,` `,(0,R.jsx)(`span`,{className:`font-medium underline underline-offset-2`,children:`manufact.com`})]})]}),(0,R.jsxs)(`div`,{className:L(`flex`,e?`flex-col items-center gap-1`:`flex-row items-center gap-2`),children:[(0,R.jsxs)(et,{children:[(0,R.jsx)(we,{render:(0,R.jsx)(`a`,{href:`https://github.com/mcp-use/mcp-use`,target:`_blank`,rel:`noopener noreferrer`,className:PB,"aria-label":`GitHub`,children:(0,R.jsx)(pB,{className:`size-4`})}),nativeButton:!1}),(0,R.jsx)(lt,{side:e?`right`:`top`,children:`GitHub`})]}),(0,R.jsxs)(et,{children:[(0,R.jsx)(we,{render:(0,R.jsx)(`a`,{href:`https://discord.gg/XkNkSkMz3V`,target:`_blank`,rel:`noopener noreferrer`,className:PB,"aria-label":`Discord`,children:(0,R.jsx)(NB,{className:`size-4`})}),nativeButton:!1}),(0,R.jsx)(lt,{side:e?`right`:`top`,children:`Discord`})]}),(0,R.jsxs)(Ya,{children:[(0,R.jsxs)(et,{children:[(0,R.jsx)(we,{render:(0,R.jsx)(Xa,{render:(0,R.jsx)(`button`,{type:`button`,className:PB,"aria-label":`Theme`,children:a===`light`?(0,R.jsx)(Ui,{className:`size-4`}):a===`dark`?(0,R.jsx)(xi,{className:`size-4`}):(0,R.jsx)(bi,{className:`size-4`})}),nativeButton:!0}),nativeButton:!0}),(0,R.jsx)(lt,{side:e?`right`:`top`,children:`Theme`})]}),(0,R.jsx)(Za,{side:e?`right`:`top`,align:e?`start`:`center`,className:`w-40`,children:(0,R.jsxs)(eo,{value:a,onValueChange:e=>o(e),children:[(0,R.jsxs)(to,{value:`light`,children:[(0,R.jsx)(Ui,{className:`size-4 mr-2`}),`Light`]}),(0,R.jsxs)(to,{value:`dark`,children:[(0,R.jsx)(xi,{className:`size-4 mr-2`}),`Dark`]}),(0,R.jsxs)(to,{value:`system`,children:[(0,R.jsx)(bi,{className:`size-4 mr-2`}),`System`]})]})})]}),(0,R.jsxs)(et,{children:[(0,R.jsx)(we,{render:(0,R.jsx)(`button`,{type:`button`,onClick:r,className:PB,"aria-label":`Command Palette`,"data-testid":`command-palette-trigger-button`,children:(0,R.jsx)(Ur,{className:`size-4`})}),nativeButton:!0}),(0,R.jsxs)(lt,{side:e?`right`:`top`,children:[`Command Palette (`,`⌘`,`K)`]})]})]})]})})}function zB(e,t){let n=0,r=0,i=e;for(;i&&i!==t;)n+=i.offsetTop,r+=i.offsetLeft,i=i.offsetParent;if(i!==t){let n=t.getBoundingClientRect(),r=e.getBoundingClientRect();return{top:r.top-n.top,left:r.left-n.left,width:r.width,height:r.height}}return{top:n,left:r,width:e.offsetWidth,height:e.offsetHeight}}function BB(e,t){let n=Object.keys(e),r=Object.keys(t);if(n.length!==r.length)return!1;for(let r of n){let n=e[r],i=t[r];if(!n||!i||n.top!==i.top||n.left!==i.left||n.width!==i.width||n.height!==i.height)return!1}return!0}function VB(e,t={}){let{axis:n=`y`}=t,r=(0,z.useRef)(new Map),[i,a]=(0,z.useState)(null),[o,s]=(0,z.useState)({}),c=(0,z.useRef)({}),l=(0,z.useRef)(0),u=(0,z.useRef)(null),d=(0,z.useRef)(null),f=(0,z.useCallback)(()=>{let t=e.current;if(!t)return;let n={};r.current.forEach((e,r)=>{n[r]=zB(e,t)}),!BB(c.current,n)&&(c.current=n,s(n))},[e]),p=(0,z.useCallback)((e,t)=>{t?r.current.set(e,t):r.current.delete(e),d.current!==null&&cancelAnimationFrame(d.current),d.current=requestAnimationFrame(()=>{d.current=null,f()})},[f]),m=(0,z.useCallback)(t=>{let r=t.clientX,i=t.clientY;u.current!==null&&cancelAnimationFrame(u.current),u.current=requestAnimationFrame(()=>{u.current=null;let t=e.current;if(!t)return;let o=t.getBoundingClientRect(),s=n===`x`?r:i,l=null,d=1/0,f=null,p=c.current,m=n===`x`?t.scrollLeft:t.scrollTop,h=n===`x`?t.clientLeft:t.clientTop,g=n===`x`?o.left:o.top,_=n===`x`?t.offsetWidth:t.offsetHeight,v=n===`x`?o.width:o.height,y=_>0?v/_:1;for(let[e,t]of Object.entries(p)){let r=g+(h+(n===`x`?t.left:t.top)-m)*y,i=(n===`x`?t.width:t.height)*y,a=r+i;s>=r&&s<=a&&(f=e);let o=r+i/2,c=Math.abs(s-o);c<d&&(d=c,l=e)}a(f??l)})},[n,e]),h=(0,z.useCallback)(()=>{l.current+=1},[]),g=(0,z.useCallback)(()=>{u.current!==null&&(cancelAnimationFrame(u.current),u.current=null),a(null)},[]);return(0,z.useEffect)(()=>{let t=e.current;if(!t||typeof ResizeObserver>`u`)return;let n=new ResizeObserver(()=>{d.current!==null&&cancelAnimationFrame(d.current),d.current=requestAnimationFrame(()=>{d.current=null,f()})});return n.observe(t),()=>n.disconnect()},[e,f]),(0,z.useEffect)(()=>()=>{u.current!==null&&cancelAnimationFrame(u.current),d.current!==null&&cancelAnimationFrame(d.current)},[]),{activeKey:i,itemRects:o,sessionRef:l,handlers:{onMouseMove:m,onMouseEnter:h,onMouseLeave:g},registerItem:p,measureItems:f}}function HB(e){if(!e)return{left:0,right:0};let t=getComputedStyle(e),n=Number.parseFloat(t.getPropertyValue(`--sidebar-nav-pill-bleed`))||0,r=Number.parseFloat(t.getPropertyValue(`--sidebar-nav-scrollbar-width`))||0,i=Number.parseFloat(t.getPropertyValue(`--sidebar-nav-pill-outer-trim-right`))||0;return{left:n,right:n+r+i}}function UB(e,t){return{...e,left:e.left-t.left,width:e.width+t.left+t.right}}var WB=(0,z.createContext)(null);function GB(){let e=(0,z.useContext)(WB),t=(0,z.useRef)(e?.registerItem);t.current=e?.registerItem;let n=(0,z.useRef)(new Map);return(0,z.useCallback)(e=>{let r=n.current,i=r.get(e);return i||(i=n=>t.current?.(e,n),r.set(e,i)),i},[])}function KB({children:e,isActiveKey:t,className:n}){let r=(0,z.useRef)(null),{activeKey:i,itemRects:a,sessionRef:o,handlers:s,registerItem:c,measureItems:l}=VB(r),u=(0,z.useMemo)(()=>({registerItem:c}),[c]),d=Object.keys(a).find(e=>t(e))??null;(0,z.useLayoutEffect)(()=>{l()},[l,e,d]);let f=HB(r.current),p=i?a[i]:null,m=d?a[d]:null,h=p?UB(p,f):null,g=m?UB(m,f):null,_=i!==null&&i!==d;return(0,R.jsx)(WB.Provider,{value:u,children:(0,R.jsxs)(`div`,{ref:r,onMouseEnter:s.onMouseEnter,onMouseMove:s.onMouseMove,onMouseLeave:s.onMouseLeave,className:L(`relative isolate`,n),children:[(0,R.jsx)(en,{initial:!1,children:g&&d?(0,R.jsx)(Pe.div,{"aria-hidden":!0,className:`pointer-events-none absolute -z-20 rounded-full bg-sidebar-accent`,initial:{opacity:0,top:g.top,left:g.left,width:g.width,height:g.height},animate:{opacity:_?.85:1,top:g.top,left:g.left,width:g.width,height:g.height},exit:{opacity:0,transition:pt.fast.exit},transition:{opacity:{duration:.08},top:{duration:0},left:{duration:0},width:{duration:0},height:{duration:0}}},d):null}),(0,R.jsx)(en,{children:h?(0,R.jsx)(Pe.div,{"aria-hidden":!0,className:`pointer-events-none absolute -z-10 rounded-full bg-sidebar-accent`,initial:{opacity:0,top:g?.top??h.top,left:g?.left??h.left,width:g?.width??h.width,height:g?.height??h.height},animate:{opacity:1,top:h.top,left:h.left,width:h.width,height:h.height},exit:{opacity:0,transition:pt.fast.exit},transition:{...pt.fast,opacity:{duration:.08}}},o.current):null}),e]})})}var qB=L(`pointer-events-auto absolute right-(--sidebar-nav-trailing-right) top-1/2 z-10 flex h-(--sidebar-nav-trailing-size) min-w-(--sidebar-nav-trailing-size) -translate-y-1/2 items-center justify-center`,L(`transition-[opacity,filter] duration-200 ease-out`,`opacity-100 blur-0`,`group-data-[collapsible=icon]:opacity-0 group-data-[collapsible=icon]:blur-[3px] group-data-[collapsible=icon]:pointer-events-none`,`group-data-[collapsed=true]:opacity-0 group-data-[collapsed=true]:blur-[3px] group-data-[collapsed=true]:pointer-events-none`)),JB=L(`truncate transition-[opacity,filter,margin] duration-200 ease-out`,`group-data-[collapsible=icon]:hidden`,`group-data-[collapsed=true]:hidden`),YB=L(`peer/menu-button flex cursor-pointer items-center gap-2 overflow-hidden rounded-full py-2 text-left text-sm outline-hidden ring-sidebar-ring hover:text-sidebar-accent-foreground group-hover/menu-item:text-sidebar-accent-foreground focus-visible:ring-2 active:text-sidebar-accent-foreground disabled:pointer-events-none disabled:opacity-50 aria-disabled:pointer-events-none aria-disabled:opacity-50 data-active:font-medium data-active:text-sidebar-accent-foreground [&>span:last-child]:truncate [&>svg]:size-4 [&>svg]:shrink-0`,`transition-[width,max-width,height,padding,border-radius] duration-200 ease-out`,`h-8 text-sm`);function XB({count:e}){return(0,R.jsx)(`span`,{className:L(`inline-flex h-5 shrink-0 items-center justify-center border border-border bg-zinc-200 px-1 text-[10px] font-medium tabular-nums leading-none text-foreground dark:bg-zinc-700`,String(e).length>=3?`min-w-5 rounded-md`:`size-5 min-w-5 rounded-full`),children:e})}function ZB(e){return e.id!==`separator`}function QB({activeTab:e,onTabChange:t,selectedServer:n,visibleTabs:r,collapsed:i}){let a=GB();return(0,R.jsx)(`ul`,{className:`flex w-full min-w-0 flex-col gap-1 px-(--sidebar-nav-inset-x) group`,"data-collapsed":i,"aria-label":`Inspector tabs`,children:(r?wz.filter(e=>ZB(e)&&r.includes(e.id)):wz.filter(ZB)).map((r,o)=>{let s=Sz(r.id,n),c=Cz(r.id,s,i),l=r.icon,u=e===r.id,d=s>0||c,f=(0,R.jsxs)(`button`,{ref:a(r.id),type:`button`,"data-testid":`tab-${r.id}`,"data-active":u?!0:void 0,onClick:()=>t(r.id),className:L(YB,i?`size-8! w-8! max-w-8! shrink-0 justify-center gap-0 p-0!`:`w-full max-w-full sidebar-nav-pill-bleed-x pl-(--sidebar-nav-icon-pl-bleed) pr-(--sidebar-nav-pr-bleed)`,d&&!i&&`pr-[calc(var(--sidebar-nav-trailing-right)+var(--sidebar-nav-trailing-size))]`),children:[(0,R.jsx)(l,{className:`size-4 shrink-0`}),(0,R.jsx)(`span`,{className:JB,children:r.label})]});return(0,R.jsxs)(`li`,{className:L(`group/menu-item relative`,o===0&&`mt-4`),children:[i?(0,R.jsxs)(et,{delayDuration:0,children:[(0,R.jsx)(we,{render:f,nativeButton:!0}),(0,R.jsx)(lt,{side:`right`,children:s>0?`${r.label} (${s})`:r.label})]}):f,d&&!i?(0,R.jsx)(`div`,{className:qB,children:s>0?(0,R.jsx)(XB,{count:s}):c?(0,R.jsx)(`span`,{className:`inline-flex h-2 w-2 shrink-0 rounded-full bg-yellow-500 animate-status-pulse-yellow`}):null}):null]},r.id)})})}function $B({activeTab:e,onTabChange:t,selectedServer:n,visibleTabs:r,collapsed:i,onCollapsedChange:a,rpcLoggerOpen:o,onRpcLoggerOpenChange:s,onCommandPaletteOpen:c}){return(0,R.jsxs)(`aside`,{className:L(`group/sidebar relative hidden lg:flex flex-col shrink-0 text-sidebar-foreground transition-[width] duration-200 ease-out @container/sidebar`,i?`w-(--sidebar-width-icon)`:`w-(--sidebar-width)`),"data-collapsed":i,"data-collapsible":i?`icon`:`expanded`,children:[(0,R.jsx)(`div`,{className:`sidebar-nav-scroll flex-1 overflow-y-auto overflow-x-hidden min-h-0`,children:(0,R.jsx)(KB,{isActiveKey:t=>t===e,className:`pb-2`,children:(0,R.jsx)(QB,{activeTab:e,onTabChange:t,selectedServer:n,visibleTabs:r,collapsed:i})})}),(0,R.jsx)(RB,{collapsed:i,rpcLoggerOpen:o,onRpcLoggerOpenChange:s,onCommandPaletteOpen:c}),(0,R.jsx)(fB,{collapsed:i,onToggle:()=>a(!i)})]})}function eV(e){if(e===0)return`0 Bytes`;let t=1024,n=[`Bytes`,`KB`,`MB`,`GB`],r=Math.floor(Math.log(e)/Math.log(t));return Math.round(e/t**r*100)/100+` `+n[r]}function tV(e){if(e===0)return`0 B`;let t=1024,n=[`B`,`KB`,`MB`],r=Math.floor(Math.log(e)/Math.log(t));return`${parseFloat((e/t**r).toFixed(1))} ${n[r]}`}var nV=100*1024,rV=1024*20;function iV(e,t){if(e==null)return e;if(typeof e==`string`)return e.length>t?e.substring(0,t)+`... (truncated)`:e;if(Array.isArray(e))return e.map(e=>iV(e,t));if(typeof e==`object`){let n={};for(let r in e)Object.prototype.hasOwnProperty.call(e,r)&&(n[r]=iV(e[r],t));return n}return e}function aV(e){let t=JSON.stringify(e,null,2);return new TextEncoder().encode(t).length>nV?iV(e,rV):e}function oV(e){let t=JSON.stringify(e,null,2),n=new TextEncoder().encode(t).length,r=n>nV,i;if(r){let t=iV(e,rV);i=JSON.stringify(t,null,2)}else i=t;return{isLarge:r,size:n,sizeFormatted:eV(n),preview:i,full:t}}function sV(e,t){try{let n=JSON.stringify(e,null,2),r=globalThis.Blob,i=new r([n],{type:`application/json`}),a=URL.createObjectURL(i),o=document.createElement(`a`);o.href=a,o.download=t||`data-${Date.now()}.json`,document.body.appendChild(o),o.click(),document.body.removeChild(o),URL.revokeObjectURL(a)}catch(e){throw console.error(`Failed to download JSON:`,e),e}}var cV={key:`text-sky-600 dark:text-sky-400`,string:`text-emerald-600 dark:text-emerald-400`,number:`text-amber-600 dark:text-amber-400`,boolean:`text-violet-600 dark:text-violet-400`,null:`text-zinc-500 dark:text-zinc-400`,punctuation:`text-muted-foreground`};function lV(e){let t=[],n=0,r=(e,n)=>{n&&t.push({kind:e,text:n})};for(;n<e.length;){let t=e[n];if(t===`"`){let t=n;for(n++;n<e.length;){if(e[n]===`\\`){n+=2;continue}if(e[n]===`"`){n++;break}n++}let i=e.slice(t,n),a=n;for(;a<e.length&&/[ \t]/.test(e[a]);)a++;r(e[a]===`:`?`key`:`string`,i);continue}if(/[0-9-]/.test(t)){let t=n;for(e[n]===`-`&&n++;n<e.length&&/[0-9.eE+-]/.test(e[n]);)n++;r(`number`,e.slice(t,n));continue}if(e.startsWith(`true`,n)||e.startsWith(`false`,n)){let t=e.startsWith(`true`,n)?`true`:`false`;r(`boolean`,t),n+=t.length;continue}if(e.startsWith(`null`,n)){r(`null`,`null`),n+=4;continue}if(/[{}[\],:]/.test(t)){r(`punctuation`,t),n++;continue}r(`punctuation`,t),n++}return t}function uV(e){return lV(e).map((e,t)=>(0,R.jsx)(`span`,{className:cV[e.kind],children:e.text},t))}var dV={string:`text-emerald-600 dark:text-emerald-400`,number:`text-amber-600 dark:text-amber-400`,boolean:`text-violet-600 dark:text-violet-400`,null:`text-zinc-500 dark:text-zinc-400`,key:`text-sky-600 dark:text-sky-400`,punctuation:`text-muted-foreground`};function fV(e){return e===null?(0,R.jsx)(`span`,{className:dV.null,children:`null`}):typeof e==`string`?(0,R.jsx)(`span`,{className:dV.string,children:JSON.stringify(e)}):typeof e==`number`?(0,R.jsx)(`span`,{className:dV.number,children:String(e)}):typeof e==`boolean`?(0,R.jsx)(`span`,{className:dV.boolean,children:String(e)}):(0,R.jsx)(`span`,{className:dV.string,children:JSON.stringify(e)})}function pV(e){return Array.isArray(e)?`[${e.length}]`:`{${Object.keys(e).length}}`}function mV({label:e,value:t,depth:n,defaultExpanded:r}){let i=typeof t==`object`&&t&&!Array.isArray(t)?Object.keys(t).length>0:Array.isArray(t)?t.length>0:!1,[a,o]=(0,z.useState)(i&&(r||n===0));if(!i){let r=Array.isArray(t)?`[]`:`{}`;return typeof t==`object`&&t?(0,R.jsxs)(`div`,{className:`font-mono text-[0.8rem] leading-relaxed`,style:{paddingLeft:n*12},children:[e!=null&&(0,R.jsxs)(R.Fragment,{children:[(0,R.jsx)(`span`,{className:dV.key,children:JSON.stringify(e)}),(0,R.jsx)(`span`,{className:dV.punctuation,children:`: `})]}),(0,R.jsx)(`span`,{className:dV.punctuation,children:r})]}):(0,R.jsxs)(`div`,{className:`font-mono text-[0.8rem] leading-relaxed`,style:{paddingLeft:n*12},children:[e!=null&&(0,R.jsxs)(R.Fragment,{children:[(0,R.jsx)(`span`,{className:dV.key,children:JSON.stringify(e)}),(0,R.jsx)(`span`,{className:dV.punctuation,children:`: `})]}),fV(t)]})}let s=Array.isArray(t)?t.map((e,t)=>[String(t),e]):Object.entries(t),c=Array.isArray(t),l=c?`[`:`{`,u=c?`]`:`}`;return(0,R.jsxs)(`div`,{className:`font-mono text-[0.8rem] leading-relaxed`,children:[(0,R.jsxs)(`div`,{className:`flex items-start gap-0.5`,style:{paddingLeft:n*12},children:[(0,R.jsx)(`button`,{type:`button`,"aria-expanded":a,onClick:()=>o(e=>!e),className:`mt-0.5 inline-flex shrink-0 items-center justify-center rounded-sm text-muted-foreground hover:text-foreground`,children:(0,R.jsx)(C,{className:L(`h-3.5 w-3.5 transition-transform`,a&&`rotate-90`)})}),(0,R.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[e!=null&&(0,R.jsxs)(R.Fragment,{children:[(0,R.jsx)(`span`,{className:dV.key,children:JSON.stringify(e)}),(0,R.jsx)(`span`,{className:dV.punctuation,children:`: `})]}),(0,R.jsx)(`span`,{className:dV.punctuation,children:l}),!a&&(0,R.jsxs)(R.Fragment,{children:[(0,R.jsx)(`button`,{type:`button`,onClick:()=>o(!0),className:`mx-1 text-xs text-muted-foreground hover:text-foreground`,children:pV(t)}),(0,R.jsx)(`span`,{className:dV.punctuation,children:u})]})]})]}),a&&(0,R.jsxs)(`div`,{children:[s.map(([e,t])=>(0,R.jsx)(mV,{label:e,value:t,depth:n+1,defaultExpanded:r},`${n}-${e}`)),(0,R.jsx)(`div`,{style:{paddingLeft:n*12},children:(0,R.jsx)(`span`,{className:dV.punctuation,children:u})})]})]})}function hV({data:e,defaultExpanded:t=!0,className:n}){return(0,R.jsx)(`div`,{className:L(`text-gray-900 dark:text-gray-100 [overflow-wrap:anywhere]`,n),"data-testid":`collapsible-json`,children:(0,R.jsx)(mV,{value:e,depth:0,defaultExpanded:t})})}var gV=`font-mono text-[0.8rem] text-gray-900 dark:text-gray-100 whitespace-pre-wrap break-words [overflow-wrap:anywhere]`;function _V({data:e,filename:t,className:n,collapsible:r=!1,defaultExpanded:i=!0,...a}){let o=oV(e),s=aV(e),c=o.isLarge?(0,R.jsx)(`div`,{className:`mb-3 p-3 bg-yellow-50 dark:bg-yellow-900/20 border border-yellow-200 dark:border-yellow-800 rounded-lg`,children:(0,R.jsxs)(`div`,{className:`flex items-center justify-between gap-2`,children:[(0,R.jsxs)(`div`,{className:`flex-1`,children:[(0,R.jsxs)(`p`,{className:`text-sm font-medium text-yellow-800 dark:text-yellow-300 mb-1`,children:[`JSON is too large (`,o.sizeFormatted,`)`]}),(0,R.jsx)(`p`,{className:`text-xs text-yellow-700 dark:text-yellow-400`,children:`Showing full structure with truncated values. Download the full JSON file to see complete values.`})]}),(0,R.jsxs)(Gt,{variant:`outline`,size:`sm`,onClick:()=>{sV(e,t)},className:`shrink-0`,children:[(0,R.jsx)(qr,{className:`h-4 w-4 mr-1`}),`Download`]})]})}):null;return r?(0,R.jsxs)(`div`,{className:n,...a,children:[c,(0,R.jsx)(hV,{data:s,defaultExpanded:i})]}):o.isLarge?(0,R.jsxs)(`div`,{className:n,...a,children:[c,(0,R.jsx)(`pre`,{className:gV,children:(0,R.jsx)(`code`,{children:uV(o.preview)})})]}):(0,R.jsx)(`div`,{className:n,...a,children:(0,R.jsx)(`pre`,{className:gV,children:(0,R.jsx)(`code`,{children:uV(o.preview)})})})}function vV(e){if(!e)return null;for(let t of e.elements){let e=t.tagName;if(e===`BUTTON`||e===`INPUT`){let e=t;if(e.type===`submit`)return e}}return null}var yV=function(e){return e.checked=`data-checked`,e.unchecked=`data-unchecked`,e.indeterminate=`data-indeterminate`,e.disabled=`data-disabled`,e.readonly=`data-readonly`,e.required=`data-required`,e.valid=`data-valid`,e.invalid=`data-invalid`,e.touched=`data-touched`,e.dirty=`data-dirty`,e.filled=`data-filled`,e.focused=`data-focused`,e}({});function bV(e){return z.useMemo(()=>({checked(t){return e.indeterminate?{}:t?{[yV.checked]:``}:{[yV.unchecked]:``}},...Tn}),[e.indeterminate])}var xV=z.createContext({disabled:!1});function SV(){return z.useContext(xV)}var CV=z.createContext(void 0);function wV(e=!0){let t=z.useContext(CV);if(t===void 0&&!e)throw Error(Vt(3));return t}var TV=z.createContext(void 0);function EV(){let e=z.useContext(TV);if(e===void 0)throw Error(Vt(14));return e}var DV=`data-parent`,OV=z.forwardRef(function(e,t){let{checked:n,className:r,defaultChecked:i=!1,"aria-labelledby":a,disabled:o=!1,form:s,id:c,indeterminate:l=!1,inputRef:u,name:d,onCheckedChange:f,parent:p=!1,readOnly:m=!1,render:h,required:g=!1,uncheckedValue:_,value:v,nativeButton:y=!1,style:b,...x}=e,{clearErrors:S}=An(),{disabled:C,name:w,setDirty:T,setFilled:E,setFocused:ee,setTouched:D,state:ne,validationMode:re,validityData:ie,validation:k}=On(),A=SV(),{labelId:j,controlId:ae,registerControlId:oe,getDescriptionProps:se}=kn(),ce=wV(),M=ce?.parent,N=M&&ce.allValues,le=C||A.disabled||ce?.disabled||o,ue=w??d,de=v??ue,fe=O(),pe=O(),me=ae;N?me=p?pe:`${M.id}-${de}`:c&&(me=c);let he={};N&&(p?he=ce.parent.getParentProps():de&&(he=ce.parent.getChildProps(de)));let{checked:ge=n,indeterminate:_e=l,onCheckedChange:ve,...ye}=he,xe=ce?.value,P=ce?.setValue,Se=ce?.defaultValue,Ce=z.useRef(null),we=qt(()=>Symbol(`checkbox-control`)),Ee=z.useRef(!1),{getButtonProps:De,buttonRef:Oe}=Lt({disabled:le,native:y}),ke=ce?.validation??k,[Ae,je]=Yt({controlled:de&&xe&&!p?xe.includes(de):ge,default:de&&Se&&!p?Se.includes(de):i,name:`Checkbox`,state:`checked`}),Me=N?!!ge:Ae,Ne=N&&_e||l;Rt(()=>{oe!==It&&(Ee.current=!0,oe(we.current,me))},[me,oe,we]),z.useEffect(()=>{let e=we.current;return()=>{!Ee.current||oe===It||(Ee.current=!1,oe(e,void 0))}},[oe,we]),En(Ce,fe,Ae,void 0,!ce&&!le,d);let Pe=z.useRef(null),Fe=Kt(u,Pe,ke.inputRef,ke.registerInput),Ie=vB(a,j,Pe,!y,me??void 0);Rt(()=>{Pe.current&&(Pe.current.indeterminate=Ne,Ae&&E(!0))},[Ae,Ne,E]),Dn(Ae,()=>{ce||(S(ue),E(Ae),T(Ae!==ie.initialValue),ke.change(Ae))});let Le=zt({checked:Ae,disabled:le,form:s,name:p?void 0:ue,id:y?void 0:me??void 0,required:g,ref:Fe,style:ue?Te:He,tabIndex:-1,type:`checkbox`,"aria-hidden":!0,onChange(e){if(e.nativeEvent.defaultPrevented)return;if(m){e.preventDefault();return}let t=e.currentTarget.checked,n=te(be,e.nativeEvent);f?.(t,n),!n.isCanceled&&(ve?.(t,n),!n.isCanceled&&(je(t),de&&xe&&P&&!p&&!N&&P(t?[...xe,de]:xe.filter(e=>e!==de),n)))},onFocus(){Ce.current?.focus()}},v===void 0?Wt:{value:(ce?Ae&&v:v)||``},se,e=>ke.getValidationProps(le,e));z.useEffect(()=>{if(!M||!de)return;let e=M.disabledStatesRef.current;return e.set(de,le),()=>{e.delete(de)}},[M,le,de]);let Re=z.useMemo(()=>({...ne,checked:Me,disabled:le,readOnly:m,required:g,indeterminate:Ne}),[ne,Me,le,m,g,Ne]),ze=bV(Re),Be=Ft(`span`,e,{state:Re,ref:[Oe,Ce,t,ce?.registerControlRef],props:[{id:y?me??void 0:fe,role:`checkbox`,"aria-checked":Ne?`mixed`:Me,"aria-readonly":m||void 0,"aria-required":g||void 0,"aria-labelledby":Ie,[DV]:p?``:void 0,onFocus(){le||ee(!0)},onBlur(){let e=Pe.current;e&&(D(!0),ee(!1),re===`onBlur`&&ke.commit(ce?xe:e.checked))},onKeyDown(e){if(e.key!==`Enter`||(e.preventBaseUIHandler(),e.defaultPrevented))return;let t=Pe.current?.form??null,n=e.currentTarget,r=e.nativeEvent,i=e.preventDefault,a=r.preventDefault,o=!1;e.preventDefault=()=>{o=!0,i.call(e)},r.preventDefault=()=>{o=!0,a.call(r)},a.call(r),Mt(n).queueMicrotask(()=>{e.preventDefault=i,r.preventDefault=a,o||vV(t)?.click()})},onClick(e){if(m||le)return;e.preventDefault();let t=Pe.current;t&&t.dispatchEvent(new(Mt(t)).PointerEvent(`click`,{bubbles:!0,shiftKey:e.shiftKey,ctrlKey:e.ctrlKey,altKey:e.altKey,metaKey:e.metaKey}))}},x,ye,De,se,e=>ke.getValidationProps(le,e)],stateAttributesMapping:ze});return(0,R.jsxs)(TV.Provider,{value:Re,children:[Be,!Ae&&!ce&&ue&&!p&&_!==void 0&&(0,R.jsx)(`input`,{type:`hidden`,form:s,name:ue,value:_,disabled:le}),(0,R.jsx)(`input`,{...Le,suppressHydrationWarning:!0})]})}),kV=z.forwardRef(function(e,t){let{render:n,className:r,style:i,keepMounted:a=!1,...o}=e,s=EV(),c=s.checked||s.indeterminate,{mounted:l,transitionStatus:u,setMounted:d}=Je(c),f=z.useRef(null),p={...s,transitionStatus:u};g({open:c,ref:f,onComplete(){c||d(!1)}});let m={...bV(s),...it,...Tn},h=a||l,_=Ft(`span`,e,{ref:[t,f],state:p,stateAttributesMapping:m,props:o});return h?_:null}),AV=(0,z.createContext)(null);function jV(){let e=(0,z.useContext)(AV);if(!e)throw Error(`useCheckboxGroup must be used within a CheckboxGroup`);return e}var MV=(0,z.forwardRef)(({children:e,checkedIndices:t,orientation:n=`vertical`,className:r,...i},a)=>{let o=(0,z.useRef)(null),s=n===`horizontal`,{activeIndex:c,setActiveIndex:l,handlers:u,registerItem:d,measureItems:f}=_n(o,{axis:s?`x`:`y`});(0,z.useEffect)(()=>{f()},[f,e]);let p=s?`ArrowLeft`:`ArrowUp`,m=s?`ArrowRight`:`ArrowDown`;return(0,R.jsx)(AV.Provider,{value:{registerItem:d,activeIndex:c},children:(0,R.jsx)(`div`,{ref:e=>{o.current=e,typeof a==`function`?a(e):a&&(a.current=e)},onMouseEnter:u.onMouseEnter,onMouseMove:u.onMouseMove,onMouseLeave:u.onMouseLeave,onFocus:e=>{let t=e.target.closest(`[data-proximity-index]`)?.getAttribute(`data-proximity-index`);t!=null&&l(Number(t))},onBlur:e=>{o.current?.contains(e.relatedTarget)||l(null)},onKeyDown:e=>{let t=Array.from(o.current?.querySelectorAll(`[data-proximity-index]`)??[]),n=t.indexOf(e.target);n!==-1&&([p,m].includes(e.key)?(e.preventDefault(),t[e.key===m?(n+1)%t.length:(n-1+t.length)%t.length]?.focus()):e.key===`Home`?(e.preventDefault(),t[0]?.focus()):e.key===`End`&&(e.preventDefault(),t[t.length-1]?.focus()))},role:`group`,className:L(`relative flex max-w-full select-none`,s?`w-auto flex-row`:`w-72 flex-col`,r),...i,children:e})})});MV.displayName=`CheckboxGroup`;var NV=(0,z.forwardRef)(({label:e,index:t,checked:n,onToggle:r,size:i=`default`,className:a,...o},s)=>{let c=(0,z.useRef)(null),l=(0,z.useRef)(!1),{registerItem:u,activeIndex:d}=jV();(0,z.useEffect)(()=>(u(t,c.current),()=>u(t,null)),[t,u]),(0,z.useEffect)(()=>{l.current=!0},[]);let f=d===t,p=!l.current,m=Nt(),h=i===`sm`;return(0,R.jsxs)(`div`,{ref:e=>{c.current=e,typeof s==`function`?s(e):s&&(s.current=e)},"data-proximity-index":t,tabIndex:0,role:`checkbox`,"aria-checked":n,"aria-label":e,onClick:r,onMouseDown:e=>{let t=e.target.closest(`button:not([tabindex="-1"]), a[href], input, select, textarea, [tabindex]:not([tabindex="-1"])`);t&&t!==e.currentTarget||(e.preventDefault(),e.currentTarget.focus())},onKeyDown:e=>{(e.key===` `||e.key===`Enter`)&&(e.preventDefault(),r())},className:L(`relative z-10 flex items-center cursor-pointer outline-none`,h?`h-7 gap-1.5 px-2`:`h-8 gap-2.5 px-3`,m.item,`focus-visible:ring-1 focus-visible:ring-[color:var(--focus-ring,#6B97FF)]`,a),...o,children:[(0,R.jsxs)(OV,{checked:n,tabIndex:-1,"aria-hidden":!0,className:L(`pointer-events-none relative shrink-0 appearance-none bg-transparent p-0 border-0 outline-none`,h?`size-[13px]`:`size-[15px]`),children:[(0,R.jsx)(`div`,{className:L(`absolute inset-0 rounded-[5px] border-solid transition-all duration-80 border-[1.5px]`,n?`border-border`:f?`border-neutral-400 dark:border-neutral-500`:`border-border`)}),(0,R.jsx)(en,{children:n&&(0,R.jsx)(kV,{keepMounted:!0,render:e=>{let{style:t,onDrag:n,onDragStart:r,onDragEnd:i,onAnimationStart:a,onAnimationEnd:o,onAnimationIteration:s,...c}=e;return(0,R.jsx)(Pe.svg,{...c,width:h?14:18,height:h?14:18,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:2,strokeLinecap:`round`,strokeLinejoin:`round`,className:`absolute left-1/2 top-1/2 -translate-x-1/2 -translate-y-1/2 text-foreground`,initial:{opacity:1},animate:{opacity:1},exit:{opacity:1},children:(0,R.jsx)(Pe.path,{d:`M6 12L10 16L18 8`,initial:{pathLength:+!!p},animate:{pathLength:1,transition:{duration:.08,ease:`easeOut`}},exit:{pathLength:0,transition:{duration:.04,ease:`easeIn`}}})})}})})]}),(0,R.jsxs)(`span`,{className:`inline-grid items-center self-center leading-none`,children:[(0,R.jsx)(`span`,{className:`col-start-1 row-start-1 invisible leading-none`,style:{fontVariationSettings:ke.semibold},"aria-hidden":`true`,children:e}),(0,R.jsx)(`span`,{className:L(`col-start-1 row-start-1 leading-none transition-[color,font-variation-settings] duration-80`,h?`text-[11px]`:`text-[13px]`,n||f?`text-foreground`:`text-muted-foreground`),style:{fontVariationSettings:n?ke.semibold:ke.normal},children:e})]})]})});NV.displayName=`CheckboxItem`;var PV=36,FV=188,IV=6;function LV(e,t,n){let[r,i]=(0,z.useState)(0),[a,o]=(0,z.useState)(0),s=(0,z.useMemo)(()=>{let n=[],r=[],i=0;for(let a of e){n.push(i);let e=PV+(t.has(a.id)?FV:0);r.push(e),i+=e}return{offsets:n,heights:r,totalHeight:i}},[t,e]),c=(0,z.useMemo)(()=>{if(e.length===0)return{totalHeight:0,visibleItems:[]};let{offsets:t,heights:n,totalHeight:i}=s,o=r+a,c=0;for(;c<e.length&&t[c]+n[c]<r;)c++;c=Math.max(0,c-IV);let l=c;for(;l<e.length&&t[l]<o;)l++;l=Math.min(e.length,l+IV);let u=[];for(let r=c;r<l;r++)u.push({index:r,item:e[r],top:t[r],height:n[r]});return{totalHeight:i,visibleItems:u}},[e,s,r,a]),l=(0,z.useCallback)(()=>{let e=n.current;e&&i(e.scrollTop)},[n]);return(0,z.useEffect)(()=>{let e=n.current;if(!e)return;let t=()=>{o(e.clientHeight),i(e.scrollTop)};t();let r=new ResizeObserver(t);return r.observe(e),e.addEventListener(`scroll`,l,{passive:!0}),()=>{r.disconnect(),e.removeEventListener(`scroll`,l)}},[l,n,e.length]),c}var RV=300,zV=/(?:^|\/)notifications\//;function BV(e){let t=e;return typeof t?.method==`string`?t.method:null}function VV(e){let t=e.message;if(t?.id!==void 0&&t.id!==null||t?.result!==void 0||t?.error!==void 0)return null;let n=BV(e.message);return!n||!zV.test(n)?null:[e.source,e.serverId,e.widgetId??``,e.direction,n].join(`|`)}function HV(e,t,n=Date.now()){let r=VV(e),i=VV(t);if(!r||r!==i)return!1;let a=Date.parse(e.timestamp);return Number.isNaN(a)?!1:n-a<=RV}function UV(e,t){return{...e,timestamp:t.timestamp,message:t.message,repeatCount:(e.repeatCount??1)+1}}var WV=new class{maxEntries;entries=[];listeners=new Set;nextId=0;emitFrame=null;constructor(e=1e3){this.maxEntries=e}publish(e){let t=this.entries[this.entries.length-1];if(t&&HV(t,e,Date.parse(e.timestamp))){this.entries[this.entries.length-1]=UV(t,e),this.scheduleEmit();return}this.entries.push({...e,id:`rpc-${++this.nextId}`}),this.entries.length>this.maxEntries&&this.entries.splice(0,this.entries.length-this.maxEntries),this.scheduleEmit()}getSnapshot=()=>this.entries;subscribe=e=>(this.listeners.add(e),()=>this.listeners.delete(e));clear(e={}){let t=new Set(e.serverIds??[]),n=new Set(e.sources??[]);t.size===0&&n.size===0?this.entries=[]:this.entries=this.entries.filter(e=>!((t.size===0||t.has(e.serverId))&&(n.size===0||n.has(e.source)))),this.scheduleEmit()}peekCoalesceKey(e){return VV(e)}scheduleEmit(){if(this.emitFrame===null){if(typeof requestAnimationFrame>`u`){this.emit();return}this.emitFrame=requestAnimationFrame(()=>{this.emitFrame=null,this.emit()})}}emit(){this.listeners.forEach(e=>e())}},GV;function KV(e){WV.publish({source:`mcp`,serverId:e.serverId,direction:e.direction,timestamp:e.timestamp,message:e.message})}function qV(){GV||=(ZO().forEach(KV),QO(KV))}qV();function JV({serverIds:e,onCountChange:t,onClearRef:n,onExportRef:r}={}){let i=(0,z.useRef)(null),[a,o]=(0,z.useState)(new Set),[s,c]=(0,z.useState)(``),[l,u]=(0,z.useState)(!1),[d,f]=(0,z.useState)(()=>new Set([`mcp`,`widget`])),p=(0,z.useSyncExternalStore)(WV.subscribe,WV.getSnapshot,WV.getSnapshot),m=async e=>{try{await zj(JSON.stringify(e,null,2)),IF.success(`Message copied to clipboard`)}catch(e){console.error(`Failed to copy message:`,e),IF.error(`Failed to copy to clipboard`)}},h=(0,z.useMemo)(()=>{if(!e?.length)return p;let t=new Set(e);return p.filter(e=>t.has(e.serverId))},[p,e]),g=(0,z.useMemo)(()=>{let e=new Set;return d.has(`mcp`)&&e.add(0),d.has(`widget`)&&e.add(1),e},[d]),_=(0,z.useCallback)(e=>{f(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})},[]),y=(0,z.useMemo)(()=>{let e=h;d.size>0&&(e=e.filter(e=>d.has(e.source)));let t=s.trim().toLowerCase();return t&&(e=e.filter(e=>{let n=XV(e);return e.serverId.toLowerCase().includes(t)||e.widgetId?.toLowerCase().includes(t)||e.source.includes(t)||n.toLowerCase().includes(t)||e.direction.toLowerCase().includes(t)||JSON.stringify(e.message).toLowerCase().includes(t)})),[...e].reverse()},[h,s,d]),{totalHeight:b,visibleItems:x}=LV(y,a,i),S=(0,z.useCallback)(e=>{o(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})},[]),C=(0,z.useCallback)(async()=>{let t=d.size===0||d.size===2?void 0:[...d];(!t||t.includes(`mcp`))&&(e?.length?e.forEach(e=>$O(e)):$O()),WV.clear({serverIds:e,sources:t}),o(new Set)},[e,d]),w=(0,z.useCallback)(async()=>{try{await zj(JSON.stringify(y,null,2)),IF.success(`Copied ${y.length} messages`)}catch(e){console.error(`Failed to copy messages:`,e),IF.error(`Failed to copy to clipboard`)}},[y]),T=(0,z.useCallback)(()=>{let e=new Blob([JSON.stringify(y,null,2)],{type:`application/json`}),t=URL.createObjectURL(e),n=document.createElement(`a`);n.href=t,n.download=`mcp-rpc-traffic-${new Date().toISOString().replaceAll(`:`,`-`)}.json`,n.click(),URL.revokeObjectURL(t)},[y]);return(0,z.useEffect)(()=>{t?.(y.length)},[y.length,t]),(0,z.useEffect)(()=>(n&&(n.current=C),()=>{n&&(n.current=null)}),[C,n]),(0,z.useEffect)(()=>(r&&(r.current=w),()=>{r&&(r.current=null)}),[w,r]),(0,R.jsxs)(`div`,{className:`flex h-full min-h-0 flex-col overflow-hidden`,children:[(0,R.jsxs)(`div`,{className:`flex shrink-0 items-center justify-between gap-2 pr-2 pt-2 pl-1`,children:[(0,R.jsx)(`h2`,{className:`text-xs font-medium text-foreground`,children:`RPC Logs`}),(0,R.jsxs)(`div`,{className:`flex items-center gap-0.5`,children:[(0,R.jsx)(Gt,{variant:`ghost`,size:`sm`,className:`size-7 p-0`,onClick:w,disabled:y.length===0,"aria-label":`Copy filtered RPC traffic`,title:`Copy filtered`,children:(0,R.jsx)(Wr,{className:`size-3.5`})}),(0,R.jsx)(Gt,{variant:`ghost`,size:`sm`,className:`size-7 p-0`,onClick:T,disabled:y.length===0,"aria-label":`Download filtered RPC traffic as JSON`,title:`Download JSON`,children:(0,R.jsx)(qr,{className:`size-3.5`})}),(0,R.jsx)(Gt,{variant:`ghost`,size:`sm`,className:`size-7 p-0`,onClick:C,disabled:p.length===0,"aria-label":`Clear RPC traffic`,title:`Clear`,children:(0,R.jsx)(Gi,{className:`size-3.5`})})]})]}),(0,R.jsxs)(`div`,{className:`flex shrink-0 items-center pr-2 pb-2 pt-1 pl-1`,children:[(0,R.jsxs)(`div`,{className:`relative min-w-0 flex-1 transition-[flex-grow] duration-200 ease-out`,children:[(0,R.jsx)(v,{className:`pointer-events-none absolute left-2 top-1/2 size-3.5 -translate-y-1/2 text-muted-foreground`}),(0,R.jsx)(ht,{value:s,onChange:e=>c(e.target.value),onFocus:()=>u(!0),onBlur:()=>u(!1),placeholder:`Search`,"aria-label":`Search RPC traffic`,className:`h-8 w-full pl-7 text-xs shadow-none transition-[width] duration-200 ease-out`})]}),(0,R.jsx)(`div`,{"aria-hidden":l,className:L(`shrink-0 overflow-hidden transition-[max-width,opacity,margin] duration-200 ease-out`,l?`pointer-events-none ml-0 max-w-0 opacity-0`:`ml-2 max-w-32 opacity-100`),children:(0,R.jsxs)(MV,{checkedIndices:g,orientation:`horizontal`,"aria-label":`Filter RPC traffic by source`,className:`w-auto shrink-0`,children:[(0,R.jsx)(NV,{index:0,label:`MCP`,size:`sm`,checked:d.has(`mcp`),onToggle:()=>_(`mcp`)}),(0,R.jsx)(NV,{index:1,label:`UI`,size:`sm`,checked:d.has(`widget`),onToggle:()=>_(`widget`)})]})})]}),(0,R.jsx)(`div`,{ref:i,className:`min-h-0 flex-1 overflow-y-auto pb-10`,style:{maskImage:`linear-gradient(to bottom, black 0, black calc(100% - 3rem), transparent 100%)`,WebkitMaskImage:`linear-gradient(to bottom, black 0, black calc(100% - 3rem), transparent 100%)`},children:y.length===0?(0,R.jsxs)(`div`,{className:`text-center py-8`,children:[(0,R.jsx)(`div`,{className:`text-xs text-muted-foreground`,children:`No messages yet`}),(0,R.jsx)(`div`,{className:`text-[10px] text-muted-foreground mt-1`,children:`JSON-RPC messages will appear here`})]}):(0,R.jsx)(`div`,{className:`relative w-full`,style:{height:b},children:x.map(({item:e,top:t,height:n})=>(0,R.jsx)(YV,{item:e,top:t,height:n,expanded:a.has(e.id),onToggle:()=>S(e.id),onCopy:()=>m(e.message)},e.id))})})]})}function YV({item:e,top:t,height:n,expanded:r,onToggle:i,onCopy:a}){let o=XV(e),s=ZV(e),c=e.repeatCount&&e.repeatCount>1?` ×${e.repeatCount}`:``;return(0,R.jsxs)(`div`,{className:`absolute inset-x-0 overflow-hidden`,style:{top:t,height:n},"data-testid":`rpc-message-${o.replace(/\//g,`-`)}`,children:[(0,R.jsxs)(`button`,{type:`button`,"aria-expanded":r,onClick:i,className:`flex h-9 w-full cursor-pointer items-center gap-2 py-2 pr-3 pl-1 text-left text-muted-foreground transition-colors hover:text-foreground`,children:[(0,R.jsxs)(et,{children:[(0,R.jsx)(we,{render:(0,R.jsx)(`span`,{className:`flex size-4 shrink-0 items-center justify-center`,children:e.direction===`receive`?(0,R.jsx)(Dr,{className:`size-3.5 text-blue-500`}):(0,R.jsx)(Ar,{className:`size-3.5 text-emerald-500`})}),nativeButton:!1}),(0,R.jsx)(lt,{side:`left`,children:s})]}),(0,R.jsxs)(et,{children:[(0,R.jsx)(we,{render:(0,R.jsx)(`span`,{className:`flex size-3.5 shrink-0 items-center justify-center`,children:e.source===`mcp`?(0,R.jsx)(bL,{className:`size-3`}):(0,R.jsx)(Ti,{className:`size-3`})}),nativeButton:!1}),(0,R.jsx)(lt,{side:`left`,children:e.source===`mcp`?`MCP server`:`UI widget`})]}),(0,R.jsxs)(`span`,{className:`min-w-0 flex-1 truncate font-mono text-xs text-foreground`,children:[o,c?(0,R.jsx)(`span`,{className:`text-muted-foreground`,children:c}):null]}),(0,R.jsxs)(et,{children:[(0,R.jsx)(we,{render:(0,R.jsx)(`time`,{dateTime:e.timestamp,className:`shrink-0 cursor-default font-mono text-[10px] tabular-nums text-muted-foreground underline decoration-dotted underline-offset-2`,children:new Date(e.timestamp).toLocaleTimeString()}),nativeButton:!1}),(0,R.jsx)(lt,{side:`left`,children:new Date(e.timestamp).toLocaleString()})]})]}),r?(0,R.jsxs)(`div`,{className:`relative mx-3 mb-2 max-h-44 overflow-auto rounded-lg p-2 pr-8`,children:[(0,R.jsx)(_V,{data:e.message,className:`[&_pre]:!text-[10px] [&_pre]:!leading-4`}),(0,R.jsx)(Gt,{variant:`secondary`,size:`icon-sm`,onClick:a,className:`absolute right-1 top-1 size-6 rounded-full p-0`,title:`Copy message`,"aria-label":`Copy message`,children:(0,R.jsx)(Wr,{className:`size-3`})})]}):null]})}function XV(e){let t=BV(e.message);if(t)return t;let n=e.message;return n?.result===void 0?n?.error===void 0?`unknown`:`error`:`result`}function ZV(e){return e.source===`widget`?e.direction===`send`?`Host → Widget`:`Widget → Host`:e.direction===`send`?`Inspector → MCP`:`MCP → Inspector`}function QV({serverId:e,open:t}){return(0,R.jsx)(`aside`,{"aria-label":`RPC Panel`,"aria-hidden":!t,className:L(`relative hidden min-h-0 shrink-0 flex-col overflow-hidden transition-[width,margin] duration-200 ease-out lg:flex`,t?`w-(--rpc-panel-width) lg:mr-[18px]`:`w-0 lg:mr-0`),children:(0,R.jsx)(`div`,{className:L(`flex h-full min-h-0 w-(--rpc-panel-width) flex-col transition-opacity duration-200 ease-out`,t?`opacity-100`:`pointer-events-none opacity-0`),children:(0,R.jsx)(JV,{serverIds:[e]})})})}function $V({...e}){return(0,R.jsx)(jI,{"data-slot":`sheet`,...e})}function eH(e){return(0,R.jsx)(NI,{"data-slot":`sheet-trigger`,...e})}function tH({...e}){return(0,R.jsx)(wI,{"data-slot":`sheet-portal`,...e})}function nH({className:e,container:t,...n}){return(0,R.jsx)(hI,{"data-slot":`sheet-overlay`,className:L(`inset-0 z-50 bg-black/50 transition-opacity duration-150 data-ending-style:opacity-0 data-starting-style:opacity-0`,t?`absolute`:`fixed`,e),...n})}function rH({className:e,children:t,side:n=`right`,showCloseButton:r=!0,container:i,...a}){return(0,R.jsxs)(tH,{container:i??void 0,children:[(0,R.jsx)(nH,{container:i}),(0,R.jsxs)(CI,{"data-slot":`sheet-content`,"data-side":n,className:L(`z-50 flex flex-col gap-4 bg-popover bg-clip-padding text-sm text-popover-foreground shadow-lg transition duration-200 ease-in-out data-ending-style:opacity-0 data-starting-style:opacity-0 data-[side=bottom]:inset-x-0 data-[side=bottom]:bottom-0 data-[side=bottom]:h-auto data-[side=bottom]:border-t data-[side=bottom]:data-ending-style:translate-y-[2.5rem] data-[side=bottom]:data-starting-style:translate-y-[2.5rem] data-[side=left]:inset-y-0 data-[side=left]:left-0 data-[side=left]:h-full data-[side=left]:w-3/4 data-[side=left]:border-r data-[side=left]:data-ending-style:translate-x-[-2.5rem] data-[side=left]:data-starting-style:translate-x-[-2.5rem] data-[side=right]:inset-y-0 data-[side=right]:right-0 data-[side=right]:h-full data-[side=right]:w-3/4 data-[side=right]:border-l data-[side=right]:data-ending-style:translate-x-[2.5rem] data-[side=right]:data-starting-style:translate-x-[2.5rem] data-[side=top]:inset-x-0 data-[side=top]:top-0 data-[side=top]:h-auto data-[side=top]:border-b data-[side=top]:data-ending-style:translate-y-[-2.5rem] data-[side=top]:data-starting-style:translate-y-[-2.5rem] data-[side=left]:sm:max-w-sm data-[side=right]:sm:max-w-sm`,i?`absolute`:`fixed`,e),...a,children:[t,r&&(0,R.jsxs)(gI,{"data-slot":`sheet-close`,render:(0,R.jsx)(Gt,{variant:`ghost`,className:`absolute top-4 right-4`,size:`icon-sm`}),children:[(0,R.jsx)(Xi,{}),(0,R.jsx)(`span`,{className:`sr-only`,children:`Close`})]})]})]})}function iH({className:e,...t}){return(0,R.jsx)(`div`,{"data-slot":`sheet-header`,className:L(`flex flex-col gap-1.5 p-4`,e),...t})}function aH({className:e,...t}){return(0,R.jsx)(MI,{"data-slot":`sheet-title`,className:L(`font-medium text-foreground`,e),...t})}function oH({className:e,...t}){return(0,R.jsx)(_I,{"data-slot":`sheet-description`,className:L(`text-sm text-muted-foreground`,e),...t})}var sH=`https://cdn.mcp-use.com/mcpuse_logo_circle_dark.svg`;function cH({symbolSize:e=14,className:t,textClassName:n}){return(0,R.jsxs)(`span`,{className:L(`inline-flex items-center gap-1.5`,t),children:[(0,R.jsx)(lH,{size:e}),(0,R.jsx)(`span`,{className:L(`font-medium leading-none text-black [font-family:var(--font-family-outfit)]`,n),children:`Manufact`})]})}function lH({size:e=14,className:t}){return(0,R.jsxs)(`svg`,{width:e,height:e,viewBox:`0 0 480 480`,"aria-hidden":!0,className:L(`block shrink-0`,t),children:[(0,R.jsx)(`path`,{d:`M101.7 0 C157.9 0 203.4 45.7 203.4 102.1 C203.4 126.6 202.1 152.1 212.2 174.3 L219.8 191 C233.8 221.8 258.5 246.4 289.2 260.5 L303.5 267 C326.5 277.5 353 275.8 378.3 275.8 C434.5 275.8 480 321.5 480 377.9 C480 434.3 434.5 480 378.3 480 C322.1 480 276.6 434.3 276.6 377.9 C276.6 354.2 277.7 329.6 267.8 308 L259.8 290.3 C245.7 259.5 221 234.8 190.2 220.7 L173 212.9 C151 202.9 125.8 204.2 101.7 204.2 C45.5 204.2 0 158.5 0 102.1 C0 45.7 45.5 0 101.7 0 Z`,fill:`currentColor`}),(0,R.jsx)(`circle`,{cx:`96.4`,cy:`383.6`,r:`96.4`,fill:`currentColor`}),(0,R.jsx)(`circle`,{cx:`383.6`,cy:`96.4`,r:`96.4`,fill:`currentColor`})]})}var uH=`data:image/svg+xml,%3Csvg%20width%3D%22512%22%20height%3D%22512%22%20viewBox%3D%220%200%20512%20512%22%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20fill%3D%22%2394A3B8%22%20stroke%3D%22%2394A3B8%22%3E%3Cg%3E%3Cpath%20fill%3D%22none%22%20d%3D%22M3%20248.945C18%20248.945%2076%20236%20106%20219C136%20202%20136%20202%20198%20158C276.497%20102.293%20332%20120.945%20423%20120.945%22%20stroke-width%3D%2290%22%2F%3E%3Cpath%20d%3D%22M511%20121.5L357.25%20210.268L357.25%2032.7324L511%20121.5Z%22%2F%3E%3Cpath%20fill%3D%22none%22%20d%3D%22M0%20249C15%20249%2073%20261.945%20103%20278.945C133%20295.945%20133%20295.945%20195%20339.945C273.497%20395.652%20329%20377%20420%20377%22%20stroke-width%3D%2290%22%2F%3E%3Cpath%20d%3D%22M508%20376.445L354.25%20287.678L354.25%20465.213L508%20376.445Z%22%2F%3E%3C%2Fg%3E%3C%2Fsvg%3E`,dH={openai:`OpenAI`,anthropic:`Anthropic`,google:`Google`};function fH(e){let t=e.split(`/`)[0]?.toLowerCase();return t===`openai`||t===`anthropic`||t===`google`?t:`openrouter`}function pH(e,t){let n=e.trim(),r=dH[t];if(r){let e=r.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`),t=RegExp(`^${e}\\s*:\\s*`,`i`),i=n.replace(t,``).trim();if(i.length>0)return i}let i=n.indexOf(`: `);return i>0&&i<48?n.slice(i+2).trim():n}function mH({provider:e,model:t,displayName:n,mode:r=`byok`,className:i,...a}){let o=n??t,s=r===`managed`&&e===`openai-compatible`?fH(t):e;return(0,R.jsxs)(`button`,{type:`button`,className:L(`inline-flex items-center gap-1.5 min-w-0 border-0 bg-transparent p-1`,`font-mono text-[11px] text-muted-foreground cursor-pointer`,`hover:text-foreground transition-colors`,`rounded-md outline-none focus-visible:ring-1 focus-visible:ring-ring`,i),...a,children:[r===`managed`?(0,R.jsx)(`img`,{src:sH,alt:`Manufact`,className:`h-3.5 w-3.5 shrink-0 rounded-full object-cover`}):(0,R.jsx)(ci,{className:`size-3 shrink-0 opacity-70`,"aria-hidden":!0}),(0,R.jsx)(_H,{provider:s,className:`shrink-0`}),(0,R.jsx)(`span`,{className:`whitespace-nowrap`,children:o}),(0,R.jsx)(Ir,{className:`size-3 shrink-0 opacity-60`,"aria-hidden":!0})]})}function hH(e){switch(e){case`openai`:return`OpenAI`;case`openai-compatible`:return`OpenAI Compatible`;case`anthropic`:return`Anthropic`;case`google`:return`Google`;case`openrouter`:return`OpenRouter`;case`ollama`:return`Ollama`;default:return e}}function gH(e,t){switch(e){case`openai`:case`anthropic`:case`google`:return`https://inspector-cdn.mcp-use.com/providers/${e}.png`;case`ollama`:return`https://inspector-cdn.mcp-use.com/providers/${t===`dark`?`ollama_dark`:`ollama_light`}.png`;case`openrouter`:return uH;case`openai-compatible`:return null;default:return null}}function _H({provider:e,className:t}){let{resolvedTheme:n}=dz();if(e===`openai-compatible`)return null;let r=gH(e,n);if(r){let n=e===`ollama`?`h-3.5 w-3.5 object-contain`:`h-4 w-4 rounded-full object-cover`;return(0,R.jsx)(`img`,{src:r,alt:hH(e),className:L(n,t)})}return(0,R.jsx)(`div`,{"aria-label":hH(e),className:L(`flex h-4 w-4 items-center justify-center rounded-full bg-neutral-900 text-[9px] font-semibold text-white dark:bg-neutral-100 dark:text-neutral-900`,t),children:hH(e).charAt(0)})}function vH({className:e}){return(0,R.jsx)(`svg`,{viewBox:`0 -28.5 256 256`,className:e,fill:`currentColor`,xmlns:`http://www.w3.org/2000/svg`,"aria-hidden":!0,children:(0,R.jsx)(`path`,{d:`M216.856339,16.5966031 C200.285002,8.84328665 182.566144,3.2084988 164.041564,0 C161.766523,4.11318106 159.108624,9.64549908 157.276099,14.0464379 C137.583995,11.0849896 118.072967,11.0849896 98.7430163,14.0464379 C96.9108417,9.64549908 94.1925838,4.11318106 91.8971895,0 C73.3526068,3.2084988 55.6133949,8.86399117 39.0420583,16.6376612 C5.61752293,67.146514 -3.4433191,116.400813 1.08711069,164.955721 C23.2560196,181.510915 44.7403634,191.567697 65.8621325,198.148576 C71.0772151,190.971126 75.7283628,183.341335 79.7352139,175.300261 C72.104019,172.400575 64.7949724,168.822202 57.8887866,164.667963 C59.7209612,163.310589 61.5131304,161.891452 63.2445898,160.431257 C105.36741,180.133187 151.134928,180.133187 192.754523,160.431257 C194.506336,161.891452 196.298154,163.310589 198.110326,164.667963 C191.183787,168.842556 183.854737,172.420929 176.223542,175.320965 C180.230393,183.341335 184.861538,190.991831 190.096624,198.16893 C211.238746,191.588051 232.743023,181.531619 254.911949,164.955721 C260.227747,108.668201 245.831087,59.8662432 216.856339,16.5966031 Z M85.4738752,135.09489 C72.8290281,135.09489 62.4592217,123.290155 62.4592217,108.914901 C62.4592217,94.5396472 72.607595,82.7145587 85.4738752,82.7145587 C98.3405064,82.7145587 108.709962,94.5189427 108.488529,108.914901 C108.508531,123.290155 98.3405064,135.09489 85.4738752,135.09489 Z M170.525237,135.09489 C157.88039,135.09489 147.510584,123.290155 147.510584,108.914901 C147.510584,94.5396472 157.658606,82.7145587 170.525237,82.7145587 C183.391518,82.7145587 193.761324,94.5189427 193.539891,108.914901 C193.539891,123.290155 183.391518,135.09489 170.525237,135.09489 Z`,fillRule:`nonzero`})})}var yH=`flex flex-1 items-center justify-center text-muted-foreground transition-colors hover:text-foreground active:text-foreground`;function bH({serverId:e,rpcLoggerOpen:t,onRpcLoggerOpenChange:n}){let r=lB(),{embeddedConfig:i}=nL(),{user:a}=WR(i.chatApiUrl),o=a?`https://manufact.com/cloud?ref=mcp-use-inspector`:`https://manufact.com/signup?ref=mcp-use-inspector`;return(0,R.jsxs)(R.Fragment,{children:[typeof document<`u`&&(0,br.createPortal)((0,R.jsxs)(`nav`,{"aria-label":`Inspector shortcuts`,className:`fixed inset-x-0 bottom-0 z-[100] flex items-center bg-transparent px-4 pt-(--mobile-chrome-gap) pb-[calc(var(--mobile-chrome-gap)+env(safe-area-inset-bottom))] lg:hidden`,children:[(0,R.jsx)(`button`,{type:`button`,onClick:()=>n(!t),className:L(yH,t&&`text-foreground`),"aria-label":`RPC logs`,"aria-pressed":t,children:(0,R.jsx)(Pi,{className:`size-4 shrink-0`})}),(0,R.jsx)(`a`,{href:`https://github.com/mcp-use/mcp-use`,target:`_blank`,rel:`noopener noreferrer`,className:yH,"aria-label":`GitHub`,children:(0,R.jsx)(pB,{className:`size-4 shrink-0`})}),(0,R.jsx)(`a`,{href:`https://discord.gg/XkNkSkMz3V`,target:`_blank`,rel:`noopener noreferrer`,className:yH,"aria-label":`Discord`,children:(0,R.jsx)(vH,{className:`size-4 shrink-0`})}),(0,R.jsx)(`a`,{href:o,target:`_blank`,rel:`noopener noreferrer`,onClick:()=>{try{bT(new Mo({referrer:`mcp-use-inspector-mobile-toolbar`})).catch(()=>{})}catch{}},className:yH,"aria-label":`manufact.com`,children:(0,R.jsx)(lH,{size:16})})]}),document.body),!r&&(0,R.jsx)($V,{open:t,onOpenChange:n,children:(0,R.jsxs)(rH,{side:`bottom`,className:`z-[101] flex h-[min(85dvh,720px)] flex-col gap-0 rounded-t-2xl border-zinc-200 p-0 dark:border-zinc-700`,children:[(0,R.jsx)(iH,{className:`sr-only`,children:(0,R.jsx)(aH,{children:`RPC logs`})}),(0,R.jsx)(`div`,{className:`flex min-h-0 flex-1 flex-col px-2 pb-2 pt-1`,children:(0,R.jsx)(JV,{serverIds:e?[e]:void 0})})]})})]})}function xH(e){return`${e.replace(/\/+$/,``)}${Uj()}`}function SH({tunnelUrl:e,tunnelMcpUrl:t,selectedServerId:n,selectedServer:r,configLoaded:i,removeConnection:a,updateConnection:o,connections:s}){let c=(0,z.useRef)(null),l=(0,z.useRef)(!1),u=(0,z.useRef)(null),[d,f]=(0,z.useState)(!1);return(0,z.useEffect)(()=>{!d||r?.url!==u.current||r.state!==`ready`&&r.state!==`failed`||(f(!1),l.current=!1,u.current=null)},[d,r]),(0,z.useEffect)(()=>{n&&qj(n)?c.current=n:r?.url&&qj(r.url)&&(c.current=r.url)},[r?.url,n]),(0,z.useEffect)(()=>{if(!i||!n||!r||l.current)return;let d=r.url??``,p=qj(d),m=Jj(d),h=t??(e?xH(e):null),g=null;e&&h&&p?g=h:!e&&m&&c.current&&(g=c.current),!(!g||g===d)&&(l.current=!0,u.current=g,f(!0),(async()=>{try{g!==n&&s.some(e=>e.id===g)&&await a(g),await o(n,uM({...fM(n)??dM(r),url:g}))}catch{f(!1),u.current=null,l.current=!1}})())},[i,s,a,r,n,t,e,o]),(0,z.useEffect)(()=>{d||(l.current=!1)},[d]),d}function CH({children:e}){let t=LN(),n=PN(),{servers:r,addServer:i,removeServer:a,updateServerMetadata:o,updateServer:s,storageLoaded:c}=oj(),l=(0,z.useCallback)(async(e,t)=>{try{await s(e,uM(t)),oM(e,t)}catch(t){console.error(`[Layout] Failed to update connection ${e}:`,t)}},[s]),u=(0,z.useCallback)(async(e,t)=>{try{await o(e,t)}catch(t){console.error(`[Layout] Failed to update connection metadata for ${e}:`,t)}},[o]),{selectedServerId:d,setSelectedServerId:f,activeTab:p,setActiveTab:m,navigateToItem:h,setTunnelUrl:g,tunnelUrl:_,isEmbedded:v,embeddedConfig:y,setEmbeddedMode:b}=nL(),[x,S]=(0,z.useState)(!1),[C,w]=(0,z.useState)(()=>{try{return localStorage.getItem(`inspector-sidebar-collapsed`)===`true`}catch{return!1}}),[T,E]=(0,z.useState)(()=>{try{return localStorage.getItem(`inspector-rpc-logger-open`)===`true`}catch{return!1}});(0,z.useEffect)(()=>{try{localStorage.setItem(`inspector-sidebar-collapsed`,C?`true`:`false`)}catch{}},[C]),(0,z.useEffect)(()=>{try{localStorage.setItem(`inspector-rpc-logger-open`,String(T))}catch{}},[T]);let{savedRequests:ee}=aL();(0,z.useEffect)(()=>{let e=new URLSearchParams(n.search),t=e.get(`embedded`)===`true`,r=e.get(`embeddedConfig`);if(t){let e={};if(r)try{e=JSON.parse(r)}catch(e){console.error(`Failed to parse embeddedConfig:`,e)}b(!0,e),e.defaultTab&&m(e.defaultTab)}},[]),(0,z.useEffect)(()=>{let e=new URLSearchParams(n.search).get(`tunnelUrl`);e!==null&&g(e)},[n.search,g]),(0,z.useEffect)(()=>{let e=new URLSearchParams(n.search).get(`tab`);e&&[`tools`,`prompts`,`resources`,`chat`,`sampling`,`elicitation`,`notifications`,`server-metadata`,`connection-settings`].includes(e)&&m(e)},[n.search,m]);let D=(0,z.useRef)(null),te=(0,z.useRef)(Date.now()),ne=(0,z.useRef)(new Set),re=(0,z.useRef)(0);(0,z.useEffect)(()=>{let e=()=>{re.current++};return window.addEventListener(`mcp-tool-executed`,e),()=>window.removeEventListener(`mcp-tool-executed`,e)},[]),(0,z.useEffect)(()=>{let e=()=>{try{bT(new Io({durationSeconds:Math.round((Date.now()-te.current)/1e3),tabsVisited:ne.current.size,toolsExecuted:re.current})).catch(()=>{})}catch{}};return window.addEventListener(`beforeunload`,e),()=>window.removeEventListener(`beforeunload`,e)},[]);let O=(0,z.useCallback)(e=>{try{bT(new Po({tab:e,previousTab:D.current})).catch(()=>{})}catch{}D.current=e,ne.current.add(e),m(e);let r=new URLSearchParams(n.search);r.set(`tab`,e),t(`/?${r.toString()}`,{replace:!0})},[m,t,n.search]);(0,z.useEffect)(()=>{let e=e=>{let t=e.detail.requestId;d&&h(d,`sampling`,t)},t=e=>{let t=e.detail.requestId;d&&h(d,`elicitation`,t)},n=e=>{let t=e.detail.toolName;d&&t?h(d,`tools`,t):d&&O(`tools`)};return window.addEventListener(`navigate-to-sampling`,e),window.addEventListener(`navigate-to-elicitation`,t),window.addEventListener(`navigate-to-tool-result`,n),()=>{window.removeEventListener(`navigate-to-sampling`,e),window.removeEventListener(`navigate-to-elicitation`,t),window.removeEventListener(`navigate-to-tool-result`,n)}},[d,O,h]);let ie=(0,z.useRef)(null),k=(0,z.useRef)(null),A=(0,z.useRef)(null),{isAutoConnecting:j}=nI({connections:r,addServer:i,removeConnection:a,configLoaded:c,embedded:v});(0,z.useEffect)(()=>{let e=()=>{let e=document.documentElement.classList.contains(`dark`)?`#000000`:`#f3f3f3`;document.documentElement.style.backgroundColor=e,document.body.style.backgroundColor=e};e();let t=new MutationObserver(e);return t.observe(document.documentElement,{attributes:!0,attributeFilter:[`class`]}),()=>t.disconnect()},[]);let ae=(0,z.useCallback)(e=>{bT(new ko({trigger:e})).catch(()=>{}),S(!0)},[]),oe=e=>{if(!r.find(t=>t.id===e))return;f(e);let i=new URLSearchParams(n.search),a=i.get(`tunnelUrl`),o=i.get(`tab`),s=new URLSearchParams;s.set(`server`,e),a&&s.set(`tunnelUrl`,a),o&&s.set(`tab`,o),t(`/?${s.toString()}`)},se=(0,z.useCallback)(e=>{if(!d)return;let t=fM(d)||r.find(e=>e.id===d);e.url===d?t&&hM(t,e)?(u(d,{name:e.name||e.url}),oM(d,e)):l(d,e):(a(d),i(e.url,uM(e))),IF.success(`Connection settings updated`)},[d,r,a,i,u,l]),ce=(e,i,a)=>{if(console.warn(`[Layout] handleCommandPaletteNavigate called:`,{tab:e,itemName:i,serverId:a}),a){let o=r.find(e=>e.id===a);if(console.warn(`[Layout] Server lookup:`,{serverId:a,serverFound:!!o,serverState:o?.state}),!o||o.state!==`ready`){console.warn(`[Layout] Server not ready, showing error`),IF.error(`Server is not connected and cannot be inspected`);return}console.warn(`[Layout] Calling navigateToItem:`,{serverId:a,tab:e,itemName:i}),h(a,e,i);let s=new URLSearchParams(n.search),c=s.get(`tunnelUrl`),l=s.get(`tab`),u=new URLSearchParams;u.set(`server`,a),c&&u.set(`tunnelUrl`,c),e?u.set(`tab`,e):l&&u.set(`tab`,l);let d=`/?${u.toString()}`;console.warn(`[Layout] Navigating to:`,d),t(d)}else console.warn(`[Layout] No serverId, just updating tab to:`,e),O(e)},M=r.find(e=>e.id===d),N=SH({tunnelUrl:_,selectedServerId:d,selectedServer:M,configLoaded:c,removeConnection:a,updateConnection:s,connections:r}),le=M?M.tools.map(e=>({...e,_serverId:M.id})):r.flatMap(e=>e.state===`ready`?e.tools.map(t=>({...t,_serverId:e.id,_serverName:Xj(e)})):[]),ue=M?M.prompts.map(e=>({...e,_serverId:M.id})):r.flatMap(e=>e.state===`ready`?e.prompts.map(t=>({...t,_serverId:e.id,_serverName:Xj(e)})):[]),de=M?M.resources.map(e=>({...e,_serverId:M.id})):r.flatMap(e=>e.state===`ready`?e.resources.map(t=>({...t,_serverId:e.id,_serverName:Xj(e)})):[]);(0,z.useEffect)(()=>{if(N)return;let e=new URLSearchParams(n.search),i=e.get(`server`);if(i&&(i.startsWith(`http://`)||i.startsWith(`https://`))&&!r.find(e=>e.id===i)){let n=new URLSearchParams(e);n.delete(`server`),n.set(`autoConnect`,i),t(`/?${n.toString()}`,{replace:!0});return}i!==d&&f(i)},[n.search,d,f,r,t,N]),(0,z.useEffect)(()=>{if(N)return;let e=new URLSearchParams(n.search).get(`server`);if(e&&!r.find(t=>t.id===e)){let e=setTimeout(()=>t(`/`),3e3);return()=>clearTimeout(e)}},[n.search,t,r,N]),(0,z.useEffect)(()=>{if(!v)return;let e=e=>{if(!e.data||typeof e.data!=`object`||e.data.type!==`mcp-inspector:connect_servers`)return;let t=e.data.servers;if(!Array.isArray(t)||t.length===0)return;let n=null;for(let e of t){if(!e.url||typeof e.url!=`string`)continue;let t=e.url,a=e.name??`Server`,o={...e.headers??{}};if(e.auth?.access_token){let t=e.auth.token_type||`bearer`;o.Authorization=`${t.charAt(0).toUpperCase()+t.slice(1)} ${e.auth.access_token}`}let s=typeof e.proxyConfig?.proxyAddress==`string`?e.proxyConfig.proxyAddress.trim():``,c=``;try{new URL(t).origin!==window.location.origin&&(c=tM())}catch{c=tM()}let l=s||c,u=nM(e.connectionMode,e.connectionType,!!s),d=uM({url:t,name:a,transportType:`http`,connectionMode:u,protocolNegotiation:$j(eM(e.protocolNegotiation)),connectionType:u===`proxy`?`Via Proxy`:`Direct`,proxyConfig:u===`proxy`&&l?{proxyAddress:l,...Object.keys(o).length>0?{headers:o}:{}}:void 0,headers:o,autoProxyFallback:u===`auto`&&l?{enabled:!0,proxyAddress:l}:!1});r.find(e=>e.url===t)||i(t,d),n||=t}window.parent!==window&&window.parent.postMessage({type:`mcp-inspector:servers_connected`,count:t.length},`*`)};return window.addEventListener(`message`,e),()=>window.removeEventListener(`message`,e)},[v,r,i]);let fe=(0,z.useRef)(!1);(0,z.useEffect)(()=>{if(!v||fe.current||d)return;let e=r.find(e=>e.state===`ready`);if(e){fe.current=!0,f(e.id);let r=new URLSearchParams(n.search);r.set(`server`,e.id),t(`/?${r.toString()}`,{replace:!0})}},[v,r,d,f,t,n.search]),rL({onCommandPalette:()=>ae(`keyboard`),onToolsTab:()=>{M&&O(`tools`)},onPromptsTab:()=>{M&&O(`prompts`)},onResourcesTab:()=>{M&&O(`resources`)},onChatTab:()=>{M&&O(`chat`)},onHome:()=>{t(`/`)},onFocusSearch:()=>{p===`tools`&&ie.current?ie.current.focusSearch():p===`prompts`&&k.current?k.current.focusSearch():p===`resources`&&A.current&&A.current.focusSearch()},onBlurSearch:()=>{p===`tools`&&ie.current?ie.current.blurSearch():p===`prompts`&&k.current?k.current.blurSearch():p===`resources`&&A.current&&A.current.blurSearch()}});let pe=new URLSearchParams(n.search).get(`server`),me=!c&&!!pe&&!pe.startsWith(`http://`)&&!pe.startsWith(`https://`),he=j||me||N,ge=M?.id??`home`,_e=he?`boot`:ge,[ve,ye]=(0,z.useState)(_e);(0,z.useLayoutEffect)(()=>{if(_e===ve)return;let e=()=>(0,br.flushSync)(()=>ye(_e));typeof document.startViewTransition==`function`?document.startViewTransition(e):e()},[_e,ve]);let be=ve===`boot`,xe=be||ve===`home`?void 0:r.find(e=>e.id===ve),P=v&&y.singleTab,Se=v?{backgroundColor:y.backgroundColor||`#f3f3f3`,padding:P?`0`:y.padding||`0.5rem`}:{},Ce=v?P?`h-screen flex flex-col`:`h-screen flex flex-col gap-2 sm:gap-4`:`h-screen bg-[#f3f3f3] dark:bg-black flex flex-col overflow-x-hidden px-4 lg:px-0 pb-[calc(var(--mobile-toolbar-height)+env(safe-area-inset-bottom))] lg:pb-4`,we=P?`flex-1 w-full bg-white dark:bg-black p-0 overflow-auto`:L(`flex-1 min-h-0 min-w-0 max-w-full w-full bg-white dark:bg-black rounded-2xl border border-zinc-200 dark:border-zinc-700 overflow-x-hidden overflow-y-auto`,!xe&&`lg:mx-4`,xe&&`lg:mr-4`);return(0,R.jsxs)(Ve,{children:[(0,R.jsx)(`div`,{className:`inspector-view-transition h-screen overflow-x-hidden bg-[#f3f3f3] dark:bg-black`,children:be?(0,R.jsx)(`div`,{className:`flex h-full items-center justify-center bg-[#f3f3f3] dark:bg-black`,children:(0,R.jsxs)(`div`,{className:`flex flex-col items-center gap-4`,children:[(0,R.jsx)(XI,{className:`h-8 w-8 text-zinc-600 dark:text-zinc-400`}),(0,R.jsx)(`p`,{className:`text-sm text-zinc-600 dark:text-zinc-400`,children:`Connecting to MCP server...`})]})}):(0,R.jsxs)(`div`,{className:Ce,style:Se,children:[!P&&(0,R.jsx)(dB,{connections:r,selectedServer:xe,activeTab:p,onServerSelect:oe,onTabChange:O,embedded:v,sidebarCollapsed:C}),(0,R.jsxs)(`div`,{className:P?`flex-1 min-h-0`:`flex min-w-0 flex-1 min-h-0 overflow-hidden`,children:[xe&&!P&&(0,R.jsx)($B,{activeTab:p,onTabChange:O,selectedServer:xe,visibleTabs:y.visibleTabs,collapsed:C,onCollapsedChange:w,rpcLoggerOpen:T,onRpcLoggerOpenChange:E,onCommandPaletteOpen:()=>ae(`button`)}),(0,R.jsx)(`main`,{className:we,children:(0,R.jsx)(FR,{selectedServer:xe,activeTab:p,toolsSearchRef:ie,promptsSearchRef:k,resourcesSearchRef:A,onUpdateConnection:se,children:e})}),xe&&!P&&(0,R.jsx)(QV,{serverId:xe.id,open:T})]})]})}),!P&&!be&&(0,R.jsx)(bH,{serverId:xe?.id,rpcLoggerOpen:T,onRpcLoggerOpenChange:E}),(0,R.jsx)(SL,{isOpen:x,onOpenChange:S,tools:le,prompts:ue,resources:de,savedRequests:ee,connections:r,selectedServer:M,tunnelUrl:_,onNavigate:ce,onServerSelect:oe})]})}function wH({...e}){let{resolvedTheme:t}=dz();return(0,R.jsx)(ZF,{theme:t,className:`toaster group`,style:{"--normal-bg":`var(--popover)`,"--normal-text":`var(--popover-foreground)`,"--normal-border":`var(--border)`},...e})}var TH=(0,z.createContext)(void 0),EH={deviceType:`desktop`,customViewport:{width:768,height:1024},cspMode:`permissive`,displayModeOverride:null,capabilities:{hover:!0,touch:!1},safeAreaInsets:{top:0,right:0,bottom:0,left:0},locale:`en-US`,timeZone:Intl.DateTimeFormat().resolvedOptions().timeZone||`UTC`};function DH({children:e}){let[t,n]=(0,z.useState)({activeWidgetId:null,widgets:new Map,playground:EH}),r=(0,z.useCallback)(e=>{n(t=>({...t,activeWidgetId:e}))},[]),i=(0,z.useCallback)((e,t)=>{n(n=>{if(n.widgets.has(e))return n;let r=new Map(n.widgets);return r.set(e,{...t,cspViolations:[]}),{...n,widgets:r}})},[]),a=(0,z.useCallback)(e=>{n(t=>{let n=new Map(t.widgets);return n.delete(e),{...t,widgets:n,activeWidgetId:t.activeWidgetId===e?null:t.activeWidgetId}})},[]),o=(0,z.useRef)(t);o.current=t;let s=(0,z.useCallback)(e=>o.current.widgets.get(e),[]),c=(0,z.useCallback)((e,t)=>{n(n=>{let r=n.widgets.get(e);if(!r)return n;let i={cspViolations:[...r.cspViolations,t]};t.originalPolicy&&r.effectivePolicy===void 0&&(i.effectivePolicy=t.originalPolicy);let a=new Map(n.widgets);return a.set(e,{...r,...i}),{...n,widgets:a}})},[]),l=(0,z.useCallback)(e=>{n(t=>{let n=t.widgets.get(e);if(!n)return t;let r=new Map(t.widgets);return r.set(e,{...n,cspViolations:[]}),{...t,widgets:r}})},[]),u=(0,z.useCallback)((e,t)=>{n(n=>{let r=n.widgets.get(e);if(!r)return n;let i=new Map(n.widgets);return i.set(e,{...r,modelContext:t}),{...n,widgets:i}})},[]),d=(0,z.useCallback)((e,t)=>{n(n=>{let r=n.widgets.get(e);if(!r)return n;let i=new Map(n.widgets);return i.set(e,{...r,widgetState:t}),{...n,widgets:i}})},[]),f=(0,z.useCallback)((e,t,r)=>{n(n=>{let i=n.widgets.get(e);if(!i)return n;let a=new Map(n.widgets);return a.set(e,{...i,declaredCsp:t,...r!==void 0&&{effectivePolicy:r}}),{...n,widgets:a}})},[]),p=(0,z.useCallback)(e=>{n(t=>({...t,playground:{...t.playground,...e}}))},[]),m=(0,z.useCallback)(()=>{n(e=>({...e,widgets:new Map,activeWidgetId:null}))},[]),h=(0,z.useCallback)(()=>{let e=new Map;for(let[n,r]of t.widgets)r.modelContext&&e.set(n,r.modelContext);return e},[t.widgets]);return(0,R.jsx)(TH,{value:(0,z.useMemo)(()=>({...t,setActiveWidget:r,addWidget:i,removeWidget:a,getWidget:s,addCspViolation:c,clearCspViolations:l,setWidgetModelContext:u,setWidgetState:d,setWidgetDeclaredCsp:f,updatePlaygroundSettings:p,clearAllWidgets:m,getAllModelContexts:h}),[t,r,i,a,s,c,l,u,d,f,p,m,h]),children:e})}function OH(){let e=(0,z.use)(TH);if(!e)throw Error(`useWidgetDebug must be used within WidgetDebugProvider`);return e}var kH={mobile:{width:390,height:844,name:`iPhone 14`},desktop:{width:1440,height:900,name:`Desktop`}},AH=(0,z.lazy)(()=>lS(()=>import(`./OAuthCallback-C9J2xEkV.js`).then(e=>({default:e.OAuthCallback})),__vite__mapDeps([39,1,3]))),jH=(0,z.lazy)(()=>lS(()=>import(`./ManufactOAuthCallback-Dp3icsBc.js`).then(e=>({default:e.ManufactOAuthCallback})),__vite__mapDeps([40,1,3]))),MH=(0,z.lazy)(()=>lS(()=>import(`./ViewPreview-D7NNsxbe.js`).then(e=>({default:e.ViewPreview})),__vite__mapDeps([41,1,3,18,2])));function NH({activeTabRef:e}){let{activeTab:t}=nL();return(0,z.useEffect)(()=>{e.current=t},[t,e]),null}function PH(){let e=(0,z.useRef)(`tools`),t=new URLSearchParams(window.location.search),n=t.get(`embedded`)===`true`,r=t.get(`theme`),i=(0,z.useMemo)(()=>n?void 0:new gM(`mcp-inspector-connections`),[n]),a=tM(),o=a?.replace(/\/proxy\/?$/,`/oauth`),s=Wj();return(0,z.useEffect)(()=>{vT()},[]),(0,z.useEffect)(()=>{let e=t.get(`auth_error`);if(!e)return;let n=t.get(`auth_error_description`);IF.error(`OAuth authentication failed: ${n||e}`,{duration:1/0,closeButton:!0});let r=new URLSearchParams(t);r.delete(`auth_error`),r.delete(`auth_error_description`);let i=r.toString();window.history.replaceState({},``,`${window.location.pathname}${i?`?${i}`:``}`)},[]),(0,R.jsx)(fz,{forcedTheme:r||void 0,children:(0,R.jsx)(Jt,{defaultShape:`pill`,children:(0,R.jsx)(DH,{children:(0,R.jsx)(aj,{storageProvider:i,enableRpcLogging:!0,defaultCallbackUrl:`${window.location.origin}${s}/oauth/callback`,defaultOAuthProxyUrl:o,defaultAutoProxyFallback:a?{enabled:!0,proxyAddress:a}:!1,defaultServerConfig:{preventAutoAuth:!0,useRedirectFlow:!0},clientInfo:{name:`mcp-use Inspector`,version:Lo(),websiteUrl:`https://mcp-use.com`,icons:[{src:`https://mcp-use.com/logo.png`}],capabilities:{extensions:{"io.modelcontextprotocol/ui":{mimeTypes:[`text/html;profile=mcp-app`]}}}},onServerAdded:(e,t)=>{console.log(`[Inspector] Server added:`,e,t.state)},onServerRemoved:e=>{console.log(`[Inspector] Server removed:`,e)},onServerStateChange:(e,t)=>{console.log(`[Inspector] Server state changed:`,e,t)},onSamplingRequest:(e,t,n,r,i)=>{let a=IF((0,R.jsx)(Fn,{title:`Sampling Request Received`,description:`New request from ${n}`,actions:[{label:`View Details`,testId:`sampling-toast-view-details`,onClick:()=>{let t=new CustomEvent(`navigate-to-sampling`,{detail:{requestId:e.id}});window.dispatchEvent(t),IF.dismiss(a)}},{label:`Approve`,testId:`sampling-toast-approve`,onClick:()=>{r(e.id,In),IF.success(`Sampling request approved`),IF.dismiss(a)}},{label:`Deny`,testId:`sampling-toast-deny`,onClick:()=>{i(e.id,`User denied from toast`),IF.dismiss(a)}}]}),{duration:1/0})},onElicitationRequest:(t,n,r,i,a)=>{if(e.current===`chat`)return;let o=t.request.mode||`form`,s=t.request.message,c=o===`url`&&`url`in t.request?t.request.url:void 0,l=IF((0,R.jsx)(Fn,{title:`Elicitation Request Received`,description:`From ${r}: ${s}`,extra:o===`url`&&c?(0,R.jsx)(`p`,{className:`text-xs text-muted-foreground mt-1 font-mono`,children:c}):void 0,actions:[{label:`View Details`,testId:`elicitation-toast-view-details`,onClick:()=>{let e=new CustomEvent(`navigate-to-elicitation`,{detail:{requestId:t.id}});window.dispatchEvent(e),IF.dismiss(l)}},...o===`url`&&c?[{label:`Open URL`,testId:`elicitation-toast-open-url`,onClick:()=>{window.open(c,`_blank`),IF.dismiss(l)}}]:[],{label:`Cancel`,testId:`elicitation-toast-cancel`,onClick:()=>{a(t.id,`User cancelled from toast`),IF.dismiss(l)}}]}),{duration:1/0})},children:(0,R.jsxs)(tL,{children:[(0,R.jsx)(NH,{activeTabRef:e}),(0,R.jsx)(eF,{basename:s,children:(0,R.jsxs)(dP,{children:[(0,R.jsx)(lP,{path:`/oauth/callback`,element:(0,R.jsx)(wR,{children:(0,R.jsx)(AH,{})})}),(0,R.jsx)(lP,{path:`/auth/callback`,element:(0,R.jsx)(wR,{children:(0,R.jsx)(jH,{})})}),(0,R.jsx)(lP,{path:`/preview/:view`,element:(0,R.jsx)(wR,{children:(0,R.jsx)(MH,{})})}),(0,R.jsx)(lP,{path:`/`,element:(0,R.jsx)(CH,{children:(0,R.jsx)($I,{})})})]})}),(0,R.jsx)(wH,{position:`top-center`})]})})})})})}var FH=document.getElementById(`root`);FH?Pn.createRoot(FH).render((0,R.jsx)(PH,{})):console.error(`[inspector] Root element not found`);export{hI as $,Wi as $t,WR as A,Q as At,BI as B,go as Bt,tV as C,Mr as Cn,Cj as Ct,qz as D,oj as Dt,Gz as E,_r as En,KA as Et,XI as F,Eo as Ft,GI as G,Ya as Gt,WI as H,vo as Ht,YI as I,wo as It,AI as J,Xa as Jt,zI as K,Za as Kt,JI as L,Co as Lt,aL as M,Bb as Mt,rL as N,Cf as Nt,Kz as O,bT as Ot,nL as P,No as Pt,gI as Q,Gi as Qt,RI as R,So as Rt,sV as S,Fr as Sn,Ij as St,vB as T,vr as Tn,wj as Tt,VI as U,mo as Ut,KI as V,bo as Vt,UI as W,ro as Wt,CI as X,Xi as Xt,wI as Y,Ia as Yt,_I as Z,Yi as Zt,DV as _,Yr as _n,Zj as _t,_H as a,xi as an,aI as at,_V as b,Vr as bn,zj as bt,$V as c,fi as cn,dF as ct,iH as d,ai as dn,fM as dt,zi as en,uI as et,aH as f,ri as fn,eM as ft,OV as g,Xr as gn,Xj as gt,kV as h,Zr as hn,Yj as ht,mH as i,Ti as in,iI as it,lR as j,lS as jt,dz as k,KC as kt,rH as l,ci as ln,sM as lt,WV as m,$r as mn,dM as mt,OH as n,Ai as nn,sI as nt,pH as o,bi as on,IF as ot,eH as p,ti as pn,$j as pt,MI as q,$a as qt,cH as r,ki as rn,oI as rt,hH as s,yi as sn,zN as st,kH as t,Ii as tn,rI as tt,oH as u,si as un,tM as ut,CV as v,qr as vn,Uj as vt,MB as w,jr as wn,Tj as wt,oV as x,Ir as xn,Bj as xt,SV as y,Wr as yn,Gj as yt,HI as z,Ao as zt};
|