@mcp-use/inspector 20.3.15-canary.0 → 20.3.15

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,4 +1,4 @@
1
- var ar=Object.create;var Be=Object.defineProperty;var cr=Object.getOwnPropertyDescriptor;var lr=Object.getOwnPropertyNames;var ur=Object.getPrototypeOf,dr=Object.prototype.hasOwnProperty;var J=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports);var pr=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of lr(e))!dr.call(t,o)&&o!==r&&Be(t,o,{get:()=>e[o],enumerable:!(n=cr(e,o))||n.enumerable});return t};var hr=(t,e,r)=>(r=t!=null?ar(ur(t)):{},pr(e||!t||!t.__esModule?Be(r,"default",{value:t,enumerable:!0}):r,t));var yt=J((ss,gt)=>{"use strict";gt.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 bt=J((as,wt)=>{"use strict";wt.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 Se=J((ls,xt)=>{"use strict";xt.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 Et=J((ds,Rt)=>{"use strict";var vt=bt(),Ae=Se();Rt.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 Ae(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 a=new vt(r,o>0?Date.now()+o:null);return this._storage.set(e,a),o>0&&(a.timeoutId=setTimeout(()=>{this._storage.delete(e)},o),a.timeoutId.unref&&a.timeoutId.unref()),new Ae(0,o===0?-1:o,a.value,!0)}get(e){let r=this._storage.get(e);if(r){let n=r.expiresAt?r.expiresAt-Date.now():-1;return new Ae(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 a=s?n-o:0,i=this._storage.get(e);i&&i.timeoutId&&clearTimeout(i.timeoutId);let c=new vt(r,n);this._storage.set(e,c),a>0&&(c.timeoutId=setTimeout(()=>{this._storage.delete(e)},a),c.timeoutId.unref&&c.timeoutId.unref())}}});var St=J((ps,_t)=>{"use strict";var Ar=yt(),Cr=Et(),Pt=Se(),Ce=class extends Ar{constructor(e={}){super(e),this._memoryStorage=new Cr}consume(e,r=1,n={}){return new Promise((o,s)=>{let a=this.getKey(e),i=this._getKeySecDuration(n),c=this._memoryStorage.incrby(a,r,i);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(a,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 a=this._getKeySecDuration(n),i=this._memoryStorage.incrby(o,r,a);i.remainingPoints=Math.max(this.points-i.consumedPoints,0),s(i)})}reward(e,r=1,n={}){let o=this.getKey(e);return new Promise(s=>{let a=this._getKeySecDuration(n),i=this._memoryStorage.incrby(o,-r,a);i.remainingPoints=Math.max(this.points-i.consumedPoints,0),s(i)})}block(e,r){let n=r*1e3,o=this.points+1;return this._memoryStorage.set(this.getKey(e),o,r),Promise.resolve(new Pt(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 Pt(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,a)=>{r?(n[s].count+=1,n[s].keys.push(a)):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 a=typeof s.key=="string"||typeof s.key=="number",i=Number.isFinite(s.value),c=s.expiresAt===null||Number.isFinite(s.expiresAt);if(!a||!i||!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}};_t.exports=Ce});var pe=(t,e,r)=>(n,o)=>{let s=-1;return a(0);async function a(i){if(i<=s)throw new Error("next() called multiple times");s=i;let c,l=!1,u;if(t[i]?(u=t[i][0][0],n.req.routeIndex=i):u=i===t.length&&o||void 0,u)try{c=await u(n,()=>a(i+1))}catch(d){if(d instanceof Error&&e)n.error=d,c=await e(d,n),l=!0;else throw d}else n.finalized===!1&&r&&(c=await r(n));return c&&(n.finalized===!1||l)&&(n.res=c),n}};var qe=Symbol();var ze=(t,e)=>new Response(t,{headers:{"Content-Type":e.replace(/^[^;]+/,n=>n.toLowerCase())}}).formData();var Fe=32,fr=1e4,Q=t=>"headers"in t,Ke=async(t,e=Object.create(null))=>{let{all:r=!1,dot:n=!1}=e,a=(Q(t)?t.headers:t.raw.headers).get("Content-Type")?.split(";")[0].trim().toLowerCase();return a==="multipart/form-data"||a==="application/x-www-form-urlencoded"?mr(t,{all:r,dot:n}):{}};async function mr(t,e){if(!Q(t)&&t.bodyCache.formData)return We(await t.bodyCache.formData,e);let r=Q(t)?t.headers:t.raw.headers,n=await t.arrayBuffer(),o=ze(n,r.get("Content-Type")||"");Q(t)||(t.bodyCache.formData=o);let s=await o;return s?We(s,e):{}}function We(t,e){let r=Object.create(null),n={count:0};return t.forEach((o,s)=>{e.all||s.endsWith("[]")?gr(r,s,o):r[s]=o}),e.dot&&Object.entries(r).forEach(([o,s])=>{o.includes(".")&&(yr(r,o,s,n),delete r[o])}),r}var gr=(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},yr=(t,e,r,n)=>{if(/(?:^|\.)__proto__\./.test(e))return;let o=t,s=e.split(".",Fe+2);s.length>Fe+1&&Ve(),s.forEach((a,i)=>{i===s.length-1?o[a]=r:((!o[a]||typeof o[a]!="object"||Array.isArray(o[a])||o[a]instanceof File)&&(n.count++>=fr&&Ve(),o[a]=Object.create(null)),o=o[a])})},Ve=()=>{throw new Error("Nesting limit exceeded")};var fe=t=>{let e=t.split("/");return e[0]===""&&e.shift(),e},Ge=t=>{let{groups:e,path:r}=wr(t),n=fe(r);return br(n,e)},wr=t=>{let e=[];return t=t.replace(/\{[^}]+\}/g,(r,n)=>{let o=`@${n}`;return e.push([o,r]),o}),{groups:e,path:t}},br=(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},Z={},Je=(t,e)=>{if(t==="*")return"*";let r=t.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);if(r){let n=`${t}#${e}`;return Z[n]||(r[2]?Z[n]=e&&e[0]!==":"&&e[0]!=="*"?[n,r[1],new RegExp(`^${r[2]}(?=/${e})`)]:[t,r[1],new RegExp(`^${r[2]}$`)]:Z[n]=[t,r[1],!0]),Z[n]}return null},Xe=(t,e)=>{try{return e(t)}catch{return t.replace(/(?:%[0-9A-Fa-f]{2})+/g,r=>{try{return e(r)}catch{return r}})}},xr=t=>Xe(t,decodeURI),me=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),a=e.indexOf("#",n),i=s===-1?a===-1?void 0:a:a===-1?s:Math.min(s,a),c=e.slice(r,i);return xr(c.includes("%25")?c.replace(/%25/g,"%2525"):c)}else if(o===63||o===35)break}return e.slice(r,n)};var Ye=t=>{let e=me(t);return e.length>1&&e.at(-1)==="/"?e.slice(0,-1):e},N=(t,e,...r)=>(r.length&&(e=N(e,...r)),`${t?.[0]==="/"?"":"/"}${t}${e==="/"?"":`${t?.at(-1)==="/"?"":"/"}${e?.[0]==="/"?e.slice(1):e}`}`),ee=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(o.charCodeAt(o.length-1)===63){r.length===0&&n===""?r.push("/"):r.push(n);let s=o.slice(0,-1);n+="/"+s,r.push(n)}else n+="/"+o}),r.filter((o,s,a)=>a.indexOf(o)===s)},te=t=>t.indexOf("%")!==-1?Xe(t,vr):t,he=t=>(t.indexOf("+")!==-1&&(t=t.replace(/\+/g," ")),te(t)),Qe=(t,e,r)=>{let n=t.indexOf("#",8);n!==-1&&(t=t.slice(0,n));let o;if(!r&&e&&e.indexOf("%")===-1&&e.indexOf("+")===-1){let i=t.indexOf("?",8);if(i===-1)return;for(t.startsWith(e,i+1)||(i=t.indexOf(`&${e}`,i+1));i!==-1;){let c=t.charCodeAt(i+e.length+1);if(c===61){let l=i+e.length+2,u=t.indexOf("&",l);return he(t.slice(l,u===-1?void 0:u))}else if(c==38||isNaN(c))return"";i=t.indexOf(`&${e}`,i+1)}if(o=/[%+]/.test(t),!o)return}let s=Object.create(null);o??=/[%+]/.test(t);let a=t.indexOf("?",8);for(;a!==-1;){let i=t.indexOf("&",a+1),c=t.indexOf("=",a);c>i&&i!==-1&&(c=-1);let l=t.slice(a+1,c===-1?i===-1?void 0:i:c);if(o&&(l=he(l)),a=i,l==="")continue;let u;c===-1?u="":(u=t.slice(c+1,i===-1?void 0:i),o&&(u=he(u))),r?(s[l]&&Array.isArray(s[l])||(s[l]=[]),s[l].push(u)):s[l]??=u}return e?s[e]:s},Ze=Qe,et=(t,e)=>Qe(t,e,!0),vr=decodeURIComponent;var tt=class{raw;#t;#e;routeIndex=0;path;bodyCache={};constructor(t,e="/",r=[[]]){this.raw=t,this.path=e,this.#e=r}param(t){return t?this.#r(t):this.#s()}#r(t){let e=this.#e[0][this.routeIndex]?.[1][t],r=this.#n(e);return r&&te(r)}#s(){let t={},e=Object.keys(this.#e[0][this.routeIndex]?.[1]??{});for(let r of e){let n=this.#n(this.#e[0][this.routeIndex][1][r]);n!==void 0&&(t[r]=te(n))}return t}#n(t){return this.#e[1]?this.#e[1][t]:t}query(t){return Ze(this.url,t)}queries(t){return et(this.url,t)}header(t){if(t)return this.raw.headers.get(t)??void 0;let e=Object.create(null);return this.raw.headers.forEach((r,n)=>{e[n]=r}),e}async parseBody(t){return Ke(this,t)}#o=t=>{let{bodyCache:e,raw:r}=this,n=e[t];if(n)return n;for(let o in e)return e[o].then(s=>(o==="json"&&(s=JSON.stringify(s)),new Response(s)[t]()));return e[t]=r[t]()};json(){return this.#o("text").then(t=>JSON.parse(t))}text(){return this.#o("text")}arrayBuffer(){return this.#o("arrayBuffer")}bytes(){return this.#o("arrayBuffer").then(t=>new Uint8Array(t))}blob(){return this.#o("blob")}formData(){return this.#o("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[qe](){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 rt={Stringify:1,BeforeStream:2,Stream:3},Rr=(t,e)=>{let r=new String(t);return r.isEscaped=!0,r.callbacks=e,r};var ge=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 a=Promise.all(s.map(i=>i({phase:e,buffer:o,context:n}))).then(i=>Promise.all(i.filter(Boolean).map(c=>ge(c,e,!1,n,o))).then(()=>o[0]));return r?Rr(await a,s):a};var Er="text/plain; charset=UTF-8",ye=(t,e)=>({"Content-Type":t,...e}),X=(t,e)=>new Response(t,e),we=class{#t;#e;env={};#r;finalized=!1;error;#s;#n;#o;#u;#c;#l;#a;#d;#p;constructor(t,e){this.#t=t,e&&(this.#n=e.executionCtx,this.env=e.env,this.#l=e.notFoundHandler,this.#p=e.path,this.#d=e.matchResult)}get req(){return this.#e??=new tt(this.#t,this.#p,this.#d),this.#e}get event(){if(this.#n&&"respondWith"in this.#n)return this.#n;throw Error("This context has no FetchEvent")}get executionCtx(){if(this.#n)return this.#n;throw Error("This context has no ExecutionContext")}get res(){return this.#o||=X(null,{headers:this.#a??=new Headers})}set res(t){if(this.#o&&t){t=X(t.body,t);for(let[e,r]of this.#o.headers.entries())if(e!=="content-type")if(e==="set-cookie"){let n=this.#o.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.#o=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.#o=X(this.#o.body,this.#o));let n=this.#o?this.#o.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.#o?new Headers(this.#o.headers):this.#a;if(typeof e=="object"&&e.headers){n??=new Headers;for(let[s,a]of new Headers(e.headers))s==="set-cookie"?n.append(s,a):n.set(s,a)}if(r){if(!n){let s=0;for(let a in r)if(++s>1||typeof r[a]!="string"){n=new Headers;break}}if(n)for(let s in r){let a=r[s];if(typeof a=="string")n.set(s,a);else{n.delete(s);for(let i of a)n.append(s,i)}}}let o=typeof e=="number"?e:e?.status??this.#s;return X(t,{status:o,headers:n??r})}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,ye(Er,r));json=(t,e,r)=>this.#i(JSON.stringify(t),e,ye("application/json",r));html=(t,e,r)=>{let n=o=>this.#i(o,e,ye("text/html; charset=UTF-8",r));return typeof t=="object"?ge(t,rt.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??=()=>X(),this.#l(this))};var _="ALL",nt="all",ot=["get","post","put","delete","options","patch","query"],re="Can not add a route since the matcher is already built.",ne=class extends Error{};var st="__COMPOSED_HANDLER";var Pr=t=>t.text("404 Not Found",404),it=(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)},at=class ct{get;post;put;delete;options;patch;query;all;on;use;router;getPath;_basePath="/";#t="/";routes=[];constructor(e={}){[...ot,nt].forEach(s=>{this[s]=(a,...i)=>(typeof a=="string"?this.#t=a:this.#s(s,this.#t,a),i.forEach(c=>{this.#s(s,this.#t,c)}),this)}),this.on=(s,a,...i)=>{for(let c of[a].flat()){this.#t=c;for(let l of[s].flat())i.map(u=>{this.#s(l.toUpperCase(),this.#t,u)})}return this},this.use=(s,...a)=>(typeof s=="string"?this.#t=s:(this.#t="*",a.unshift(s)),a.forEach(i=>{this.#s(_,this.#t,i)}),this);let{strict:n,...o}=e;Object.assign(this,o),this.getPath=n??!0?e.getPath??me:Ye}#e(){let e=new ct({router:this.router,getPath:this.getPath});return e.errorHandler=this.errorHandler,e.#r=this.#r,e.routes=this.routes,e}#r=Pr;errorHandler=it;route(e,r){let n=this.basePath(e);return r.routes.map(o=>{let s;r.errorHandler===it?s=o.handler:(s=async(a,i)=>(await pe([],r.errorHandler)(a,()=>o.handler(a,i))).res,s[st]=o.handler),n.#s(o.method,o.path,s,o.basePath)}),this}basePath(e){let r=this.#e();return r._basePath=N(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 a=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=N(this._basePath,e),l=c==="/"?0:c.length;return u=>{let d=new URL(u.url);return d.pathname=this.getPath(u).slice(l)||"/",new Request(d,u)}})();let i=async(c,l)=>{let u=await r(o(c.req.raw),...a(c));if(u)return u;await l()};return this.#s(_,N(e,"*"),i),this}#s(e,r,n,o){e=e.toUpperCase(),r=N(this._basePath,r);let s={basePath:o!==void 0?N(this._basePath,o):this._basePath,path:r,method:e,handler:n};this.router.add(e,r,[n,s]),this.routes.push(s)}#n(e,r){if(e instanceof Error)return this.errorHandler(e,r);throw e}#o(e,r,n,o){if(o==="HEAD")return(async()=>new Response(null,await this.#o(e,r,n,"GET")))();let s=this.getPath(e,{env:n}),a=this.router.match(o,s),i=new we(e,{path:s,matchResult:a,env:n,executionCtx:r,notFoundHandler:this.#r});if(a[0].length===1){let l;try{l=a[0][0][0][0](i,async()=>{i.res=await this.#r(i)})}catch(u){return this.#n(u,i)}return l instanceof Promise?l.then(u=>u||(i.finalized?i.res:this.#r(i))).catch(u=>this.#n(u,i)):l??this.#r(i)}let c=pe(a[0],this.errorHandler,this.#r);return(async()=>{try{let l=await c(i);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.#n(l,i)}})()}fetch=(e,...r)=>this.#o(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${N("/",e)}`,r),n,o));fire=()=>{addEventListener("fetch",e=>{e.respondWith(this.#o(e.request,e,void 0,e.request.method))})}};var R=()=>Object.create(null);var oe=[];function be(t,e){let r=this.buildAllMatchers(),n=((o,s)=>{let a=r[o]||r[_],i=a[2][s];if(i)return i;let c=s.match(a[0]);if(!c)return[[],oe];let l=c.indexOf("",1);return[a[1][l],c]});return this.match=n,n(t,e)}var K="[^/]+",j=".*",M="(?:|/.*)",U=Symbol(),lt=new Set(".\\+*[^]$()");function _r(t,e){return t.length===1?e.length===1?t<e?-1:1:-1:e.length===1?1:t===j||t===M?e===M?-1:1:e===j||e===M?-1:t===K?1:e===K?-1:t.length===e.length?t<e?-1:1:e.length-t.length}var ut=class xe{#t;#e;#r=R();insert(e,r,n,o,s){let a=this;for(let i=0,c=e.length;i<c;i++){let l=e[i],u=l.length===1?l==="*"?i===c-1?["","",j]:["","",K]:null:l==="/*"?["","",M]:l.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/),d;if(u){let h=u[1],f=u[2]||K;if(h&&u[2]&&(f===".*"||(f=f.replace(/^\((?!\?:)(?=[^)]+\)$)/,"(?:"),/\((?!\?:)/.test(f))||f.length===1&&lt.has(f)))throw U;if(d=a.#r[f],!d){if(f!==j&&f!==M){for(let x in a.#r)if((f.length>1||x.length>1)&&x!==j&&x!==M)throw U}d=a.#r[f]=new xe}h!==""&&(d.#e??=o.varIndex++,n.push([h,d.#e]))}else if(d=a.#r[l],!d){for(let h in a.#r)if(h.length>1&&h!==j&&h!==M)throw U;d=a.#r[l]=new xe}a=d}if(a.#t!==void 0)throw U;a.#t=s?-1:r}buildRegExpStr(){let r=Object.keys(this.#r).sort(_r).map(n=>{let o=this.#r[n],s=o.buildRegExpStr();return s===""?"":(typeof o.#e=="number"?`(${n})@${o.#e}`:lt.has(n)?`\\${n}`:n)+s}).filter(Boolean);return typeof this.#t=="number"&&this.#t!==-1&&r.unshift(`#${this.#t}`),r.length===0?"":r.length===1?r[0]:"(?:"+r.join("|")+")"}};var ve=class{#t={varIndex:0};#e=new ut;#r=0;paths=R();insert(t,e){if(e){this.#e.insert(t.split(""),0,[],this.#t,!0);return}let r=[],n=[],o=t;for(let a=0;;){let i=!1;if(o=o.replace(/\{[^}]+\}/g,c=>{let l=`@\\${a}`;return n[a]=[l,c],a++,i=!0,l}),!i)break}let s=o.match(/(?::[^\/]+)|(?:\/\*$)|./g)||[];for(let a=n.length-1;a>=0;a--){let[i]=n[a];for(let c=s.length-1;c>=0;c--)if(s[c].indexOf(i)!==-1){s[c]=s[c].replace(i,n[a][1]);break}}this.#e.insert(s,this.#r,r,this.#t,!1),this.paths[t]=[this.#r++,r]}buildRegExp(){let t=this.#e.buildRegExpStr();if(t==="")return[/^$/,[],[]];let e=0,r=[],n=[];return t=t.replace(/#(\d+)|@(\d+)|\.\*\$/g,(o,s,a)=>s!==void 0?(r[++e]=Number(s),"$()"):(a!==void 0&&(n[Number(a)]=++e),"")),[new RegExp(`^${t}`),r,n]}};var dt=R();function pt(t){return dt[t]??=new RegExp(`^${t.replace(/\/:[^/{}]+(?:\{\[\^\/]\+})?(?=[/{]|$)|\/?\*$|([.\\+*[^\]$()?{}|])/g,(e,r)=>r?`\\${r}`:e==="/*"?M:e==="*"?j:`/:${K}`)}$`)}function se(t,e){for(let r of Object.keys(t).sort((n,o)=>o.length-n.length))if(pt(r).test(e))return[...t[r]]}var ie=class{name="RegExpRouter";#t;#e;#r;constructor(){this.#t={[_]:R()},this.#e={[_]:R()},this.#r={[_]:new ve}}#s(t,e){try{this.#r[t].insert(e,!/\*|\/:/.test(e))}catch(r){throw r===U?new ne(e):r}}add(t,e,r){let n=this.#t,o=this.#e;if(!n)throw new Error(re);if(!n[t]){this.#r[t]=new ve;for(let i of[n,o]){i[t]=R();for(let c in i[_])i[t][c]=[...i[_][c]],this.#s(t,c)}}e==="/*"&&(e="*");let s=t===_?Object.keys(n):[t];if(/\*$/.test(e)){let i=pt(e);for(let c of s)n[c][e]||(this.#s(c,e),n[c][e]=se(n[c],e)||se(n[_],e)||[]);for(let c of[n,o])for(let l of s)for(let u in c[l])i.test(u)&&c[l][u].push([r,e]);return}let a=ee(e)||[e];for(let i of a)for(let c of s)o[c][i]||(this.#s(c,i),o[c][i]=se(n[c],i)||se(n[_],i)||[]),o[c][i].push([r,i])}match=be;buildAllMatchers(){let t=R();for(let e of Object.keys(this.#e))t[e]=this.#n(e);return this.#t=this.#e=this.#r=void 0,dt=R(),t}#n(t){let e=this.#t[t],r=this.#e[t],n=this.#r[t],o=R(),s=[],[a,i,c]=n.buildRegExp();for(let l of[e,r])for(let u in l){let d=l[u],h=n.paths[u];if(!h){o[u]=[d.map(([f])=>[f,R()]),oe];continue}s[h[0]]=d.map(([f,x])=>[f,n.paths[x][1].reduceRight((w,[v],g)=>(w[v]=c[h[1][g][1]],w),R())])}return[a,i.map(l=>s[l]),o]}};var Re=class{name="SmartRouter";#t=[];#e=[];constructor(t){this.#t=t.routers}add(t,e,r){if(!this.#e)throw new Error(re);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,a;for(;s<o;s++){let i=r[s];try{for(let c=0,l=n.length;c<l;c++)i.add(...n[c]);a=i.match(t,e)}catch(c){if(c instanceof ne)continue;throw c}this.match=i.match.bind(i),this.#t=[i],this.#e=void 0;break}if(s===o)throw new Error("Fatal error");return this.name=`SmartRouter + ${this.activeRouter.name}`,a}get activeRouter(){if(this.#e||this.#t.length!==1)throw new Error("No active router has been determined yet.");return this.#t[0]}};var Ee=R(),Sr=0,ht=class ft{#t=[];#e=R();#r=[];#s;#n=Ee;insert(e,r,n){let o=this,s=Ge(r),a=new Set,i=0;for(let c of s){let l=s[++i],u=Je(c,l)||(l===void 0&&c&&c.indexOf("*")===c.length-1?c:null),d=Array.isArray(u),h=d?u[0]:u||c,f=o.#e[h]||=new ft;u&&!f.#s&&(f.#s=u,o.#r.push(f)),o=f,d&&a.add(u[1])}o.#t.push({[e]:{handler:n,possibleKeys:[...a],score:++Sr}})}#o(e,r,n,o,s){for(let a=0,i=r.#t.length;a<i;a++){let c=r.#t[a],l=c[n]||c[_];if(l){l.params=R(),e.push(l);for(let u=0,d=l.possibleKeys.length;u<d;u++){let h=l.possibleKeys[u];l.params[h]=s?.[h]&&!u?s[h]:o[h]??s?.[h]}}}}search(e,r){let n=[];this.#n=Ee;let s=[this],a=fe(r),i=[],c=a.length,l=null;for(let u=0;u<c;u++){let d=a[u],h=u===c-1,f=[];for(let w=0,v=s.length;w<v;w++){let g=s[w],p=g.#e[d];p&&(p.#n=g.#n,h?(p.#e["*"]&&this.#o(n,p.#e["*"],e,g.#n),this.#o(n,p,e,g.#n)):f.push(p));for(let m of g.#r){let y=m.#s,E=g.#n===Ee?{}:{...g.#n};if(typeof y=="string"){(y==="*"||d.startsWith(y.slice(0,-1)))&&(this.#o(n,m,e,g.#n),y==="*"&&(m.#n=E,f.push(m)));continue}let[,T,C]=y;if(!(!d&&C===!0)){if(C!==!0){if(!l){l=[];let b=r[0]==="/"?1:0;for(let O=0;O<c;O++)l[O]=b,b+=a[O].length+1}let P=r.slice(l[u]),S=C.exec(P);if(S){E[T]=S[0],this.#o(n,m,e,g.#n,E),S[0].length===P.length&&m.#e["*"]&&this.#o(n,m.#e["*"],e,g.#n,E);for(let b in m.#e){m.#n=E;let O=S[0].match(/\//g)?.length??0;(i[O]||=[]).push(m);break}continue}}(C===!0||C.test(d))&&(E[T]=d,h?(this.#o(n,m,e,E,g.#n),m.#e["*"]&&this.#o(n,m.#e["*"],e,E,g.#n)):(m.#n=E,f.push(m)))}}}let x=i.shift();s=x?f.concat(x):f}return n[1]&&n.sort((u,d)=>u.score-d.score),[n.map(({handler:u,params:d})=>[u,d])]}};var Pe=class{name="TrieRouter";#t=new ht;add(t,e,r){for(let n of ee(e)||[e])this.#t.insert(t,n,r)}match(t,e){return this.#t.search(t,e)}};var _e=class extends at{constructor(t={}){super(t),this.router=t.router??new Re({routers:[new ie,new Pe]})}};import{Readable as bn}from"stream";function mt(t=""){return`<link rel="icon" type="image/svg+xml" href="${`${t.replace(/\/$/,"")}/favicon-black.svg?v=4`}" />`}import{existsSync as At,readFileSync as Tr}from"fs";import k from"path";import{fileURLToPath as Ir}from"url";import{gunzipSync as Mr}from"zlib";var D=hr(St(),1);function G(t,e){return t.header("Retry-After",String(Or(e))),t.json({error:"Too Many Requests"},429)}function Or(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 Dr={".js":"application/javascript",".css":"text/css",".svg":"image/svg+xml",".png":"image/png",".ico":"image/x-icon",".webmanifest":"application/manifest+json"};function kr(){let t=k.dirname(Ir(import.meta.url));for(let e of[k.resolve(t,"app"),k.resolve(t,"../app"),k.resolve(t,"../../dist/app")])if(At(k.join(e,"inspector.js.gz")))return e;throw new Error("Inspector bundle not found (expected dist/app/inspector.js.gz)")}function Ct(t,e="/inspector/assets"){let r=kr(),n=new Map,o=new D.default({points:600,duration:60}),s=async(a,i)=>{try{await o.consume(a.req)}catch(c){return G(a,c)}return i()};t.use(`${e}/*`,s),t.get(`${e}/*`,async a=>{let i=a.req.path.slice(e.length),c=i.startsWith("/")?i.slice(1):i;if(!c||c.includes(".."))return a.notFound();let l=c==="inspector.js"||c==="inspector.css"?`${c}.gz`:c,u=k.resolve(r,l),d=r.endsWith(k.sep)?r:`${r}${k.sep}`;if(!u.startsWith(d)||!At(u))return a.notFound();let h=k.extname(c),f=l.endsWith(".gz"),x=/(?:^|,)\s*gzip\s*(?:,|$)/i.test(a.req.header("accept-encoding")??""),w=Tr(u),v=f&&!x?n.get(u)??Nr(n,u,w):w,g=v.buffer.slice(v.byteOffset,v.byteOffset+v.byteLength);return a.body(g,200,{"Content-Type":Dr[h]??"application/octet-stream",...f&&x?{"Content-Encoding":"gzip"}:{},...f?{Vary:"Accept-Encoding"}:{},"Cache-Control":"no-cache"})})}function Nr(t,e,r){let n=Mr(r);return t.set(e,n),n}var Ot={name:"@mcp-use/inspector",type:"module",version:"20.3.15-canary.0",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"},"./client/styles.css":{default:"./dist/client/styles.css"}},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 --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:"pnpm run clean && pnpm run build:client-exports && pnpm run build:server && pnpm run build:app && pnpm 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 && node scripts/copy-client-styles.mjs","build:server":"tsup --config tsup.server.ts","verify:package":"node scripts/verify-package.mjs",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:"vitest run","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.16 || ^2.0.17 || ^2.0.18 || ^2.0.19 || ^2.0.20","@mcp-use/client":"^2.0.1 || ^2.1.0 || ^2.1.1 || ^2.1.2 || ^2.1.3 || ^2.1.4 || ^2.1.5 || ^2.2.0 || ^2.2.1 || ^2.2.2 || ^2.2.3 || ^2.2.4 || ^2.2.5 || ^2.3.0 || ^2.3.1 || ^2.3.2 || ^2.3.3 || ^2.3.4 || ^2.3.5 || ^2.4.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":"^2.4.3 || ^2.4.4 || ^2.5.0 || ^2.5.1 || ^2.5.2 || ^2.6.0 || ^2.6.1 || ^2.7.0 || ^2.7.1 || ^2.7.2 || ^2.7.3-canary.0",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},"mcp-use":{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":"^2.0.5","@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.13.5",jsdom:"^27.0.0","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":"^8.3.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",yaml:"^2.8.3",zod:"^4.2.0"}};var jr=Ot.version;function Lt(){return jr}var Hr=`<!doctype html>
1
+ var nr=Object.create;var je=Object.defineProperty;var or=Object.getOwnPropertyDescriptor;var sr=Object.getOwnPropertyNames;var ir=Object.getPrototypeOf,ar=Object.prototype.hasOwnProperty;var W=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports);var cr=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of sr(e))!ar.call(t,o)&&o!==r&&je(t,o,{get:()=>e[o],enumerable:!(n=or(e,o))||n.enumerable});return t};var lr=(t,e,r)=>(r=t!=null?nr(ir(t)):{},cr(e||!t||!t.__esModule?je(r,"default",{value:t,enumerable:!0}):r,t));var ft=W((ts,pt)=>{"use strict";pt.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 mt=W((ns,ht)=>{"use strict";ht.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 Pe=W((ss,gt)=>{"use strict";gt.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 bt=W((as,wt)=>{"use strict";var yt=mt(),Ee=Pe();wt.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 a=new yt(r,o>0?Date.now()+o:null);return this._storage.set(e,a),o>0&&(a.timeoutId=setTimeout(()=>{this._storage.delete(e)},o),a.timeoutId.unref&&a.timeoutId.unref()),new Ee(0,o===0?-1:o,a.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 a=s?n-o:0,i=this._storage.get(e);i&&i.timeoutId&&clearTimeout(i.timeoutId);let c=new yt(r,n);this._storage.set(e,c),a>0&&(c.timeoutId=setTimeout(()=>{this._storage.delete(e)},a),c.timeoutId.unref&&c.timeoutId.unref())}}});var vt=W((cs,Rt)=>{"use strict";var Pr=ft(),Er=bt(),xt=Pe(),Ae=class extends Pr{constructor(e={}){super(e),this._memoryStorage=new Er}consume(e,r=1,n={}){return new Promise((o,s)=>{let a=this.getKey(e),i=this._getKeySecDuration(n),c=this._memoryStorage.incrby(a,r,i);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(a,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 a=this._getKeySecDuration(n),i=this._memoryStorage.incrby(o,r,a);i.remainingPoints=Math.max(this.points-i.consumedPoints,0),s(i)})}reward(e,r=1,n={}){let o=this.getKey(e);return new Promise(s=>{let a=this._getKeySecDuration(n),i=this._memoryStorage.incrby(o,-r,a);i.remainingPoints=Math.max(this.points-i.consumedPoints,0),s(i)})}block(e,r){let n=r*1e3,o=this.points+1;return this._memoryStorage.set(this.getKey(e),o,r),Promise.resolve(new xt(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 xt(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,a)=>{r?(n[s].count+=1,n[s].keys.push(a)):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 a=typeof s.key=="string"||typeof s.key=="number",i=Number.isFinite(s.value),c=s.expiresAt===null||Number.isFinite(s.expiresAt);if(!a||!i||!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}};Rt.exports=Ae});var He=Symbol();var $e=(t,e)=>new Response(t,{headers:{"Content-Type":e.replace(/^[^;]+/,r=>r.toLowerCase())}}).formData();var ur=1e4,J=t=>"headers"in t,ze=async(t,e=Object.create(null))=>{let{all:r=!1,dot:n=!1}=e,o=(J(t)?t.headers:t.raw.headers).get("Content-Type")?.split(";")[0].trim().toLowerCase();return o==="multipart/form-data"||o==="application/x-www-form-urlencoded"?dr(t,{all:r,dot:n}):{}};async function dr(t,e){if(!J(t)&&t.bodyCache.formData)return Be(await t.bodyCache.formData,e);let r=J(t)?t.headers:t.raw.headers,n=await t.arrayBuffer(),o=$e(n,r.get("Content-Type")||"");J(t)||(t.bodyCache.formData=o);let s=await o;return s?Be(s,e):{}}function Be(t,e){let r=Object.create(null),n={count:0};return t.forEach((o,s)=>{e.all||s.endsWith("[]")?pr(r,s,o):r[s]=o}),e.dot&&Object.entries(r).forEach(([o,s])=>{o.includes(".")&&(fr(r,o,s,n),delete r[o])}),r}var pr=(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},fr=(t,e,r,n)=>{if(/(?:^|\.)__proto__\./.test(e))return;let o=t,s=e.split(".",34);s.length>33&&qe(),s.forEach((a,i)=>{i===s.length-1?o[a]=r:((!o[a]||typeof o[a]!="object"||Array.isArray(o[a])||o[a]instanceof File)&&(n.count++>=ur&&qe(),o[a]=Object.create(null)),o=o[a])})},qe=()=>{throw new Error("Nesting limit exceeded")};var le=t=>{let e=t.split("/");return e[0]===""&&e.shift(),e},Fe=t=>{let{groups:e,path:r}=hr(t),n=le(r);return mr(n,e)},hr=t=>{let e=[];return t=t.replace(/\{[^}]+\}/g,(r,n)=>{let o=`@${n}`;return e.push([o,r]),o}),{groups:e,path:t}},mr=(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},G={},We=(t,e)=>{if(t==="*")return"*";let r=t.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);if(r){let n=`${t}#${e}`;return G[n]||(r[2]?G[n]=e&&e[0]!==":"&&e[0]!=="*"?[n,r[1],new RegExp(`^${r[2]}(?=/${e})`)]:[t,r[1],new RegExp(`^${r[2]}$`)]:G[n]=[t,r[1],!0]),G[n]}return null},Ve=(t,e)=>{try{return e(t)}catch{return t.replace(/(?:%[0-9A-Fa-f]{2})+/g,r=>{try{return e(r)}catch{return r}})}},gr=t=>Ve(t,decodeURI),ue=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),a=e.indexOf("#",n),i=s===-1?a===-1?void 0:a:a===-1?s:Math.min(s,a),c=e.slice(r,i);return gr(c.includes("%25")?c.replace(/%25/g,"%2525"):c)}else if(o===63||o===35)break}return e.slice(r,n)};var Ke=t=>{let e=ue(t);return e.length>1&&e.at(-1)==="/"?e.slice(0,-1):e},M=(t,e,...r)=>(r.length&&(e=M(e,...r)),`${t?.[0]==="/"?"":"/"}${t}${e==="/"?"":`${t?.at(-1)==="/"?"":"/"}${e?.[0]==="/"?e.slice(1):e}`}`),X=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(o.charCodeAt(o.length-1)===63){r.length===0&&n===""?r.push("/"):r.push(n);let s=o.slice(0,-1);n+="/"+s,r.push(n)}else n+="/"+o}),r.filter((o,s,a)=>a.indexOf(o)===s)},Y=t=>t.indexOf("%")!==-1?Ve(t,yr):t,ce=t=>(t.indexOf("+")!==-1&&(t=t.replace(/\+/g," ")),Y(t)),Je=(t,e,r)=>{let n=t.indexOf("#",8);n!==-1&&(t=t.slice(0,n));let o;if(!r&&e&&e.indexOf("%")===-1&&e.indexOf("+")===-1){let i=t.indexOf("?",8);if(i===-1)return;for(t.startsWith(e,i+1)||(i=t.indexOf(`&${e}`,i+1));i!==-1;){let c=t.charCodeAt(i+e.length+1);if(c===61){let l=i+e.length+2,u=t.indexOf("&",l);return ce(t.slice(l,u===-1?void 0:u))}else if(c==38||isNaN(c))return"";i=t.indexOf(`&${e}`,i+1)}if(o=/[%+]/.test(t),!o)return}let s=Object.create(null);o??=/[%+]/.test(t);let a=t.indexOf("?",8);for(;a!==-1;){let i=t.indexOf("&",a+1),c=t.indexOf("=",a);c>i&&i!==-1&&(c=-1);let l=t.slice(a+1,c===-1?i===-1?void 0:i:c);if(o&&(l=ce(l)),a=i,l==="")continue;let u;c===-1?u="":(u=t.slice(c+1,i===-1?void 0:i),o&&(u=ce(u))),r?(s[l]&&Array.isArray(s[l])||(s[l]=[]),s[l].push(u)):s[l]??=u}return e?s[e]:s},Ge=Je,Xe=(t,e)=>Je(t,e,!0),yr=decodeURIComponent;var Ye=class{raw;#t;#e;routeIndex=0;path;bodyCache={};constructor(t,e="/",r=[[]]){this.raw=t,this.path=e,this.#e=r}param(t){return t?this.#r(t):this.#s()}#r(t){let e=this.#e[0][this.routeIndex]?.[1][t],r=this.#n(e);return r&&Y(r)}#s(){let t={},e=Object.keys(this.#e[0][this.routeIndex]?.[1]??{});for(let r of e){let n=this.#n(this.#e[0][this.routeIndex][1][r]);n!==void 0&&(t[r]=Y(n))}return t}#n(t){return this.#e[1]?this.#e[1][t]:t}query(t){return Ge(this.url,t)}queries(t){return Xe(this.url,t)}header(t){if(t)return this.raw.headers.get(t)??void 0;let e=Object.create(null);return this.raw.headers.forEach((r,n)=>{e[n]=r}),e}async parseBody(t){return ze(this,t)}#o=t=>{let{bodyCache:e,raw:r}=this,n=e[t];if(n)return n;for(let o in e)return e[o].then(s=>{o==="json"&&(s=JSON.stringify(s));let a=o==="formData"?void 0:r.headers.get("content-type");return new Response(s,{headers:a?{"Content-Type":a}:void 0})[t]()});return e[t]=r[t]()};json(){return this.#o("text").then(t=>JSON.parse(t))}text(){return this.#o("text")}arrayBuffer(){return this.#o("arrayBuffer")}bytes(){return this.#o("arrayBuffer").then(t=>new Uint8Array(t))}blob(){return this.#o("blob")}formData(){return this.#o("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[He](){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 Qe={Stringify:1,BeforeStream:2,Stream:3},wr=(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 a=Promise.all(s.map(i=>i({phase:e,buffer:o,context:n}))).then(i=>Promise.all(i.filter(Boolean).map(c=>de(c,e,!1,n,o))).then(()=>o[0]));return r?wr(await a,s):a};var br="text/plain; charset=UTF-8",pe=(t,e)=>({"Content-Type":t,...e}),V=(t,e)=>new Response(t,e),fe=class{#t;#e;env={};#r;finalized=!1;error;#s;#n;#o;#u;#c;#l;#a;#d;#p;constructor(t,e){this.#t=t,e&&(this.#n=e.executionCtx,this.env=e.env,this.#l=e.notFoundHandler,this.#p=e.path,this.#d=e.matchResult)}get req(){return this.#e??=new Ye(this.#t,this.#p,this.#d),this.#e}get event(){if(this.#n&&"respondWith"in this.#n)return this.#n;throw Error("This context has no FetchEvent")}get executionCtx(){if(this.#n)return this.#n;throw Error("This context has no ExecutionContext")}get res(){return this.#o||=V(null,{headers:this.#a??=new Headers})}set res(t){if(this.#o&&t){t=V(t.body,t);for(let[e,r]of this.#o.headers.entries())if(e!=="content-type")if(e==="set-cookie"){let n=this.#o.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.#o=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.#o=V(this.#o.body,this.#o));let n=this.#o?this.#o.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.#o?new Headers(this.#o.headers):this.#a;if(typeof e=="object"&&e.headers){n??=new Headers;for(let[s,a]of new Headers(e.headers))s==="set-cookie"?n.append(s,a):n.set(s,a)}if(r){if(!n){let s=0;for(let a in r)if(++s>1||typeof r[a]!="string"){n=new Headers;break}}if(n)for(let s in r){let a=r[s];if(typeof a=="string")n.set(s,a);else{n.delete(s);for(let i of a)n.append(s,i)}}}let o=typeof e=="number"?e:e?.status??this.#s;return V(t,{status:o,headers:n??r})}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,pe(br,r));json=(t,e,r)=>this.#i(JSON.stringify(t),e,pe("application/json",r));html=(t,e,r)=>{let n=o=>this.#i(o,e,pe("text/html; charset=UTF-8",r));return typeof t=="object"?de(t,Qe.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??=()=>V(),this.#l(this))};var he=(t,e,r)=>(n,o)=>{let s=-1;return a(0);async function a(i){if(i<=s)throw new Error("next() called multiple times");s=i;let c,l=!1,u;if(t[i]?(u=t[i][0][0],n.req.routeIndex=i):u=i===t.length&&o||void 0,u)try{c=await u(n,()=>a(i+1))}catch(p){if(p instanceof Error&&e)n.error=p,c=await e(p,n),l=!0;else throw p}else n.finalized===!1&&r&&(c=await r(n));return c&&(n.finalized===!1||l)&&(n.res=c),n}};var Ze=["get","post","put","delete","options","patch","query"],Q="Can not add a route since the matcher is already built.",Z=class extends Error{};var et="__COMPOSED_HANDLER";var xr=t=>t.text("404 Not Found",404),tt=(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)},rt=class nt{get;post;put;delete;options;patch;query;all;on;use;router;getPath;_basePath="/";#t="/";routes=[];constructor(e={}){[...Ze,"all"].forEach(o=>{this[o]=(s,...a)=>{let i=o.toUpperCase();return typeof s=="string"?this.#t=s:this.#s(i,this.#t,s),a.forEach(c=>{this.#s(i,this.#t,c)}),this}}),this.on=(o,s,...a)=>{for(let i of[s].flat()){this.#t=i;for(let c of[o].flat()){let l=c.toUpperCase();for(let u of a)this.#s(l,this.#t,u)}}return this},this.use=(o,...s)=>(typeof o=="string"?this.#t=o:(this.#t="*",s.unshift(o)),s.forEach(a=>{this.#s("ALL",this.#t,a)}),this);let{strict:r,...n}=e;Object.assign(this,n),this.getPath=r??!0?e.getPath??ue:Ke}#e(){let e=new nt({router:this.router,getPath:this.getPath});return e.errorHandler=this.errorHandler,e.#r=this.#r,e.routes=this.routes,e}#r=xr;errorHandler=tt;route(e,r){let n=this.basePath(e);return r.routes.map(o=>{let s;r.errorHandler===tt?s=o.handler:(s=async(a,i)=>(await he([],r.errorHandler)(a,()=>o.handler(a,i))).res,s[et]=o.handler),n.#s(o.method,o.path,s,o.basePath)}),this}basePath(e){let r=this.#e();return r._basePath=M(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 a=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=M(this._basePath,e),l=c==="/"?0:c.length;return u=>{let p=new URL(u.url);return p.pathname=this.getPath(u).slice(l)||"/",new Request(p,u)}})();let i=async(c,l)=>{let u=await r(o(c.req.raw),...a(c));if(u)return u;await l()};return this.#s("ALL",M(e,"*"),i),this}#s(e,r,n,o){r=M(this._basePath,r);let s={basePath:o!==void 0?M(this._basePath,o):this._basePath,path:r,method:e,handler:n};this.router.add(e,r,[n,s]),this.routes.push(s)}#n(e,r){if(e instanceof Error)return this.errorHandler(e,r);throw e}#o(e,r,n,o){if(o==="HEAD")return(async()=>new Response(null,await this.#o(e,r,n,"GET")))();let s=this.getPath(e,{env:n}),a=this.router.match(o,s),i=new fe(e,{path:s,matchResult:a,env:n,executionCtx:r,notFoundHandler:this.#r});if(a[0].length===1){let l;try{l=a[0][0][0][0](i,async()=>{i.res=await this.#r(i)})}catch(u){return this.#n(u,i)}return l instanceof Promise?l.then(u=>u||(i.finalized?i.res:this.#r(i))).catch(u=>this.#n(u,i)):l??this.#r(i)}let c=he(a[0],this.errorHandler,this.#r);return(async()=>{try{let l=await c(i);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.#n(l,i)}})()}fetch=(e,...r)=>this.#o(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${M("/",e)}`,r),n,o));fire=()=>{addEventListener("fetch",e=>{e.respondWith(this.#o(e.request,e,void 0,e.request.method))})}};var P=()=>Object.create(null);var ee=[];function me(t,e){let r=this.buildAllMatchers(),n=((o,s)=>{let a=r[o]||r.ALL,i=a[2][s];if(i)return i;let c=s.match(a[0]);if(!c)return[[],ee];let l=c.indexOf("",1);return[a[1][l],c]});return this.match=n,n(t,e)}var ye="[^/]+";var we="(?:|/.*)",k=Symbol(),ot=new Set(".\\+*[^]$()");function Rr(t,e){return t.length===1?e.length===1?t<e?-1:1:-1:e.length===1?1:t===".*"||t==="(?:|/.*)"?e==="(?:|/.*)"?-1:1:e===".*"||e==="(?:|/.*)"?-1:t==="[^/]+"?1:e==="[^/]+"?-1:t.length===e.length?t<e?-1:1:e.length-t.length}var st=class ge{#t;#e;#r=P();insert(e,r,n,o,s){let a=this;for(let i=0,c=e.length;i<c;i++){let l=e[i],u=l.length===1?l==="*"?i===c-1?["","",".*"]:["","",ye]:null:l==="/*"?["","",we]:l.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/),p;if(u){let f=u[1],h=u[2]||"[^/]+";if(f&&u[2]&&(h===".*"||(h=h.replace(/^\((?!\?:)(?=[^)]+\)$)/,"(?:"),/\((?!\?:)/.test(h))||h.length===1&&ot.has(h)))throw k;if(p=a.#r[h],!p){if(h!==".*"&&h!=="(?:|/.*)"){for(let x in a.#r)if((h.length>1||x.length>1)&&x!==".*"&&x!=="(?:|/.*)")throw k}p=a.#r[h]=new ge}f!==""&&(p.#e??=o.varIndex++,n.push([f,p.#e]))}else if(p=a.#r[l],!p){for(let f in a.#r)if(f.length>1&&f!==".*"&&f!=="(?:|/.*)")throw k;p=a.#r[l]=new ge}a=p}if(a.#t!==void 0)throw k;a.#t=s?-1:r}buildRegExpStr(){let e=Object.keys(this.#r).sort(Rr).map(r=>{let n=this.#r[r],o=n.buildRegExpStr();return o===""?"":(typeof n.#e=="number"?`(${r})@${n.#e}`:ot.has(r)?`\\${r}`:r)+o}).filter(Boolean);return typeof this.#t=="number"&&this.#t!==-1&&e.unshift(`#${this.#t}`),e.length===0?"":e.length===1?e[0]:"(?:"+e.join("|")+")"}};var be=class{#t={varIndex:0};#e=new st;#r=0;paths=P();insert(t,e){if(e){this.#e.insert(t.split(""),0,[],this.#t,!0);return}let r=[],n=[],o=t;for(let a=0;;){let i=!1;if(o=o.replace(/\{[^}]+\}/g,c=>{let l=`@\\${a}`;return n[a]=[l,c],a++,i=!0,l}),!i)break}let s=o.match(/(?::[^\/]+)|(?:\/\*$)|./g)||[];for(let a=n.length-1;a>=0;a--){let[i]=n[a];for(let c=s.length-1;c>=0;c--)if(s[c].indexOf(i)!==-1){s[c]=s[c].replace(i,n[a][1]);break}}this.#e.insert(s,this.#r,r,this.#t,!1),this.paths[t]=[this.#r++,r]}buildRegExp(){let t=this.#e.buildRegExpStr();if(t==="")return[/^$/,[],[]];let e=0,r=[],n=[];return t=t.replace(/#(\d+)|@(\d+)|\.\*\$/g,(o,s,a)=>s!==void 0?(r[++e]=Number(s),"$()"):(a!==void 0&&(n[Number(a)]=++e),"")),[new RegExp(`^${t}`),r,n]}};var it=P();function at(t){return it[t]??=new RegExp(`^${t.replace(/\/:[^/{}]+(?:\{\[\^\/]\+})?(?=[/{]|$)|\/?\*$|([.\\+*[^\]$()?{}|])/g,(e,r)=>r?`\\${r}`:e==="/*"?we:e==="*"?".*":`/:${ye}`)}$`)}function te(t,e){for(let r of Object.keys(t).sort((n,o)=>o.length-n.length))if(at(r).test(e))return[...t[r]]}var re=class{name="RegExpRouter";#t;#e;#r;constructor(){this.#t={ALL:P()},this.#e={ALL:P()},this.#r={ALL:new be}}#s(t,e){try{this.#r[t].insert(e,!/\*|\/:/.test(e))}catch(r){throw r===k?new Z(e):r}}add(t,e,r){let n=this.#t,o=this.#e;if(!n)throw new Error(Q);if(!n[t]){this.#r[t]=new be;for(let i of[n,o]){i[t]=P();for(let c in i.ALL)i[t][c]=[...i.ALL[c]],this.#s(t,c)}}e==="/*"&&(e="*");let s=t==="ALL"?Object.keys(n):[t];if(/\*$/.test(e)){let i=at(e);for(let c of s)n[c][e]||(this.#s(c,e),n[c][e]=te(n[c],e)||te(n.ALL,e)||[]);for(let c of[n,o])for(let l of s)for(let u in c[l])i.test(u)&&c[l][u].push([r,e]);return}let a=X(e)||[e];for(let i of a)for(let c of s)o[c][i]||(this.#s(c,i),o[c][i]=te(n[c],i)||te(n.ALL,i)||[]),o[c][i].push([r,i])}match=me;buildAllMatchers(){let t=P();for(let e of Object.keys(this.#e))t[e]=this.#n(e);return this.#t=this.#e=this.#r=void 0,it=P(),t}#n(t){let e=this.#t[t],r=this.#e[t],n=this.#r[t],o=P(),s=[],[a,i,c]=n.buildRegExp();for(let l of[e,r])for(let u in l){let p=l[u],f=n.paths[u];if(!f){o[u]=[p.map(([h])=>[h,P()]),ee];continue}s[f[0]]=p.map(([h,x])=>[h,n.paths[x][1].reduceRight((v,[m],b)=>(v[m]=c[f[1][b][1]],v),P())])}return[a,i.map(l=>s[l]),o]}};var ct=class{name="SmartRouter";#t=[];#e=[];constructor(t){this.#t=t.routers}add(t,e,r){if(!this.#e)throw new Error(Q);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,a;for(;s<o;s++){let i=r[s];try{for(let c=0,l=n.length;c<l;c++)i.add(...n[c]);a=i.match(t,e)}catch(c){if(c instanceof Z)continue;throw c}this.match=i.match.bind(i),this.#t=[i],this.#e=void 0;break}if(s===o)throw new Error("Fatal error");return this.name=`SmartRouter + ${this.activeRouter.name}`,a}get activeRouter(){if(this.#e||this.#t.length!==1)throw new Error("No active router has been determined yet.");return this.#t[0]}};var xe=P(),vr=0,lt=class ut{#t=[];#e=P();#r=[];#s;#n=xe;insert(e,r,n){let o=this,s=Fe(r),a=new Set,i=0;for(let c of s){let l=s[++i],u=We(c,l)||(l===void 0&&c&&c.indexOf("*")===c.length-1?c:null),p=Array.isArray(u),f=p?u[0]:u||c,h=o.#e[f]||=new ut;u&&!h.#s&&(h.#s=u,o.#r.push(h)),o=h,p&&a.add(u[1])}o.#t.push({[e]:{handler:n,possibleKeys:[...a],score:++vr}})}#o(e,r,n,o,s){for(let a=0,i=r.#t.length;a<i;a++){let c=r.#t[a],l=c[n]||c.ALL;if(l){l.params=P(),e.push(l);for(let u=0,p=l.possibleKeys.length;u<p;u++){let f=l.possibleKeys[u];l.params[f]=s?.[f]&&!u?s[f]:o[f]??s?.[f]}}}}search(e,r){let n=[];this.#n=xe;let o=[this],s=le(r),a=[],i=s.length,c=null;for(let l=0;l<i;l++){let u=s[l],p=l===i-1,f=[];for(let x=0,v=o.length;x<v;x++){let m=o[x],b=m.#e[u];b&&(b.#n=m.#n,p?(b.#e["*"]&&this.#o(n,b.#e["*"],e,m.#n),this.#o(n,b,e,m.#n)):f.push(b));for(let d of m.#r){let y=d.#s,g=m.#n===xe?{}:{...m.#n};if(typeof y=="string"){(y==="*"||u.startsWith(y.slice(0,-1)))&&(this.#o(n,d,e,m.#n),y==="*"&&(d.#n=g,f.push(d)));continue}let[,L,S]=y;if(!(!u&&S===!0)){if(S!==!0){if(!c){c=[];let E=r[0]==="/"?1:0;for(let w=0;w<i;w++)c[w]=E,E+=s[w].length+1}let I=r.slice(c[l]),R=S.exec(I);if(R){g[L]=R[0],this.#o(n,d,e,m.#n,g),R[0].length===I.length&&d.#e["*"]&&this.#o(n,d.#e["*"],e,m.#n,g);for(let E in d.#e){d.#n=g;let w=R[0].match(/\//g)?.length??0;(a[w]||=[]).push(d);break}continue}}(S===!0||S.test(u))&&(g[L]=u,p?(this.#o(n,d,e,g,m.#n),d.#e["*"]&&this.#o(n,d.#e["*"],e,g,m.#n)):(d.#n=g,f.push(d)))}}}let h=a.shift();o=h?f.concat(h):f}return n[1]&&n.sort((l,u)=>l.score-u.score),[n.map(({handler:l,params:u})=>[l,u])]}};var Re=class{name="TrieRouter";#t=new lt;add(t,e,r){for(let n of X(e)||[e])this.#t.insert(t,n,r)}match(t,e){return this.#t.search(t,e)}};var ve=class extends rt{constructor(t={}){super(t),this.router=t.router??new ct({routers:[new re,new Re]})}};import{Readable as mn}from"stream";function dt(t=""){return`<link rel="icon" type="image/svg+xml" href="${`${t.replace(/\/$/,"")}/favicon-black.svg?v=4`}" />`}import{existsSync as Pt,readFileSync as _r}from"fs";import T from"path";import{fileURLToPath as Cr}from"url";import{gunzipSync as Lr}from"zlib";var O=lr(vt(),1);function z(t,e){return t.header("Retry-After",String(Ar(e))),t.json({error:"Too Many Requests"},429)}function Ar(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 Ir={".js":"application/javascript",".css":"text/css",".svg":"image/svg+xml",".png":"image/png",".ico":"image/x-icon",".webmanifest":"application/manifest+json"};function Or(){let t=T.dirname(Cr(import.meta.url));for(let e of[T.resolve(t,"app"),T.resolve(t,"../app"),T.resolve(t,"../../dist/app")])if(Pt(T.join(e,"inspector.js.gz")))return e;throw new Error("Inspector bundle not found (expected dist/app/inspector.js.gz)")}function Et(t,e="/inspector/assets"){let r=Or(),n=new Map,o=new O.default({points:600,duration:60}),s=async(a,i)=>{try{await o.consume(a.req)}catch(c){return z(a,c)}return i()};t.use(`${e}/*`,s),t.get(`${e}/*`,async a=>{let i=a.req.path.slice(e.length),c=i.startsWith("/")?i.slice(1):i;if(!c||c.includes(".."))return a.notFound();let l=c==="inspector.js"||c==="inspector.css"?`${c}.gz`:c,u=T.resolve(r,l),p=r.endsWith(T.sep)?r:`${r}${T.sep}`;if(!u.startsWith(p)||!Pt(u))return a.notFound();let f=T.extname(c),h=l.endsWith(".gz"),x=/(?:^|,)\s*gzip\s*(?:,|$)/i.test(a.req.header("accept-encoding")??""),v=_r(u),m=h&&!x?n.get(u)??Tr(n,u,v):v,b=m.buffer.slice(m.byteOffset,m.byteOffset+m.byteLength);return a.body(b,200,{"Content-Type":Ir[f]??"application/octet-stream",...h&&x?{"Content-Encoding":"gzip"}:{},...h?{Vary:"Accept-Encoding"}:{},"Cache-Control":"no-cache"})})}function Tr(t,e,r){let n=Lr(r);return t.set(e,n),n}var At={name:"@mcp-use/inspector",type:"module",version:"20.3.15",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"},"./client/styles.css":{default:"./dist/client/styles.css"}},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 --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:"pnpm run clean && pnpm run build:client-exports && pnpm run build:server && pnpm run build:app && pnpm 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 && node scripts/copy-client-styles.mjs","build:server":"tsup --config tsup.server.ts","verify:package":"node scripts/verify-package.mjs",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:"vitest run","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.16 || ^2.0.17 || ^2.0.18 || ^2.0.19 || ^2.0.20","@mcp-use/client":"^2.0.1 || ^2.1.0 || ^2.1.1 || ^2.1.2 || ^2.1.3 || ^2.1.4 || ^2.1.5 || ^2.2.0 || ^2.2.1 || ^2.2.2 || ^2.2.3 || ^2.2.4 || ^2.2.5 || ^2.3.0 || ^2.3.1 || ^2.3.2 || ^2.3.3 || ^2.3.4 || ^2.3.5 || ^2.4.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":"^2.4.3 || ^2.4.4 || ^2.5.0 || ^2.5.1 || ^2.5.2 || ^2.6.0 || ^2.6.1 || ^2.7.0 || ^2.7.1 || ^2.7.2 || ^2.7.3",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},"mcp-use":{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":"^2.0.5","@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.13.7",jsdom:"^27.0.0","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":"^8.3.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.11","wait-on":"^9.0.4",yaml:"^2.8.3",zod:"^4.2.0"}};var kr=At.version;function St(){return kr}var Dr=`<!doctype html>
2
2
  <html>
3
3
  <head>
4
4
  <meta charset="utf-8" />
@@ -270,18 +270,18 @@ window.addEventListener('unhandledrejection', function(event) {
270
270
  }, "*");
271
271
  </script>
272
272
  </body>
273
- </html>`;function Tt(t){let r="<script>window.__SANDBOX_SEARCH__ = "+JSON.stringify(t).replace(/</g,"\\u003c")+";</script>";return Hr.replace(` const scriptSrcParts = ["'unsafe-inline'", "'unsafe-eval'", resourceSrc];
273
+ </html>`;function _t(t){let r="<script>window.__SANDBOX_SEARCH__ = "+JSON.stringify(t).replace(/</g,"\\u003c")+";</script>";return Dr.replace(` const scriptSrcParts = ["'unsafe-inline'", "'unsafe-eval'", resourceSrc];
274
274
  `,` const scriptSrcParts = ["'unsafe-inline'", resourceSrc];
275
- `).replace("<body>","<body>"+r)}var It=Lt();function $r(t){let e=t.hostname==="localhost"?"127.0.0.1":t.hostname==="127.0.0.1"||t.hostname==="::1"?"localhost":void 0;if(!e)return;let r=new URL(t.origin);return r.hostname=e,r.origin}var Br=`<!doctype html>
275
+ `).replace("<body>","<body>"+r)}var Ct=St();function Ur(t){let e=t.hostname==="localhost"?"127.0.0.1":t.hostname==="127.0.0.1"||t.hostname==="::1"?"localhost":void 0;if(!e)return;let r=new URL(t.origin);return r.hostname=e,r.origin}var Nr=`<!doctype html>
276
276
  <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>
277
277
  <body><div>Signed in. You can close this window.</div>
278
278
  <script>try{if(window.opener&&!window.opener.closed)window.opener.postMessage({type:"manufact:oauth-complete"},"*")}catch(e){}try{window.close()}catch(e){}</script>
279
- </body></html>`;function qr(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(`
279
+ </body></html>`;function jr(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(`
280
280
  `);return`<!doctype html>
281
281
  <html lang="en">
282
282
  <head>
283
283
  <meta charset="UTF-8" />
284
- ${mt(`${e}/inspector/assets`)}
284
+ ${dt(`${e}/inspector/assets`)}
285
285
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
286
286
  <link rel="preconnect" href="https://fonts.googleapis.com" />
287
287
  <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
@@ -328,7 +328,7 @@ window.addEventListener('unhandledrejection', function(event) {
328
328
  .mcp-boot-spinner, .mcp-boot-label { color: #a1a1aa; }
329
329
  }
330
330
  </style>
331
- <script>window.__INSPECTOR_VERSION__ = ${JSON.stringify(It)};</script>
331
+ <script>window.__INSPECTOR_VERSION__ = ${JSON.stringify(Ct)};</script>
332
332
  ${o}
333
333
  </head>
334
334
  <body>
@@ -368,6 +368,6 @@ window.addEventListener('unhandledrejection', function(event) {
368
368
  </div>
369
369
  <script type="module" src="${r.jsUrl}"></script>
370
370
  </body>
371
- </html>`}function Mt(t,e,r=""){let n=`${r}/inspector/assets`,o=encodeURIComponent(It),s={jsUrl:`${n}/inspector.js?v=${o}`,cssUrl:`${n}/inspector.css?v=${o}`},a=u=>`${r}${u}`,i={...e,basePath:e?.basePath??r,proxyUrl:e?.proxyUrl!==void 0?e.proxyUrl:a("/inspector/api/proxy"),disableTelemetry:e?.disableTelemetry??process.env.MCP_USE_ANONYMIZED_TELEMETRY==="false"},c=u=>{let d=new URL(u.req.url),h={...i,sandboxOrigin:i.sandboxOrigin??$r(d)??null};return u.html(qr(h,r,s))};Ct(t,n),t.get(a("/inspector/oauth-popup-closed.html"),u=>u.html(Br)),t.get(a("/inspector/sandbox"),u=>u.html(Tt(new URL(u.req.url).search))),t.get(a("/inspector"),c),t.get(`${a("/inspector")}/`,c);let l=a("/inspector/api/");t.get(a("/inspector/*"),u=>u.req.path.startsWith(l)?u.notFound():c(u)),t.post(a("/inspector/*"),u=>u.req.path.startsWith(l)?u.notFound():c(u)),r===""&&e?.rootRedirect!==!1&&t.get("/",u=>{let d=new URL(u.req.url);return u.redirect(`${a("/inspector")}${d.search}`)})}var Dt=t=>{let e={origin:"*",allowMethods:["GET","HEAD","PUT","POST","DELETE","PATCH","QUERY"],allowHeaders:[],exposeHeaders:[],...t},r=e.exposeHeaders?.length?e.exposeHeaders.join(","):void 0,n=e.allowHeaders?.length?e.allowHeaders.join(","):void 0,o=(a=>typeof a=="string"?a==="*"?()=>a:i=>a===i?i:null:typeof a=="function"?a:i=>a.includes(i)?i:null)(e.origin),s=(a=>{if(typeof a=="function")return async(i,c)=>(await a(i,c)).join(",");if(Array.isArray(a)){let i=a.join(",");return()=>i}else return()=>""})(e.allowMethods);return async function(i,c){function l(d,h){i.res.headers.set(d,h)}let u=await o(i.req.header("origin")||"",i);if(u&&l("Access-Control-Allow-Origin",u),e.credentials&&l("Access-Control-Allow-Credentials","true"),r&&l("Access-Control-Expose-Headers",r),i.req.method==="OPTIONS"){e.origin!=="*"&&i.res.headers.append("Vary","Origin"),e.maxAge!=null&&l("Access-Control-Max-Age",e.maxAge.toString());let d=await s(i.req.header("origin")||"",i);d&&l("Access-Control-Allow-Methods",d);let h=n;if(!h){let f=i.req.header("Access-Control-Request-Headers");f&&(h=f.split(",").map(x=>x.trim()).join(","))}return h&&(l("Access-Control-Allow-Headers",h),i.res.headers.append("Vary","Access-Control-Request-Headers")),i.res.headers.delete("Content-Length"),i.res.headers.delete("Content-Type"),new Response(null,{headers:i.res.headers,status:204,statusText:"No Content"})}await c(),e.origin!=="*"&&i.header("Vary","Origin",{append:!0})}};function zr(){let{process:t,Deno:e}=globalThis;return!(typeof e?.noColor=="boolean"?e.noColor:t!==void 0?"NO_COLOR"in t?.env:!1)}async function kt(){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}})():!zr())}var Fr=t=>{let[e,r]=[",","."];return t.map(o=>o.replace(/(\d)(?=(\d\d\d)+(?!\d))/g,"$1"+e)).join(r)},Wr=t=>{let e=Date.now()-t;return Fr([e<1e3?e+"ms":Math.round(e/1e3)+"s"])},Vr=async t=>{if(await kt())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 Nt(t,e,r,n,o=0,s){let a=e==="<--"?`${e} ${r} ${n}`:`${e} ${r} ${n} ${await Vr(o)} ${s}`;t(a)}var Oe=(t=console.log)=>async function(r,n){let{method:o,url:s}=r.req,a=s.slice(s.indexOf("/",8));await Nt(t,"<--",o,a);let i=Date.now();await n(),await Nt(t,"-->",o,a,r.res.status,Wr(i))};import{lookup as Kr}from"dns/promises";import{Buffer as Gr}from"buffer";import{isIP as Jr}from"net";var Xr=new Set(["accept","authorization","content-type","dpop"]),Yr=new Set(["cache-control","content-type","dpop-nonce","expires","pragma","retry-after","www-authenticate"]),Qr=[["registration_endpoint","registration"],["token_endpoint","token"],["revocation_endpoint","revocation"],["introspection_endpoint","introspection"]],zt=600*1e3,Zr=100,en=1440*60*1e3,tn=500;function De(t,e={}){let{basePath:r="/oauth",allowedOrigins:n=[],allowLoopback:o=!1,timeoutMs:s=1e4,maxRequestBodyBytes:a=64*1024,maxResponseBodyBytes:i=1024*1024,callbackPath:c="/oauth/callback",enableLogging:l=!0,logPrefix:u,authenticate:d,validateServerUrl:h,rateLimiter:f=new D.default({points:120,duration:60})}=e,x=new Set(n.map(Me)),w=new Map,v=new Map,g=async(p,m)=>{try{await f.consume(p.req)}catch(y){return G(p,y)}return m()};t.use(`${r}/*`,async(p,m)=>{let y=p.req.header("Origin");if(y&&!hn(y,p,x))return p.json({error:"Origin not allowed"},403);if(p.req.method==="OPTIONS")return fn(y);await m(),y&&Xt(p.res.headers,y)}),t.use(`${r}/*`,g),t.get(`${r}/metadata`,async p=>{if(!await qt(p,d))return p.json({error:"Unauthorized"},401);let m=await H(p.req.query("serverUrl"),o);if("error"in m)return p.json({error:m.error},400);let y=m.url;if(h&&!await h(y.toString(),p))return p.json({error:"MCP server URL not allowed"},403);let E=await H(p.req.query("url"),o);if("error"in E)return p.json({error:E.error},400);let T=E.url,C=L(y),P=$t(w,C),S=Ut(y,T,P);if(!S&&P.authorizationServers.size===0)try{await jt(y,P,o,s,i),w.set(C,P),S=Ut(y,T,P)}catch{}if(!S)return p.json({error:"Metadata target is not bound to this MCP server"},403);try{Le(l,u,`GET ${T}`);let b=await ae(T,{method:"GET",headers:{Accept:"application/json"},redirect:"manual",signal:AbortSignal.timeout(s)});if(le(b.status))return p.json({error:"OAuth metadata redirects are not allowed"},502);let O=await ce(b,i);if(!b.ok)return p.body(O,b.status,{"Content-Type":b.headers.get("content-type")??"application/json"});let W=Ie(O);return S.type==="protected-resource"?await Vt(W,y,S.resourceIdentifier,P,o):await Kt(W,S.issuer,P,o),P.updatedAt=Date.now(),w.set(C,P),Bt(w),p.body(O,200,{"Content-Type":b.headers.get("content-type")??"application/json"})}catch(b){return Te(p,b,l,u)}}),t.post(`${r}/proxy`,async p=>{if(!await qt(p,d))return p.json({error:"Unauthorized"},401);let m;try{m=JSON.parse(await dn(p.req.raw,a))}catch(I){return p.json({error:I instanceof $?"Request body too large":"Invalid JSON request body"},I instanceof $?413:400)}let y=await H(m.serverUrl,o);if("error"in y)return p.json({error:y.error},400);let E=y.url;if(h&&!await h(E.toString(),p))return p.json({error:"MCP server URL not allowed"},403);let T=await H(m.url,o);if("error"in T)return p.json({error:T.error},400);let C=T.url,P=m.method??"POST";if(P!=="GET"&&P!=="POST")return p.json({error:"OAuth endpoint method not allowed"},405);let S=L(E),b=$t(w,S);if(b.endpoints.size===0&&b.userInfoEndpoints.size===0)try{await jt(E,b,o,s,i),w.set(S,b),Bt(w)}catch(I){return Te(p,I,l,u)}let O=L(C),W=b.endpoints.get(O),He=b.userInfoEndpoints.has(O);if(!W&&!He)return p.json({error:"OAuth endpoint is not bound to this MCP server"},403);let B=P==="GET"&&He?"userinfo":W,de=B==="userinfo"?"GET":"POST";if(!B||P!==de)return p.json({error:"OAuth endpoint method not allowed"},405);try{let I=on(m.headers),V=B==="userinfo"?void 0:an(m.body,I);if(B==="registration"){let ir=Me(p.req.header("Origin")??new URL(p.req.url).origin);V=pn(V,I,new URL(c,ir).toString())}else B!=="userinfo"&&(V=ln({body:V,headers:I,bindingKey:S,clients:v}));if(new TextEncoder().encode(V??"").byteLength>a)return p.json({error:"OAuth request body too large"},413);Le(l,u,`${de} ${B} ${C}`);let q=await ae(C,{method:de,headers:I,body:V,redirect:"manual",signal:AbortSignal.timeout(s)});if(le(q.status))return p.json({error:"OAuth endpoint redirects are not allowed"},502);let $e=await ce(q,i),or=sn(q.headers),sr=q.headers.get("content-type")??"",z=$e;if(sr.includes("json"))try{z=JSON.parse($e)}catch{}return B==="registration"&&q.ok&&z&&typeof z=="object"&&!Array.isArray(z)&&(z=cn({responseBody:z,binding:b,bindingKey:S,clients:v})),p.json({status:q.status,statusText:q.statusText,headers:or,body:z})}catch(I){return Te(p,I,l,u)}}),Le(l,u,`Mounted at ${r}/metadata and ${r}/proxy`)}async function H(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=Yt(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(mn(r.hostname))return{error:"Local network URL not allowed"};try{let o=Jr(r.hostname)?[r.hostname]:(await Kr(r.hostname,{all:!0,verbatim:!0})).map(({address:s})=>s);if(o.length===0||o.some(s=>!Qt(s)))return{error:"Private or non-routable URL not allowed"}}catch{return{error:"URL hostname could not be resolved"}}return{url:r}}async function ke(t,e=!1){return!("error"in await H(t,e))}function Ut(t,e,r){let n=L(e),o=Ft(t).find(s=>L(s.url)===n);if(o)return{type:"protected-resource",resourceIdentifier:o.resourceIdentifier};for(let s of r.authorizationServers)if(Wt(new URL(s)).some(a=>L(a)===n))return{type:"authorization-server",issuer:s}}function Ft(t){let e=t.pathname==="/"?"":t.pathname;return[{url:new URL(`/.well-known/oauth-protected-resource${e}`,t.origin),resourceIdentifier:t},{url:new URL("/.well-known/oauth-protected-resource",t.origin),resourceIdentifier:new URL(t.origin)}]}function Wt(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 Vt(t,e,r,n,o){let s=rn(t.resource,o),a=s!==void 0&&L(s)===L(r),i=s!==void 0&&nn(e,s);if(!a&&!i)throw new A("Protected-resource metadata does not match serverUrl");if(!Array.isArray(t.authorization_servers)||t.authorization_servers.length===0)throw new A("Protected-resource metadata has no authorization servers");let c=new Set;for(let l of t.authorization_servers){let u=await H(l,o);if("error"in u)throw new A(`Unsafe authorization server: ${u.error}`);c.add(L(u.url))}n.authorizationServers=c,n.endpoints.clear(),n.userInfoEndpoints.clear(),n.tokenEndpointAuthMethods.clear()}function rn(t,e){if(!(typeof t!="string"||t.length===0))try{let r=new URL(t);return!(r.protocol==="https:"||e&&r.protocol==="http:"&&Yt(r.hostname))||r.username||r.password||r.hash?void 0:r}catch{return}}function nn(t,e){if(t.origin!==e.origin||t.pathname.length<e.pathname.length)return!1;let r=t.pathname.endsWith("/")?t.pathname:`${t.pathname}/`,n=e.pathname.endsWith("/")?e.pathname:`${e.pathname}/`;return r.startsWith(n)}async function Kt(t,e,r,n){if(typeof t.issuer!="string"||L(new URL(t.issuer))!==e)throw new A("Authorization-server metadata issuer mismatch");r.endpoints.clear(),r.userInfoEndpoints.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 Qr){let a=t[o];if(a===void 0)continue;let i=await H(a,n);if("error"in i)throw new A(`Unsafe ${o}: ${i.error}`);r.endpoints.set(L(i.url),s)}if(t.userinfo_endpoint!==void 0){let o=await H(t.userinfo_endpoint,n);if("error"in o)throw new A(`Unsafe userinfo_endpoint: ${o.error}`);r.userInfoEndpoints.add(L(o.url))}}async function jt(t,e,r,n,o){for(let s of Ft(t)){let a=await ae(s.url,{method:"GET",headers:{Accept:"application/json"},redirect:"manual",signal:AbortSignal.timeout(n)});if(le(a.status))throw new A("OAuth metadata redirects are not allowed");if(a.ok){await Vt(Ie(await ce(a,o)),t,s.resourceIdentifier,e,r);break}}if(e.authorizationServers.size===0)throw new A("Protected-resource metadata could not be discovered");for(let s of e.authorizationServers){let a=!1;for(let i of Wt(new URL(s))){let c=await ae(i,{method:"GET",headers:{Accept:"application/json"},redirect:"manual",signal:AbortSignal.timeout(n)});if(le(c.status))throw new A("OAuth metadata redirects are not allowed");if(c.ok){await Kt(Ie(await ce(c,o)),s,e,r),a=!0;break}}if(a)break}if(e.endpoints.size===0&&e.userInfoEndpoints.size===0)throw new A("Authorization-server metadata could not be discovered");e.updatedAt=Date.now()}async function ae(t,e){return fetch(t,e)}function on(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();Xr.has(o)&&typeof n=="string"&&e.set(o,n)}return e}function sn(t){let e={};return t.forEach((r,n)=>{Yr.has(n.toLowerCase())&&(e[n]=r)}),e}function an(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 Gt(t,e){return`${t}\0${e}`}function cn(t){let{responseBody:e,binding:r,bindingKey:n,clients:o}=t,s=e.client_id,a=e.client_secret;if(typeof s!="string"||typeof a!="string")return e;let i=e.token_endpoint_auth_method,c=i==="client_secret_post"||i==="client_secret_basic"?i: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()+en;for(un(o),o.set(Gt(n,s),{clientSecret:a,authMethod:c,expiresAt:u});o.size>tn;){let h=o.keys().next().value;if(!h)break;o.delete(h)}let d={...e};return delete d.client_secret,delete d.client_secret_expires_at,d.token_endpoint_auth_method="none",d}function ln(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),a=s.get("client_id");if(!a)return e;let i=Gt(n,a),c=o.get(i);if(!c)return e;if(c.expiresAt<=Date.now())return o.delete(i),e;if(s.delete("client_secret"),c.authMethod==="client_secret_basic"){let l=Gr.from(`${Ht(a)}:${Ht(c.clientSecret)}`,"utf8").toString("base64");r.set("authorization",`Basic ${l}`)}else r.delete("authorization"),s.set("client_id",a),s.set("client_secret",c.clientSecret);return s.toString()}function Ht(t){return new URLSearchParams({value:t}).toString().slice(6)}function un(t){let e=Date.now();for(let[r,n]of t)n.expiresAt<=e&&t.delete(r)}async function dn(t,e){let r=Number(t.headers.get("content-length"));if(Number.isFinite(r)&&r>e)throw new $;return Jt(t.body,e)}async function ce(t,e){let r=Number(t.headers.get("content-length"));if(Number.isFinite(r)&&r>e)throw await t.body?.cancel(),new $;return Jt(t.body,e)}async function Jt(t,e){if(!t)return"";let r=t.getReader(),n=[],o=0;for(;;){let{done:i,value:c}=await r.read();if(i)break;if(o+=c.byteLength,o>e)throw await r.cancel(),new $;n.push(c)}let s=new Uint8Array(o),a=0;for(let i of n)s.set(i,a),a+=i.byteLength;return new TextDecoder().decode(s)}function Ie(t){let e;try{e=JSON.parse(t)}catch{throw new A("OAuth metadata is not valid JSON")}if(!e||typeof e!="object"||Array.isArray(e))throw new A("OAuth metadata is not an object");return e}function $t(t,e){let r=t.get(e);return r&&Date.now()-r.updatedAt<=zt?r:(t.delete(e),{authorizationServers:new Set,endpoints:new Map,userInfoEndpoints:new Set,tokenEndpointAuthMethods:new Set,updatedAt:Date.now()})}function Bt(t){let e=Date.now();for(let[r,n]of t)e-n.updatedAt>zt&&t.delete(r);for(;t.size>Zr;){let r=t.keys().next().value;if(!r)break;t.delete(r)}}function L(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 pn(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 Me(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 hn(t,e,r){try{let n=Me(t);if(n===new URL(e.req.url).origin||r.has(n))return!0;let o=new URL(n),a=e.req.header("x-forwarded-host")?.split(",")[0]?.trim()||e.req.header("host");if(!a||o.host!==a)return!1;let i=e.req.header("x-forwarded-proto")?.split(",")[0]?.trim();return!i||`${i}:`===o.protocol}catch{return!1}}function fn(t){let e=new Headers;return t&&Xt(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 Xt(t,e){t.set("Access-Control-Allow-Origin",e),t.append("Vary","Origin")}async function qt(t,e){return e?e(t):!0}function le(t){return t>=300&&t<400}function Yt(t){let e=t.toLowerCase().replace(/^\[|\]$/g,"");return e==="localhost"||e.endsWith(".localhost")||e==="::1"||e.startsWith("127.")}function mn(t){let e=t.toLowerCase();return e.endsWith(".local")||e.endsWith(".internal")||e.endsWith(".home.arpa")}function Qt(t){if(t.includes(":")){let s=t.toLowerCase();return s.startsWith("::ffff:")?Qt(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 Le(t,e,r){t&&console.log(e===void 0?`[OAuth BFF] ${r}`:`${e} [OAuth BFF] ${r}`)}function Te(t,e,r,n){let o=e instanceof Error?e.message:"Unknown error";return r&&console.error(n===void 0?"[OAuth BFF]":`${n} [OAuth BFF]`,o),e instanceof $?t.json({error:"Upstream response too large"},502):e instanceof A?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 $=class extends Error{},A=class extends Error{};var gn=3;function yn(t,e){return t.includes("text/event-stream")&&!e}function Ne(t,e={}){let r=e.path||"/mcp/proxy",n=e.enableLogging!==!1,o=e.logPrefix,s=e.rateLimiter??new D.default({points:120,duration:60}),a=async(i,c)=>{try{await s.consume(i.req)}catch(l){return G(i,l)}return c()};t.use(`${r}/*`,Dt({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}/*`,o===void 0?Oe():Oe((i,...c)=>console.log(o,i,...c))),t.use(`${r}/*`,a),t.all(`${r}/*`,async i=>{try{if(e.authenticate&&!await e.authenticate(i))return i.json({error:"Unauthorized"},401);let c=i.req.header("X-Target-URL");if(!c)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 ke(c,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(c,i))return i.json({error:"Invalid target URL",details:"The requested target URL is not allowed"},403);try{new URL(c)}catch{return i.json({error:"Invalid target URL format",details:"The X-Target-URL must be a valid HTTP/HTTPS URL"},400)}let l=i.req.method,u={},d=i.req.header();for(let[v,g]of Object.entries(d)){let p=v.toLowerCase();!p.startsWith("x-proxy-")&&!p.startsWith("x-target-")&&!p.startsWith("x-mcp-")&&!p.startsWith("x-forwarded-")&&!p.startsWith("cf-")&&p!=="x-original-host"&&p!=="host"&&p!=="origin"&&p!=="referer"&&p!=="cookie"&&p!=="proxy-authorization"&&p!=="accept-encoding"&&p!=="cdn-loop"&&!p.startsWith("sec-fetch-")&&(u[v]=g)}u["Accept-Encoding"]="identity";let h=l!=="GET"&&l!=="HEAD"?new Uint8Array(await i.req.arrayBuffer()).slice():void 0,f=c,x=l,w=h;for(let v=0;;v+=1){let g=await fetch(f,{method:x,headers:u,body:w,redirect:"manual",signal:i.req.raw.signal}),p=g.headers.get("location");if(!(g.status>=300&&g.status<400&&p))return await wn(g);if(v>=gn)return i.json({error:"Too many upstream redirects"},502);let m=new URL(p,f);if(!await ke(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(f).origin&&(ue(u,"authorization"),ue(u,"proxy-authorization")),(g.status===303||(g.status===301||g.status===302)&&x==="POST")&&(x="GET",w=void 0,ue(u,"content-type"),ue(u,"content-length")),f=m.toString()}}catch(c){let l=c instanceof Error?c.message:"Unknown error",{signal:u}=i.req.raw;if(u.aborted&&(c===u.reason||c instanceof Error&&c.name==="AbortError"))return new Response(null,{status:499});let d=i.req.header("X-Target-URL");return c instanceof Error&&(c.message.includes("ECONNREFUSED")||c.message.includes("fetch failed"))?console.warn(`[MCP Proxy] Connection refused to ${d||"unknown target"} - server may not be running`):console.error("[MCP Proxy] Request failed:",l,`
372
- Target URL:`,d||"unknown",`
373
- Error:`,c),i.json({error:"Proxy request failed",details:l,targetUrl:d||"unknown"},500)}})}function ue(t,e){for(let r of Object.keys(t))r.toLowerCase()===e&&delete t[r]}async function wn(t){let e={};if(t.headers.forEach((o,s)=>{let a=s.toLowerCase();a!=="content-encoding"&&a!=="transfer-encoding"&&a!=="content-length"&&a!=="set-cookie"&&(e[s]=o)}),yn(t.headers.get("content-type")||"",t.headers.get("content-length")))return e["x-accel-buffering"]="no",e["cache-control"]??="no-cache, no-transform",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 Ue(t,e,r=""){let n=i=>`${r}${i}`,o=e?.oauthProxyAllowLoopback??!1,s=e?.oauth!==!1,a=new D.default({points:120,duration:60});if(t.get(n("/inspector/health"),i=>i.json({status:"ok",protocol:"mcp-use-inspector-preview",version:1,capabilities:["view-preview"]})),Ne(t,{path:n("/inspector/api/proxy"),allowLoopback:o,rateLimiter:a,logPrefix:e?.logPrefix}),s&&De(t,{basePath:n("/inspector/api/oauth"),callbackPath:n("/inspector/oauth/callback"),enableLogging:!0,logPrefix:e?.logPrefix,allowedOrigins:e?.oauthProxyAllowedOrigins??[],allowLoopback:o,rateLimiter:a}),e?.autoConnectUrl!==void 0){let i=e.autoConnectUrl;t.get(n("/inspector/config.json"),c=>c.json({autoConnectUrl:i??null}))}}function xn(t,e){if(Sn(t)){let o=t,s=e,a=tr(s?.basePath);if(nr(o)){rr(o,s,a);return}let i=Zt(s,a),c=er(i);o.use(vn(c,i.routes.map(l=>l.path)));return}let r=t,n=tr(r?.basePath);return er(Zt(r,n))}function Zt(t,e){let r=new _e;return rr(r,t,e),r}function rr(t,e,r){let n={oauthProxyAllowedOrigins:e?.oauthProxyAllowedOrigins??[],oauthProxyAllowLoopback:e?.oauthProxyAllowLoopback??!1,logPrefix:e?.logPrefix};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}`})}),Ue(t,n,r),Mt(t,{devMode:e?.devMode??!0,sandboxOrigin:e?.sandboxOrigin,inspectorMode:"embedded",rootRedirect:!1,basePath:r,proxyUrl:`${r}/inspector/api/proxy`,manufactChatUrl:e?.manufactChatUrl},r)}function er(t){return e=>Promise.resolve(t.fetch(e))}function vn(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,a)=>{let i=new URL(o.originalUrl||o.url||"",Rn(o));if(!r.has(i.pathname)&&!n.some(d=>i.pathname.startsWith(d))){a();return}let c=!1,l=new AbortController;s.on("close",()=>{c||l.abort()}),s.destroyed===!0&&l.abort();let u=En(o,i,l.signal);t(u).then(d=>_n(s,d,l.signal)).catch(d=>{l.signal.aborted&&d instanceof Error&&d.name==="AbortError"||a(d)}).finally(()=>{c=!0})}}function Rn(t){let r=je(t.headers["x-forwarded-proto"])||t.protocol||"http",o=je(t.headers["x-forwarded-host"])||je(t.headers.host)||"localhost";return`${r}://${o}`}function je(t){return Array.isArray(t)?t[0]??"":(t??"").split(",")[0].trim()}function En(t,e,r){let n={method:t.method,headers:t.headers,signal:r};return t.method!=="GET"&&t.method!=="HEAD"&&(t.body!==void 0?n.body=Pn(t.body):(n.body=bn.toWeb(t),n.duplex="half")),new globalThis.Request(e,n)}function Pn(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 _n(t,e,r){t.status(e.status),e.headers.forEach((a,i)=>{i!=="set-cookie"&&t.setHeader(i,a)});let n=e.headers.getSetCookie();if(n.length>0&&t.setHeader("set-cookie",n),!e.body){t.end();return}let o=e.body.getReader(),s=()=>{o.cancel().catch(()=>{})};r.aborted?s():r.addEventListener("abort",s,{once:!0});try{for(;!r.aborted;){let{done:a,value:i}=await o.read();if(a||r.aborted)break;t.write(i)}r.aborted||t.end()}finally{r.removeEventListener("abort",s)}}function Sn(t){return!t||typeof t!="object"&&typeof t!="function"?!1:typeof t.use=="function"||nr(t)}function nr(t){return!!t&&typeof t=="object"&&typeof t.fetch=="function"&&typeof t.route=="function"}function tr(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{xn as mountInspector,Ue as registerInspectorProxyRoutes};
371
+ </html>`}function Lt(t,e,r=""){let n=`${r}/inspector/assets`,o=encodeURIComponent(Ct),s={jsUrl:`${n}/inspector.js?v=${o}`,cssUrl:`${n}/inspector.css?v=${o}`},a=u=>`${r}${u}`,i={...e,basePath:e?.basePath??r,proxyUrl:e?.proxyUrl!==void 0?e.proxyUrl:a("/inspector/api/proxy"),disableTelemetry:e?.disableTelemetry??process.env.MCP_USE_ANONYMIZED_TELEMETRY==="false"},c=u=>{let p=new URL(u.req.url),f={...i,sandboxOrigin:i.sandboxOrigin??Ur(p)??null};return u.html(jr(f,r,s))};Et(t,n),t.get(a("/inspector/oauth-popup-closed.html"),u=>u.html(Nr)),t.get(a("/inspector/sandbox"),u=>u.html(_t(new URL(u.req.url).search))),t.get(a("/inspector"),c),t.get(`${a("/inspector")}/`,c);let l=a("/inspector/api/");t.get(a("/inspector/*"),u=>u.req.path.startsWith(l)?u.notFound():c(u)),t.post(a("/inspector/*"),u=>u.req.path.startsWith(l)?u.notFound():c(u)),r===""&&e?.rootRedirect!==!1&&t.get("/",u=>{let p=new URL(u.req.url);return u.redirect(`${a("/inspector")}${p.search}`)})}var It=t=>{let e={origin:"*",allowMethods:["GET","HEAD","PUT","POST","DELETE","PATCH","QUERY"],allowHeaders:[],exposeHeaders:[],...t},r=e.exposeHeaders?.length?e.exposeHeaders.join(","):void 0,n=e.allowHeaders?.length?e.allowHeaders.join(","):void 0,o=(a=>typeof a=="string"?a==="*"?()=>a:i=>a===i?i:null:typeof a=="function"?a:i=>a.includes(i)?i:null)(e.origin),s=(a=>{if(typeof a=="function")return async(i,c)=>(await a(i,c)).join(",");if(Array.isArray(a)){let i=a.join(",");return()=>i}else return()=>""})(e.allowMethods);return async function(i,c){function l(p,f){i.res.headers.set(p,f)}let u=await o(i.req.header("origin")||"",i);if(u&&l("Access-Control-Allow-Origin",u),e.credentials&&l("Access-Control-Allow-Credentials","true"),r&&l("Access-Control-Expose-Headers",r),i.req.method==="OPTIONS"){e.origin!=="*"&&i.res.headers.append("Vary","Origin"),e.maxAge!=null&&l("Access-Control-Max-Age",e.maxAge.toString());let p=await s(i.req.header("origin")||"",i);p&&l("Access-Control-Allow-Methods",p);let f=n;if(!f){let h=i.req.header("Access-Control-Request-Headers");h&&(f=h.split(",").map(x=>x.trim()).join(","))}return f&&(l("Access-Control-Allow-Headers",f),i.res.headers.append("Vary","Access-Control-Request-Headers")),i.res.headers.delete("Content-Length"),i.res.headers.delete("Content-Type"),new Response(null,{headers:i.res.headers,status:204,statusText:"No Content"})}await c(),e.origin!=="*"&&i.header("Vary","Origin",{append:!0})}};function Hr(){let{process:t,Deno:e}=globalThis;return!(typeof e?.noColor=="boolean"?e.noColor:t!==void 0&&"NO_COLOR"in t?.env)}async function Ot(){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}})():!Hr())}var $r=t=>{let[e,r]=[",","."];return t.map(n=>n.replace(/(\d)(?=(\d\d\d)+(?!\d))/g,"$1"+e)).join(r)},Br=t=>{let e=Date.now()-t;return $r([e<1e3?e+"ms":Math.round(e/1e3)+"s"])},qr=async t=>{if(await Ot())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 Tt(t,e,r,n,o=0,s){t(e==="<--"?`${e} ${r} ${n}`:`${e} ${r} ${n} ${await qr(o)} ${s}`)}var Se=(t=console.log)=>async function(r,n){let{method:o,url:s}=r.req,a=s.slice(s.indexOf("/",8));await Tt(t,"<--",o,a);let i=Date.now();await n(),await Tt(t,"-->",o,a,r.res.status,Br(i))};import{lookup as zr}from"dns/promises";import{Buffer as Fr}from"buffer";import{isIP as Wr}from"net";var Vr=new Set(["accept","authorization","content-type","dpop"]),Kr=new Set(["cache-control","content-type","dpop-nonce","expires","pragma","retry-after","www-authenticate"]),Jr=[["registration_endpoint","registration"],["token_endpoint","token"],["revocation_endpoint","revocation"],["introspection_endpoint","introspection"]],Ht=600*1e3,Gr=100,Xr=1440*60*1e3,Yr=500;function Oe(t,e={}){let{basePath:r="/oauth",allowedOrigins:n=[],allowLoopback:o=!1,timeoutMs:s=1e4,maxRequestBodyBytes:a=64*1024,maxResponseBodyBytes:i=1024*1024,callbackPath:c="/oauth/callback",enableLogging:l=!0,logPrefix:u,authenticate:p,validateServerUrl:f,rateLimiter:h=new O.default({points:120,duration:60})}=e,x=new Set(n.map(Ie)),v=new Map,m=new Map,b=async(d,y)=>{try{await h.consume(d.req)}catch(g){return z(d,g)}return y()};t.use(`${r}/*`,async(d,y)=>{let g=d.req.header("Origin");if(g&&!ln(g,d,x))return d.json({error:"Origin not allowed"},403);if(d.req.method==="OPTIONS")return un(g);await y(),g&&Vt(d.res.headers,g)}),t.use(`${r}/*`,b),t.get(`${r}/metadata`,async d=>{if(!await jt(d,p))return d.json({error:"Unauthorized"},401);let y=await D(d.req.query("serverUrl"),o);if("error"in y)return d.json({error:y.error},400);let g=y.url;if(f&&!await f(g.toString(),d))return d.json({error:"MCP server URL not allowed"},403);let L=await D(d.req.query("url"),o);if("error"in L)return d.json({error:L.error},400);let S=L.url,I=_(g),R=Ut(v,I),E=Mt(g,S,R);if(!E&&R.authorizationServers.size===0)try{await kt(g,R,o,s,i),v.set(I,R),E=Mt(g,S,R)}catch{}if(!E)return d.json({error:"Metadata target is not bound to this MCP server"},403);try{_e(l,u,`GET ${S}`);let w=await ne(S,{method:"GET",headers:{Accept:"application/json"},redirect:"manual",signal:AbortSignal.timeout(s)});if(se(w.status))return d.json({error:"OAuth metadata redirects are not allowed"},502);let B=await oe(w,i);if(!w.ok)return d.body(B,w.status,{"Content-Type":w.headers.get("content-type")??"application/json"});let F=Le(B);return E.type==="protected-resource"?await qt(F,g,E.resourceIdentifier,R,o):await zt(F,E.issuer,R,o),R.updatedAt=Date.now(),v.set(I,R),Nt(v),d.body(B,200,{"Content-Type":w.headers.get("content-type")??"application/json"})}catch(w){return Ce(d,w,l,u)}}),t.post(`${r}/proxy`,async d=>{if(!await jt(d,p))return d.json({error:"Unauthorized"},401);let y;try{y=JSON.parse(await an(d.req.raw,a))}catch(C){return d.json({error:C instanceof U?"Request body too large":"Invalid JSON request body"},C instanceof U?413:400)}let g=await D(y.serverUrl,o);if("error"in g)return d.json({error:g.error},400);let L=g.url;if(f&&!await f(L.toString(),d))return d.json({error:"MCP server URL not allowed"},403);let S=await D(y.url,o);if("error"in S)return d.json({error:S.error},400);let I=S.url,R=y.method??"POST";if(R!=="GET"&&R!=="POST")return d.json({error:"OAuth endpoint method not allowed"},405);let E=_(L),w=Ut(v,E);if(w.endpoints.size===0&&w.userInfoEndpoints.size===0)try{await kt(L,w,o,s,i),v.set(E,w),Nt(v)}catch(C){return Ce(d,C,l,u)}let B=_(I),F=w.endpoints.get(B),Ue=w.userInfoEndpoints.has(B);if(!F&&!Ue)return d.json({error:"OAuth endpoint is not bound to this MCP server"},403);let N=R==="GET"&&Ue?"userinfo":F,ae=N==="userinfo"?"GET":"POST";if(!N||R!==ae)return d.json({error:"OAuth endpoint method not allowed"},405);try{let C=en(y.headers),q=N==="userinfo"?void 0:rn(y.body,C);if(N==="registration"){let rr=Ie(d.req.header("Origin")??new URL(d.req.url).origin);q=cn(q,C,new URL(c,rr).toString())}else N!=="userinfo"&&(q=on({body:q,headers:C,bindingKey:E,clients:m}));if(new TextEncoder().encode(q??"").byteLength>a)return d.json({error:"OAuth request body too large"},413);_e(l,u,`${ae} ${N} ${I}`);let j=await ne(I,{method:ae,headers:C,body:q,redirect:"manual",signal:AbortSignal.timeout(s)});if(se(j.status))return d.json({error:"OAuth endpoint redirects are not allowed"},502);let Ne=await oe(j,i),er=tn(j.headers),tr=j.headers.get("content-type")??"",H=Ne;if(tr.includes("json"))try{H=JSON.parse(Ne)}catch{}return N==="registration"&&j.ok&&H&&typeof H=="object"&&!Array.isArray(H)&&(H=nn({responseBody:H,binding:w,bindingKey:E,clients:m})),d.json({status:j.status,statusText:j.statusText,headers:er,body:H})}catch(C){return Ce(d,C,l,u)}}),_e(l,u,`Mounted at ${r}/metadata and ${r}/proxy`)}async function D(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=Kt(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(dn(r.hostname))return{error:"Local network URL not allowed"};try{let o=Wr(r.hostname)?[r.hostname]:(await zr(r.hostname,{all:!0,verbatim:!0})).map(({address:s})=>s);if(o.length===0||o.some(s=>!Jt(s)))return{error:"Private or non-routable URL not allowed"}}catch{return{error:"URL hostname could not be resolved"}}return{url:r}}async function Te(t,e=!1){return!("error"in await D(t,e))}function Mt(t,e,r){let n=_(e),o=$t(t).find(s=>_(s.url)===n);if(o)return{type:"protected-resource",resourceIdentifier:o.resourceIdentifier};for(let s of r.authorizationServers)if(Bt(new URL(s)).some(a=>_(a)===n))return{type:"authorization-server",issuer:s}}function $t(t){let e=t.pathname==="/"?"":t.pathname;return[{url:new URL(`/.well-known/oauth-protected-resource${e}`,t.origin),resourceIdentifier:t},{url:new URL("/.well-known/oauth-protected-resource",t.origin),resourceIdentifier:new URL(t.origin)}]}function Bt(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 qt(t,e,r,n,o){let s=Qr(t.resource,o),a=s!==void 0&&_(s)===_(r),i=s!==void 0&&Zr(e,s);if(!a&&!i)throw new A("Protected-resource metadata does not match serverUrl");if(!Array.isArray(t.authorization_servers)||t.authorization_servers.length===0)throw new A("Protected-resource metadata has no authorization servers");let c=new Set;for(let l of t.authorization_servers){let u=await D(l,o);if("error"in u)throw new A(`Unsafe authorization server: ${u.error}`);c.add(_(u.url))}n.authorizationServers=c,n.endpoints.clear(),n.userInfoEndpoints.clear(),n.tokenEndpointAuthMethods.clear()}function Qr(t,e){if(!(typeof t!="string"||t.length===0))try{let r=new URL(t);return!(r.protocol==="https:"||e&&r.protocol==="http:"&&Kt(r.hostname))||r.username||r.password||r.hash?void 0:r}catch{return}}function Zr(t,e){if(t.origin!==e.origin||t.pathname.length<e.pathname.length)return!1;let r=t.pathname.endsWith("/")?t.pathname:`${t.pathname}/`,n=e.pathname.endsWith("/")?e.pathname:`${e.pathname}/`;return r.startsWith(n)}async function zt(t,e,r,n){if(typeof t.issuer!="string"||_(new URL(t.issuer))!==e)throw new A("Authorization-server metadata issuer mismatch");r.endpoints.clear(),r.userInfoEndpoints.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 Jr){let a=t[o];if(a===void 0)continue;let i=await D(a,n);if("error"in i)throw new A(`Unsafe ${o}: ${i.error}`);r.endpoints.set(_(i.url),s)}if(t.userinfo_endpoint!==void 0){let o=await D(t.userinfo_endpoint,n);if("error"in o)throw new A(`Unsafe userinfo_endpoint: ${o.error}`);r.userInfoEndpoints.add(_(o.url))}}async function kt(t,e,r,n,o){for(let s of $t(t)){let a=await ne(s.url,{method:"GET",headers:{Accept:"application/json"},redirect:"manual",signal:AbortSignal.timeout(n)});if(se(a.status))throw new A("OAuth metadata redirects are not allowed");if(a.ok){await qt(Le(await oe(a,o)),t,s.resourceIdentifier,e,r);break}}if(e.authorizationServers.size===0)throw new A("Protected-resource metadata could not be discovered");for(let s of e.authorizationServers){let a=!1;for(let i of Bt(new URL(s))){let c=await ne(i,{method:"GET",headers:{Accept:"application/json"},redirect:"manual",signal:AbortSignal.timeout(n)});if(se(c.status))throw new A("OAuth metadata redirects are not allowed");if(c.ok){await zt(Le(await oe(c,o)),s,e,r),a=!0;break}}if(a)break}if(e.endpoints.size===0&&e.userInfoEndpoints.size===0)throw new A("Authorization-server metadata could not be discovered");e.updatedAt=Date.now()}async function ne(t,e){return fetch(t,e)}function en(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();Vr.has(o)&&typeof n=="string"&&e.set(o,n)}return e}function tn(t){let e={};return t.forEach((r,n)=>{Kr.has(n.toLowerCase())&&(e[n]=r)}),e}function rn(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 Ft(t,e){return`${t}\0${e}`}function nn(t){let{responseBody:e,binding:r,bindingKey:n,clients:o}=t,s=e.client_id,a=e.client_secret;if(typeof s!="string"||typeof a!="string")return e;let i=e.token_endpoint_auth_method,c=i==="client_secret_post"||i==="client_secret_basic"?i: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()+Xr;for(sn(o),o.set(Ft(n,s),{clientSecret:a,authMethod:c,expiresAt:u});o.size>Yr;){let f=o.keys().next().value;if(!f)break;o.delete(f)}let p={...e};return delete p.client_secret,delete p.client_secret_expires_at,p.token_endpoint_auth_method="none",p}function on(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),a=s.get("client_id");if(!a)return e;let i=Ft(n,a),c=o.get(i);if(!c)return e;if(c.expiresAt<=Date.now())return o.delete(i),e;if(s.delete("client_secret"),c.authMethod==="client_secret_basic"){let l=Fr.from(`${Dt(a)}:${Dt(c.clientSecret)}`,"utf8").toString("base64");r.set("authorization",`Basic ${l}`)}else r.delete("authorization"),s.set("client_id",a),s.set("client_secret",c.clientSecret);return s.toString()}function Dt(t){return new URLSearchParams({value:t}).toString().slice(6)}function sn(t){let e=Date.now();for(let[r,n]of t)n.expiresAt<=e&&t.delete(r)}async function an(t,e){let r=Number(t.headers.get("content-length"));if(Number.isFinite(r)&&r>e)throw new U;return Wt(t.body,e)}async function oe(t,e){let r=Number(t.headers.get("content-length"));if(Number.isFinite(r)&&r>e)throw await t.body?.cancel(),new U;return Wt(t.body,e)}async function Wt(t,e){if(!t)return"";let r=t.getReader(),n=[],o=0;for(;;){let{done:i,value:c}=await r.read();if(i)break;if(o+=c.byteLength,o>e)throw await r.cancel(),new U;n.push(c)}let s=new Uint8Array(o),a=0;for(let i of n)s.set(i,a),a+=i.byteLength;return new TextDecoder().decode(s)}function Le(t){let e;try{e=JSON.parse(t)}catch{throw new A("OAuth metadata is not valid JSON")}if(!e||typeof e!="object"||Array.isArray(e))throw new A("OAuth metadata is not an object");return e}function Ut(t,e){let r=t.get(e);return r&&Date.now()-r.updatedAt<=Ht?r:(t.delete(e),{authorizationServers:new Set,endpoints:new Map,userInfoEndpoints:new Set,tokenEndpointAuthMethods:new Set,updatedAt:Date.now()})}function Nt(t){let e=Date.now();for(let[r,n]of t)e-n.updatedAt>Ht&&t.delete(r);for(;t.size>Gr;){let r=t.keys().next().value;if(!r)break;t.delete(r)}}function _(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 cn(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 Ie(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 ln(t,e,r){try{let n=Ie(t);if(n===new URL(e.req.url).origin||r.has(n))return!0;let o=new URL(n),a=e.req.header("x-forwarded-host")?.split(",")[0]?.trim()||e.req.header("host");if(!a||o.host!==a)return!1;let i=e.req.header("x-forwarded-proto")?.split(",")[0]?.trim();return!i||`${i}:`===o.protocol}catch{return!1}}function un(t){let e=new Headers;return t&&Vt(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 Vt(t,e){t.set("Access-Control-Allow-Origin",e),t.append("Vary","Origin")}async function jt(t,e){return e?e(t):!0}function se(t){return t>=300&&t<400}function Kt(t){let e=t.toLowerCase().replace(/^\[|\]$/g,"");return e==="localhost"||e.endsWith(".localhost")||e==="::1"||e.startsWith("127.")}function dn(t){let e=t.toLowerCase();return e.endsWith(".local")||e.endsWith(".internal")||e.endsWith(".home.arpa")}function Jt(t){if(t.includes(":")){let s=t.toLowerCase();return s.startsWith("::ffff:")?Jt(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 _e(t,e,r){t&&console.log(e===void 0?`[OAuth BFF] ${r}`:`${e} [OAuth BFF] ${r}`)}function Ce(t,e,r,n){let o=e instanceof Error?e.message:"Unknown error";return r&&console.error(n===void 0?"[OAuth BFF]":`${n} [OAuth BFF]`,o),e instanceof U?t.json({error:"Upstream response too large"},502):e instanceof A?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{},A=class extends Error{};var pn=3;function fn(t,e){return t.includes("text/event-stream")&&!e}function Me(t,e={}){let r=e.path||"/mcp/proxy",n=e.enableLogging!==!1,o=e.logPrefix,s=e.rateLimiter??new O.default({points:120,duration:60}),a=async(i,c)=>{try{await s.consume(i.req)}catch(l){return z(i,l)}return c()};t.use(`${r}/*`,It({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}/*`,o===void 0?Se():Se((i,...c)=>console.log(o,i,...c))),t.use(`${r}/*`,a),t.all(`${r}/*`,async i=>{try{if(e.authenticate&&!await e.authenticate(i))return i.json({error:"Unauthorized"},401);let c=i.req.header("X-Target-URL");if(!c)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 Te(c,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(c,i))return i.json({error:"Invalid target URL",details:"The requested target URL is not allowed"},403);try{new URL(c)}catch{return i.json({error:"Invalid target URL format",details:"The X-Target-URL must be a valid HTTP/HTTPS URL"},400)}let l=i.req.method,u={},p=i.req.header();for(let[m,b]of Object.entries(p)){let d=m.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[m]=b)}u["Accept-Encoding"]="identity";let f=l!=="GET"&&l!=="HEAD"?new Uint8Array(await i.req.arrayBuffer()).slice():void 0,h=c,x=l,v=f;for(let m=0;;m+=1){let b=await fetch(h,{method:x,headers:u,body:v,redirect:"manual",signal:i.req.raw.signal}),d=b.headers.get("location");if(!(b.status>=300&&b.status<400&&d))return await hn(b);if(m>=pn)return i.json({error:"Too many upstream redirects"},502);let y=new URL(d,h);if(!await Te(y.toString(),e.allowLoopback??!1)||e.validateRequest&&!await e.validateRequest(y.toString(),i))return i.json({error:"Redirect target is not allowed"},403);y.origin!==new URL(h).origin&&(ie(u,"authorization"),ie(u,"proxy-authorization")),(b.status===303||(b.status===301||b.status===302)&&x==="POST")&&(x="GET",v=void 0,ie(u,"content-type"),ie(u,"content-length")),h=y.toString()}}catch(c){let l=c instanceof Error?c.message:"Unknown error",{signal:u}=i.req.raw;if(u.aborted&&(c===u.reason||c instanceof Error&&c.name==="AbortError"))return new Response(null,{status:499});let p=i.req.header("X-Target-URL");return c instanceof Error&&(c.message.includes("ECONNREFUSED")||c.message.includes("fetch failed"))?console.warn(`[MCP Proxy] Connection refused to ${p||"unknown target"} - server may not be running`):console.error("[MCP Proxy] Request failed:",l,`
372
+ Target URL:`,p||"unknown",`
373
+ Error:`,c),i.json({error:"Proxy request failed",details:l,targetUrl:p||"unknown"},500)}})}function ie(t,e){for(let r of Object.keys(t))r.toLowerCase()===e&&delete t[r]}async function hn(t){let e={};if(t.headers.forEach((o,s)=>{let a=s.toLowerCase();a!=="content-encoding"&&a!=="transfer-encoding"&&a!=="content-length"&&a!=="set-cookie"&&(e[s]=o)}),fn(t.headers.get("content-type")||"",t.headers.get("content-length")))return e["x-accel-buffering"]="no",e["cache-control"]??="no-cache, no-transform",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 ke(t,e,r=""){let n=i=>`${r}${i}`,o=e?.oauthProxyAllowLoopback??!1,s=e?.oauth!==!1,a=new O.default({points:120,duration:60});if(t.get(n("/inspector/health"),i=>i.json({status:"ok",protocol:"mcp-use-inspector-preview",version:1,capabilities:["view-preview"]})),Me(t,{path:n("/inspector/api/proxy"),allowLoopback:o,rateLimiter:a,logPrefix:e?.logPrefix}),s&&Oe(t,{basePath:n("/inspector/api/oauth"),callbackPath:n("/inspector/oauth/callback"),enableLogging:!0,logPrefix:e?.logPrefix,allowedOrigins:e?.oauthProxyAllowedOrigins??[],allowLoopback:o,rateLimiter:a}),e?.autoConnectUrl!==void 0){let i=e.autoConnectUrl;t.get(n("/inspector/config.json"),c=>c.json({autoConnectUrl:i??null}))}}function gn(t,e){if(vn(t)){let o=t,s=e,a=Yt(s?.basePath);if(Zt(o)){Qt(o,s,a);return}let i=Gt(s,a),c=Xt(i);o.use(yn(c,i.routes.map(l=>l.path)));return}let r=t,n=Yt(r?.basePath);return Xt(Gt(r,n))}function Gt(t,e){let r=new ve;return Qt(r,t,e),r}function Qt(t,e,r){let n={oauthProxyAllowedOrigins:e?.oauthProxyAllowedOrigins??[],oauthProxyAllowLoopback:e?.oauthProxyAllowLoopback??!1,logPrefix:e?.logPrefix};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}`})}),ke(t,n,r),Lt(t,{devMode:e?.devMode??!0,sandboxOrigin:e?.sandboxOrigin,inspectorMode:"embedded",rootRedirect:!1,basePath:r,proxyUrl:`${r}/inspector/api/proxy`,manufactChatUrl:e?.manufactChatUrl},r)}function Xt(t){return e=>Promise.resolve(t.fetch(e))}function yn(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,a)=>{let i=new URL(o.originalUrl||o.url||"",wn(o));if(!r.has(i.pathname)&&!n.some(p=>i.pathname.startsWith(p))){a();return}let c=!1,l=new AbortController;s.on("close",()=>{c||l.abort()}),s.destroyed===!0&&l.abort();let u=bn(o,i,l.signal);t(u).then(p=>Rn(s,p,l.signal)).catch(p=>{l.signal.aborted&&p instanceof Error&&p.name==="AbortError"||a(p)}).finally(()=>{c=!0})}}function wn(t){let r=De(t.headers["x-forwarded-proto"])||t.protocol||"http",o=De(t.headers["x-forwarded-host"])||De(t.headers.host)||"localhost";return`${r}://${o}`}function De(t){return Array.isArray(t)?t[0]??"":(t??"").split(",")[0].trim()}function bn(t,e,r){let n={method:t.method,headers:t.headers,signal:r};return t.method!=="GET"&&t.method!=="HEAD"&&(t.body!==void 0?n.body=xn(t.body):(n.body=mn.toWeb(t),n.duplex="half")),new globalThis.Request(e,n)}function xn(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 Rn(t,e,r){t.status(e.status),e.headers.forEach((a,i)=>{i!=="set-cookie"&&t.setHeader(i,a)});let n=e.headers.getSetCookie();if(n.length>0&&t.setHeader("set-cookie",n),!e.body){t.end();return}let o=e.body.getReader(),s=()=>{o.cancel().catch(()=>{})};r.aborted?s():r.addEventListener("abort",s,{once:!0});try{for(;!r.aborted;){let{done:a,value:i}=await o.read();if(a||r.aborted)break;t.write(i)}r.aborted||t.end()}finally{r.removeEventListener("abort",s)}}function vn(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 Yt(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{gn as mountInspector,ke 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.3.15-canary.0",
4
+ "version": "20.3.15",
5
5
  "description": "MCP Inspector - A tool for inspecting and debugging MCP servers",
6
6
  "author": "",
7
7
  "license": "MIT",
@@ -53,7 +53,7 @@
53
53
  "express": "^4.21.2 || ^5.0.0",
54
54
  "lucide-react": "^0.562.0",
55
55
  "markdown-to-jsx": "^9.7.4",
56
- "mcp-use": "^2.4.3 || ^2.4.4 || ^2.5.0 || ^2.5.1 || ^2.5.2 || ^2.6.0 || ^2.6.1 || ^2.7.0 || ^2.7.1 || ^2.7.2 || ^2.7.3-canary.0",
56
+ "mcp-use": "^2.4.3 || ^2.4.4 || ^2.5.0 || ^2.5.1 || ^2.5.2 || ^2.6.0 || ^2.6.1 || ^2.7.0 || ^2.7.1 || ^2.7.2 || ^2.7.3",
57
57
  "motion": "^12.34.2",
58
58
  "react": "^18.0.0 || ^19.0.0",
59
59
  "react-dom": "^18.0.0 || ^19.0.0",
@@ -124,7 +124,7 @@
124
124
  "emulate": "0.5.0",
125
125
  "eslint": "^9.39.2",
126
126
  "express": "^5.2.1",
127
- "hono": "^4.13.5",
127
+ "hono": "^4.13.7",
128
128
  "jsdom": "^27.0.0",
129
129
  "lucide-react": "^0.562.0",
130
130
  "markdown-to-jsx": "^9.7.4",
@@ -145,12 +145,12 @@
145
145
  "tw-animate-css": "^1.4.0",
146
146
  "typescript": "^5.9.3",
147
147
  "vite": "^8.0.16",
148
- "vitest": "^4.1.0",
148
+ "vitest": "^4.1.11",
149
149
  "wait-on": "^9.0.4",
150
150
  "yaml": "^2.8.3",
151
151
  "zod": "^4.2.0",
152
- "@mcp-use/client": "2.4.0",
153
- "@mcp-use/agent": "2.0.20"
152
+ "@mcp-use/agent": "2.0.20",
153
+ "@mcp-use/client": "2.4.0"
154
154
  },
155
155
  "scripts": {
156
156
  "dev": "rimraf node_modules/.vite && vite --strictPort",