@mcp-use/inspector 20.0.0-beta.35 → 20.0.0-beta.37

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.
@@ -1,13 +1,13 @@
1
- var Kt=Object.create;var Me=Object.defineProperty;var Vt=Object.getOwnPropertyDescriptor;var Gt=Object.getOwnPropertyNames;var Jt=Object.getPrototypeOf,Yt=Object.prototype.hasOwnProperty;var $=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports);var Xt=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Gt(e))!Yt.call(t,o)&&o!==r&&Me(t,o,{get:()=>e[o],enumerable:!(n=Vt(e,o))||n.enumerable});return t};var Qt=(t,e,r)=>(r=t!=null?Kt(Jt(t)):{},Xt(e||!t||!t.__esModule?Me(r,"default",{value:t,enumerable:!0}):r,t));var rt=$((Lo,tt)=>{"use strict";tt.exports=class{constructor(e={}){this.points=e.points,this.duration=e.duration,this.blockDuration=e.blockDuration,this.execEvenly=e.execEvenly,this.execEvenlyMinDelayMs=e.execEvenlyMinDelayMs,this.keyPrefix=e.keyPrefix}get points(){return this._points}set points(e){if(Number.isFinite(e))this._points=e;else throw new Error("points must be set and must be a finite number")}get duration(){return this._duration}set duration(e){if(typeof e=="number"&&Number.isFinite(e)&&e>=0)this._duration=e;else throw new Error("duration must be set and must be a finite, non-negative number")}get msDuration(){return this.duration*1e3}get blockDuration(){return this._blockDuration}set blockDuration(e){this._blockDuration=typeof e>"u"?0:e}get msBlockDuration(){return this.blockDuration*1e3}get execEvenly(){return this._execEvenly}set execEvenly(e){this._execEvenly=typeof e>"u"?!1:!!e}get execEvenlyMinDelayMs(){return this._execEvenlyMinDelayMs===void 0?this._getExecEvenlyMinDelayMsDefault():this._execEvenlyMinDelayMs}set execEvenlyMinDelayMs(e){this._execEvenlyMinDelayMs=e}_getExecEvenlyMinDelayMsDefault(){return this.points>0?Math.ceil(this.msDuration/this.points):0}get keyPrefix(){return this._keyPrefix}set keyPrefix(e){if(typeof e>"u"&&(e="rlflx"),typeof e!="string")throw new Error("keyPrefix must be string");this._keyPrefix=e}_getKeySecDuration(e={}){return e&&e.customDuration>=0?e.customDuration:this.duration}getKey(e){return this.keyPrefix.length>0?`${this.keyPrefix}:${e}`:e}parseKey(e){return this.keyPrefix.length>0?e.substring(this.keyPrefix.length+1):e}consume(){throw new Error("You have to implement the method 'consume'!")}penalty(){throw new Error("You have to implement the method 'penalty'!")}reward(){throw new Error("You have to implement the method 'reward'!")}get(){throw new Error("You have to implement the method 'get'!")}set(){throw new Error("You have to implement the method 'set'!")}block(){throw new Error("You have to implement the method 'block'!")}delete(){throw new Error("You have to implement the method 'delete'!")}}});var ot=$((jo,nt)=>{"use strict";nt.exports=class{constructor(e,r,n=null){this.value=e,this.expiresAt=r,this.timeoutId=n}get value(){return this._value}set value(e){this._value=parseInt(e,10)}get expiresAt(){return this._expiresAt}set expiresAt(e){e instanceof Date?this._expiresAt=e.getTime():this._expiresAt=e}get timeoutId(){return this._timeoutId}set timeoutId(e){this._timeoutId=e}}});var xe=$((Do,st)=>{"use strict";st.exports=class{constructor(e,r,n,o){this.remainingPoints=typeof e>"u"?0:e,this.msBeforeNext=typeof r>"u"?0:r,this.consumedPoints=typeof n>"u"?0:n,this.isFirstInDuration=typeof o>"u"?!1:o}get msBeforeNext(){return this._msBeforeNext}set msBeforeNext(e){return this._msBeforeNext=e,this}get remainingPoints(){return this._remainingPoints}set remainingPoints(e){return this._remainingPoints=e,this}get consumedPoints(){return this._consumedPoints}set consumedPoints(e){return this._consumedPoints=e,this}get isFirstInDuration(){return this._isFirstInDuration}set isFirstInDuration(e){this._isFirstInDuration=!!e}_getDecoratedProperties(){return{remainingPoints:this.remainingPoints,msBeforeNext:this.msBeforeNext,consumedPoints:this.consumedPoints,isFirstInDuration:this.isFirstInDuration}}[Symbol.for("nodejs.util.inspect.custom")](){return this._getDecoratedProperties()}toString(){return JSON.stringify(this._getDecoratedProperties())}toJSON(){return this._getDecoratedProperties()}}});var ct=$(($o,at)=>{"use strict";var it=ot(),be=xe();at.exports=class{constructor(){this._storage=new Map}incrby(e,r,n){let o=this._storage.get(e);if(o){let s=o.expiresAt?o.expiresAt-Date.now():-1;return!o.expiresAt||s>0?(o.value=o.value+r,new be(0,s,o.value,!1)):this.set(e,r,n)}return this.set(e,r,n)}set(e,r,n){let o=n*1e3,s=this._storage.get(e);s&&s.timeoutId&&clearTimeout(s.timeoutId);let i=new it(r,o>0?Date.now()+o:null);return this._storage.set(e,i),o>0&&(i.timeoutId=setTimeout(()=>{this._storage.delete(e)},o),i.timeoutId.unref&&i.timeoutId.unref()),new be(0,o===0?-1:o,i.value,!0)}get(e){let r=this._storage.get(e);if(r){let n=r.expiresAt?r.expiresAt-Date.now():-1;return new be(0,n,r.value,!1)}return null}delete(e){let r=this._storage.get(e);return r?(r.timeoutId&&clearTimeout(r.timeoutId),this._storage.delete(e),!0):!1}_restoreRecord(e,r,n){let o=Date.now(),s=n!==null;if(s&&!Number.isFinite(n)||s&&n<=o)return;let i=s?n-o:0,a=this._storage.get(e);a&&a.timeoutId&&clearTimeout(a.timeoutId);let c=new it(r,n);this._storage.set(e,c),i>0&&(c.timeoutId=setTimeout(()=>{this._storage.delete(e)},i),c.timeoutId.unref&&c.timeoutId.unref())}}});var dt=$((Bo,ut)=>{"use strict";var mr=rt(),gr=ct(),lt=xe(),Re=class extends mr{constructor(e={}){super(e),this._memoryStorage=new gr}consume(e,r=1,n={}){return new Promise((o,s)=>{let i=this.getKey(e),a=this._getKeySecDuration(n),c=this._memoryStorage.incrby(i,r,a);if(c.remainingPoints=Math.max(this.points-c.consumedPoints,0),c.consumedPoints>this.points)this.blockDuration>0&&c.consumedPoints<=this.points+r&&(c=this._memoryStorage.set(i,c.consumedPoints,this.blockDuration)),s(c);else if(this.execEvenly&&this.points>0&&c.msBeforeNext>0&&!c.isFirstInDuration){let l=Math.ceil(c.msBeforeNext/(c.remainingPoints+2));l<this.execEvenlyMinDelayMs&&(l=c.consumedPoints*this.execEvenlyMinDelayMs),c.msBeforeNext=Math.max(c.msBeforeNext-l,0),setTimeout(o,l,c)}else o(c)})}penalty(e,r=1,n={}){let o=this.getKey(e);return new Promise(s=>{let i=this._getKeySecDuration(n),a=this._memoryStorage.incrby(o,r,i);a.remainingPoints=Math.max(this.points-a.consumedPoints,0),s(a)})}reward(e,r=1,n={}){let o=this.getKey(e);return new Promise(s=>{let i=this._getKeySecDuration(n),a=this._memoryStorage.incrby(o,-r,i);a.remainingPoints=Math.max(this.points-a.consumedPoints,0),s(a)})}block(e,r){let n=r*1e3,o=this.points+1;return this._memoryStorage.set(this.getKey(e),o,r),Promise.resolve(new lt(0,n===0?-1:n,o))}set(e,r,n){let o=(n>=0?n:this.duration)*1e3;return this._memoryStorage.set(this.getKey(e),r,n),Promise.resolve(new lt(0,o===0?-1:o,r))}get(e){let r=this._memoryStorage.get(this.getKey(e));return r!==null&&(r.remainingPoints=Math.max(this.points-r.consumedPoints,0)),Promise.resolve(r)}delete(e){return Promise.resolve(this._memoryStorage.delete(this.getKey(e)))}dump(){let e=[];for(let[r,n]of this._memoryStorage._storage)e.push({key:this.parseKey(r),value:n.value,expiresAt:n.expiresAt});return{version:1,dumpedAt:Date.now(),storage:e}}restore(e,r=!1){if(!e||typeof e!="object"||e.version!==1)return;let n=r?{invalid:{count:0,keys:[]},expired:{count:0,keys:[]},restored:{count:0,keys:[]}}:{invalid:0,expired:0,restored:0},o=(s,i)=>{r?(n[s].count+=1,n[s].keys.push(i)):n[s]+=1};if(!Array.isArray(e.storage))return n;for(let s of e.storage){if(!s||typeof s!="object"){o("invalid","N/A");continue}let i=typeof s.key=="string"||typeof s.key=="number",a=Number.isFinite(s.value),c=s.expiresAt===null||Number.isFinite(s.expiresAt);if(!i||!a||!c){o("invalid",s.key);continue}if(s.expiresAt!==null&&s.expiresAt<=Date.now()){o("expired",s.key);continue}this._memoryStorage._restoreRecord(this.getKey(s.key),s.value,s.expiresAt),o("restored",s.key)}return n}};ut.exports=Re});var ie=(t,e,r)=>(n,o)=>{let s=-1;return i(0);async function i(a){if(a<=s)throw new Error("next() called multiple times");s=a;let c,l=!1,u;if(t[a]?(u=t[a][0][0],n.req.routeIndex=a):u=a===t.length&&o||void 0,u)try{c=await u(n,()=>i(a+1))}catch(h){if(h instanceof Error&&e)n.error=h,c=await e(h,n),l=!0;else throw h}else n.finalized===!1&&r&&(c=await r(n));return c&&(n.finalized===!1||l)&&(n.res=c),n}};var Te=Symbol();var ke=async(t,e=Object.create(null))=>{let{all:r=!1,dot:n=!1}=e,s=(t instanceof W?t.raw.headers:t.headers).get("Content-Type");return s?.startsWith("multipart/form-data")||s?.startsWith("application/x-www-form-urlencoded")?Zt(t,{all:r,dot:n}):{}};async function Zt(t,e){let r=await t.formData();return r?er(r,e):{}}function er(t,e){let r=Object.create(null);return t.forEach((n,o)=>{e.all||o.endsWith("[]")?tr(r,o,n):r[o]=n}),e.dot&&Object.entries(r).forEach(([n,o])=>{n.includes(".")&&(rr(r,n,o),delete r[n])}),r}var tr=(t,e,r)=>{t[e]!==void 0?Array.isArray(t[e])?t[e].push(r):t[e]=[t[e],r]:e.endsWith("[]")?t[e]=[r]:t[e]=r},rr=(t,e,r)=>{if(/(?:^|\.)__proto__\./.test(e))return;let n=t,o=e.split(".");o.forEach((s,i)=>{i===o.length-1?n[s]=r:((!n[s]||typeof n[s]!="object"||Array.isArray(n[s])||n[s]instanceof File)&&(n[s]=Object.create(null)),n=n[s])})};var ce=t=>{let e=t.split("/");return e[0]===""&&e.shift(),e},Le=t=>{let{groups:e,path:r}=nr(t),n=ce(r);return or(n,e)},nr=t=>{let e=[];return t=t.replace(/\{[^}]+\}/g,(r,n)=>{let o=`@${n}`;return e.push([o,r]),o}),{groups:e,path:t}},or=(t,e)=>{for(let r=e.length-1;r>=0;r--){let[n]=e[r];for(let o=t.length-1;o>=0;o--)if(t[o].includes(n)){t[o]=t[o].replace(n,e[r][1]);break}}return t},K={},Ue=(t,e)=>{if(t==="*")return"*";let r=t.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);if(r){let n=`${t}#${e}`;return K[n]||(r[2]?K[n]=e&&e[0]!==":"&&e[0]!=="*"?[n,r[1],new RegExp(`^${r[2]}(?=/${e})`)]:[t,r[1],new RegExp(`^${r[2]}$`)]:K[n]=[t,r[1],!0]),K[n]}return null},V=(t,e)=>{try{return e(t)}catch{return t.replace(/(?:%[0-9A-Fa-f]{2})+/g,r=>{try{return e(r)}catch{return r}})}},sr=t=>V(t,decodeURI),le=t=>{let e=t.url,r=e.indexOf("/",e.indexOf(":")+4),n=r;for(;n<e.length;n++){let o=e.charCodeAt(n);if(o===37){let s=e.indexOf("?",n),i=e.indexOf("#",n),a=s===-1?i===-1?void 0:i:i===-1?s:Math.min(s,i),c=e.slice(r,a);return sr(c.includes("%25")?c.replace(/%25/g,"%2525"):c)}else if(o===63||o===35)break}return e.slice(r,n)};var je=t=>{let e=le(t);return e.length>1&&e.at(-1)==="/"?e.slice(0,-1):e},k=(t,e,...r)=>(r.length&&(e=k(e,...r)),`${t?.[0]==="/"?"":"/"}${t}${e==="/"?"":`${t?.at(-1)==="/"?"":"/"}${e?.[0]==="/"?e.slice(1):e}`}`),G=t=>{if(t.charCodeAt(t.length-1)!==63||!t.includes(":"))return null;let e=t.split("/"),r=[],n="";return e.forEach(o=>{if(o!==""&&!/\:/.test(o))n+="/"+o;else if(/\:/.test(o))if(/\?/.test(o)){r.length===0&&n===""?r.push("/"):r.push(n);let s=o.replace("?","");n+="/"+s,r.push(n)}else n+="/"+o}),r.filter((o,s,i)=>i.indexOf(o)===s)},ae=t=>/[%+]/.test(t)?(t.indexOf("+")!==-1&&(t=t.replace(/\+/g," ")),t.indexOf("%")!==-1?V(t,ue):t):t,Ne=(t,e,r)=>{let n;if(!r&&e&&!/[%+]/.test(e)){let i=t.indexOf("?",8);if(i===-1)return;for(t.startsWith(e,i+1)||(i=t.indexOf(`&${e}`,i+1));i!==-1;){let a=t.charCodeAt(i+e.length+1);if(a===61){let c=i+e.length+2,l=t.indexOf("&",c);return ae(t.slice(c,l===-1?void 0:l))}else if(a==38||isNaN(a))return"";i=t.indexOf(`&${e}`,i+1)}if(n=/[%+]/.test(t),!n)return}let o={};n??=/[%+]/.test(t);let s=t.indexOf("?",8);for(;s!==-1;){let i=t.indexOf("&",s+1),a=t.indexOf("=",s);a>i&&i!==-1&&(a=-1);let c=t.slice(s+1,a===-1?i===-1?void 0:i:a);if(n&&(c=ae(c)),s=i,c==="")continue;let l;a===-1?l="":(l=t.slice(a+1,i===-1?void 0:i),n&&(l=ae(l))),r?(o[c]&&Array.isArray(o[c])||(o[c]=[]),o[c].push(l)):o[c]??=l}return e?o[e]:o},De=Ne,He=(t,e)=>Ne(t,e,!0),ue=decodeURIComponent;var $e=t=>V(t,ue),W=class{raw;#t;#e;routeIndex=0;path;bodyCache={};constructor(t,e="/",r=[[]]){this.raw=t,this.path=e,this.#e=r,this.#t={}}param(t){return t?this.#r(t):this.#s()}#r(t){let e=this.#e[0][this.routeIndex][1][t],r=this.#o(e);return r&&/\%/.test(r)?$e(r):r}#s(){let t={},e=Object.keys(this.#e[0][this.routeIndex][1]);for(let r of e){let n=this.#o(this.#e[0][this.routeIndex][1][r]);n!==void 0&&(t[r]=/\%/.test(n)?$e(n):n)}return t}#o(t){return this.#e[1]?this.#e[1][t]:t}query(t){return De(this.url,t)}queries(t){return He(this.url,t)}header(t){if(t)return this.raw.headers.get(t)??void 0;let e={};return this.raw.headers.forEach((r,n)=>{e[n]=r}),e}async parseBody(t){return ke(this,t)}#n=t=>{let{bodyCache:e,raw:r}=this,n=e[t];if(n)return n;let o=Object.keys(e)[0];return o?e[o].then(s=>(o==="json"&&(s=JSON.stringify(s)),new Response(s)[t]())):e[t]=r[t]()};json(){return this.#n("text").then(t=>JSON.parse(t))}text(){return this.#n("text")}arrayBuffer(){return this.#n("arrayBuffer")}bytes(){return this.#n("arrayBuffer").then(t=>new Uint8Array(t))}blob(){return this.#n("blob")}formData(){return this.#n("formData")}addValidatedData(t,e){this.#t[t]=e}valid(t){return this.#t[t]}get url(){return this.raw.url}get method(){return this.raw.method}get[Te](){return this.#e}get matchedRoutes(){return this.#e[0].map(([[,t]])=>t)}get routePath(){return this.#e[0].map(([[,t]])=>t)[this.routeIndex].path}};var Be={Stringify:1,BeforeStream:2,Stream:3},ir=(t,e)=>{let r=new String(t);return r.isEscaped=!0,r.callbacks=e,r};var de=async(t,e,r,n,o)=>{typeof t=="object"&&!(t instanceof String)&&(t instanceof Promise||(t=t.toString()),t instanceof Promise&&(t=await t));let s=t.callbacks;if(!s?.length)return Promise.resolve(t);o?o[0]+=t:o=[t];let i=Promise.all(s.map(a=>a({phase:e,buffer:o,context:n}))).then(a=>Promise.all(a.filter(Boolean).map(c=>de(c,e,!1,n,o))).then(()=>o[0]));return r?ir(await i,s):i};var ar="text/plain; charset=UTF-8",he=(t,e)=>({"Content-Type":t,...e}),B=(t,e)=>new Response(t,e),pe=class{#t;#e;env={};#r;finalized=!1;error;#s;#o;#n;#u;#c;#l;#a;#d;#h;constructor(t,e){this.#t=t,e&&(this.#o=e.executionCtx,this.env=e.env,this.#l=e.notFoundHandler,this.#h=e.path,this.#d=e.matchResult)}get req(){return this.#e??=new W(this.#t,this.#h,this.#d),this.#e}get event(){if(this.#o&&"respondWith"in this.#o)return this.#o;throw Error("This context has no FetchEvent")}get executionCtx(){if(this.#o)return this.#o;throw Error("This context has no ExecutionContext")}get res(){return this.#n||=B(null,{headers:this.#a??=new Headers})}set res(t){if(this.#n&&t){t=B(t.body,t);for(let[e,r]of this.#n.headers.entries())if(e!=="content-type")if(e==="set-cookie"){let n=this.#n.headers.getSetCookie();t.headers.delete("set-cookie");for(let o of n)t.headers.append("set-cookie",o)}else t.headers.set(e,r)}this.#n=t,this.finalized=!0}render=(...t)=>(this.#c??=e=>this.html(e),this.#c(...t));setLayout=t=>this.#u=t;getLayout=()=>this.#u;setRenderer=t=>{this.#c=t};header=(t,e,r)=>{this.finalized&&(this.#n=B(this.#n.body,this.#n));let n=this.#n?this.#n.headers:this.#a??=new Headers;e===void 0?n.delete(t):r?.append?n.append(t,e):n.set(t,e)};status=t=>{this.#s=t};set=(t,e)=>{this.#r??=new Map,this.#r.set(t,e)};get=t=>this.#r?this.#r.get(t):void 0;get var(){return this.#r?Object.fromEntries(this.#r):{}}#i(t,e,r){let n=this.#n?new Headers(this.#n.headers):this.#a??new Headers;if(typeof e=="object"&&"headers"in e){let s=e.headers instanceof Headers?e.headers:new Headers(e.headers);for(let[i,a]of s)i.toLowerCase()==="set-cookie"?n.append(i,a):n.set(i,a)}if(r)for(let[s,i]of Object.entries(r))if(typeof i=="string")n.set(s,i);else{n.delete(s);for(let a of i)n.append(s,a)}let o=typeof e=="number"?e:e?.status??this.#s;return B(t,{status:o,headers:n})}newResponse=(...t)=>this.#i(...t);body=(t,e,r)=>this.#i(t,e,r);text=(t,e,r)=>!this.#a&&!this.#s&&!e&&!r&&!this.finalized?new Response(t):this.#i(t,e,he(ar,r));json=(t,e,r)=>this.#i(JSON.stringify(t),e,he("application/json",r));html=(t,e,r)=>{let n=o=>this.#i(o,e,he("text/html; charset=UTF-8",r));return typeof t=="object"?de(t,Be.Stringify,!1,{}).then(n):n(t)};redirect=(t,e)=>{let r=String(t);return this.header("Location",/[^\x00-\xFF]/.test(r)?encodeURI(r):r),this.newResponse(null,e??302)};notFound=()=>(this.#l??=()=>B(),this.#l(this))};var w="ALL",Fe="all",qe=["get","post","put","delete","options","patch"],J="Can not add a route since the matcher is already built.",Y=class extends Error{};var ze="__COMPOSED_HANDLER";var cr=t=>t.text("404 Not Found",404),We=(t,e)=>{if("getResponse"in t){let r=t.getResponse();return e.newResponse(r.body,r)}return console.error(t),e.text("Internal Server Error",500)},Ke=class Ve{get;post;put;delete;options;patch;all;on;use;router;getPath;_basePath="/";#t="/";routes=[];constructor(e={}){[...qe,Fe].forEach(s=>{this[s]=(i,...a)=>(typeof i=="string"?this.#t=i:this.#s(s,this.#t,i),a.forEach(c=>{this.#s(s,this.#t,c)}),this)}),this.on=(s,i,...a)=>{for(let c of[i].flat()){this.#t=c;for(let l of[s].flat())a.map(u=>{this.#s(l.toUpperCase(),this.#t,u)})}return this},this.use=(s,...i)=>(typeof s=="string"?this.#t=s:(this.#t="*",i.unshift(s)),i.forEach(a=>{this.#s(w,this.#t,a)}),this);let{strict:n,...o}=e;Object.assign(this,o),this.getPath=n??!0?e.getPath??le:je}#e(){let e=new Ve({router:this.router,getPath:this.getPath});return e.errorHandler=this.errorHandler,e.#r=this.#r,e.routes=this.routes,e}#r=cr;errorHandler=We;route(e,r){let n=this.basePath(e);return r.routes.map(o=>{let s;r.errorHandler===We?s=o.handler:(s=async(i,a)=>(await ie([],r.errorHandler)(i,()=>o.handler(i,a))).res,s[ze]=o.handler),n.#s(o.method,o.path,s,o.basePath)}),this}basePath(e){let r=this.#e();return r._basePath=k(this._basePath,e),r}onError=e=>(this.errorHandler=e,this);notFound=e=>(this.#r=e,this);mount(e,r,n){let o,s;n&&(typeof n=="function"?s=n:(s=n.optionHandler,n.replaceRequest===!1?o=c=>c:o=n.replaceRequest));let i=s?c=>{let l=s(c);return Array.isArray(l)?l:[l]}:c=>{let l;try{l=c.executionCtx}catch{}return[c.env,l]};o||=(()=>{let c=k(this._basePath,e),l=c==="/"?0:c.length;return u=>{let h=new URL(u.url);return h.pathname=this.getPath(u).slice(l)||"/",new Request(h,u)}})();let a=async(c,l)=>{let u=await r(o(c.req.raw),...i(c));if(u)return u;await l()};return this.#s(w,k(e,"*"),a),this}#s(e,r,n,o){e=e.toUpperCase(),r=k(this._basePath,r);let s={basePath:o!==void 0?k(this._basePath,o):this._basePath,path:r,method:e,handler:n};this.router.add(e,r,[n,s]),this.routes.push(s)}#o(e,r){if(e instanceof Error)return this.errorHandler(e,r);throw e}#n(e,r,n,o){if(o==="HEAD")return(async()=>new Response(null,await this.#n(e,r,n,"GET")))();let s=this.getPath(e,{env:n}),i=this.router.match(o,s),a=new pe(e,{path:s,matchResult:i,env:n,executionCtx:r,notFoundHandler:this.#r});if(i[0].length===1){let l;try{l=i[0][0][0][0](a,async()=>{a.res=await this.#r(a)})}catch(u){return this.#o(u,a)}return l instanceof Promise?l.then(u=>u||(a.finalized?a.res:this.#r(a))).catch(u=>this.#o(u,a)):l??this.#r(a)}let c=ie(i[0],this.errorHandler,this.#r);return(async()=>{try{let l=await c(a);if(!l.finalized)throw new Error("Context is not finalized. Did you forget to return a Response object or `await next()`?");return l.res}catch(l){return this.#o(l,a)}})()}fetch=(e,...r)=>this.#n(e,r[1],r[0],e.method);request=(e,r,n,o)=>e instanceof Request?this.fetch(r?new Request(e,r):e,n,o):(e=e.toString(),this.fetch(new Request(/^https?:\/\//.test(e)?e:`http://localhost${k("/",e)}`,r),n,o));fire=()=>{addEventListener("fetch",e=>{e.respondWith(this.#n(e.request,e,void 0,e.request.method))})}};var X=[];function fe(t,e){let r=this.buildAllMatchers(),n=((o,s)=>{let i=r[o]||r[w],a=i[2][s];if(a)return a;let c=s.match(i[0]);if(!c)return[[],X];let l=c.indexOf("",1);return[i[1][l],c]});return this.match=n,n(t,e)}var Q="[^/]+",F=".*",q="(?:|/.*)",U=Symbol(),lr=new Set(".\\+*[^]$()");function ur(t,e){return t.length===1?e.length===1?t<e?-1:1:-1:e.length===1||t===F||t===q?1:e===F||e===q?-1:t===Q?1:e===Q?-1:t.length===e.length?t<e?-1:1:e.length-t.length}var Ge=class me{#t;#e;#r=Object.create(null);insert(e,r,n,o,s){if(e.length===0){if(this.#t!==void 0)throw U;if(s)return;this.#t=r;return}let[i,...a]=e,c=i==="*"?a.length===0?["","",F]:["","",Q]:i==="/*"?["","",q]:i.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/),l;if(c){let u=c[1],h=c[2]||Q;if(u&&c[2]&&(h===".*"||(h=h.replace(/^\((?!\?:)(?=[^)]+\)$)/,"(?:"),/\((?!\?:)/.test(h))))throw U;if(l=this.#r[h],!l){if(Object.keys(this.#r).some(m=>m!==F&&m!==q))throw U;if(s)return;l=this.#r[h]=new me,u!==""&&(l.#e=o.varIndex++)}!s&&u!==""&&n.push([u,l.#e])}else if(l=this.#r[i],!l){if(Object.keys(this.#r).some(u=>u.length>1&&u!==F&&u!==q))throw U;if(s)return;l=this.#r[i]=new me}l.insert(a,r,n,o,s)}buildRegExpStr(){let r=Object.keys(this.#r).sort(ur).map(n=>{let o=this.#r[n];return(typeof o.#e=="number"?`(${n})@${o.#e}`:lr.has(n)?`\\${n}`:n)+o.buildRegExpStr()});return typeof this.#t=="number"&&r.unshift(`#${this.#t}`),r.length===0?"":r.length===1?r[0]:"(?:"+r.join("|")+")"}};var Je=class{#t={varIndex:0};#e=new Ge;insert(t,e,r){let n=[],o=[];for(let i=0;;){let a=!1;if(t=t.replace(/\{[^}]+\}/g,c=>{let l=`@\\${i}`;return o[i]=[l,c],i++,a=!0,l}),!a)break}let s=t.match(/(?::[^\/]+)|(?:\/\*$)|./g)||[];for(let i=o.length-1;i>=0;i--){let[a]=o[i];for(let c=s.length-1;c>=0;c--)if(s[c].indexOf(a)!==-1){s[c]=s[c].replace(a,o[i][1]);break}}return this.#e.insert(s,e,n,this.#t,r),n}buildRegExp(){let t=this.#e.buildRegExpStr();if(t==="")return[/^$/,[],[]];let e=0,r=[],n=[];return t=t.replace(/#(\d+)|@(\d+)|\.\*\$/g,(o,s,i)=>s!==void 0?(r[++e]=Number(s),"$()"):(i!==void 0&&(n[Number(i)]=++e),"")),[new RegExp(`^${t}`),r,n]}};var dr=[/^$/,[],Object.create(null)],Ye=Object.create(null);function Xe(t){return Ye[t]??=new RegExp(t==="*"?"":`^${t.replace(/\/\*$|([.\\+*[^\]$()])/g,(e,r)=>r?`\\${r}`:"(?:|/.*)")}$`)}function hr(){Ye=Object.create(null)}function pr(t){let e=new Je,r=[];if(t.length===0)return dr;let n=t.map(l=>[!/\*|\/:/.test(l[0]),...l]).sort(([l,u],[h,m])=>l?1:h?-1:u.length-m.length),o=Object.create(null);for(let l=0,u=-1,h=n.length;l<h;l++){let[m,p,g]=n[l];m?o[p]=[g.map(([y])=>[y,Object.create(null)]),X]:u++;let d;try{d=e.insert(p,u,m)}catch(y){throw y===U?new Y(p):y}m||(r[u]=g.map(([y,f])=>{let R=Object.create(null);for(f-=1;f>=0;f--){let[A,C]=d[f];R[A]=C}return[y,R]}))}let[s,i,a]=e.buildRegExp();for(let l=0,u=r.length;l<u;l++)for(let h=0,m=r[l].length;h<m;h++){let p=r[l][h]?.[1];if(!p)continue;let g=Object.keys(p);for(let d=0,y=g.length;d<y;d++)p[g[d]]=a[p[g[d]]]}let c=[];for(let l in i)c[l]=r[i[l]];return[s,c,o]}function D(t,e){if(t){for(let r of Object.keys(t).sort((n,o)=>o.length-n.length))if(Xe(r).test(e))return[...t[r]]}}var Z=class{name="RegExpRouter";#t;#e;constructor(){this.#t={[w]:Object.create(null)},this.#e={[w]:Object.create(null)}}add(t,e,r){let n=this.#t,o=this.#e;if(!n||!o)throw new Error(J);n[t]||[n,o].forEach(a=>{a[t]=Object.create(null),Object.keys(a[w]).forEach(c=>{a[t][c]=[...a[w][c]]})}),e==="/*"&&(e="*");let s=(e.match(/\/:/g)||[]).length;if(/\*$/.test(e)){let a=Xe(e);t===w?Object.keys(n).forEach(c=>{n[c][e]||=D(n[c],e)||D(n[w],e)||[]}):n[t][e]||=D(n[t],e)||D(n[w],e)||[],Object.keys(n).forEach(c=>{(t===w||t===c)&&Object.keys(n[c]).forEach(l=>{a.test(l)&&n[c][l].push([r,s])})}),Object.keys(o).forEach(c=>{(t===w||t===c)&&Object.keys(o[c]).forEach(l=>a.test(l)&&o[c][l].push([r,s]))});return}let i=G(e)||[e];for(let a=0,c=i.length;a<c;a++){let l=i[a];Object.keys(o).forEach(u=>{(t===w||t===u)&&(o[u][l]||=[...D(n[u],l)||D(n[w],l)||[]],o[u][l].push([r,s-c+a+1]))})}}match=fe;buildAllMatchers(){let t=Object.create(null);return Object.keys(this.#e).concat(Object.keys(this.#t)).forEach(e=>{t[e]||=this.#r(e)}),this.#t=this.#e=void 0,hr(),t}#r(t){let e=[],r=t===w;return[this.#t,this.#e].forEach(n=>{let o=n[t]?Object.keys(n[t]).map(s=>[s,n[t][s]]):[];o.length!==0?(r||=!0,e.push(...o)):t!==w&&e.push(...Object.keys(n[w]).map(s=>[s,n[w][s]]))}),r?pr(e):null}};var ge=class{name="SmartRouter";#t=[];#e=[];constructor(t){this.#t=t.routers}add(t,e,r){if(!this.#e)throw new Error(J);this.#e.push([t,e,r])}match(t,e){if(!this.#e)throw new Error("Fatal error");let r=this.#t,n=this.#e,o=r.length,s=0,i;for(;s<o;s++){let a=r[s];try{for(let c=0,l=n.length;c<l;c++)a.add(...n[c]);i=a.match(t,e)}catch(c){if(c instanceof Y)continue;throw c}this.match=a.match.bind(a),this.#t=[a],this.#e=void 0;break}if(s===o)throw new Error("Fatal error");return this.name=`SmartRouter + ${this.activeRouter.name}`,i}get activeRouter(){if(this.#e||this.#t.length!==1)throw new Error("No active router has been determined yet.");return this.#t[0]}};var z=Object.create(null),fr=t=>{for(let e in t)return!0;return!1},Qe=class Ze{#t;#e;#r;#s=0;#o=z;constructor(e,r,n){if(this.#e=n||Object.create(null),this.#t=[],e&&r){let o=Object.create(null);o[e]={handler:r,possibleKeys:[],score:0},this.#t=[o]}this.#r=[]}insert(e,r,n){this.#s=++this.#s;let o=this,s=Le(r),i=[];for(let a=0,c=s.length;a<c;a++){let l=s[a],u=s[a+1],h=Ue(l,u),m=Array.isArray(h)?h[0]:l;if(m in o.#e){o=o.#e[m],h&&i.push(h[1]);continue}o.#e[m]=new Ze,h&&(o.#r.push(h),i.push(h[1])),o=o.#e[m]}return o.#t.push({[e]:{handler:n,possibleKeys:i.filter((a,c,l)=>l.indexOf(a)===c),score:this.#s}}),o}#n(e,r,n,o,s){for(let i=0,a=r.#t.length;i<a;i++){let c=r.#t[i],l=c[n]||c[w],u={};if(l!==void 0&&(l.params=Object.create(null),e.push(l),o!==z||s&&s!==z))for(let h=0,m=l.possibleKeys.length;h<m;h++){let p=l.possibleKeys[h],g=u[l.score];l.params[p]=s?.[p]&&!g?s[p]:o[p]??s?.[p],u[l.score]=!0}}}search(e,r){let n=[];this.#o=z;let s=[this],i=ce(r),a=[],c=i.length,l=null;for(let u=0;u<c;u++){let h=i[u],m=u===c-1,p=[];for(let d=0,y=s.length;d<y;d++){let f=s[d],R=f.#e[h];R&&(R.#o=f.#o,m?(R.#e["*"]&&this.#n(n,R.#e["*"],e,f.#o),this.#n(n,R,e,f.#o)):p.push(R));for(let A=0,C=f.#r.length;A<C;A++){let v=f.#r[A],x=f.#o===z?{}:{...f.#o};if(v==="*"){let M=f.#e["*"];M&&(this.#n(n,M,e,f.#o),M.#o=x,p.push(M));continue}let[_,b,P]=v;if(!h&&!(P instanceof RegExp))continue;let E=f.#e[_];if(P instanceof RegExp){if(l===null){l=new Array(c);let N=r[0]==="/"?1:0;for(let O=0;O<c;O++)l[O]=N,N+=i[O].length+1}let M=r.substring(l[u]),H=P.exec(M);if(H){if(x[b]=H[0],this.#n(n,E,e,f.#o,x),fr(E.#e)){E.#o=x;let N=H[0].match(/\//)?.length??0;(a[N]||=[]).push(E)}continue}}(P===!0||P.test(h))&&(x[b]=h,m?(this.#n(n,E,e,x,f.#o),E.#e["*"]&&this.#n(n,E.#e["*"],e,x,f.#o)):(E.#o=x,p.push(E)))}}let g=a.shift();s=g?p.concat(g):p}return n.length>1&&n.sort((u,h)=>u.score-h.score),[n.map(({handler:u,params:h})=>[u,h])]}};var ye=class{name="TrieRouter";#t;constructor(){this.#t=new Qe}add(t,e,r){let n=G(e);if(n){for(let o=0,s=n.length;o<s;o++)this.#t.insert(t,n[o],r);return}this.#t.insert(t,e,r)}match(t,e){return this.#t.search(t,e)}};var we=class extends Ke{constructor(t={}){super(t),this.router=t.router??new ge({routers:[new Z,new ye]})}};import{Readable as rn}from"stream";function et(t=""){return`<link rel="icon" type="image/svg+xml" href="${`${t.replace(/\/$/,"")}/favicon-black.svg?v=4`}" />`}import{existsSync as mt,readFileSync as wr}from"fs";import T from"path";import{fileURLToPath as xr}from"url";import{gunzipSync as br}from"zlib";var ht=Qt(dt(),1),pt=600,ft=120,ee=60;function te(t){let e=new ht.default({points:t.points,duration:t.durationSeconds});return async(r,n)=>{try{await e.consume(t.key)}catch(o){return r.header("Retry-After",String(yr(o))),r.json({error:"Too Many Requests"},429)}await n()}}function yr(t){return t&&typeof t=="object"&&"msBeforeNext"in t&&typeof t.msBeforeNext=="number"?Math.max(1,Math.ceil(t.msBeforeNext/1e3)):60}var Rr={".js":"application/javascript",".css":"text/css",".svg":"image/svg+xml",".png":"image/png",".ico":"image/x-icon",".webmanifest":"application/manifest+json"};function vr(){let t=T.dirname(xr(import.meta.url));for(let e of[T.resolve(t,"app"),T.resolve(t,"../app"),T.resolve(t,"../../dist/app")])if(mt(T.join(e,"inspector.js.gz")))return e;throw new Error("Inspector bundle not found (expected dist/app/inspector.js.gz)")}function gt(t,e="/inspector/assets"){let r=vr(),n=new Map;t.use(`${e}/*`,te({points:pt,durationSeconds:ee,key:"inspector-assets"})),t.get(`${e}/*`,o=>{let s=o.req.path.slice(e.length),i=s.startsWith("/")?s.slice(1):s;if(!i||i.includes(".."))return o.notFound();let a=i==="inspector.js"||i==="inspector.css"?`${i}.gz`:i,c=T.resolve(r,a),l=r.endsWith(T.sep)?r:`${r}${T.sep}`;if(!c.startsWith(l)||!mt(c))return o.notFound();let u=T.extname(i),h=a.endsWith(".gz"),m=/(?:^|,)\s*gzip\s*(?:,|$)/i.test(o.req.header("accept-encoding")??""),p=wr(c),g=h&&!m?n.get(c)??Er(n,c,p):p,d=g.buffer.slice(g.byteOffset,g.byteOffset+g.byteLength);return o.body(d,200,{"Content-Type":Rr[u]??"application/octet-stream",...h&&m?{"Content-Encoding":"gzip"}:{},...h?{Vary:"Accept-Encoding"}:{},"Cache-Control":"no-cache"})})}function Er(t,e,r){let n=br(r);return t.set(e,n),n}var yt={name:"@mcp-use/inspector",type:"module",version:"20.0.0-beta.35",description:"MCP Inspector - A tool for inspecting and debugging MCP servers",author:"",license:"MIT",homepage:"https://github.com/mcp-use/mcp-use#readme",repository:{type:"git",url:"git+https://github.com/mcp-use/mcp-use.git",directory:"libraries/typescript/packages/inspector"},bugs:{url:"https://github.com/mcp-use/mcp-use/issues"},keywords:["mcp","inspector","debug","tools"],exports:{".":{types:"./dist/server/index.d.ts",import:"./dist/server/index.js"},"./client":{types:"./dist/client/index.d.ts",import:"./dist/client/index.js"}},main:"./dist/server/index.js",types:"./dist/server/index.d.ts",bin:{"mcp-inspect":"./dist/cli.js"},files:["dist"],scripts:{dev:"rimraf node_modules/.vite && VITE_MANUFACT_CHAT_URL=${VITE_MANUFACT_CHAT_URL:-http://localhost:8000/api/v1/inspector/chat/stream} vite --strictPort","dev:client":"pnpm run dev","dev:server":"VITE_DEV=true tsx watch src/server/server.ts","dev:standalone":"tsx watch src/server/server.ts",clean:"rimraf dist",build:"npm run clean && npm run build:client-exports && npm run build:server && npm run build:app && npm run verify:package","build:app":"vite build --config vite.app.config.ts && node scripts/compress-app.mjs","watch:app":"vite build --watch --config vite.app.config.ts","preview:app":"vite preview --config vite.app.config.ts --host 127.0.0.1","serve:app":"pnpm build:app && pnpm preview:app","analyze:app":"ANALYZE=true vite build --config vite.app.config.ts","build:client-exports":"tsup --config tsup.client.ts","build:server":"tsup --config tsup.server.ts","verify:package":"node scripts/verify-package.mjs",prepublishOnly:"pnpm --filter @mcp-use/client build && pnpm build",start:"node dist/cli.js --port 3000",preview:"vite preview","type-check":"tsc --noEmit",lint:"eslint .","lint:fix":"eslint . --fix","test:e2e":"playwright test","test:e2e:ui":"playwright test --ui","test:e2e:debug":"playwright test --debug","test:e2e:builtin":"node tests/e2e/scripts/run-test-matrix.mjs builtin","test:e2e:prod":"node tests/e2e/scripts/run-test-matrix.mjs prod","test:e2e:mix":"node tests/e2e/scripts/run-test-matrix.mjs mix","test:e2e:prod:ui":"TEST_MODE=production playwright test --ui","test:e2e:codegen":"playwright codegen http://localhost:3000/inspector","test:e2e:report":"playwright show-report","test:e2e:python":"node tests/e2e/scripts/run-python-e2e.mjs","test:unit":"vitest run","test:unit:watch":"vitest","test:e2e:tunnel":"node tests/e2e/scripts/run-tunnel-test.mjs","install:pnpm":"pnpm install","install:npm":"npm install","lint:npm":"npm run lint:fix","lint:pnpm":"pnpm lint:fix"},engines:{node:">=22.22.2"},peerDependencies:{"@base-ui/react":"^1.6.0","@mcp-use/agent":"^2.0.0-alpha.0","@mcp-use/client":"^2.0.0-alpha.0","class-variance-authority":"^0.7.1",clsx:"^2.1.1",express:"^4.21.2 || ^5.0.0","lucide-react":"^0.562.0","markdown-to-jsx":"^9.7.4","mcp-use":"workspace:*",motion:"^12.34.2",react:"^18.0.0 || ^19.0.0","react-dom":"^18.0.0 || ^19.0.0","react-resizable-panels":"^4.6.4",sonner:"^2.0.7","tailwind-merge":"^3.5.0"},peerDependenciesMeta:{"@base-ui/react":{optional:!0},"@mcp-use/agent":{optional:!0},"@mcp-use/client":{optional:!0},"class-variance-authority":{optional:!0},clsx:{optional:!0},express:{optional:!0},"lucide-react":{optional:!0},"markdown-to-jsx":{optional:!0},motion:{optional:!0},react:{optional:!0},"react-dom":{optional:!0},"react-resizable-panels":{optional:!0},sonner:{optional:!0},"tailwind-merge":{optional:!0}},dependencies:{},publishConfig:{access:"public"},devDependencies:{"@base-ui/react":"^1.6.0","@hono/node-server":"^1.19.13","@mcp-use/agent":"workspace:*","@mcp-use/client":"workspace:*","@playwright/test":"^1.58.2","@tailwindcss/vite":"^4.2.0","@types/express":"^5.0.6","@vitejs/plugin-react":"^6.0.0","class-variance-authority":"^0.7.1",clsx:"^2.1.1",emulate:"0.5.0",eslint:"^9.39.2",express:"^5.2.1",hono:"^4.12.12","lucide-react":"^0.562.0","markdown-to-jsx":"^9.7.4",motion:"^12.34.2","oauth2-mock-server":"^8.2.2",open:"^11.0.0",react:"^19.2.3","react-dom":"^19.2.3","react-router":"^7.12.0","react-resizable-panels":"^4.6.4","rate-limiter-flexible":"^11.2.0","rollup-plugin-visualizer":"^6.0.3",sonner:"^2.0.7","tailwind-merge":"^3.5.0",tailwindcss:"^4.2.0",tsup:"^8.5.1",tsx:"^4.21.0","tw-animate-css":"^1.4.0",typescript:"^5.9.3",vite:"^8.0.16",vitest:"^4.1.0","wait-on":"^9.0.4",zod:"^4.2.0"}};var Pr=yt.version;function wt(){return Pr}var xt=wt(),Ar=`<!doctype html>
1
+ var Vt=Object.create;var ke=Object.defineProperty;var Gt=Object.getOwnPropertyDescriptor;var Jt=Object.getOwnPropertyNames;var Yt=Object.getPrototypeOf,Xt=Object.prototype.hasOwnProperty;var z=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports);var Qt=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Jt(e))!Xt.call(t,o)&&o!==r&&ke(t,o,{get:()=>e[o],enumerable:!(n=Gt(e,o))||n.enumerable});return t};var Zt=(t,e,r)=>(r=t!=null?Vt(Yt(t)):{},Qt(e||!t||!t.__esModule?ke(r,"default",{value:t,enumerable:!0}):r,t));var st=z((No,ot)=>{"use strict";ot.exports=class{constructor(e={}){this.points=e.points,this.duration=e.duration,this.blockDuration=e.blockDuration,this.execEvenly=e.execEvenly,this.execEvenlyMinDelayMs=e.execEvenlyMinDelayMs,this.keyPrefix=e.keyPrefix}get points(){return this._points}set points(e){if(Number.isFinite(e))this._points=e;else throw new Error("points must be set and must be a finite number")}get duration(){return this._duration}set duration(e){if(typeof e=="number"&&Number.isFinite(e)&&e>=0)this._duration=e;else throw new Error("duration must be set and must be a finite, non-negative number")}get msDuration(){return this.duration*1e3}get blockDuration(){return this._blockDuration}set blockDuration(e){this._blockDuration=typeof e>"u"?0:e}get msBlockDuration(){return this.blockDuration*1e3}get execEvenly(){return this._execEvenly}set execEvenly(e){this._execEvenly=typeof e>"u"?!1:!!e}get execEvenlyMinDelayMs(){return this._execEvenlyMinDelayMs===void 0?this._getExecEvenlyMinDelayMsDefault():this._execEvenlyMinDelayMs}set execEvenlyMinDelayMs(e){this._execEvenlyMinDelayMs=e}_getExecEvenlyMinDelayMsDefault(){return this.points>0?Math.ceil(this.msDuration/this.points):0}get keyPrefix(){return this._keyPrefix}set keyPrefix(e){if(typeof e>"u"&&(e="rlflx"),typeof e!="string")throw new Error("keyPrefix must be string");this._keyPrefix=e}_getKeySecDuration(e={}){return e&&e.customDuration>=0?e.customDuration:this.duration}getKey(e){return this.keyPrefix.length>0?`${this.keyPrefix}:${e}`:e}parseKey(e){return this.keyPrefix.length>0?e.substring(this.keyPrefix.length+1):e}consume(){throw new Error("You have to implement the method 'consume'!")}penalty(){throw new Error("You have to implement the method 'penalty'!")}reward(){throw new Error("You have to implement the method 'reward'!")}get(){throw new Error("You have to implement the method 'get'!")}set(){throw new Error("You have to implement the method 'set'!")}block(){throw new Error("You have to implement the method 'block'!")}delete(){throw new Error("You have to implement the method 'delete'!")}}});var at=z((Do,it)=>{"use strict";it.exports=class{constructor(e,r,n=null){this.value=e,this.expiresAt=r,this.timeoutId=n}get value(){return this._value}set value(e){this._value=parseInt(e,10)}get expiresAt(){return this._expiresAt}set expiresAt(e){e instanceof Date?this._expiresAt=e.getTime():this._expiresAt=e}get timeoutId(){return this._timeoutId}set timeoutId(e){this._timeoutId=e}}});var ve=z(($o,ct)=>{"use strict";ct.exports=class{constructor(e,r,n,o){this.remainingPoints=typeof e>"u"?0:e,this.msBeforeNext=typeof r>"u"?0:r,this.consumedPoints=typeof n>"u"?0:n,this.isFirstInDuration=typeof o>"u"?!1:o}get msBeforeNext(){return this._msBeforeNext}set msBeforeNext(e){return this._msBeforeNext=e,this}get remainingPoints(){return this._remainingPoints}set remainingPoints(e){return this._remainingPoints=e,this}get consumedPoints(){return this._consumedPoints}set consumedPoints(e){return this._consumedPoints=e,this}get isFirstInDuration(){return this._isFirstInDuration}set isFirstInDuration(e){this._isFirstInDuration=!!e}_getDecoratedProperties(){return{remainingPoints:this.remainingPoints,msBeforeNext:this.msBeforeNext,consumedPoints:this.consumedPoints,isFirstInDuration:this.isFirstInDuration}}[Symbol.for("nodejs.util.inspect.custom")](){return this._getDecoratedProperties()}toString(){return JSON.stringify(this._getDecoratedProperties())}toJSON(){return this._getDecoratedProperties()}}});var dt=z((Fo,lt)=>{"use strict";var ut=at(),Ee=ve();lt.exports=class{constructor(){this._storage=new Map}incrby(e,r,n){let o=this._storage.get(e);if(o){let s=o.expiresAt?o.expiresAt-Date.now():-1;return!o.expiresAt||s>0?(o.value=o.value+r,new Ee(0,s,o.value,!1)):this.set(e,r,n)}return this.set(e,r,n)}set(e,r,n){let o=n*1e3,s=this._storage.get(e);s&&s.timeoutId&&clearTimeout(s.timeoutId);let i=new ut(r,o>0?Date.now()+o:null);return this._storage.set(e,i),o>0&&(i.timeoutId=setTimeout(()=>{this._storage.delete(e)},o),i.timeoutId.unref&&i.timeoutId.unref()),new Ee(0,o===0?-1:o,i.value,!0)}get(e){let r=this._storage.get(e);if(r){let n=r.expiresAt?r.expiresAt-Date.now():-1;return new Ee(0,n,r.value,!1)}return null}delete(e){let r=this._storage.get(e);return r?(r.timeoutId&&clearTimeout(r.timeoutId),this._storage.delete(e),!0):!1}_restoreRecord(e,r,n){let o=Date.now(),s=n!==null;if(s&&!Number.isFinite(n)||s&&n<=o)return;let i=s?n-o:0,a=this._storage.get(e);a&&a.timeoutId&&clearTimeout(a.timeoutId);let c=new ut(r,n);this._storage.set(e,c),i>0&&(c.timeoutId=setTimeout(()=>{this._storage.delete(e)},i),c.timeoutId.unref&&c.timeoutId.unref())}}});var ft=z((qo,pt)=>{"use strict";var gr=st(),yr=dt(),ht=ve(),_e=class extends gr{constructor(e={}){super(e),this._memoryStorage=new yr}consume(e,r=1,n={}){return new Promise((o,s)=>{let i=this.getKey(e),a=this._getKeySecDuration(n),c=this._memoryStorage.incrby(i,r,a);if(c.remainingPoints=Math.max(this.points-c.consumedPoints,0),c.consumedPoints>this.points)this.blockDuration>0&&c.consumedPoints<=this.points+r&&(c=this._memoryStorage.set(i,c.consumedPoints,this.blockDuration)),s(c);else if(this.execEvenly&&this.points>0&&c.msBeforeNext>0&&!c.isFirstInDuration){let u=Math.ceil(c.msBeforeNext/(c.remainingPoints+2));u<this.execEvenlyMinDelayMs&&(u=c.consumedPoints*this.execEvenlyMinDelayMs),c.msBeforeNext=Math.max(c.msBeforeNext-u,0),setTimeout(o,u,c)}else o(c)})}penalty(e,r=1,n={}){let o=this.getKey(e);return new Promise(s=>{let i=this._getKeySecDuration(n),a=this._memoryStorage.incrby(o,r,i);a.remainingPoints=Math.max(this.points-a.consumedPoints,0),s(a)})}reward(e,r=1,n={}){let o=this.getKey(e);return new Promise(s=>{let i=this._getKeySecDuration(n),a=this._memoryStorage.incrby(o,-r,i);a.remainingPoints=Math.max(this.points-a.consumedPoints,0),s(a)})}block(e,r){let n=r*1e3,o=this.points+1;return this._memoryStorage.set(this.getKey(e),o,r),Promise.resolve(new ht(0,n===0?-1:n,o))}set(e,r,n){let o=(n>=0?n:this.duration)*1e3;return this._memoryStorage.set(this.getKey(e),r,n),Promise.resolve(new ht(0,o===0?-1:o,r))}get(e){let r=this._memoryStorage.get(this.getKey(e));return r!==null&&(r.remainingPoints=Math.max(this.points-r.consumedPoints,0)),Promise.resolve(r)}delete(e){return Promise.resolve(this._memoryStorage.delete(this.getKey(e)))}dump(){let e=[];for(let[r,n]of this._memoryStorage._storage)e.push({key:this.parseKey(r),value:n.value,expiresAt:n.expiresAt});return{version:1,dumpedAt:Date.now(),storage:e}}restore(e,r=!1){if(!e||typeof e!="object"||e.version!==1)return;let n=r?{invalid:{count:0,keys:[]},expired:{count:0,keys:[]},restored:{count:0,keys:[]}}:{invalid:0,expired:0,restored:0},o=(s,i)=>{r?(n[s].count+=1,n[s].keys.push(i)):n[s]+=1};if(!Array.isArray(e.storage))return n;for(let s of e.storage){if(!s||typeof s!="object"){o("invalid","N/A");continue}let i=typeof s.key=="string"||typeof s.key=="number",a=Number.isFinite(s.value),c=s.expiresAt===null||Number.isFinite(s.expiresAt);if(!i||!a||!c){o("invalid",s.key);continue}if(s.expiresAt!==null&&s.expiresAt<=Date.now()){o("expired",s.key);continue}this._memoryStorage._restoreRecord(this.getKey(s.key),s.value,s.expiresAt),o("restored",s.key)}return n}};pt.exports=_e});var ue=(t,e,r)=>(n,o)=>{let s=-1;return i(0);async function i(a){if(a<=s)throw new Error("next() called multiple times");s=a;let c,u=!1,l;if(t[a]?(l=t[a][0][0],n.req.routeIndex=a):l=a===t.length&&o||void 0,l)try{c=await l(n,()=>i(a+1))}catch(h){if(h instanceof Error&&e)n.error=h,c=await e(h,n),u=!0;else throw h}else n.finalized===!1&&r&&(c=await r(n));return c&&(n.finalized===!1||u)&&(n.res=c),n}};var Ue=Symbol();var Ne=async(t,e=Object.create(null))=>{let{all:r=!1,dot:n=!1}=e,s=(t instanceof Y?t.raw.headers:t.headers).get("Content-Type");return s?.startsWith("multipart/form-data")||s?.startsWith("application/x-www-form-urlencoded")?er(t,{all:r,dot:n}):{}};async function er(t,e){let r=await t.formData();return r?tr(r,e):{}}function tr(t,e){let r=Object.create(null);return t.forEach((n,o)=>{e.all||o.endsWith("[]")?rr(r,o,n):r[o]=n}),e.dot&&Object.entries(r).forEach(([n,o])=>{n.includes(".")&&(nr(r,n,o),delete r[n])}),r}var rr=(t,e,r)=>{t[e]!==void 0?Array.isArray(t[e])?t[e].push(r):t[e]=[t[e],r]:e.endsWith("[]")?t[e]=[r]:t[e]=r},nr=(t,e,r)=>{if(/(?:^|\.)__proto__\./.test(e))return;let n=t,o=e.split(".");o.forEach((s,i)=>{i===o.length-1?n[s]=r:((!n[s]||typeof n[s]!="object"||Array.isArray(n[s])||n[s]instanceof File)&&(n[s]=Object.create(null)),n=n[s])})};var de=t=>{let e=t.split("/");return e[0]===""&&e.shift(),e},je=t=>{let{groups:e,path:r}=or(t),n=de(r);return sr(n,e)},or=t=>{let e=[];return t=t.replace(/\{[^}]+\}/g,(r,n)=>{let o=`@${n}`;return e.push([o,r]),o}),{groups:e,path:t}},sr=(t,e)=>{for(let r=e.length-1;r>=0;r--){let[n]=e[r];for(let o=t.length-1;o>=0;o--)if(t[o].includes(n)){t[o]=t[o].replace(n,e[r][1]);break}}return t},X={},De=(t,e)=>{if(t==="*")return"*";let r=t.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);if(r){let n=`${t}#${e}`;return X[n]||(r[2]?X[n]=e&&e[0]!==":"&&e[0]!=="*"?[n,r[1],new RegExp(`^${r[2]}(?=/${e})`)]:[t,r[1],new RegExp(`^${r[2]}$`)]:X[n]=[t,r[1],!0]),X[n]}return null},Q=(t,e)=>{try{return e(t)}catch{return t.replace(/(?:%[0-9A-Fa-f]{2})+/g,r=>{try{return e(r)}catch{return r}})}},ir=t=>Q(t,decodeURI),he=t=>{let e=t.url,r=e.indexOf("/",e.indexOf(":")+4),n=r;for(;n<e.length;n++){let o=e.charCodeAt(n);if(o===37){let s=e.indexOf("?",n),i=e.indexOf("#",n),a=s===-1?i===-1?void 0:i:i===-1?s:Math.min(s,i),c=e.slice(r,a);return ir(c.includes("%25")?c.replace(/%25/g,"%2525"):c)}else if(o===63||o===35)break}return e.slice(r,n)};var He=t=>{let e=he(t);return e.length>1&&e.at(-1)==="/"?e.slice(0,-1):e},k=(t,e,...r)=>(r.length&&(e=k(e,...r)),`${t?.[0]==="/"?"":"/"}${t}${e==="/"?"":`${t?.at(-1)==="/"?"":"/"}${e?.[0]==="/"?e.slice(1):e}`}`),Z=t=>{if(t.charCodeAt(t.length-1)!==63||!t.includes(":"))return null;let e=t.split("/"),r=[],n="";return e.forEach(o=>{if(o!==""&&!/\:/.test(o))n+="/"+o;else if(/\:/.test(o))if(/\?/.test(o)){r.length===0&&n===""?r.push("/"):r.push(n);let s=o.replace("?","");n+="/"+s,r.push(n)}else n+="/"+o}),r.filter((o,s,i)=>i.indexOf(o)===s)},le=t=>/[%+]/.test(t)?(t.indexOf("+")!==-1&&(t=t.replace(/\+/g," ")),t.indexOf("%")!==-1?Q(t,pe):t):t,$e=(t,e,r)=>{let n;if(!r&&e&&!/[%+]/.test(e)){let i=t.indexOf("?",8);if(i===-1)return;for(t.startsWith(e,i+1)||(i=t.indexOf(`&${e}`,i+1));i!==-1;){let a=t.charCodeAt(i+e.length+1);if(a===61){let c=i+e.length+2,u=t.indexOf("&",c);return le(t.slice(c,u===-1?void 0:u))}else if(a==38||isNaN(a))return"";i=t.indexOf(`&${e}`,i+1)}if(n=/[%+]/.test(t),!n)return}let o={};n??=/[%+]/.test(t);let s=t.indexOf("?",8);for(;s!==-1;){let i=t.indexOf("&",s+1),a=t.indexOf("=",s);a>i&&i!==-1&&(a=-1);let c=t.slice(s+1,a===-1?i===-1?void 0:i:a);if(n&&(c=le(c)),s=i,c==="")continue;let u;a===-1?u="":(u=t.slice(a+1,i===-1?void 0:i),n&&(u=le(u))),r?(o[c]&&Array.isArray(o[c])||(o[c]=[]),o[c].push(u)):o[c]??=u}return e?o[e]:o},Be=$e,Fe=(t,e)=>$e(t,e,!0),pe=decodeURIComponent;var qe=t=>Q(t,pe),Y=class{raw;#t;#e;routeIndex=0;path;bodyCache={};constructor(t,e="/",r=[[]]){this.raw=t,this.path=e,this.#e=r,this.#t={}}param(t){return t?this.#r(t):this.#s()}#r(t){let e=this.#e[0][this.routeIndex][1][t],r=this.#o(e);return r&&/\%/.test(r)?qe(r):r}#s(){let t={},e=Object.keys(this.#e[0][this.routeIndex][1]);for(let r of e){let n=this.#o(this.#e[0][this.routeIndex][1][r]);n!==void 0&&(t[r]=/\%/.test(n)?qe(n):n)}return t}#o(t){return this.#e[1]?this.#e[1][t]:t}query(t){return Be(this.url,t)}queries(t){return Fe(this.url,t)}header(t){if(t)return this.raw.headers.get(t)??void 0;let e={};return this.raw.headers.forEach((r,n)=>{e[n]=r}),e}async parseBody(t){return Ne(this,t)}#n=t=>{let{bodyCache:e,raw:r}=this,n=e[t];if(n)return n;let o=Object.keys(e)[0];return o?e[o].then(s=>(o==="json"&&(s=JSON.stringify(s)),new Response(s)[t]())):e[t]=r[t]()};json(){return this.#n("text").then(t=>JSON.parse(t))}text(){return this.#n("text")}arrayBuffer(){return this.#n("arrayBuffer")}bytes(){return this.#n("arrayBuffer").then(t=>new Uint8Array(t))}blob(){return this.#n("blob")}formData(){return this.#n("formData")}addValidatedData(t,e){this.#t[t]=e}valid(t){return this.#t[t]}get url(){return this.raw.url}get method(){return this.raw.method}get[Ue](){return this.#e}get matchedRoutes(){return this.#e[0].map(([[,t]])=>t)}get routePath(){return this.#e[0].map(([[,t]])=>t)[this.routeIndex].path}};var ze={Stringify:1,BeforeStream:2,Stream:3},ar=(t,e)=>{let r=new String(t);return r.isEscaped=!0,r.callbacks=e,r};var fe=async(t,e,r,n,o)=>{typeof t=="object"&&!(t instanceof String)&&(t instanceof Promise||(t=t.toString()),t instanceof Promise&&(t=await t));let s=t.callbacks;if(!s?.length)return Promise.resolve(t);o?o[0]+=t:o=[t];let i=Promise.all(s.map(a=>a({phase:e,buffer:o,context:n}))).then(a=>Promise.all(a.filter(Boolean).map(c=>fe(c,e,!1,n,o))).then(()=>o[0]));return r?ar(await i,s):i};var cr="text/plain; charset=UTF-8",me=(t,e)=>({"Content-Type":t,...e}),W=(t,e)=>new Response(t,e),ge=class{#t;#e;env={};#r;finalized=!1;error;#s;#o;#n;#l;#c;#u;#a;#d;#h;constructor(t,e){this.#t=t,e&&(this.#o=e.executionCtx,this.env=e.env,this.#u=e.notFoundHandler,this.#h=e.path,this.#d=e.matchResult)}get req(){return this.#e??=new Y(this.#t,this.#h,this.#d),this.#e}get event(){if(this.#o&&"respondWith"in this.#o)return this.#o;throw Error("This context has no FetchEvent")}get executionCtx(){if(this.#o)return this.#o;throw Error("This context has no ExecutionContext")}get res(){return this.#n||=W(null,{headers:this.#a??=new Headers})}set res(t){if(this.#n&&t){t=W(t.body,t);for(let[e,r]of this.#n.headers.entries())if(e!=="content-type")if(e==="set-cookie"){let n=this.#n.headers.getSetCookie();t.headers.delete("set-cookie");for(let o of n)t.headers.append("set-cookie",o)}else t.headers.set(e,r)}this.#n=t,this.finalized=!0}render=(...t)=>(this.#c??=e=>this.html(e),this.#c(...t));setLayout=t=>this.#l=t;getLayout=()=>this.#l;setRenderer=t=>{this.#c=t};header=(t,e,r)=>{this.finalized&&(this.#n=W(this.#n.body,this.#n));let n=this.#n?this.#n.headers:this.#a??=new Headers;e===void 0?n.delete(t):r?.append?n.append(t,e):n.set(t,e)};status=t=>{this.#s=t};set=(t,e)=>{this.#r??=new Map,this.#r.set(t,e)};get=t=>this.#r?this.#r.get(t):void 0;get var(){return this.#r?Object.fromEntries(this.#r):{}}#i(t,e,r){let n=this.#n?new Headers(this.#n.headers):this.#a??new Headers;if(typeof e=="object"&&"headers"in e){let s=e.headers instanceof Headers?e.headers:new Headers(e.headers);for(let[i,a]of s)i.toLowerCase()==="set-cookie"?n.append(i,a):n.set(i,a)}if(r)for(let[s,i]of Object.entries(r))if(typeof i=="string")n.set(s,i);else{n.delete(s);for(let a of i)n.append(s,a)}let o=typeof e=="number"?e:e?.status??this.#s;return W(t,{status:o,headers:n})}newResponse=(...t)=>this.#i(...t);body=(t,e,r)=>this.#i(t,e,r);text=(t,e,r)=>!this.#a&&!this.#s&&!e&&!r&&!this.finalized?new Response(t):this.#i(t,e,me(cr,r));json=(t,e,r)=>this.#i(JSON.stringify(t),e,me("application/json",r));html=(t,e,r)=>{let n=o=>this.#i(o,e,me("text/html; charset=UTF-8",r));return typeof t=="object"?fe(t,ze.Stringify,!1,{}).then(n):n(t)};redirect=(t,e)=>{let r=String(t);return this.header("Location",/[^\x00-\xFF]/.test(r)?encodeURI(r):r),this.newResponse(null,e??302)};notFound=()=>(this.#u??=()=>W(),this.#u(this))};var R="ALL",We="all",Ke=["get","post","put","delete","options","patch"],ee="Can not add a route since the matcher is already built.",te=class extends Error{};var Ve="__COMPOSED_HANDLER";var ur=t=>t.text("404 Not Found",404),Ge=(t,e)=>{if("getResponse"in t){let r=t.getResponse();return e.newResponse(r.body,r)}return console.error(t),e.text("Internal Server Error",500)},Je=class Ye{get;post;put;delete;options;patch;all;on;use;router;getPath;_basePath="/";#t="/";routes=[];constructor(e={}){[...Ke,We].forEach(s=>{this[s]=(i,...a)=>(typeof i=="string"?this.#t=i:this.#s(s,this.#t,i),a.forEach(c=>{this.#s(s,this.#t,c)}),this)}),this.on=(s,i,...a)=>{for(let c of[i].flat()){this.#t=c;for(let u of[s].flat())a.map(l=>{this.#s(u.toUpperCase(),this.#t,l)})}return this},this.use=(s,...i)=>(typeof s=="string"?this.#t=s:(this.#t="*",i.unshift(s)),i.forEach(a=>{this.#s(R,this.#t,a)}),this);let{strict:n,...o}=e;Object.assign(this,o),this.getPath=n??!0?e.getPath??he:He}#e(){let e=new Ye({router:this.router,getPath:this.getPath});return e.errorHandler=this.errorHandler,e.#r=this.#r,e.routes=this.routes,e}#r=ur;errorHandler=Ge;route(e,r){let n=this.basePath(e);return r.routes.map(o=>{let s;r.errorHandler===Ge?s=o.handler:(s=async(i,a)=>(await ue([],r.errorHandler)(i,()=>o.handler(i,a))).res,s[Ve]=o.handler),n.#s(o.method,o.path,s,o.basePath)}),this}basePath(e){let r=this.#e();return r._basePath=k(this._basePath,e),r}onError=e=>(this.errorHandler=e,this);notFound=e=>(this.#r=e,this);mount(e,r,n){let o,s;n&&(typeof n=="function"?s=n:(s=n.optionHandler,n.replaceRequest===!1?o=c=>c:o=n.replaceRequest));let i=s?c=>{let u=s(c);return Array.isArray(u)?u:[u]}:c=>{let u;try{u=c.executionCtx}catch{}return[c.env,u]};o||=(()=>{let c=k(this._basePath,e),u=c==="/"?0:c.length;return l=>{let h=new URL(l.url);return h.pathname=this.getPath(l).slice(u)||"/",new Request(h,l)}})();let a=async(c,u)=>{let l=await r(o(c.req.raw),...i(c));if(l)return l;await u()};return this.#s(R,k(e,"*"),a),this}#s(e,r,n,o){e=e.toUpperCase(),r=k(this._basePath,r);let s={basePath:o!==void 0?k(this._basePath,o):this._basePath,path:r,method:e,handler:n};this.router.add(e,r,[n,s]),this.routes.push(s)}#o(e,r){if(e instanceof Error)return this.errorHandler(e,r);throw e}#n(e,r,n,o){if(o==="HEAD")return(async()=>new Response(null,await this.#n(e,r,n,"GET")))();let s=this.getPath(e,{env:n}),i=this.router.match(o,s),a=new ge(e,{path:s,matchResult:i,env:n,executionCtx:r,notFoundHandler:this.#r});if(i[0].length===1){let u;try{u=i[0][0][0][0](a,async()=>{a.res=await this.#r(a)})}catch(l){return this.#o(l,a)}return u instanceof Promise?u.then(l=>l||(a.finalized?a.res:this.#r(a))).catch(l=>this.#o(l,a)):u??this.#r(a)}let c=ue(i[0],this.errorHandler,this.#r);return(async()=>{try{let u=await c(a);if(!u.finalized)throw new Error("Context is not finalized. Did you forget to return a Response object or `await next()`?");return u.res}catch(u){return this.#o(u,a)}})()}fetch=(e,...r)=>this.#n(e,r[1],r[0],e.method);request=(e,r,n,o)=>e instanceof Request?this.fetch(r?new Request(e,r):e,n,o):(e=e.toString(),this.fetch(new Request(/^https?:\/\//.test(e)?e:`http://localhost${k("/",e)}`,r),n,o));fire=()=>{addEventListener("fetch",e=>{e.respondWith(this.#n(e.request,e,void 0,e.request.method))})}};var re=[];function ye(t,e){let r=this.buildAllMatchers(),n=((o,s)=>{let i=r[o]||r[R],a=i[2][s];if(a)return a;let c=s.match(i[0]);if(!c)return[[],re];let u=c.indexOf("",1);return[i[1][u],c]});return this.match=n,n(t,e)}var ne="[^/]+",K=".*",V="(?:|/.*)",H=Symbol(),lr=new Set(".\\+*[^]$()");function dr(t,e){return t.length===1?e.length===1?t<e?-1:1:-1:e.length===1||t===K||t===V?1:e===K||e===V?-1:t===ne?1:e===ne?-1:t.length===e.length?t<e?-1:1:e.length-t.length}var Xe=class we{#t;#e;#r=Object.create(null);insert(e,r,n,o,s){if(e.length===0){if(this.#t!==void 0)throw H;if(s)return;this.#t=r;return}let[i,...a]=e,c=i==="*"?a.length===0?["","",K]:["","",ne]:i==="/*"?["","",V]:i.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/),u;if(c){let l=c[1],h=c[2]||ne;if(l&&c[2]&&(h===".*"||(h=h.replace(/^\((?!\?:)(?=[^)]+\)$)/,"(?:"),/\((?!\?:)/.test(h))))throw H;if(u=this.#r[h],!u){if(Object.keys(this.#r).some(p=>p!==K&&p!==V))throw H;if(s)return;u=this.#r[h]=new we,l!==""&&(u.#e=o.varIndex++)}!s&&l!==""&&n.push([l,u.#e])}else if(u=this.#r[i],!u){if(Object.keys(this.#r).some(l=>l.length>1&&l!==K&&l!==V))throw H;if(s)return;u=this.#r[i]=new we}u.insert(a,r,n,o,s)}buildRegExpStr(){let r=Object.keys(this.#r).sort(dr).map(n=>{let o=this.#r[n];return(typeof o.#e=="number"?`(${n})@${o.#e}`:lr.has(n)?`\\${n}`:n)+o.buildRegExpStr()});return typeof this.#t=="number"&&r.unshift(`#${this.#t}`),r.length===0?"":r.length===1?r[0]:"(?:"+r.join("|")+")"}};var Qe=class{#t={varIndex:0};#e=new Xe;insert(t,e,r){let n=[],o=[];for(let i=0;;){let a=!1;if(t=t.replace(/\{[^}]+\}/g,c=>{let u=`@\\${i}`;return o[i]=[u,c],i++,a=!0,u}),!a)break}let s=t.match(/(?::[^\/]+)|(?:\/\*$)|./g)||[];for(let i=o.length-1;i>=0;i--){let[a]=o[i];for(let c=s.length-1;c>=0;c--)if(s[c].indexOf(a)!==-1){s[c]=s[c].replace(a,o[i][1]);break}}return this.#e.insert(s,e,n,this.#t,r),n}buildRegExp(){let t=this.#e.buildRegExpStr();if(t==="")return[/^$/,[],[]];let e=0,r=[],n=[];return t=t.replace(/#(\d+)|@(\d+)|\.\*\$/g,(o,s,i)=>s!==void 0?(r[++e]=Number(s),"$()"):(i!==void 0&&(n[Number(i)]=++e),"")),[new RegExp(`^${t}`),r,n]}};var hr=[/^$/,[],Object.create(null)],Ze=Object.create(null);function et(t){return Ze[t]??=new RegExp(t==="*"?"":`^${t.replace(/\/\*$|([.\\+*[^\]$()])/g,(e,r)=>r?`\\${r}`:"(?:|/.*)")}$`)}function pr(){Ze=Object.create(null)}function fr(t){let e=new Qe,r=[];if(t.length===0)return hr;let n=t.map(u=>[!/\*|\/:/.test(u[0]),...u]).sort(([u,l],[h,p])=>u?1:h?-1:l.length-p.length),o=Object.create(null);for(let u=0,l=-1,h=n.length;u<h;u++){let[p,f,y]=n[u];p?o[f]=[y.map(([g])=>[g,Object.create(null)]),re]:l++;let w;try{w=e.insert(f,l,p)}catch(g){throw g===H?new te(f):g}p||(r[l]=y.map(([g,d])=>{let m=Object.create(null);for(d-=1;d>=0;d--){let[b,O]=w[d];m[b]=O}return[g,m]}))}let[s,i,a]=e.buildRegExp();for(let u=0,l=r.length;u<l;u++)for(let h=0,p=r[u].length;h<p;h++){let f=r[u][h]?.[1];if(!f)continue;let y=Object.keys(f);for(let w=0,g=y.length;w<g;w++)f[y[w]]=a[f[y[w]]]}let c=[];for(let u in i)c[u]=r[i[u]];return[s,c,o]}function F(t,e){if(t){for(let r of Object.keys(t).sort((n,o)=>o.length-n.length))if(et(r).test(e))return[...t[r]]}}var oe=class{name="RegExpRouter";#t;#e;constructor(){this.#t={[R]:Object.create(null)},this.#e={[R]:Object.create(null)}}add(t,e,r){let n=this.#t,o=this.#e;if(!n||!o)throw new Error(ee);n[t]||[n,o].forEach(a=>{a[t]=Object.create(null),Object.keys(a[R]).forEach(c=>{a[t][c]=[...a[R][c]]})}),e==="/*"&&(e="*");let s=(e.match(/\/:/g)||[]).length;if(/\*$/.test(e)){let a=et(e);t===R?Object.keys(n).forEach(c=>{n[c][e]||=F(n[c],e)||F(n[R],e)||[]}):n[t][e]||=F(n[t],e)||F(n[R],e)||[],Object.keys(n).forEach(c=>{(t===R||t===c)&&Object.keys(n[c]).forEach(u=>{a.test(u)&&n[c][u].push([r,s])})}),Object.keys(o).forEach(c=>{(t===R||t===c)&&Object.keys(o[c]).forEach(u=>a.test(u)&&o[c][u].push([r,s]))});return}let i=Z(e)||[e];for(let a=0,c=i.length;a<c;a++){let u=i[a];Object.keys(o).forEach(l=>{(t===R||t===l)&&(o[l][u]||=[...F(n[l],u)||F(n[R],u)||[]],o[l][u].push([r,s-c+a+1]))})}}match=ye;buildAllMatchers(){let t=Object.create(null);return Object.keys(this.#e).concat(Object.keys(this.#t)).forEach(e=>{t[e]||=this.#r(e)}),this.#t=this.#e=void 0,pr(),t}#r(t){let e=[],r=t===R;return[this.#t,this.#e].forEach(n=>{let o=n[t]?Object.keys(n[t]).map(s=>[s,n[t][s]]):[];o.length!==0?(r||=!0,e.push(...o)):t!==R&&e.push(...Object.keys(n[R]).map(s=>[s,n[R][s]]))}),r?fr(e):null}};var xe=class{name="SmartRouter";#t=[];#e=[];constructor(t){this.#t=t.routers}add(t,e,r){if(!this.#e)throw new Error(ee);this.#e.push([t,e,r])}match(t,e){if(!this.#e)throw new Error("Fatal error");let r=this.#t,n=this.#e,o=r.length,s=0,i;for(;s<o;s++){let a=r[s];try{for(let c=0,u=n.length;c<u;c++)a.add(...n[c]);i=a.match(t,e)}catch(c){if(c instanceof te)continue;throw c}this.match=a.match.bind(a),this.#t=[a],this.#e=void 0;break}if(s===o)throw new Error("Fatal error");return this.name=`SmartRouter + ${this.activeRouter.name}`,i}get activeRouter(){if(this.#e||this.#t.length!==1)throw new Error("No active router has been determined yet.");return this.#t[0]}};var G=Object.create(null),mr=t=>{for(let e in t)return!0;return!1},tt=class rt{#t;#e;#r;#s=0;#o=G;constructor(e,r,n){if(this.#e=n||Object.create(null),this.#t=[],e&&r){let o=Object.create(null);o[e]={handler:r,possibleKeys:[],score:0},this.#t=[o]}this.#r=[]}insert(e,r,n){this.#s=++this.#s;let o=this,s=je(r),i=[];for(let a=0,c=s.length;a<c;a++){let u=s[a],l=s[a+1],h=De(u,l),p=Array.isArray(h)?h[0]:u;if(p in o.#e){o=o.#e[p],h&&i.push(h[1]);continue}o.#e[p]=new rt,h&&(o.#r.push(h),i.push(h[1])),o=o.#e[p]}return o.#t.push({[e]:{handler:n,possibleKeys:i.filter((a,c,u)=>u.indexOf(a)===c),score:this.#s}}),o}#n(e,r,n,o,s){for(let i=0,a=r.#t.length;i<a;i++){let c=r.#t[i],u=c[n]||c[R],l={};if(u!==void 0&&(u.params=Object.create(null),e.push(u),o!==G||s&&s!==G))for(let h=0,p=u.possibleKeys.length;h<p;h++){let f=u.possibleKeys[h],y=l[u.score];u.params[f]=s?.[f]&&!y?s[f]:o[f]??s?.[f],l[u.score]=!0}}}search(e,r){let n=[];this.#o=G;let s=[this],i=de(r),a=[],c=i.length,u=null;for(let l=0;l<c;l++){let h=i[l],p=l===c-1,f=[];for(let w=0,g=s.length;w<g;w++){let d=s[w],m=d.#e[h];m&&(m.#o=d.#o,p?(m.#e["*"]&&this.#n(n,m.#e["*"],e,d.#o),this.#n(n,m,e,d.#o)):f.push(m));for(let b=0,O=d.#r.length;b<O;b++){let C=d.#r[b],E=d.#o===G?{}:{...d.#o};if(C==="*"){let P=d.#e["*"];P&&(this.#n(n,P,e,d.#o),P.#o=E,f.push(P));continue}let[_,A,v]=C;if(!h&&!(v instanceof RegExp))continue;let x=d.#e[_];if(v instanceof RegExp){if(u===null){u=new Array(c);let N=r[0]==="/"?1:0;for(let j=0;j<c;j++)u[j]=N,N+=i[j].length+1}let P=r.substring(u[l]),I=v.exec(P);if(I){if(E[A]=I[0],this.#n(n,x,e,d.#o,E),mr(x.#e)){x.#o=E;let N=I[0].match(/\//)?.length??0;(a[N]||=[]).push(x)}continue}}(v===!0||v.test(h))&&(E[A]=h,p?(this.#n(n,x,e,E,d.#o),x.#e["*"]&&this.#n(n,x.#e["*"],e,E,d.#o)):(x.#o=E,f.push(x)))}}let y=a.shift();s=y?f.concat(y):f}return n.length>1&&n.sort((l,h)=>l.score-h.score),[n.map(({handler:l,params:h})=>[l,h])]}};var be=class{name="TrieRouter";#t;constructor(){this.#t=new tt}add(t,e,r){let n=Z(e);if(n){for(let o=0,s=n.length;o<s;o++)this.#t.insert(t,n[o],r);return}this.#t.insert(t,e,r)}match(t,e){return this.#t.search(t,e)}};var Re=class extends Je{constructor(t={}){super(t),this.router=t.router??new xe({routers:[new oe,new be]})}};import{Readable as on}from"stream";function nt(t=""){return`<link rel="icon" type="image/svg+xml" href="${`${t.replace(/\/$/,"")}/favicon-black.svg?v=4`}" />`}import{existsSync as mt,readFileSync as br}from"fs";import L from"path";import{fileURLToPath as Rr}from"url";import{gunzipSync as vr}from"zlib";var M=Zt(ft(),1);function q(t,e){return t.header("Retry-After",String(wr(e))),t.json({error:"Too Many Requests"},429)}function wr(t){return t&&typeof t=="object"&&"msBeforeNext"in t&&typeof t.msBeforeNext=="number"&&Number.isFinite(t.msBeforeNext)?Math.max(1,Math.ceil(t.msBeforeNext/1e3)):60}var Er={".js":"application/javascript",".css":"text/css",".svg":"image/svg+xml",".png":"image/png",".ico":"image/x-icon",".webmanifest":"application/manifest+json"};function _r(){let t=L.dirname(Rr(import.meta.url));for(let e of[L.resolve(t,"app"),L.resolve(t,"../app"),L.resolve(t,"../../dist/app")])if(mt(L.join(e,"inspector.js.gz")))return e;throw new Error("Inspector bundle not found (expected dist/app/inspector.js.gz)")}function gt(t,e="/inspector/assets"){let r=_r(),n=new Map,o=new M.default({points:600,duration:60}),s=async(i,a)=>{try{await o.consume(i.req)}catch(c){return q(i,c)}return a()};t.use(`${e}/*`,s),t.get(`${e}/*`,async i=>{let a=i.req.path.slice(e.length),c=a.startsWith("/")?a.slice(1):a;if(!c||c.includes(".."))return i.notFound();let u=c==="inspector.js"||c==="inspector.css"?`${c}.gz`:c,l=L.resolve(r,u),h=r.endsWith(L.sep)?r:`${r}${L.sep}`;if(!l.startsWith(h)||!mt(l))return i.notFound();let p=L.extname(c),f=u.endsWith(".gz"),y=/(?:^|,)\s*gzip\s*(?:,|$)/i.test(i.req.header("accept-encoding")??""),w=br(l),g=f&&!y?n.get(l)??Pr(n,l,w):w,d=g.buffer.slice(g.byteOffset,g.byteOffset+g.byteLength);return i.body(d,200,{"Content-Type":Er[p]??"application/octet-stream",...f&&y?{"Content-Encoding":"gzip"}:{},...f?{Vary:"Accept-Encoding"}:{},"Cache-Control":"no-cache"})})}function Pr(t,e,r){let n=vr(r);return t.set(e,n),n}var yt={name:"@mcp-use/inspector",type:"module",version:"20.0.0-beta.37",description:"MCP Inspector - A tool for inspecting and debugging MCP servers",author:"",license:"MIT",homepage:"https://github.com/mcp-use/mcp-use#readme",repository:{type:"git",url:"git+https://github.com/mcp-use/mcp-use.git",directory:"libraries/typescript/packages/inspector"},bugs:{url:"https://github.com/mcp-use/mcp-use/issues"},keywords:["mcp","inspector","debug","tools"],exports:{".":{types:"./dist/server/index.d.ts",import:"./dist/server/index.js"},"./client":{types:"./dist/client/index.d.ts",import:"./dist/client/index.js"}},main:"./dist/server/index.js",types:"./dist/server/index.d.ts",bin:{"mcp-inspect":"./dist/cli.js"},files:["dist"],scripts:{dev:"rimraf node_modules/.vite && VITE_MANUFACT_CHAT_URL=${VITE_MANUFACT_CHAT_URL:-http://localhost:8000/api/v1/inspector/chat/stream} vite --strictPort","dev:client":"pnpm run dev","dev:server":"VITE_DEV=true tsx watch src/server/server.ts","dev:standalone":"tsx watch src/server/server.ts",clean:"rimraf dist",build:"npm run clean && npm run build:client-exports && npm run build:server && npm run build:app && npm run verify:package","build:app":"vite build --config vite.app.config.ts && node scripts/compress-app.mjs","watch:app":"vite build --watch --config vite.app.config.ts","preview:app":"vite preview --config vite.app.config.ts --host 127.0.0.1","serve:app":"pnpm build:app && pnpm preview:app","analyze:app":"ANALYZE=true vite build --config vite.app.config.ts","build:client-exports":"tsup --config tsup.client.ts","build:server":"tsup --config tsup.server.ts","verify:package":"node scripts/verify-package.mjs",prepublishOnly:"pnpm --filter @mcp-use/client build && pnpm build",start:"node dist/cli.js --port 3000",preview:"vite preview","type-check":"tsc --noEmit",lint:"eslint .","lint:fix":"eslint . --fix","test:e2e":"playwright test","test:e2e:ui":"playwright test --ui","test:e2e:debug":"playwright test --debug","test:e2e:builtin":"node tests/e2e/scripts/run-test-matrix.mjs builtin","test:e2e:prod":"node tests/e2e/scripts/run-test-matrix.mjs prod","test:e2e:mix":"node tests/e2e/scripts/run-test-matrix.mjs mix","test:e2e:prod:ui":"TEST_MODE=production playwright test --ui","test:e2e:codegen":"playwright codegen http://localhost:3000/inspector","test:e2e:report":"playwright show-report","test:e2e:python":"node tests/e2e/scripts/run-python-e2e.mjs","test:unit":"vitest run","test:unit:watch":"vitest","test:e2e:tunnel":"node tests/e2e/scripts/run-tunnel-test.mjs","install:pnpm":"pnpm install","install:npm":"npm install","lint:npm":"npm run lint:fix","lint:pnpm":"pnpm lint:fix"},engines:{node:">=22.22.2"},peerDependencies:{"@base-ui/react":"^1.6.0","@mcp-use/agent":"^2.0.0-alpha.0","@mcp-use/client":"^2.0.0-alpha.0","class-variance-authority":"^0.7.1",clsx:"^2.1.1",express:"^4.21.2 || ^5.0.0","lucide-react":"^0.562.0","markdown-to-jsx":"^9.7.4","mcp-use":"workspace:*",motion:"^12.34.2",react:"^18.0.0 || ^19.0.0","react-dom":"^18.0.0 || ^19.0.0","react-resizable-panels":"^4.6.4",sonner:"^2.0.7","tailwind-merge":"^3.5.0"},peerDependenciesMeta:{"@base-ui/react":{optional:!0},"@mcp-use/agent":{optional:!0},"@mcp-use/client":{optional:!0},"class-variance-authority":{optional:!0},clsx:{optional:!0},express:{optional:!0},"lucide-react":{optional:!0},"markdown-to-jsx":{optional:!0},motion:{optional:!0},react:{optional:!0},"react-dom":{optional:!0},"react-resizable-panels":{optional:!0},sonner:{optional:!0},"tailwind-merge":{optional:!0}},dependencies:{},publishConfig:{access:"public"},devDependencies:{"@base-ui/react":"^1.6.0","@hono/node-server":"^1.19.13","@mcp-use/agent":"workspace:*","@mcp-use/client":"workspace:*","@playwright/test":"^1.58.2","@tailwindcss/vite":"^4.2.0","@types/express":"^5.0.6","@vitejs/plugin-react":"^6.0.0","class-variance-authority":"^0.7.1",clsx:"^2.1.1",emulate:"0.5.0",eslint:"^9.39.2",express:"^5.2.1",hono:"^4.12.12","lucide-react":"^0.562.0","markdown-to-jsx":"^9.7.4",motion:"^12.34.2","oauth2-mock-server":"^8.2.2",open:"^11.0.0",react:"^19.2.3","react-dom":"^19.2.3","react-router":"^7.12.0","react-resizable-panels":"^4.6.4","rate-limiter-flexible":"^11.2.0","rollup-plugin-visualizer":"^6.0.3",sonner:"^2.0.7","tailwind-merge":"^3.5.0",tailwindcss:"^4.2.0",tsup:"^8.5.1",tsx:"^4.21.0","tw-animate-css":"^1.4.0",typescript:"^5.9.3",vite:"^8.0.16",vitest:"^4.1.0","wait-on":"^9.0.4",zod:"^4.2.0"}};var Sr=yt.version;function wt(){return Sr}var xt=wt(),Or=`<!doctype html>
2
2
  <html lang="en"><head><meta charset="utf-8"><title>Signed in</title><meta name="robots" content="noindex"><style>html,body{margin:0;height:100%;display:flex;align-items:center;justify-content:center;font-family:-apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif;color:#4b5563;background:#fff}</style></head>
3
3
  <body><div>Signed in. You can close this window.</div>
4
4
  <script>try{if(window.opener&&!window.opener.closed)window.opener.postMessage({type:"manufact:oauth-complete"},"*")}catch(e){}try{window.close()}catch(e){}</script>
5
- </body></html>`;function Sr(t,e,r){let n=[];t?.basePath!==void 0&&n.push(`<script>window.__MCP_BASE_PATH__ = ${JSON.stringify(t.basePath)};</script>`),t?.devMode&&n.push("<script>window.__MCP_DEV_MODE__ = true;</script>"),t?.sandboxOrigin&&n.push(`<script>window.__MCP_SANDBOX_ORIGIN__ = ${JSON.stringify(t.sandboxOrigin)};</script>`),t?.proxyUrl!==void 0&&n.push(`<script>window.__MCP_PROXY_URL__ = ${JSON.stringify(t.proxyUrl)};</script>`),t?.inspectorMode&&n.push(`<script>window.__MCP_INSPECTOR_MODE__ = ${JSON.stringify(t.inspectorMode)};</script>`),t?.manufactChatUrl&&n.push(`<script>window.__MANUFACT_CHAT_URL__ = ${JSON.stringify(t.manufactChatUrl)};</script>`),t?.disableTelemetry&&n.push('<script>window.__MCP_USE_ANONYMIZED_TELEMETRY__ = false;try{localStorage.setItem("MCP_USE_ANONYMIZED_TELEMETRY","false");}catch(e){}</script>'),process.env.MCP_USE_DEV_CLI==="1"&&n.push("<script>window.__MCP_DEV_CLI__ = true;</script>");let o=n.join(`
5
+ </body></html>`;function Cr(t,e,r){let n=[];t?.basePath!==void 0&&n.push(`<script>window.__MCP_BASE_PATH__ = ${JSON.stringify(t.basePath)};</script>`),t?.devMode&&n.push("<script>window.__MCP_DEV_MODE__ = true;</script>"),t?.sandboxOrigin&&n.push(`<script>window.__MCP_SANDBOX_ORIGIN__ = ${JSON.stringify(t.sandboxOrigin)};</script>`),t?.proxyUrl!==void 0&&n.push(`<script>window.__MCP_PROXY_URL__ = ${JSON.stringify(t.proxyUrl)};</script>`),t?.inspectorMode&&n.push(`<script>window.__MCP_INSPECTOR_MODE__ = ${JSON.stringify(t.inspectorMode)};</script>`),t?.manufactChatUrl&&n.push(`<script>window.__MANUFACT_CHAT_URL__ = ${JSON.stringify(t.manufactChatUrl)};</script>`),t?.disableTelemetry&&n.push('<script>window.__MCP_USE_ANONYMIZED_TELEMETRY__ = false;try{localStorage.setItem("MCP_USE_ANONYMIZED_TELEMETRY","false");}catch(e){}</script>'),process.env.MCP_USE_DEV_CLI==="1"&&n.push("<script>window.__MCP_DEV_CLI__ = true;</script>");let o=n.join(`
6
6
  `);return`<!doctype html>
7
7
  <html lang="en">
8
8
  <head>
9
9
  <meta charset="UTF-8" />
10
- ${et(`${e}/inspector/assets`)}
10
+ ${nt(`${e}/inspector/assets`)}
11
11
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
12
12
  <link rel="preconnect" href="https://fonts.googleapis.com" />
13
13
  <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
@@ -94,6 +94,6 @@ var Kt=Object.create;var Me=Object.defineProperty;var Vt=Object.getOwnPropertyDe
94
94
  </div>
95
95
  <script type="module" src="${r.jsUrl}"></script>
96
96
  </body>
97
- </html>`}function bt(t,e,r=""){let n=`${r}/inspector/assets`,o=encodeURIComponent(xt),s={jsUrl:`${n}/inspector.js?v=${o}`,cssUrl:`${n}/inspector.css?v=${o}`},i=u=>`${r}${u}`,a={...e,basePath:e?.basePath??r,proxyUrl:e?.proxyUrl!==void 0?e.proxyUrl:i("/inspector/api/proxy"),disableTelemetry:e?.disableTelemetry??process.env.MCP_USE_ANONYMIZED_TELEMETRY==="false"},c=u=>u.html(Sr(a,r,s));gt(t,n),t.get(i("/inspector/oauth-popup-closed.html"),u=>u.html(Ar)),t.get(i("/inspector"),c),t.get(`${i("/inspector")}/`,c);let l=i("/inspector/api/");t.get(i("/inspector/*"),u=>u.req.path.startsWith(l)?u.notFound():c(u)),t.post(i("/inspector/*"),u=>u.req.path.startsWith(l)?u.notFound():c(u)),r===""&&e?.rootRedirect!==!1&&t.get("/",u=>{let h=new URL(u.req.url);return u.redirect(`${i("/inspector")}${h.search}`)})}var Rt=t=>{let e={origin:"*",allowMethods:["GET","HEAD","PUT","POST","DELETE","PATCH"],allowHeaders:[],exposeHeaders:[],...t},r=(o=>typeof o=="string"?o==="*"?()=>o:s=>o===s?s:null:typeof o=="function"?o:s=>o.includes(s)?s:null)(e.origin),n=(o=>typeof o=="function"?o:Array.isArray(o)?()=>o:()=>[])(e.allowMethods);return async function(s,i){function a(l,u){s.res.headers.set(l,u)}let c=await r(s.req.header("origin")||"",s);if(c&&a("Access-Control-Allow-Origin",c),e.credentials&&a("Access-Control-Allow-Credentials","true"),e.exposeHeaders?.length&&a("Access-Control-Expose-Headers",e.exposeHeaders.join(",")),s.req.method==="OPTIONS"){e.origin!=="*"&&a("Vary","Origin"),e.maxAge!=null&&a("Access-Control-Max-Age",e.maxAge.toString());let l=await n(s.req.header("origin")||"",s);l.length&&a("Access-Control-Allow-Methods",l.join(","));let u=e.allowHeaders;if(!u?.length){let h=s.req.header("Access-Control-Request-Headers");h&&(u=h.split(/\s*,\s*/))}return u?.length&&(a("Access-Control-Allow-Headers",u.join(",")),s.res.headers.append("Vary","Access-Control-Request-Headers")),s.res.headers.delete("Content-Length"),s.res.headers.delete("Content-Type"),new Response(null,{headers:s.res.headers,status:204,statusText:"No Content"})}await i(),e.origin!=="*"&&s.header("Vary","Origin",{append:!0})}};function Or(){let{process:t,Deno:e}=globalThis;return!(typeof e?.noColor=="boolean"?e.noColor:t!==void 0?"NO_COLOR"in t?.env:!1)}async function vt(){let{navigator:t}=globalThis,e="cloudflare:workers";return!(t!==void 0&&t.userAgent==="Cloudflare-Workers"?await(async()=>{try{return"NO_COLOR"in((await import(e)).env??{})}catch{return!1}})():!Or())}var Cr=t=>{let[e,r]=[",","."];return t.map(o=>o.replace(/(\d)(?=(\d\d\d)+(?!\d))/g,"$1"+e)).join(r)},Ir=t=>{let e=Date.now()-t;return Cr([e<1e3?e+"ms":Math.round(e/1e3)+"s"])},Mr=async t=>{if(await vt())switch(t/100|0){case 5:return`\x1B[31m${t}\x1B[0m`;case 4:return`\x1B[33m${t}\x1B[0m`;case 3:return`\x1B[36m${t}\x1B[0m`;case 2:return`\x1B[32m${t}\x1B[0m`}return`${t}`};async function Et(t,e,r,n,o=0,s){let i=e==="<--"?`${e} ${r} ${n}`:`${e} ${r} ${n} ${await Mr(o)} ${s}`;t(i)}var _t=(t=console.log)=>async function(r,n){let{method:o,url:s}=r.req,i=s.slice(s.indexOf("/",8));await Et(t,"<--",o,i);let a=Date.now();await n(),await Et(t,"-->",o,i,r.res.status,Ir(a))};import{lookup as Tr}from"dns/promises";import{Buffer as kr}from"buffer";import{isIP as Lr}from"net";var Ur=new Set(["accept","authorization","content-type","dpop"]),jr=new Set(["cache-control","content-type","dpop-nonce","expires","pragma","retry-after","www-authenticate"]),Nr=[["registration_endpoint","registration"],["token_endpoint","token"],["revocation_endpoint","revocation"],["introspection_endpoint","introspection"]],Mt=600*1e3,Dr=100,Hr=1440*60*1e3,$r=500;function Ae(t,e={}){let{basePath:r="/oauth",allowedOrigins:n=[],allowLoopback:o=!1,timeoutMs:s=1e4,maxRequestBodyBytes:i=64*1024,maxResponseBodyBytes:a=1024*1024,callbackPath:c="/oauth/callback",enableLogging:l=!0,authenticate:u,validateServerUrl:h}=e,m=new Set(n.map(Pe)),p=new Map,g=new Map;t.use(`${r}/*`,async(d,y)=>{let f=d.req.header("Origin");if(f&&!Jr(f,d,m))return d.json({error:"Origin not allowed"},403);if(d.req.method==="OPTIONS")return Yr(f);await y(),f&&Dt(d.res.headers,f)}),t.get(`${r}/metadata`,async d=>{if(!await It(d,u))return d.json({error:"Unauthorized"},401);let y=await j(d.req.query("serverUrl"),o);if("error"in y)return d.json({error:y.error},400);let f=y.url;if(h&&!await h(f.toString(),d))return d.json({error:"MCP server URL not allowed"},403);let R=await j(d.req.query("url"),o);if("error"in R)return d.json({error:R.error},400);let A=R.url,C=I(f),v=Ot(p,C),x=Pt(f,A,v);if(!x&&v.authorizationServers.size===0)try{await At(f,v,o,s,a),p.set(C,v),x=Pt(f,A,v)}catch{}if(!x)return d.json({error:"Metadata target is not bound to this MCP server"},403);try{ve(l,`GET ${A}`);let _=await re(A,{method:"GET",headers:{Accept:"application/json"},redirect:"manual",signal:AbortSignal.timeout(s)});if(oe(_.status))return d.json({error:"OAuth metadata redirects are not allowed"},502);let b=await ne(_,a);if(!_.ok)return d.body(b,_.status,{"Content-Type":_.headers.get("content-type")??"application/json"});let P=_e(b);return x.type==="protected-resource"?await Lt(P,f,v,o):await Ut(P,x.issuer,v,o),v.updatedAt=Date.now(),p.set(C,v),Ct(p),d.body(b,200,{"Content-Type":_.headers.get("content-type")??"application/json"})}catch(_){return Ee(d,_,l)}}),t.post(`${r}/proxy`,async d=>{if(!await It(d,u))return d.json({error:"Unauthorized"},401);let y;try{y=JSON.parse(await Vr(d.req.raw,i))}catch(b){return d.json({error:b instanceof L?"Request body too large":"Invalid JSON request body"},b instanceof L?413:400)}let f=await j(y.serverUrl,o);if("error"in f)return d.json({error:f.error},400);let R=f.url;if(h&&!await h(R.toString(),d))return d.json({error:"MCP server URL not allowed"},403);let A=await j(y.url,o);if("error"in A)return d.json({error:A.error},400);let C=A.url;if(y.method!==void 0&&y.method!=="POST")return d.json({error:"Only OAuth endpoint POST is allowed"},405);let v=I(R),x=Ot(p,v);if(x.endpoints.size===0)try{await At(R,x,o,s,a),p.set(v,x),Ct(p)}catch(b){return Ee(d,b,l)}let _=x.endpoints.get(I(C));if(!_)return d.json({error:"OAuth endpoint is not bound to this MCP server"},403);try{let b=Br(y.headers),P=qr(y.body,b);if(_==="registration"){let Wt=Pe(d.req.header("Origin")??new URL(d.req.url).origin);P=Gr(P,b,new URL(c,Wt).toString())}else P=Wr({body:P,headers:b,bindingKey:v,clients:g});if(new TextEncoder().encode(P??"").byteLength>i)return d.json({error:"OAuth request body too large"},413);ve(l,`POST ${_} ${C}`);let E=await re(C,{method:"POST",headers:b,body:P,redirect:"manual",signal:AbortSignal.timeout(s)});if(oe(E.status))return d.json({error:"OAuth endpoint redirects are not allowed"},502);let M=await ne(E,a),H=Fr(E.headers),N=E.headers.get("content-type")??"",O=M;if(N.includes("json"))try{O=JSON.parse(M)}catch{}return _==="registration"&&E.ok&&O&&typeof O=="object"&&!Array.isArray(O)&&(O=zr({responseBody:O,binding:x,bindingKey:v,clients:g})),d.json({status:E.status,statusText:E.statusText,headers:H,body:O})}catch(b){return Ee(d,b,l)}}),ve(l,`Mounted at ${r}/metadata and ${r}/proxy`)}async function j(t,e){if(typeof t!="string"||!t)return{error:"Missing or invalid URL"};let r;try{r=new URL(t)}catch{return{error:"Invalid URL"}}if(r.username||r.password||r.hash)return{error:"URL credentials and fragments are not allowed"};let n=Xr(r.hostname);if(r.protocol!=="https:"&&!(e&&n&&r.protocol==="http:"))return{error:"HTTPS is required"};if(n)return e?{url:r}:{error:"Loopback URL not allowed"};if(Qr(r.hostname))return{error:"Local network URL not allowed"};try{let o=Lr(r.hostname)?[r.hostname]:(await Tr(r.hostname,{all:!0,verbatim:!0})).map(({address:s})=>s);if(o.length===0||o.some(s=>!Ht(s)))return{error:"Private or non-routable URL not allowed"}}catch{return{error:"URL hostname could not be resolved"}}return{url:r}}async function Se(t,e=!1){return!("error"in await j(t,e))}function Pt(t,e,r){let n=I(e);if(Tt(t).some(o=>I(o)===n))return{type:"protected-resource"};for(let o of r.authorizationServers)if(kt(new URL(o)).some(s=>I(s)===n))return{type:"authorization-server",issuer:o}}function Tt(t){let e=t.pathname==="/"?"":t.pathname;return[new URL(`/.well-known/oauth-protected-resource${e}`,t.origin),new URL("/.well-known/oauth-protected-resource",t.origin)]}function kt(t){let e=t.pathname==="/"?"":t.pathname;return[new URL(`/.well-known/oauth-authorization-server${e}`,t.origin),new URL(`/.well-known/openid-configuration${e}`,t.origin),new URL(`${e||""}/.well-known/openid-configuration`,t.origin)]}async function Lt(t,e,r,n){if(typeof t.resource!="string"||I(new URL(t.resource))!==I(e))throw new S("Protected-resource metadata does not match serverUrl");if(!Array.isArray(t.authorization_servers)||t.authorization_servers.length===0)throw new S("Protected-resource metadata has no authorization servers");let o=new Set;for(let s of t.authorization_servers){let i=await j(s,n);if("error"in i)throw new S(`Unsafe authorization server: ${i.error}`);o.add(I(i.url))}r.authorizationServers=o,r.endpoints.clear(),r.tokenEndpointAuthMethods.clear()}async function Ut(t,e,r,n){if(typeof t.issuer!="string"||I(new URL(t.issuer))!==e)throw new S("Authorization-server metadata issuer mismatch");r.endpoints.clear(),r.tokenEndpointAuthMethods=new Set(Array.isArray(t.token_endpoint_auth_methods_supported)?t.token_endpoint_auth_methods_supported.filter(o=>typeof o=="string"):[]);for(let[o,s]of Nr){let i=t[o];if(i===void 0)continue;let a=await j(i,n);if("error"in a)throw new S(`Unsafe ${o}: ${a.error}`);r.endpoints.set(I(a.url),s)}}async function At(t,e,r,n,o){for(let s of Tt(t)){let i=await re(s,{method:"GET",headers:{Accept:"application/json"},redirect:"manual",signal:AbortSignal.timeout(n)});if(oe(i.status))throw new S("OAuth metadata redirects are not allowed");if(i.ok){await Lt(_e(await ne(i,o)),t,e,r);break}}if(e.authorizationServers.size===0)throw new S("Protected-resource metadata could not be discovered");for(let s of e.authorizationServers){let i=!1;for(let a of kt(new URL(s))){let c=await re(a,{method:"GET",headers:{Accept:"application/json"},redirect:"manual",signal:AbortSignal.timeout(n)});if(oe(c.status))throw new S("OAuth metadata redirects are not allowed");if(c.ok){await Ut(_e(await ne(c,o)),s,e,r),i=!0;break}}if(i)break}if(e.endpoints.size===0)throw new S("Authorization-server metadata could not be discovered");e.updatedAt=Date.now()}async function re(t,e){return fetch(t,e)}function Br(t){let e=new Headers;if(!t||typeof t!="object"||Array.isArray(t))return e;for(let[r,n]of Object.entries(t)){let o=r.toLowerCase();Ur.has(o)&&typeof n=="string"&&e.set(o,n)}return e}function Fr(t){let e={};return t.forEach((r,n)=>{jr.has(n.toLowerCase())&&(e[n]=r)}),e}function qr(t,e){if(t==null)return;if(typeof t=="string"){if(!e.has("content-type"))try{JSON.parse(t),e.set("content-type","application/json")}catch{e.set("content-type","application/x-www-form-urlencoded")}return t}if((e.get("content-type")??"").includes("application/x-www-form-urlencoded")&&typeof t=="object"&&!Array.isArray(t)){let n=new URLSearchParams;for(let[o,s]of Object.entries(t))n.append(o,String(s));return n.toString()}return e.has("content-type")||e.set("content-type","application/json"),JSON.stringify(t)}function jt(t,e){return`${t}\0${e}`}function zr(t){let{responseBody:e,binding:r,bindingKey:n,clients:o}=t,s=e.client_id,i=e.client_secret;if(typeof s!="string"||typeof i!="string")return e;let a=e.token_endpoint_auth_method,c=a==="client_secret_post"||a==="client_secret_basic"?a:r.tokenEndpointAuthMethods.has("client_secret_basic")?"client_secret_basic":"client_secret_post",l=e.client_secret_expires_at,u=l===0?Number.POSITIVE_INFINITY:typeof l=="number"&&l>0?l*1e3:Date.now()+Hr;for(Kr(o),o.set(jt(n,s),{clientSecret:i,authMethod:c,expiresAt:u});o.size>$r;){let m=o.keys().next().value;if(!m)break;o.delete(m)}let h={...e};return delete h.client_secret,delete h.client_secret_expires_at,h.token_endpoint_auth_method="none",h}function Wr(t){let{body:e,headers:r,bindingKey:n,clients:o}=t;if(!e||!(r.get("content-type")??"").includes("application/x-www-form-urlencoded"))return e;let s=new URLSearchParams(e),i=s.get("client_id");if(!i)return e;let a=jt(n,i),c=o.get(a);if(!c)return e;if(c.expiresAt<=Date.now())return o.delete(a),e;if(s.delete("client_secret"),c.authMethod==="client_secret_basic"){let l=kr.from(`${St(i)}:${St(c.clientSecret)}`,"utf8").toString("base64");r.set("authorization",`Basic ${l}`)}else r.delete("authorization"),s.set("client_id",i),s.set("client_secret",c.clientSecret);return s.toString()}function St(t){return new URLSearchParams({value:t}).toString().slice(6)}function Kr(t){let e=Date.now();for(let[r,n]of t)n.expiresAt<=e&&t.delete(r)}async function Vr(t,e){let r=Number(t.headers.get("content-length"));if(Number.isFinite(r)&&r>e)throw new L;return Nt(t.body,e)}async function ne(t,e){let r=Number(t.headers.get("content-length"));if(Number.isFinite(r)&&r>e)throw await t.body?.cancel(),new L;return Nt(t.body,e)}async function Nt(t,e){if(!t)return"";let r=t.getReader(),n=[],o=0;for(;;){let{done:a,value:c}=await r.read();if(a)break;if(o+=c.byteLength,o>e)throw await r.cancel(),new L;n.push(c)}let s=new Uint8Array(o),i=0;for(let a of n)s.set(a,i),i+=a.byteLength;return new TextDecoder().decode(s)}function _e(t){let e;try{e=JSON.parse(t)}catch{throw new S("OAuth metadata is not valid JSON")}if(!e||typeof e!="object"||Array.isArray(e))throw new S("OAuth metadata is not an object");return e}function Ot(t,e){let r=t.get(e);return r&&Date.now()-r.updatedAt<=Mt?r:(t.delete(e),{authorizationServers:new Set,endpoints:new Map,tokenEndpointAuthMethods:new Set,updatedAt:Date.now()})}function Ct(t){let e=Date.now();for(let[r,n]of t)e-n.updatedAt>Mt&&t.delete(r);for(;t.size>Dr;){let r=t.keys().next().value;if(!r)break;t.delete(r)}}function I(t){let e=new URL(t);return e.hash="",(e.protocol==="https:"&&e.port==="443"||e.protocol==="http:"&&e.port==="80")&&(e.port=""),e.toString().replace(/\/$/,"")}function Gr(t,e,r){if(!t||!(e.get("content-type")??"").includes("json"))return t;try{let o=JSON.parse(t);return!o||typeof o!="object"||Array.isArray(o)?t:JSON.stringify({...o,redirect_uris:[r]})}catch{return t}}function Pe(t){let e=new URL(t);if(e.pathname!=="/"||e.search||e.hash)throw new Error(`OAuth proxy allowed origin must be an origin: ${t}`);return e.origin}function Jr(t,e,r){try{let n=Pe(t);if(n===new URL(e.req.url).origin||r.has(n))return!0;let o=new URL(n),i=e.req.header("x-forwarded-host")?.split(",")[0]?.trim()||e.req.header("host");if(!i||o.host!==i)return!1;let a=e.req.header("x-forwarded-proto")?.split(",")[0]?.trim();return!a||`${a}:`===o.protocol}catch{return!1}}function Yr(t){let e=new Headers;return t&&Dt(e,t),e.set("Access-Control-Allow-Methods","GET, POST, OPTIONS"),e.set("Access-Control-Allow-Headers","Accept, Authorization, Content-Type"),e.set("Access-Control-Max-Age","600"),new Response(null,{status:204,headers:e})}function Dt(t,e){t.set("Access-Control-Allow-Origin",e),t.append("Vary","Origin")}async function It(t,e){return e?e(t):!0}function oe(t){return t>=300&&t<400}function Xr(t){let e=t.toLowerCase().replace(/^\[|\]$/g,"");return e==="localhost"||e.endsWith(".localhost")||e==="::1"||e.startsWith("127.")}function Qr(t){let e=t.toLowerCase();return e.endsWith(".local")||e.endsWith(".internal")||e.endsWith(".home.arpa")}function Ht(t){if(t.includes(":")){let s=t.toLowerCase();return s.startsWith("::ffff:")?Ht(s.slice(7)):!(s==="::"||s==="::1"||s.startsWith("fc")||s.startsWith("fd")||/^fe[89ab]/.test(s)||s.startsWith("ff")||s.startsWith("2001:db8:"))}let e=t.split(".").map(Number);if(e.length!==4||e.some(s=>!Number.isInteger(s)))return!1;let[r,n,o]=e;return!(r===0||r===10||r===127||r===100&&n>=64&&n<=127||r===169&&n===254||r===172&&n>=16&&n<=31||r===192&&n===0&&o===0||r===192&&n===0&&o===2||r===192&&n===168||r===198&&(n===18||n===19)||r===198&&n===51&&o===100||r===203&&n===0&&o===113||r>=224)}function ve(t,e){t&&console.log(`[OAuth BFF] ${e}`)}function Ee(t,e,r){let n=e instanceof Error?e.message:"Unknown error";return r&&console.error("[OAuth BFF]",n),e instanceof L?t.json({error:"Upstream response too large"},502):e instanceof S?t.json({error:e.message},502):e instanceof DOMException&&e.name==="TimeoutError"?t.json({error:"OAuth upstream timed out"},504):t.json({error:"OAuth upstream request failed"},502)}var L=class extends Error{},S=class extends Error{};var Zr=3;function en(t,e){return t.includes("text/event-stream")&&!e}function Oe(t,e={}){let r=e.path||"/mcp/proxy",n=e.enableLogging!==!1;t.use(`${r}/*`,Rt({origin:"*",allowHeaders:["Authorization","Content-Type","Accept","X-Target-URL","X-MCP-Target","Mcp-Session-Id","mcp-session-id","mcp-protocol-version","X-Server-Id","X-Requested-With"],exposeHeaders:["*"]})),n&&t.use(`${r}/*`,_t()),t.all(`${r}/*`,async o=>{try{if(e.authenticate&&!await e.authenticate(o))return o.json({error:"Unauthorized"},401);let s=o.req.header("X-Target-URL");if(!s)return o.json({error:"X-Target-URL header is required",usage:"Set X-Target-URL header to the MCP server URL you want to proxy to"},400);if(!await Se(s,e.allowLoopback??!1))return o.json({error:"Invalid target URL",details:"Target is not allowed by the proxy network policy"},403);if(e.validateRequest&&!await e.validateRequest(s,o))return o.json({error:"Invalid target URL",details:"The requested target URL is not allowed"},403);try{new URL(s)}catch{return o.json({error:"Invalid target URL format",details:"The X-Target-URL must be a valid HTTP/HTTPS URL"},400)}let i=o.req.method,a={},c=o.req.header();for(let[p,g]of Object.entries(c)){let d=p.toLowerCase();!d.startsWith("x-proxy-")&&!d.startsWith("x-target-")&&!d.startsWith("x-mcp-")&&!d.startsWith("x-forwarded-")&&!d.startsWith("cf-")&&d!=="x-original-host"&&d!=="host"&&d!=="origin"&&d!=="referer"&&d!=="cookie"&&d!=="proxy-authorization"&&d!=="accept-encoding"&&d!=="cdn-loop"&&!d.startsWith("sec-fetch-")&&(a[p]=g)}a["Accept-Encoding"]="identity";let l=i!=="GET"&&i!=="HEAD"?new Uint8Array(await o.req.arrayBuffer()).slice():void 0,u=s,h=i,m=l;for(let p=0;;p+=1){let g=await fetch(u,{method:h,headers:a,body:m,redirect:"manual"}),d=g.headers.get("location");if(!(g.status>=300&&g.status<400&&d))return tn(g);if(p>=Zr)return o.json({error:"Too many upstream redirects"},502);let y=new URL(d,u);if(!await Se(y.toString(),e.allowLoopback??!1)||e.validateRequest&&!await e.validateRequest(y.toString(),o))return o.json({error:"Redirect target is not allowed"},403);y.origin!==new URL(u).origin&&(se(a,"authorization"),se(a,"proxy-authorization")),(g.status===303||(g.status===301||g.status===302)&&h==="POST")&&(h="GET",m=void 0,se(a,"content-type"),se(a,"content-length")),u=y.toString()}}catch(s){let i=s instanceof Error?s.message:"Unknown error",a=o.req.header("X-Target-URL");return s instanceof Error&&(s.message.includes("ECONNREFUSED")||s.message.includes("fetch failed"))?console.warn(`[MCP Proxy] Connection refused to ${a||"unknown target"} - server may not be running`):console.error("[MCP Proxy] Request failed:",i,`
98
- Target URL:`,a||"unknown",`
99
- Error:`,s),o.json({error:"Proxy request failed",details:i,targetUrl:a||"unknown"},500)}})}function se(t,e){for(let r of Object.keys(t))r.toLowerCase()===e&&delete t[r]}async function tn(t){let e={};if(t.headers.forEach((o,s)=>{let i=s.toLowerCase();i!=="content-encoding"&&i!=="transfer-encoding"&&i!=="content-length"&&i!=="set-cookie"&&(e[s]=o)}),en(t.headers.get("content-type")||"",t.headers.get("content-length")))return new Response(t.body,{status:t.status,statusText:t.statusText,headers:e});if([204,205,304].includes(t.status))return new Response(null,{status:t.status,statusText:t.statusText,headers:e});let n=await t.arrayBuffer();return e["Content-Length"]=String(n.byteLength),new Response(n,{status:t.status,statusText:t.statusText,headers:e})}function Ce(t,e,r=""){let n=i=>`${r}${i}`,o=e?.oauthProxyAllowLoopback??!1,s=e?.oauth!==!1;if(t.use(n("/inspector/api/*"),te({points:ft,durationSeconds:ee,key:"inspector-api"})),t.get(n("/inspector/health"),i=>i.json({status:"ok",protocol:"mcp-use-inspector-preview",version:1,capabilities:["view-preview"]})),Oe(t,{path:n("/inspector/api/proxy"),allowLoopback:o}),s&&Ae(t,{basePath:n("/inspector/api/oauth"),callbackPath:n("/inspector/oauth/callback"),enableLogging:!0,allowedOrigins:e?.oauthProxyAllowedOrigins??[],allowLoopback:o}),e?.autoConnectUrl!==void 0){let i=e.autoConnectUrl;t.get(n("/inspector/config.json"),a=>a.json({autoConnectUrl:i??null}))}}function nn(t,e){if(un(t)){let o=t,s=e,i=Ft(s?.basePath);if(zt(o)){qt(o,s,i);return}let a=$t(s,i),c=Bt(a);o.use(on(c,a.routes.map(l=>l.path)));return}let r=t,n=Ft(r?.basePath);return Bt($t(r,n))}function $t(t,e){let r=new we;return qt(r,t,e),r}function qt(t,e,r){let n={oauthProxyAllowedOrigins:e?.oauthProxyAllowedOrigins??[],oauthProxyAllowLoopback:e?.oauthProxyAllowLoopback??!0};e?.autoConnectUrl!==void 0?n.autoConnectUrl=e.autoConnectUrl:t.get(`${r}/inspector/config.json`,o=>{let s=new URL(o.req.url);return o.json({autoConnectUrl:`${s.origin}${r}`})}),Ce(t,n,r),bt(t,{devMode:e?.devMode??!0,sandboxOrigin:e?.sandboxOrigin,inspectorMode:"embedded",rootRedirect:!1,basePath:r,proxyUrl:`${r}/inspector/api/proxy`,manufactChatUrl:e?.manufactChatUrl},r)}function Bt(t){return e=>Promise.resolve(t.fetch(e))}function on(t,e){let r=new Set(e.filter(o=>!o.includes("*"))),n=e.filter(o=>o.endsWith("/*")).map(o=>o.slice(0,-1));return(o,s,i)=>{let a=new URL(o.originalUrl||o.url||"",sn(o));if(!r.has(a.pathname)&&!n.some(l=>a.pathname.startsWith(l))){i();return}let c=an(o,a);t(c).then(l=>ln(s,l)).catch(i)}}function sn(t){let r=Ie(t.headers["x-forwarded-proto"])||t.protocol||"http",o=Ie(t.headers["x-forwarded-host"])||Ie(t.headers.host)||"localhost";return`${r}://${o}`}function Ie(t){return Array.isArray(t)?t[0]??"":(t??"").split(",")[0].trim()}function an(t,e){let r={method:t.method,headers:t.headers};return t.method!=="GET"&&t.method!=="HEAD"&&(t.body!==void 0?r.body=cn(t.body):(r.body=rn.toWeb(t),r.duplex="half")),new globalThis.Request(e,r)}function cn(t){return typeof t=="string"||t instanceof ArrayBuffer||ArrayBuffer.isView(t)||t instanceof Blob||t instanceof FormData||t instanceof URLSearchParams||t instanceof ReadableStream?t:JSON.stringify(t)}async function ln(t,e){t.status(e.status),e.headers.forEach((o,s)=>{s!=="set-cookie"&&t.setHeader(s,o)});let r=e.headers.getSetCookie();if(r.length>0&&t.setHeader("set-cookie",r),!e.body){t.end();return}let n=e.body.getReader();for(;;){let{done:o,value:s}=await n.read();if(o)break;t.write(s)}t.end()}function un(t){return!t||typeof t!="object"&&typeof t!="function"?!1:typeof t.use=="function"||zt(t)}function zt(t){return!!t&&typeof t=="object"&&typeof t.fetch=="function"&&typeof t.route=="function"}function Ft(t){if(t===void 0)return"/mcp";let e=t.trim(),r=[],n=!1;for(let s of e)s==="/"?(n||r.push(s),n=!0):(r.push(s),n=!1);for(;r.length>0&&r[r.length-1]==="/";)r.pop();let o=r.join("");return o===""||o==="/"?"":(o.startsWith("/")||(o=`/${o}`),o)}export{nn as mountInspector,Ce as registerInspectorProxyRoutes};
97
+ </html>`}function bt(t,e,r=""){let n=`${r}/inspector/assets`,o=encodeURIComponent(xt),s={jsUrl:`${n}/inspector.js?v=${o}`,cssUrl:`${n}/inspector.css?v=${o}`},i=l=>`${r}${l}`,a={...e,basePath:e?.basePath??r,proxyUrl:e?.proxyUrl!==void 0?e.proxyUrl:i("/inspector/api/proxy"),disableTelemetry:e?.disableTelemetry??process.env.MCP_USE_ANONYMIZED_TELEMETRY==="false"},c=l=>l.html(Cr(a,r,s));gt(t,n),t.get(i("/inspector/oauth-popup-closed.html"),l=>l.html(Or)),t.get(i("/inspector"),c),t.get(`${i("/inspector")}/`,c);let u=i("/inspector/api/");t.get(i("/inspector/*"),l=>l.req.path.startsWith(u)?l.notFound():c(l)),t.post(i("/inspector/*"),l=>l.req.path.startsWith(u)?l.notFound():c(l)),r===""&&e?.rootRedirect!==!1&&t.get("/",l=>{let h=new URL(l.req.url);return l.redirect(`${i("/inspector")}${h.search}`)})}var Rt=t=>{let e={origin:"*",allowMethods:["GET","HEAD","PUT","POST","DELETE","PATCH"],allowHeaders:[],exposeHeaders:[],...t},r=(o=>typeof o=="string"?o==="*"?()=>o:s=>o===s?s:null:typeof o=="function"?o:s=>o.includes(s)?s:null)(e.origin),n=(o=>typeof o=="function"?o:Array.isArray(o)?()=>o:()=>[])(e.allowMethods);return async function(s,i){function a(u,l){s.res.headers.set(u,l)}let c=await r(s.req.header("origin")||"",s);if(c&&a("Access-Control-Allow-Origin",c),e.credentials&&a("Access-Control-Allow-Credentials","true"),e.exposeHeaders?.length&&a("Access-Control-Expose-Headers",e.exposeHeaders.join(",")),s.req.method==="OPTIONS"){e.origin!=="*"&&a("Vary","Origin"),e.maxAge!=null&&a("Access-Control-Max-Age",e.maxAge.toString());let u=await n(s.req.header("origin")||"",s);u.length&&a("Access-Control-Allow-Methods",u.join(","));let l=e.allowHeaders;if(!l?.length){let h=s.req.header("Access-Control-Request-Headers");h&&(l=h.split(/\s*,\s*/))}return l?.length&&(a("Access-Control-Allow-Headers",l.join(",")),s.res.headers.append("Vary","Access-Control-Request-Headers")),s.res.headers.delete("Content-Length"),s.res.headers.delete("Content-Type"),new Response(null,{headers:s.res.headers,status:204,statusText:"No Content"})}await i(),e.origin!=="*"&&s.header("Vary","Origin",{append:!0})}};function Ir(){let{process:t,Deno:e}=globalThis;return!(typeof e?.noColor=="boolean"?e.noColor:t!==void 0?"NO_COLOR"in t?.env:!1)}async function vt(){let{navigator:t}=globalThis,e="cloudflare:workers";return!(t!==void 0&&t.userAgent==="Cloudflare-Workers"?await(async()=>{try{return"NO_COLOR"in((await import(e)).env??{})}catch{return!1}})():!Ir())}var Tr=t=>{let[e,r]=[",","."];return t.map(o=>o.replace(/(\d)(?=(\d\d\d)+(?!\d))/g,"$1"+e)).join(r)},Mr=t=>{let e=Date.now()-t;return Tr([e<1e3?e+"ms":Math.round(e/1e3)+"s"])},Lr=async t=>{if(await vt())switch(t/100|0){case 5:return`\x1B[31m${t}\x1B[0m`;case 4:return`\x1B[33m${t}\x1B[0m`;case 3:return`\x1B[36m${t}\x1B[0m`;case 2:return`\x1B[32m${t}\x1B[0m`}return`${t}`};async function Et(t,e,r,n,o=0,s){let i=e==="<--"?`${e} ${r} ${n}`:`${e} ${r} ${n} ${await Lr(o)} ${s}`;t(i)}var _t=(t=console.log)=>async function(r,n){let{method:o,url:s}=r.req,i=s.slice(s.indexOf("/",8));await Et(t,"<--",o,i);let a=Date.now();await n(),await Et(t,"-->",o,i,r.res.status,Mr(a))};import{lookup as kr}from"dns/promises";import{Buffer as Ur}from"buffer";import{isIP as Nr}from"net";var jr=new Set(["accept","authorization","content-type","dpop"]),Dr=new Set(["cache-control","content-type","dpop-nonce","expires","pragma","retry-after","www-authenticate"]),Hr=[["registration_endpoint","registration"],["token_endpoint","token"],["revocation_endpoint","revocation"],["introspection_endpoint","introspection"]],Tt=600*1e3,$r=100,Br=1440*60*1e3,Fr=500;function Ce(t,e={}){let{basePath:r="/oauth",allowedOrigins:n=[],allowLoopback:o=!1,timeoutMs:s=1e4,maxRequestBodyBytes:i=64*1024,maxResponseBodyBytes:a=1024*1024,callbackPath:c="/oauth/callback",enableLogging:u=!0,authenticate:l,validateServerUrl:h,rateLimiter:p=new M.default({points:120,duration:60})}=e,f=new Set(n.map(Oe)),y=new Map,w=new Map,g=async(d,m)=>{try{await p.consume(d.req)}catch(b){return q(d,b)}return m()};t.use(`${r}/*`,async(d,m)=>{let b=d.req.header("Origin");if(b&&!Xr(b,d,f))return d.json({error:"Origin not allowed"},403);if(d.req.method==="OPTIONS")return Qr(b);await m(),b&&Dt(d.res.headers,b)}),t.use(`${r}/*`,g),t.get(`${r}/metadata`,async d=>{if(!await It(d,l))return d.json({error:"Unauthorized"},401);let m=await B(d.req.query("serverUrl"),o);if("error"in m)return d.json({error:m.error},400);let b=m.url;if(h&&!await h(b.toString(),d))return d.json({error:"MCP server URL not allowed"},403);let O=await B(d.req.query("url"),o);if("error"in O)return d.json({error:O.error},400);let C=O.url,E=T(b),_=Ot(y,E),A=Pt(b,C,_);if(!A&&_.authorizationServers.size===0)try{await At(b,_,o,s,a),y.set(E,_),A=Pt(b,C,_)}catch{}if(!A)return d.json({error:"Metadata target is not bound to this MCP server"},403);try{Pe(u,`GET ${C}`);let v=await se(C,{method:"GET",headers:{Accept:"application/json"},redirect:"manual",signal:AbortSignal.timeout(s)});if(ae(v.status))return d.json({error:"OAuth metadata redirects are not allowed"},502);let x=await ie(v,a);if(!v.ok)return d.body(x,v.status,{"Content-Type":v.headers.get("content-type")??"application/json"});let P=Se(x);return A.type==="protected-resource"?await kt(P,b,_,o):await Ut(P,A.issuer,_,o),_.updatedAt=Date.now(),y.set(E,_),Ct(y),d.body(x,200,{"Content-Type":v.headers.get("content-type")??"application/json"})}catch(v){return Ae(d,v,u)}}),t.post(`${r}/proxy`,async d=>{if(!await It(d,l))return d.json({error:"Unauthorized"},401);let m;try{m=JSON.parse(await Jr(d.req.raw,i))}catch(x){return d.json({error:x instanceof U?"Request body too large":"Invalid JSON request body"},x instanceof U?413:400)}let b=await B(m.serverUrl,o);if("error"in b)return d.json({error:b.error},400);let O=b.url;if(h&&!await h(O.toString(),d))return d.json({error:"MCP server URL not allowed"},403);let C=await B(m.url,o);if("error"in C)return d.json({error:C.error},400);let E=C.url;if(m.method!==void 0&&m.method!=="POST")return d.json({error:"Only OAuth endpoint POST is allowed"},405);let _=T(O),A=Ot(y,_);if(A.endpoints.size===0)try{await At(O,A,o,s,a),y.set(_,A),Ct(y)}catch(x){return Ae(d,x,u)}let v=A.endpoints.get(T(E));if(!v)return d.json({error:"OAuth endpoint is not bound to this MCP server"},403);try{let x=qr(m.headers),P=Wr(m.body,x);if(v==="registration"){let Kt=Oe(d.req.header("Origin")??new URL(d.req.url).origin);P=Yr(P,x,new URL(c,Kt).toString())}else P=Vr({body:P,headers:x,bindingKey:_,clients:w});if(new TextEncoder().encode(P??"").byteLength>i)return d.json({error:"OAuth request body too large"},413);Pe(u,`POST ${v} ${E}`);let I=await se(E,{method:"POST",headers:x,body:P,redirect:"manual",signal:AbortSignal.timeout(s)});if(ae(I.status))return d.json({error:"OAuth endpoint redirects are not allowed"},502);let N=await ie(I,a),j=zr(I.headers),Wt=I.headers.get("content-type")??"",D=N;if(Wt.includes("json"))try{D=JSON.parse(N)}catch{}return v==="registration"&&I.ok&&D&&typeof D=="object"&&!Array.isArray(D)&&(D=Kr({responseBody:D,binding:A,bindingKey:_,clients:w})),d.json({status:I.status,statusText:I.statusText,headers:j,body:D})}catch(x){return Ae(d,x,u)}}),Pe(u,`Mounted at ${r}/metadata and ${r}/proxy`)}async function B(t,e){if(typeof t!="string"||!t)return{error:"Missing or invalid URL"};let r;try{r=new URL(t)}catch{return{error:"Invalid URL"}}if(r.username||r.password||r.hash)return{error:"URL credentials and fragments are not allowed"};let n=Zr(r.hostname);if(r.protocol!=="https:"&&!(e&&n&&r.protocol==="http:"))return{error:"HTTPS is required"};if(n)return e?{url:r}:{error:"Loopback URL not allowed"};if(en(r.hostname))return{error:"Local network URL not allowed"};try{let o=Nr(r.hostname)?[r.hostname]:(await kr(r.hostname,{all:!0,verbatim:!0})).map(({address:s})=>s);if(o.length===0||o.some(s=>!Ht(s)))return{error:"Private or non-routable URL not allowed"}}catch{return{error:"URL hostname could not be resolved"}}return{url:r}}async function Ie(t,e=!1){return!("error"in await B(t,e))}function Pt(t,e,r){let n=T(e);if(Mt(t).some(o=>T(o)===n))return{type:"protected-resource"};for(let o of r.authorizationServers)if(Lt(new URL(o)).some(s=>T(s)===n))return{type:"authorization-server",issuer:o}}function Mt(t){let e=t.pathname==="/"?"":t.pathname;return[new URL(`/.well-known/oauth-protected-resource${e}`,t.origin),new URL("/.well-known/oauth-protected-resource",t.origin)]}function Lt(t){let e=t.pathname==="/"?"":t.pathname;return[new URL(`/.well-known/oauth-authorization-server${e}`,t.origin),new URL(`/.well-known/openid-configuration${e}`,t.origin),new URL(`${e||""}/.well-known/openid-configuration`,t.origin)]}async function kt(t,e,r,n){if(typeof t.resource!="string"||T(new URL(t.resource))!==T(e))throw new S("Protected-resource metadata does not match serverUrl");if(!Array.isArray(t.authorization_servers)||t.authorization_servers.length===0)throw new S("Protected-resource metadata has no authorization servers");let o=new Set;for(let s of t.authorization_servers){let i=await B(s,n);if("error"in i)throw new S(`Unsafe authorization server: ${i.error}`);o.add(T(i.url))}r.authorizationServers=o,r.endpoints.clear(),r.tokenEndpointAuthMethods.clear()}async function Ut(t,e,r,n){if(typeof t.issuer!="string"||T(new URL(t.issuer))!==e)throw new S("Authorization-server metadata issuer mismatch");r.endpoints.clear(),r.tokenEndpointAuthMethods=new Set(Array.isArray(t.token_endpoint_auth_methods_supported)?t.token_endpoint_auth_methods_supported.filter(o=>typeof o=="string"):[]);for(let[o,s]of Hr){let i=t[o];if(i===void 0)continue;let a=await B(i,n);if("error"in a)throw new S(`Unsafe ${o}: ${a.error}`);r.endpoints.set(T(a.url),s)}}async function At(t,e,r,n,o){for(let s of Mt(t)){let i=await se(s,{method:"GET",headers:{Accept:"application/json"},redirect:"manual",signal:AbortSignal.timeout(n)});if(ae(i.status))throw new S("OAuth metadata redirects are not allowed");if(i.ok){await kt(Se(await ie(i,o)),t,e,r);break}}if(e.authorizationServers.size===0)throw new S("Protected-resource metadata could not be discovered");for(let s of e.authorizationServers){let i=!1;for(let a of Lt(new URL(s))){let c=await se(a,{method:"GET",headers:{Accept:"application/json"},redirect:"manual",signal:AbortSignal.timeout(n)});if(ae(c.status))throw new S("OAuth metadata redirects are not allowed");if(c.ok){await Ut(Se(await ie(c,o)),s,e,r),i=!0;break}}if(i)break}if(e.endpoints.size===0)throw new S("Authorization-server metadata could not be discovered");e.updatedAt=Date.now()}async function se(t,e){return fetch(t,e)}function qr(t){let e=new Headers;if(!t||typeof t!="object"||Array.isArray(t))return e;for(let[r,n]of Object.entries(t)){let o=r.toLowerCase();jr.has(o)&&typeof n=="string"&&e.set(o,n)}return e}function zr(t){let e={};return t.forEach((r,n)=>{Dr.has(n.toLowerCase())&&(e[n]=r)}),e}function Wr(t,e){if(t==null)return;if(typeof t=="string"){if(!e.has("content-type"))try{JSON.parse(t),e.set("content-type","application/json")}catch{e.set("content-type","application/x-www-form-urlencoded")}return t}if((e.get("content-type")??"").includes("application/x-www-form-urlencoded")&&typeof t=="object"&&!Array.isArray(t)){let n=new URLSearchParams;for(let[o,s]of Object.entries(t))n.append(o,String(s));return n.toString()}return e.has("content-type")||e.set("content-type","application/json"),JSON.stringify(t)}function Nt(t,e){return`${t}\0${e}`}function Kr(t){let{responseBody:e,binding:r,bindingKey:n,clients:o}=t,s=e.client_id,i=e.client_secret;if(typeof s!="string"||typeof i!="string")return e;let a=e.token_endpoint_auth_method,c=a==="client_secret_post"||a==="client_secret_basic"?a:r.tokenEndpointAuthMethods.has("client_secret_basic")?"client_secret_basic":"client_secret_post",u=e.client_secret_expires_at,l=u===0?Number.POSITIVE_INFINITY:typeof u=="number"&&u>0?u*1e3:Date.now()+Br;for(Gr(o),o.set(Nt(n,s),{clientSecret:i,authMethod:c,expiresAt:l});o.size>Fr;){let p=o.keys().next().value;if(!p)break;o.delete(p)}let h={...e};return delete h.client_secret,delete h.client_secret_expires_at,h.token_endpoint_auth_method="none",h}function Vr(t){let{body:e,headers:r,bindingKey:n,clients:o}=t;if(!e||!(r.get("content-type")??"").includes("application/x-www-form-urlencoded"))return e;let s=new URLSearchParams(e),i=s.get("client_id");if(!i)return e;let a=Nt(n,i),c=o.get(a);if(!c)return e;if(c.expiresAt<=Date.now())return o.delete(a),e;if(s.delete("client_secret"),c.authMethod==="client_secret_basic"){let u=Ur.from(`${St(i)}:${St(c.clientSecret)}`,"utf8").toString("base64");r.set("authorization",`Basic ${u}`)}else r.delete("authorization"),s.set("client_id",i),s.set("client_secret",c.clientSecret);return s.toString()}function St(t){return new URLSearchParams({value:t}).toString().slice(6)}function Gr(t){let e=Date.now();for(let[r,n]of t)n.expiresAt<=e&&t.delete(r)}async function Jr(t,e){let r=Number(t.headers.get("content-length"));if(Number.isFinite(r)&&r>e)throw new U;return jt(t.body,e)}async function ie(t,e){let r=Number(t.headers.get("content-length"));if(Number.isFinite(r)&&r>e)throw await t.body?.cancel(),new U;return jt(t.body,e)}async function jt(t,e){if(!t)return"";let r=t.getReader(),n=[],o=0;for(;;){let{done:a,value:c}=await r.read();if(a)break;if(o+=c.byteLength,o>e)throw await r.cancel(),new U;n.push(c)}let s=new Uint8Array(o),i=0;for(let a of n)s.set(a,i),i+=a.byteLength;return new TextDecoder().decode(s)}function Se(t){let e;try{e=JSON.parse(t)}catch{throw new S("OAuth metadata is not valid JSON")}if(!e||typeof e!="object"||Array.isArray(e))throw new S("OAuth metadata is not an object");return e}function Ot(t,e){let r=t.get(e);return r&&Date.now()-r.updatedAt<=Tt?r:(t.delete(e),{authorizationServers:new Set,endpoints:new Map,tokenEndpointAuthMethods:new Set,updatedAt:Date.now()})}function Ct(t){let e=Date.now();for(let[r,n]of t)e-n.updatedAt>Tt&&t.delete(r);for(;t.size>$r;){let r=t.keys().next().value;if(!r)break;t.delete(r)}}function T(t){let e=new URL(t);return e.hash="",(e.protocol==="https:"&&e.port==="443"||e.protocol==="http:"&&e.port==="80")&&(e.port=""),e.toString().replace(/\/$/,"")}function Yr(t,e,r){if(!t||!(e.get("content-type")??"").includes("json"))return t;try{let o=JSON.parse(t);return!o||typeof o!="object"||Array.isArray(o)?t:JSON.stringify({...o,redirect_uris:[r]})}catch{return t}}function Oe(t){let e=new URL(t);if(e.pathname!=="/"||e.search||e.hash)throw new Error(`OAuth proxy allowed origin must be an origin: ${t}`);return e.origin}function Xr(t,e,r){try{let n=Oe(t);if(n===new URL(e.req.url).origin||r.has(n))return!0;let o=new URL(n),i=e.req.header("x-forwarded-host")?.split(",")[0]?.trim()||e.req.header("host");if(!i||o.host!==i)return!1;let a=e.req.header("x-forwarded-proto")?.split(",")[0]?.trim();return!a||`${a}:`===o.protocol}catch{return!1}}function Qr(t){let e=new Headers;return t&&Dt(e,t),e.set("Access-Control-Allow-Methods","GET, POST, OPTIONS"),e.set("Access-Control-Allow-Headers","Accept, Authorization, Content-Type"),e.set("Access-Control-Max-Age","600"),new Response(null,{status:204,headers:e})}function Dt(t,e){t.set("Access-Control-Allow-Origin",e),t.append("Vary","Origin")}async function It(t,e){return e?e(t):!0}function ae(t){return t>=300&&t<400}function Zr(t){let e=t.toLowerCase().replace(/^\[|\]$/g,"");return e==="localhost"||e.endsWith(".localhost")||e==="::1"||e.startsWith("127.")}function en(t){let e=t.toLowerCase();return e.endsWith(".local")||e.endsWith(".internal")||e.endsWith(".home.arpa")}function Ht(t){if(t.includes(":")){let s=t.toLowerCase();return s.startsWith("::ffff:")?Ht(s.slice(7)):!(s==="::"||s==="::1"||s.startsWith("fc")||s.startsWith("fd")||/^fe[89ab]/.test(s)||s.startsWith("ff")||s.startsWith("2001:db8:"))}let e=t.split(".").map(Number);if(e.length!==4||e.some(s=>!Number.isInteger(s)))return!1;let[r,n,o]=e;return!(r===0||r===10||r===127||r===100&&n>=64&&n<=127||r===169&&n===254||r===172&&n>=16&&n<=31||r===192&&n===0&&o===0||r===192&&n===0&&o===2||r===192&&n===168||r===198&&(n===18||n===19)||r===198&&n===51&&o===100||r===203&&n===0&&o===113||r>=224)}function Pe(t,e){t&&console.log(`[OAuth BFF] ${e}`)}function Ae(t,e,r){let n=e instanceof Error?e.message:"Unknown error";return r&&console.error("[OAuth BFF]",n),e instanceof U?t.json({error:"Upstream response too large"},502):e instanceof S?t.json({error:e.message},502):e instanceof DOMException&&e.name==="TimeoutError"?t.json({error:"OAuth upstream timed out"},504):t.json({error:"OAuth upstream request failed"},502)}var U=class extends Error{},S=class extends Error{};var tn=3;function rn(t,e){return t.includes("text/event-stream")&&!e}function Te(t,e={}){let r=e.path||"/mcp/proxy",n=e.enableLogging!==!1,o=e.rateLimiter??new M.default({points:120,duration:60}),s=async(i,a)=>{try{await o.consume(i.req)}catch(c){return q(i,c)}return a()};t.use(`${r}/*`,Rt({origin:"*",allowHeaders:["Authorization","Content-Type","Accept","X-Target-URL","X-MCP-Target","Mcp-Session-Id","mcp-session-id","mcp-protocol-version","X-Server-Id","X-Requested-With"],exposeHeaders:["*"]})),n&&t.use(`${r}/*`,_t()),t.use(`${r}/*`,s),t.all(`${r}/*`,async i=>{try{if(e.authenticate&&!await e.authenticate(i))return i.json({error:"Unauthorized"},401);let a=i.req.header("X-Target-URL");if(!a)return i.json({error:"X-Target-URL header is required",usage:"Set X-Target-URL header to the MCP server URL you want to proxy to"},400);if(!await Ie(a,e.allowLoopback??!1))return i.json({error:"Invalid target URL",details:"Target is not allowed by the proxy network policy"},403);if(e.validateRequest&&!await e.validateRequest(a,i))return i.json({error:"Invalid target URL",details:"The requested target URL is not allowed"},403);try{new URL(a)}catch{return i.json({error:"Invalid target URL format",details:"The X-Target-URL must be a valid HTTP/HTTPS URL"},400)}let c=i.req.method,u={},l=i.req.header();for(let[w,g]of Object.entries(l)){let d=w.toLowerCase();!d.startsWith("x-proxy-")&&!d.startsWith("x-target-")&&!d.startsWith("x-mcp-")&&!d.startsWith("x-forwarded-")&&!d.startsWith("cf-")&&d!=="x-original-host"&&d!=="host"&&d!=="origin"&&d!=="referer"&&d!=="cookie"&&d!=="proxy-authorization"&&d!=="accept-encoding"&&d!=="cdn-loop"&&!d.startsWith("sec-fetch-")&&(u[w]=g)}u["Accept-Encoding"]="identity";let h=c!=="GET"&&c!=="HEAD"?new Uint8Array(await i.req.arrayBuffer()).slice():void 0,p=a,f=c,y=h;for(let w=0;;w+=1){let g=await fetch(p,{method:f,headers:u,body:y,redirect:"manual"}),d=g.headers.get("location");if(!(g.status>=300&&g.status<400&&d))return nn(g);if(w>=tn)return i.json({error:"Too many upstream redirects"},502);let m=new URL(d,p);if(!await Ie(m.toString(),e.allowLoopback??!1)||e.validateRequest&&!await e.validateRequest(m.toString(),i))return i.json({error:"Redirect target is not allowed"},403);m.origin!==new URL(p).origin&&(ce(u,"authorization"),ce(u,"proxy-authorization")),(g.status===303||(g.status===301||g.status===302)&&f==="POST")&&(f="GET",y=void 0,ce(u,"content-type"),ce(u,"content-length")),p=m.toString()}}catch(a){let c=a instanceof Error?a.message:"Unknown error",u=i.req.header("X-Target-URL");return a instanceof Error&&(a.message.includes("ECONNREFUSED")||a.message.includes("fetch failed"))?console.warn(`[MCP Proxy] Connection refused to ${u||"unknown target"} - server may not be running`):console.error("[MCP Proxy] Request failed:",c,`
98
+ Target URL:`,u||"unknown",`
99
+ Error:`,a),i.json({error:"Proxy request failed",details:c,targetUrl:u||"unknown"},500)}})}function ce(t,e){for(let r of Object.keys(t))r.toLowerCase()===e&&delete t[r]}async function nn(t){let e={};if(t.headers.forEach((o,s)=>{let i=s.toLowerCase();i!=="content-encoding"&&i!=="transfer-encoding"&&i!=="content-length"&&i!=="set-cookie"&&(e[s]=o)}),rn(t.headers.get("content-type")||"",t.headers.get("content-length")))return new Response(t.body,{status:t.status,statusText:t.statusText,headers:e});if([204,205,304].includes(t.status))return new Response(null,{status:t.status,statusText:t.statusText,headers:e});let n=await t.arrayBuffer();return e["Content-Length"]=String(n.byteLength),new Response(n,{status:t.status,statusText:t.statusText,headers:e})}function Me(t,e,r=""){let n=a=>`${r}${a}`,o=e?.oauthProxyAllowLoopback??!1,s=e?.oauth!==!1,i=new M.default({points:120,duration:60});if(t.get(n("/inspector/health"),a=>a.json({status:"ok",protocol:"mcp-use-inspector-preview",version:1,capabilities:["view-preview"]})),Te(t,{path:n("/inspector/api/proxy"),allowLoopback:o,rateLimiter:i}),s&&Ce(t,{basePath:n("/inspector/api/oauth"),callbackPath:n("/inspector/oauth/callback"),enableLogging:!0,allowedOrigins:e?.oauthProxyAllowedOrigins??[],allowLoopback:o,rateLimiter:i}),e?.autoConnectUrl!==void 0){let a=e.autoConnectUrl;t.get(n("/inspector/config.json"),c=>c.json({autoConnectUrl:a??null}))}}function sn(t,e){if(hn(t)){let o=t,s=e,i=Ft(s?.basePath);if(zt(o)){qt(o,s,i);return}let a=$t(s,i),c=Bt(a);o.use(an(c,a.routes.map(u=>u.path)));return}let r=t,n=Ft(r?.basePath);return Bt($t(r,n))}function $t(t,e){let r=new Re;return qt(r,t,e),r}function qt(t,e,r){let n={oauthProxyAllowedOrigins:e?.oauthProxyAllowedOrigins??[],oauthProxyAllowLoopback:e?.oauthProxyAllowLoopback??!0};e?.autoConnectUrl!==void 0?n.autoConnectUrl=e.autoConnectUrl:t.get(`${r}/inspector/config.json`,o=>{let s=new URL(o.req.url);return o.json({autoConnectUrl:`${s.origin}${r}`})}),Me(t,n,r),bt(t,{devMode:e?.devMode??!0,sandboxOrigin:e?.sandboxOrigin,inspectorMode:"embedded",rootRedirect:!1,basePath:r,proxyUrl:`${r}/inspector/api/proxy`,manufactChatUrl:e?.manufactChatUrl},r)}function Bt(t){return e=>Promise.resolve(t.fetch(e))}function an(t,e){let r=new Set(e.filter(o=>!o.includes("*"))),n=e.filter(o=>o.endsWith("/*")).map(o=>o.slice(0,-1));return(o,s,i)=>{let a=new URL(o.originalUrl||o.url||"",cn(o));if(!r.has(a.pathname)&&!n.some(u=>a.pathname.startsWith(u))){i();return}let c=un(o,a);t(c).then(u=>dn(s,u)).catch(i)}}function cn(t){let r=Le(t.headers["x-forwarded-proto"])||t.protocol||"http",o=Le(t.headers["x-forwarded-host"])||Le(t.headers.host)||"localhost";return`${r}://${o}`}function Le(t){return Array.isArray(t)?t[0]??"":(t??"").split(",")[0].trim()}function un(t,e){let r={method:t.method,headers:t.headers};return t.method!=="GET"&&t.method!=="HEAD"&&(t.body!==void 0?r.body=ln(t.body):(r.body=on.toWeb(t),r.duplex="half")),new globalThis.Request(e,r)}function ln(t){return typeof t=="string"||t instanceof ArrayBuffer||ArrayBuffer.isView(t)||t instanceof Blob||t instanceof FormData||t instanceof URLSearchParams||t instanceof ReadableStream?t:JSON.stringify(t)}async function dn(t,e){t.status(e.status),e.headers.forEach((o,s)=>{s!=="set-cookie"&&t.setHeader(s,o)});let r=e.headers.getSetCookie();if(r.length>0&&t.setHeader("set-cookie",r),!e.body){t.end();return}let n=e.body.getReader();for(;;){let{done:o,value:s}=await n.read();if(o)break;t.write(s)}t.end()}function hn(t){return!t||typeof t!="object"&&typeof t!="function"?!1:typeof t.use=="function"||zt(t)}function zt(t){return!!t&&typeof t=="object"&&typeof t.fetch=="function"&&typeof t.route=="function"}function Ft(t){if(t===void 0)return"/mcp";let e=t.trim(),r=[],n=!1;for(let s of e)s==="/"?(n||r.push(s),n=!0):(r.push(s),n=!1);for(;r.length>0&&r[r.length-1]==="/";)r.pop();let o=r.join("");return o===""||o==="/"?"":(o.startsWith("/")||(o=`/${o}`),o)}export{sn as mountInspector,Me as registerInspectorProxyRoutes};
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@mcp-use/inspector",
3
3
  "type": "module",
4
- "version": "20.0.0-beta.35",
4
+ "version": "20.0.0-beta.37",
5
5
  "description": "MCP Inspector - A tool for inspecting and debugging MCP servers",
6
6
  "author": "",
7
7
  "license": "MIT",
@@ -56,7 +56,7 @@
56
56
  "react-resizable-panels": "^4.6.4",
57
57
  "sonner": "^2.0.7",
58
58
  "tailwind-merge": "^3.5.0",
59
- "mcp-use": "2.0.0-beta.43"
59
+ "mcp-use": "2.0.0-beta.45"
60
60
  },
61
61
  "peerDependenciesMeta": {
62
62
  "@base-ui/react": {