@mcp-use/inspector 20.0.0-beta.33 → 20.0.0-beta.34

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -278,7 +278,10 @@ For **Ollama**, the API key is optional and you can point the inspector at a loc
278
278
  The inspector automatically saves your configurations:
279
279
 
280
280
  - **Server connections** persist across page reloads
281
- - **Credentials** are stored securely in your browser's localStorage
281
+ - **OAuth sessions** persist as AES-256-GCM ciphertext using a non-extractable
282
+ origin key in IndexedDB
283
+ - **Secret headers and client secrets** are runtime-only and must be supplied
284
+ again after reload
282
285
  - **Session preferences** are maintained automatically
283
286
  - Clear all sessions anytime with the **"Clear All"** button
284
287
 
Binary file
package/dist/cli.js CHANGED
@@ -1,16 +1,16 @@
1
1
  #!/usr/bin/env node
2
- import{createServer as qr}from"http";import{Http2ServerRequest as yt,constants as zr}from"http2";import{Http2ServerRequest as _e}from"http2";import{Readable as mt}from"stream";import rn from"crypto";var N=class extends Error{constructor(e,t){super(e,t),this.name="RequestError"}},Wr=e=>e instanceof N?e:new N(e.message,{cause:e}),Vr=global.Request,Z=class extends Vr{constructor(e,t){typeof e=="object"&&V in e&&(e=e[V]()),typeof t?.body?.getReader<"u"&&(t.duplex??="half"),super(e,t)}},Gr=e=>{let t=[],r=e.rawHeaders;for(let n=0;n<r.length;n+=2){let{[n]:o,[n+1]:s}=r;o.charCodeAt(0)!==58&&t.push([o,s])}return new Headers(t)},bt=Symbol("wrapBodyStream"),Kr=(e,t,r,n,o)=>{let s={method:e,headers:r,signal:o.signal};if(e==="TRACE"){s.method="GET";let i=new Z(t,s);return Object.defineProperty(i,"method",{get(){return"TRACE"}}),i}if(!(e==="GET"||e==="HEAD"))if("rawBody"in n&&n.rawBody instanceof Buffer)s.body=new ReadableStream({start(i){i.enqueue(n.rawBody),i.close()}});else if(n[bt]){let i;s.body=new ReadableStream({async pull(a){try{i||=mt.toWeb(n).getReader();let{done:c,value:l}=await i.read();c?a.close():a.enqueue(l)}catch(c){a.error(c)}}})}else s.body=mt.toWeb(n);return new Z(t,s)},V=Symbol("getRequestCache"),Xr=Symbol("requestCache"),ae=Symbol("incomingKey"),ce=Symbol("urlKey"),Jr=Symbol("headersKey"),W=Symbol("abortControllerKey"),Yr=Symbol("getAbortController"),le={get method(){return this[ae].method||"GET"},get url(){return this[ce]},get headers(){return this[Jr]||=Gr(this[ae])},[Yr](){return this[V](),this[W]},[V](){return this[W]||=new AbortController,this[Xr]||=Kr(this.method,this[ce],this.headers,this[ae],this[W])}};["body","bodyUsed","cache","credentials","destination","integrity","mode","redirect","referrer","referrerPolicy","signal","keepalive"].forEach(e=>{Object.defineProperty(le,e,{get(){return this[V]()[e]}})});["arrayBuffer","blob","clone","formData","json","text"].forEach(e=>{Object.defineProperty(le,e,{value:function(){return this[V]()[e]()}})});Object.setPrototypeOf(le,Z.prototype);var Qr=(e,t)=>{let r=Object.create(le);r[ae]=e;let n=e.url||"";if(n[0]!=="/"&&(n.startsWith("http://")||n.startsWith("https://"))){if(e instanceof _e)throw new N("Absolute URL for :path is not allowed in HTTP/2");try{let a=new URL(n);r[ce]=a.href}catch(a){throw new N("Invalid absolute URL",{cause:a})}return r}let o=(e instanceof _e?e.authority:e.headers.host)||t;if(!o)throw new N("Missing host header");let s;if(e instanceof _e){if(s=e.scheme,!(s==="http"||s==="https"))throw new N("Unsupported scheme")}else s=e.socket&&e.socket.encrypted?"https":"http";let i=new URL(`${s}://${o}${n}`);if(i.hostname.length!==o.length&&i.hostname!==o.replace(/:\d+$/,""))throw new N("Invalid host header");return r[ce]=i.href,r},gt=Symbol("responseCache"),z=Symbol("getResponseCache"),$=Symbol("cache"),Ue=global.Response,ee=class vt{#t;#e;[z](){return delete this[$],this[gt]||=new Ue(this.#t,this.#e)}constructor(t,r){let n;if(this.#t=t,r instanceof vt){let o=r[gt];if(o){this.#e=o,this[z]();return}else this.#e=r.#e,n=new Headers(r.#e.headers)}else this.#e=r;(typeof t=="string"||typeof t?.getReader<"u"||t instanceof Blob||t instanceof Uint8Array)&&(this[$]=[r?.status||200,t,n||r?.headers])}get headers(){let t=this[$];return t?(t[2]instanceof Headers||(t[2]=new Headers(t[2]||{"content-type":"text/plain; charset=UTF-8"})),t[2]):this[z]().headers}get status(){return this[$]?.[0]??this[z]().status}get ok(){let t=this.status;return t>=200&&t<300}};["body","bodyUsed","redirected","statusText","trailers","type","url"].forEach(e=>{Object.defineProperty(ee.prototype,e,{get(){return this[z]()[e]}})});["arrayBuffer","blob","clone","formData","json","text"].forEach(e=>{Object.defineProperty(ee.prototype,e,{value:function(){return this[z]()[e]()}})});Object.setPrototypeOf(ee,Ue);Object.setPrototypeOf(ee.prototype,Ue.prototype);async function Zr(e){return Promise.race([e,Promise.resolve().then(()=>Promise.resolve(void 0))])}function xt(e,t,r){let n=a=>{e.cancel(a).catch(()=>{})};return t.on("close",n),t.on("error",n),(r??e.read()).then(i,o),e.closed.finally(()=>{t.off("close",n),t.off("error",n)});function o(a){a&&t.destroy(a)}function s(){e.read().then(i,o)}function i({done:a,value:c}){try{if(a)t.end();else if(!t.write(c))t.once("drain",s);else return e.read().then(i,o)}catch(l){o(l)}}}function en(e,t){if(e.locked)throw new TypeError("ReadableStream is locked.");return t.destroyed?void 0:xt(e.getReader(),t)}var Le=e=>{let t={};e instanceof Headers||(e=new Headers(e??void 0));let r=[];for(let[n,o]of e)n==="set-cookie"?r.push(o):t[n]=o;return r.length>0&&(t["set-cookie"]=r),t["content-type"]??="text/plain; charset=UTF-8",t},tn="x-hono-already-sent";typeof global.crypto>"u"&&(global.crypto=rn);var Me=Symbol("outgoingEnded"),wt=Symbol("incomingDraining"),nn=500,on=64*1024*1024,Te=e=>{let t=e;if(e.destroyed||t[wt])return;if(t[wt]=!0,e instanceof yt){try{e.stream?.close?.(zr.NGHTTP2_NO_ERROR)}catch{}return}let r=0,n=()=>{clearTimeout(s),e.off("data",i),e.off("end",n),e.off("error",n)},o=()=>{n();let a=e.socket;a&&!a.destroyed&&a.destroySoon()},s=setTimeout(o,nn);s.unref?.();let i=a=>{r+=a.length,r>on&&o()};e.on("data",i),e.on("end",n),e.on("error",n),e.resume()},sn=()=>new Response(null,{status:400}),Rt=e=>new Response(null,{status:e instanceof Error&&(e.name==="TimeoutError"||e.constructor.name==="TimeoutError")?504:500}),ke=(e,t)=>{let r=e instanceof Error?e:new Error("unknown error",{cause:e});r.code==="ERR_STREAM_PREMATURE_CLOSE"?console.info("The user aborted a request."):(console.error(e),t.headersSent||t.writeHead(500,{"Content-Type":"text/plain"}),t.end(`Error: ${r.message}`),t.destroy(r))},Et=e=>{"flushHeaders"in e&&e.writable&&e.flushHeaders()},St=async(e,t)=>{let[r,n,o]=e[$],s=!1;if(!o)o={"content-type":"text/plain; charset=UTF-8"};else if(o instanceof Headers)s=o.has("content-length"),o=Le(o);else if(Array.isArray(o)){let i=new Headers(o);s=i.has("content-length"),o=Le(i)}else for(let i in o)if(i.length===14&&i.toLowerCase()==="content-length"){s=!0;break}s||(typeof n=="string"?o["Content-Length"]=Buffer.byteLength(n):n instanceof Uint8Array?o["Content-Length"]=n.byteLength:n instanceof Blob&&(o["Content-Length"]=n.size)),t.writeHead(r,o),typeof n=="string"||n instanceof Uint8Array?t.end(n):n instanceof Blob?t.end(new Uint8Array(await n.arrayBuffer())):(Et(t),await en(n,t)?.catch(i=>ke(i,t))),t[Me]?.()},an=e=>typeof e.then=="function",cn=async(e,t,r={})=>{if(an(e))if(r.errorHandler)try{e=await e}catch(o){let s=await r.errorHandler(o);if(!s)return;e=s}else e=await e.catch(Rt);if($ in e)return St(e,t);let n=Le(e.headers);if(e.body){let o=e.body.getReader(),s=[],i=!1,a;if(n["transfer-encoding"]!=="chunked"){let c=2;for(let l=0;l<c;l++){a||=o.read();let u=await Zr(a).catch(d=>{console.error(d),i=!0});if(!u){if(l===1){await new Promise(d=>setTimeout(d)),c=3;continue}break}if(a=void 0,u.value&&s.push(u.value),u.done){i=!0;break}}i&&!("content-length"in n)&&(n["content-length"]=s.reduce((l,u)=>l+u.length,0))}t.writeHead(e.status,n),s.forEach(c=>{t.write(c)}),i?t.end():(s.length===0&&Et(t),await xt(o,t,a))}else n[tn]||(t.writeHead(e.status,n),t.end());t[Me]?.()},ln=(e,t={})=>{let r=t.autoCleanupIncoming??!0;return t.overrideGlobalObjects!==!1&&global.Request!==Z&&(Object.defineProperty(global,"Request",{value:Z}),Object.defineProperty(global,"Response",{value:ee})),async(n,o)=>{let s,i;try{i=Qr(n,t.hostname);let a=!r||n.method==="GET"||n.method==="HEAD";if(a||(n[bt]=!0,n.on("end",()=>{a=!0}),n instanceof yt&&(o[Me]=()=>{a||setTimeout(()=>{a||setTimeout(()=>{Te(n)})})}),o.on("finish",()=>{a||Te(n)})),o.on("close",()=>{i[W]&&(n.errored?i[W].abort(n.errored.toString()):o.writableFinished||i[W].abort("Client connection prematurely closed.")),a||setTimeout(()=>{a||setTimeout(()=>{Te(n)})})}),s=e(i,{incoming:n,outgoing:o}),$ in s)return St(s,o)}catch(a){if(s)return ke(a,o);if(t.errorHandler){if(s=await t.errorHandler(i?a:Wr(a)),!s)return}else i?s=Rt(a):s=sn()}try{return await cn(s,o,t)}catch(a){return ke(a,o)}}},un=e=>{let t=e.fetch,r=ln(t,{hostname:e.hostname,overrideGlobalObjects:e.overrideGlobalObjects,autoCleanupIncoming:e.autoCleanupIncoming});return(e.createServer||qr)(e.serverOptions||{},r)},Pt=(e,t)=>{let r=un(e);return r.listen(e?.port??3e3,e.hostname,()=>{let n=r.address();t&&t(n)}),r};var Ie=(e,t,r)=>(n,o)=>{let s=-1;return i(0);async function i(a){if(a<=s)throw new Error("next() called multiple times");s=a;let c,l=!1,u;if(e[a]?(u=e[a][0][0],n.req.routeIndex=a):u=a===e.length&&o||void 0,u)try{c=await u(n,()=>i(a+1))}catch(d){if(d instanceof Error&&t)n.error=d,c=await t(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 At=Symbol();var Ct=async(e,t=Object.create(null))=>{let{all:r=!1,dot:n=!1}=t,s=(e instanceof ue?e.raw.headers:e.headers).get("Content-Type");return s?.startsWith("multipart/form-data")||s?.startsWith("application/x-www-form-urlencoded")?dn(e,{all:r,dot:n}):{}};async function dn(e,t){let r=await e.formData();return r?pn(r,t):{}}function pn(e,t){let r=Object.create(null);return e.forEach((n,o)=>{t.all||o.endsWith("[]")?fn(r,o,n):r[o]=n}),t.dot&&Object.entries(r).forEach(([n,o])=>{n.includes(".")&&(hn(r,n,o),delete r[n])}),r}var fn=(e,t,r)=>{e[t]!==void 0?Array.isArray(e[t])?e[t].push(r):e[t]=[e[t],r]:t.endsWith("[]")?e[t]=[r]:e[t]=r},hn=(e,t,r)=>{if(/(?:^|\.)__proto__\./.test(t))return;let n=e,o=t.split(".");o.forEach((s,i)=>{i===o.length-1?n[s]=r:((!n[s]||typeof n[s]!="object"||Array.isArray(n[s])||n[s]instanceof File)&&(n[s]=Object.create(null)),n=n[s])})};var je=e=>{let t=e.split("/");return t[0]===""&&t.shift(),t},Ot=e=>{let{groups:t,path:r}=mn(e),n=je(r);return gn(n,t)},mn=e=>{let t=[];return e=e.replace(/\{[^}]+\}/g,(r,n)=>{let o=`@${n}`;return t.push([o,r]),o}),{groups:t,path:e}},gn=(e,t)=>{for(let r=t.length-1;r>=0;r--){let[n]=t[r];for(let o=e.length-1;o>=0;o--)if(e[o].includes(n)){e[o]=e[o].replace(n,t[r][1]);break}}return e},de={},_t=(e,t)=>{if(e==="*")return"*";let r=e.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);if(r){let n=`${e}#${t}`;return de[n]||(r[2]?de[n]=t&&t[0]!==":"&&t[0]!=="*"?[n,r[1],new RegExp(`^${r[2]}(?=/${t})`)]:[e,r[1],new RegExp(`^${r[2]}$`)]:de[n]=[e,r[1],!0]),de[n]}return null},pe=(e,t)=>{try{return t(e)}catch{return e.replace(/(?:%[0-9A-Fa-f]{2})+/g,r=>{try{return t(r)}catch{return r}})}},wn=e=>pe(e,decodeURI),Ne=e=>{let t=e.url,r=t.indexOf("/",t.indexOf(":")+4),n=r;for(;n<t.length;n++){let o=t.charCodeAt(n);if(o===37){let s=t.indexOf("?",n),i=t.indexOf("#",n),a=s===-1?i===-1?void 0:i:i===-1?s:Math.min(s,i),c=t.slice(r,a);return wn(c.includes("%25")?c.replace(/%25/g,"%2525"):c)}else if(o===63||o===35)break}return t.slice(r,n)};var Tt=e=>{let t=Ne(e);return t.length>1&&t.at(-1)==="/"?t.slice(0,-1):t},H=(e,t,...r)=>(r.length&&(t=H(t,...r)),`${e?.[0]==="/"?"":"/"}${e}${t==="/"?"":`${e?.at(-1)==="/"?"":"/"}${t?.[0]==="/"?t.slice(1):t}`}`),fe=e=>{if(e.charCodeAt(e.length-1)!==63||!e.includes(":"))return null;let t=e.split("/"),r=[],n="";return t.forEach(o=>{if(o!==""&&!/\:/.test(o))n+="/"+o;else if(/\:/.test(o))if(/\?/.test(o)){r.length===0&&n===""?r.push("/"):r.push(n);let s=o.replace("?","");n+="/"+s,r.push(n)}else n+="/"+o}),r.filter((o,s,i)=>i.indexOf(o)===s)},He=e=>/[%+]/.test(e)?(e.indexOf("+")!==-1&&(e=e.replace(/\+/g," ")),e.indexOf("%")!==-1?pe(e,$e):e):e,Lt=(e,t,r)=>{let n;if(!r&&t&&!/[%+]/.test(t)){let i=e.indexOf("?",8);if(i===-1)return;for(e.startsWith(t,i+1)||(i=e.indexOf(`&${t}`,i+1));i!==-1;){let a=e.charCodeAt(i+t.length+1);if(a===61){let c=i+t.length+2,l=e.indexOf("&",c);return He(e.slice(c,l===-1?void 0:l))}else if(a==38||isNaN(a))return"";i=e.indexOf(`&${t}`,i+1)}if(n=/[%+]/.test(e),!n)return}let o={};n??=/[%+]/.test(e);let s=e.indexOf("?",8);for(;s!==-1;){let i=e.indexOf("&",s+1),a=e.indexOf("=",s);a>i&&i!==-1&&(a=-1);let c=e.slice(s+1,a===-1?i===-1?void 0:i:a);if(n&&(c=He(c)),s=i,c==="")continue;let l;a===-1?l="":(l=e.slice(a+1,i===-1?void 0:i),n&&(l=He(l))),r?(o[c]&&Array.isArray(o[c])||(o[c]=[]),o[c].push(l)):o[c]??=l}return t?o[t]:o},kt=Lt,Ut=(e,t)=>Lt(e,t,!0),$e=decodeURIComponent;var Mt=e=>pe(e,$e),ue=class{raw;#t;#e;routeIndex=0;path;bodyCache={};constructor(e,t="/",r=[[]]){this.raw=e,this.path=t,this.#e=r,this.#t={}}param(e){return e?this.#r(e):this.#s()}#r(e){let t=this.#e[0][this.routeIndex][1][e],r=this.#o(t);return r&&/\%/.test(r)?Mt(r):r}#s(){let e={},t=Object.keys(this.#e[0][this.routeIndex][1]);for(let r of t){let n=this.#o(this.#e[0][this.routeIndex][1][r]);n!==void 0&&(e[r]=/\%/.test(n)?Mt(n):n)}return e}#o(e){return this.#e[1]?this.#e[1][e]:e}query(e){return kt(this.url,e)}queries(e){return Ut(this.url,e)}header(e){if(e)return this.raw.headers.get(e)??void 0;let t={};return this.raw.headers.forEach((r,n)=>{t[n]=r}),t}async parseBody(e){return Ct(this,e)}#n=e=>{let{bodyCache:t,raw:r}=this,n=t[e];if(n)return n;let o=Object.keys(t)[0];return o?t[o].then(s=>(o==="json"&&(s=JSON.stringify(s)),new Response(s)[e]())):t[e]=r[e]()};json(){return this.#n("text").then(e=>JSON.parse(e))}text(){return this.#n("text")}arrayBuffer(){return this.#n("arrayBuffer")}bytes(){return this.#n("arrayBuffer").then(e=>new Uint8Array(e))}blob(){return this.#n("blob")}formData(){return this.#n("formData")}addValidatedData(e,t){this.#t[e]=t}valid(e){return this.#t[e]}get url(){return this.raw.url}get method(){return this.raw.method}get[At](){return this.#e}get matchedRoutes(){return this.#e[0].map(([[,e]])=>e)}get routePath(){return this.#e[0].map(([[,e]])=>e)[this.routeIndex].path}};var It={Stringify:1,BeforeStream:2,Stream:3},yn=(e,t)=>{let r=new String(e);return r.isEscaped=!0,r.callbacks=t,r};var Be=async(e,t,r,n,o)=>{typeof e=="object"&&!(e instanceof String)&&(e instanceof Promise||(e=e.toString()),e instanceof Promise&&(e=await e));let s=e.callbacks;if(!s?.length)return Promise.resolve(e);o?o[0]+=e:o=[e];let i=Promise.all(s.map(a=>a({phase:t,buffer:o,context:n}))).then(a=>Promise.all(a.filter(Boolean).map(c=>Be(c,t,!1,n,o))).then(()=>o[0]));return r?yn(await i,s):i};var bn="text/plain; charset=UTF-8",De=(e,t)=>({"Content-Type":e,...t}),te=(e,t)=>new Response(e,t),Fe=class{#t;#e;env={};#r;finalized=!1;error;#s;#o;#n;#u;#c;#l;#a;#d;#p;constructor(e,t){this.#t=e,t&&(this.#o=t.executionCtx,this.env=t.env,this.#l=t.notFoundHandler,this.#p=t.path,this.#d=t.matchResult)}get req(){return this.#e??=new ue(this.#t,this.#p,this.#d),this.#e}get event(){if(this.#o&&"respondWith"in this.#o)return this.#o;throw Error("This context has no FetchEvent")}get executionCtx(){if(this.#o)return this.#o;throw Error("This context has no ExecutionContext")}get res(){return this.#n||=te(null,{headers:this.#a??=new Headers})}set res(e){if(this.#n&&e){e=te(e.body,e);for(let[t,r]of this.#n.headers.entries())if(t!=="content-type")if(t==="set-cookie"){let n=this.#n.headers.getSetCookie();e.headers.delete("set-cookie");for(let o of n)e.headers.append("set-cookie",o)}else e.headers.set(t,r)}this.#n=e,this.finalized=!0}render=(...e)=>(this.#c??=t=>this.html(t),this.#c(...e));setLayout=e=>this.#u=e;getLayout=()=>this.#u;setRenderer=e=>{this.#c=e};header=(e,t,r)=>{this.finalized&&(this.#n=te(this.#n.body,this.#n));let n=this.#n?this.#n.headers:this.#a??=new Headers;t===void 0?n.delete(e):r?.append?n.append(e,t):n.set(e,t)};status=e=>{this.#s=e};set=(e,t)=>{this.#r??=new Map,this.#r.set(e,t)};get=e=>this.#r?this.#r.get(e):void 0;get var(){return this.#r?Object.fromEntries(this.#r):{}}#i(e,t,r){let n=this.#n?new Headers(this.#n.headers):this.#a??new Headers;if(typeof t=="object"&&"headers"in t){let s=t.headers instanceof Headers?t.headers:new Headers(t.headers);for(let[i,a]of s)i.toLowerCase()==="set-cookie"?n.append(i,a):n.set(i,a)}if(r)for(let[s,i]of Object.entries(r))if(typeof i=="string")n.set(s,i);else{n.delete(s);for(let a of i)n.append(s,a)}let o=typeof t=="number"?t:t?.status??this.#s;return te(e,{status:o,headers:n})}newResponse=(...e)=>this.#i(...e);body=(e,t,r)=>this.#i(e,t,r);text=(e,t,r)=>!this.#a&&!this.#s&&!t&&!r&&!this.finalized?new Response(e):this.#i(e,t,De(bn,r));json=(e,t,r)=>this.#i(JSON.stringify(e),t,De("application/json",r));html=(e,t,r)=>{let n=o=>this.#i(o,t,De("text/html; charset=UTF-8",r));return typeof e=="object"?Be(e,It.Stringify,!1,{}).then(n):n(e)};redirect=(e,t)=>{let r=String(e);return this.header("Location",/[^\x00-\xFF]/.test(r)?encodeURI(r):r),this.newResponse(null,t??302)};notFound=()=>(this.#l??=()=>te(),this.#l(this))};var y="ALL",Ht="all",jt=["get","post","put","delete","options","patch"],he="Can not add a route since the matcher is already built.",me=class extends Error{};var Nt="__COMPOSED_HANDLER";var vn=e=>e.text("404 Not Found",404),$t=(e,t)=>{if("getResponse"in e){let r=e.getResponse();return t.newResponse(r.body,r)}return console.error(e),t.text("Internal Server Error",500)},Bt=class Dt{get;post;put;delete;options;patch;all;on;use;router;getPath;_basePath="/";#t="/";routes=[];constructor(t={}){[...jt,Ht].forEach(s=>{this[s]=(i,...a)=>(typeof i=="string"?this.#t=i:this.#s(s,this.#t,i),a.forEach(c=>{this.#s(s,this.#t,c)}),this)}),this.on=(s,i,...a)=>{for(let c of[i].flat()){this.#t=c;for(let l of[s].flat())a.map(u=>{this.#s(l.toUpperCase(),this.#t,u)})}return this},this.use=(s,...i)=>(typeof s=="string"?this.#t=s:(this.#t="*",i.unshift(s)),i.forEach(a=>{this.#s(y,this.#t,a)}),this);let{strict:n,...o}=t;Object.assign(this,o),this.getPath=n??!0?t.getPath??Ne:Tt}#e(){let t=new Dt({router:this.router,getPath:this.getPath});return t.errorHandler=this.errorHandler,t.#r=this.#r,t.routes=this.routes,t}#r=vn;errorHandler=$t;route(t,r){let n=this.basePath(t);return r.routes.map(o=>{let s;r.errorHandler===$t?s=o.handler:(s=async(i,a)=>(await Ie([],r.errorHandler)(i,()=>o.handler(i,a))).res,s[Nt]=o.handler),n.#s(o.method,o.path,s,o.basePath)}),this}basePath(t){let r=this.#e();return r._basePath=H(this._basePath,t),r}onError=t=>(this.errorHandler=t,this);notFound=t=>(this.#r=t,this);mount(t,r,n){let o,s;n&&(typeof n=="function"?s=n:(s=n.optionHandler,n.replaceRequest===!1?o=c=>c:o=n.replaceRequest));let i=s?c=>{let l=s(c);return Array.isArray(l)?l:[l]}:c=>{let l;try{l=c.executionCtx}catch{}return[c.env,l]};o||=(()=>{let c=H(this._basePath,t),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 a=async(c,l)=>{let u=await r(o(c.req.raw),...i(c));if(u)return u;await l()};return this.#s(y,H(t,"*"),a),this}#s(t,r,n,o){t=t.toUpperCase(),r=H(this._basePath,r);let s={basePath:o!==void 0?H(this._basePath,o):this._basePath,path:r,method:t,handler:n};this.router.add(t,r,[n,s]),this.routes.push(s)}#o(t,r){if(t instanceof Error)return this.errorHandler(t,r);throw t}#n(t,r,n,o){if(o==="HEAD")return(async()=>new Response(null,await this.#n(t,r,n,"GET")))();let s=this.getPath(t,{env:n}),i=this.router.match(o,s),a=new Fe(t,{path:s,matchResult:i,env:n,executionCtx:r,notFoundHandler:this.#r});if(i[0].length===1){let l;try{l=i[0][0][0][0](a,async()=>{a.res=await this.#r(a)})}catch(u){return this.#o(u,a)}return l instanceof Promise?l.then(u=>u||(a.finalized?a.res:this.#r(a))).catch(u=>this.#o(u,a)):l??this.#r(a)}let c=Ie(i[0],this.errorHandler,this.#r);return(async()=>{try{let l=await c(a);if(!l.finalized)throw new Error("Context is not finalized. Did you forget to return a Response object or `await next()`?");return l.res}catch(l){return this.#o(l,a)}})()}fetch=(t,...r)=>this.#n(t,r[1],r[0],t.method);request=(t,r,n,o)=>t instanceof Request?this.fetch(r?new Request(t,r):t,n,o):(t=t.toString(),this.fetch(new Request(/^https?:\/\//.test(t)?t:`http://localhost${H("/",t)}`,r),n,o));fire=()=>{addEventListener("fetch",t=>{t.respondWith(this.#n(t.request,t,void 0,t.request.method))})}};var ge=[];function qe(e,t){let r=this.buildAllMatchers(),n=((o,s)=>{let i=r[o]||r[y],a=i[2][s];if(a)return a;let c=s.match(i[0]);if(!c)return[[],ge];let l=c.indexOf("",1);return[i[1][l],c]});return this.match=n,n(e,t)}var we="[^/]+",re=".*",ne="(?:|/.*)",B=Symbol(),xn=new Set(".\\+*[^]$()");function Rn(e,t){return e.length===1?t.length===1?e<t?-1:1:-1:t.length===1||e===re||e===ne?1:t===re||t===ne?-1:e===we?1:t===we?-1:e.length===t.length?e<t?-1:1:t.length-e.length}var Ft=class ze{#t;#e;#r=Object.create(null);insert(t,r,n,o,s){if(t.length===0){if(this.#t!==void 0)throw B;if(s)return;this.#t=r;return}let[i,...a]=t,c=i==="*"?a.length===0?["","",re]:["","",we]:i==="/*"?["","",ne]:i.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/),l;if(c){let u=c[1],d=c[2]||we;if(u&&c[2]&&(d===".*"||(d=d.replace(/^\((?!\?:)(?=[^)]+\)$)/,"(?:"),/\((?!\?:)/.test(d))))throw B;if(l=this.#r[d],!l){if(Object.keys(this.#r).some(h=>h!==re&&h!==ne))throw B;if(s)return;l=this.#r[d]=new ze,u!==""&&(l.#e=o.varIndex++)}!s&&u!==""&&n.push([u,l.#e])}else if(l=this.#r[i],!l){if(Object.keys(this.#r).some(u=>u.length>1&&u!==re&&u!==ne))throw B;if(s)return;l=this.#r[i]=new ze}l.insert(a,r,n,o,s)}buildRegExpStr(){let r=Object.keys(this.#r).sort(Rn).map(n=>{let o=this.#r[n];return(typeof o.#e=="number"?`(${n})@${o.#e}`:xn.has(n)?`\\${n}`:n)+o.buildRegExpStr()});return typeof this.#t=="number"&&r.unshift(`#${this.#t}`),r.length===0?"":r.length===1?r[0]:"(?:"+r.join("|")+")"}};var qt=class{#t={varIndex:0};#e=new Ft;insert(e,t,r){let n=[],o=[];for(let i=0;;){let a=!1;if(e=e.replace(/\{[^}]+\}/g,c=>{let l=`@\\${i}`;return o[i]=[l,c],i++,a=!0,l}),!a)break}let s=e.match(/(?::[^\/]+)|(?:\/\*$)|./g)||[];for(let i=o.length-1;i>=0;i--){let[a]=o[i];for(let c=s.length-1;c>=0;c--)if(s[c].indexOf(a)!==-1){s[c]=s[c].replace(a,o[i][1]);break}}return this.#e.insert(s,t,n,this.#t,r),n}buildRegExp(){let e=this.#e.buildRegExpStr();if(e==="")return[/^$/,[],[]];let t=0,r=[],n=[];return e=e.replace(/#(\d+)|@(\d+)|\.\*\$/g,(o,s,i)=>s!==void 0?(r[++t]=Number(s),"$()"):(i!==void 0&&(n[Number(i)]=++t),"")),[new RegExp(`^${e}`),r,n]}};var En=[/^$/,[],Object.create(null)],zt=Object.create(null);function Wt(e){return zt[e]??=new RegExp(e==="*"?"":`^${e.replace(/\/\*$|([.\\+*[^\]$()])/g,(t,r)=>r?`\\${r}`:"(?:|/.*)")}$`)}function Sn(){zt=Object.create(null)}function Pn(e){let t=new qt,r=[];if(e.length===0)return En;let n=e.map(l=>[!/\*|\/:/.test(l[0]),...l]).sort(([l,u],[d,h])=>l?1:d?-1:u.length-h.length),o=Object.create(null);for(let l=0,u=-1,d=n.length;l<d;l++){let[h,f,g]=n[l];h?o[f]=[g.map(([w])=>[w,Object.create(null)]),ge]:u++;let p;try{p=t.insert(f,u,h)}catch(w){throw w===B?new me(f):w}h||(r[u]=g.map(([w,m])=>{let x=Object.create(null);for(m-=1;m>=0;m--){let[C,L]=p[m];x[C]=L}return[w,x]}))}let[s,i,a]=t.buildRegExp();for(let l=0,u=r.length;l<u;l++)for(let d=0,h=r[l].length;d<h;d++){let f=r[l][d]?.[1];if(!f)continue;let g=Object.keys(f);for(let p=0,w=g.length;p<w;p++)f[g[p]]=a[f[g[p]]]}let c=[];for(let l in i)c[l]=r[i[l]];return[s,c,o]}function G(e,t){if(e){for(let r of Object.keys(e).sort((n,o)=>o.length-n.length))if(Wt(r).test(t))return[...e[r]]}}var ye=class{name="RegExpRouter";#t;#e;constructor(){this.#t={[y]:Object.create(null)},this.#e={[y]:Object.create(null)}}add(e,t,r){let n=this.#t,o=this.#e;if(!n||!o)throw new Error(he);n[e]||[n,o].forEach(a=>{a[e]=Object.create(null),Object.keys(a[y]).forEach(c=>{a[e][c]=[...a[y][c]]})}),t==="/*"&&(t="*");let s=(t.match(/\/:/g)||[]).length;if(/\*$/.test(t)){let a=Wt(t);e===y?Object.keys(n).forEach(c=>{n[c][t]||=G(n[c],t)||G(n[y],t)||[]}):n[e][t]||=G(n[e],t)||G(n[y],t)||[],Object.keys(n).forEach(c=>{(e===y||e===c)&&Object.keys(n[c]).forEach(l=>{a.test(l)&&n[c][l].push([r,s])})}),Object.keys(o).forEach(c=>{(e===y||e===c)&&Object.keys(o[c]).forEach(l=>a.test(l)&&o[c][l].push([r,s]))});return}let i=fe(t)||[t];for(let a=0,c=i.length;a<c;a++){let l=i[a];Object.keys(o).forEach(u=>{(e===y||e===u)&&(o[u][l]||=[...G(n[u],l)||G(n[y],l)||[]],o[u][l].push([r,s-c+a+1]))})}}match=qe;buildAllMatchers(){let e=Object.create(null);return Object.keys(this.#e).concat(Object.keys(this.#t)).forEach(t=>{e[t]||=this.#r(t)}),this.#t=this.#e=void 0,Sn(),e}#r(e){let t=[],r=e===y;return[this.#t,this.#e].forEach(n=>{let o=n[e]?Object.keys(n[e]).map(s=>[s,n[e][s]]):[];o.length!==0?(r||=!0,t.push(...o)):e!==y&&t.push(...Object.keys(n[y]).map(s=>[s,n[y][s]]))}),r?Pn(t):null}};var We=class{name="SmartRouter";#t=[];#e=[];constructor(e){this.#t=e.routers}add(e,t,r){if(!this.#e)throw new Error(he);this.#e.push([e,t,r])}match(e,t){if(!this.#e)throw new Error("Fatal error");let r=this.#t,n=this.#e,o=r.length,s=0,i;for(;s<o;s++){let a=r[s];try{for(let c=0,l=n.length;c<l;c++)a.add(...n[c]);i=a.match(e,t)}catch(c){if(c instanceof me)continue;throw c}this.match=a.match.bind(a),this.#t=[a],this.#e=void 0;break}if(s===o)throw new Error("Fatal error");return this.name=`SmartRouter + ${this.activeRouter.name}`,i}get activeRouter(){if(this.#e||this.#t.length!==1)throw new Error("No active router has been determined yet.");return this.#t[0]}};var oe=Object.create(null),An=e=>{for(let t in e)return!0;return!1},Vt=class Gt{#t;#e;#r;#s=0;#o=oe;constructor(t,r,n){if(this.#e=n||Object.create(null),this.#t=[],t&&r){let o=Object.create(null);o[t]={handler:r,possibleKeys:[],score:0},this.#t=[o]}this.#r=[]}insert(t,r,n){this.#s=++this.#s;let o=this,s=Ot(r),i=[];for(let a=0,c=s.length;a<c;a++){let l=s[a],u=s[a+1],d=_t(l,u),h=Array.isArray(d)?d[0]:l;if(h in o.#e){o=o.#e[h],d&&i.push(d[1]);continue}o.#e[h]=new Gt,d&&(o.#r.push(d),i.push(d[1])),o=o.#e[h]}return o.#t.push({[t]:{handler:n,possibleKeys:i.filter((a,c,l)=>l.indexOf(a)===c),score:this.#s}}),o}#n(t,r,n,o,s){for(let i=0,a=r.#t.length;i<a;i++){let c=r.#t[i],l=c[n]||c[y],u={};if(l!==void 0&&(l.params=Object.create(null),t.push(l),o!==oe||s&&s!==oe))for(let d=0,h=l.possibleKeys.length;d<h;d++){let f=l.possibleKeys[d],g=u[l.score];l.params[f]=s?.[f]&&!g?s[f]:o[f]??s?.[f],u[l.score]=!0}}}search(t,r){let n=[];this.#o=oe;let s=[this],i=je(r),a=[],c=i.length,l=null;for(let u=0;u<c;u++){let d=i[u],h=u===c-1,f=[];for(let p=0,w=s.length;p<w;p++){let m=s[p],x=m.#e[d];x&&(x.#o=m.#o,h?(x.#e["*"]&&this.#n(n,x.#e["*"],t,m.#o),this.#n(n,x,t,m.#o)):f.push(x));for(let C=0,L=m.#r.length;C<L;C++){let R=m.#r[C],b=m.#o===oe?{}:{...m.#o};if(R==="*"){let U=m.#e["*"];U&&(this.#n(n,U,t,m.#o),U.#o=b,f.push(U));continue}let[P,v,A]=R;if(!d&&!(A instanceof RegExp))continue;let E=m.#e[P];if(A instanceof RegExp){if(l===null){l=new Array(c);let q=r[0]==="/"?1:0;for(let _=0;_<c;_++)l[_]=q,q+=i[_].length+1}let U=r.substring(l[u]),Q=A.exec(U);if(Q){if(b[v]=Q[0],this.#n(n,E,t,m.#o,b),An(E.#e)){E.#o=b;let q=Q[0].match(/\//)?.length??0;(a[q]||=[]).push(E)}continue}}(A===!0||A.test(d))&&(b[v]=d,h?(this.#n(n,E,t,b,m.#o),E.#e["*"]&&this.#n(n,E.#e["*"],t,b,m.#o)):(E.#o=b,f.push(E)))}}let g=a.shift();s=g?f.concat(g):f}return n.length>1&&n.sort((u,d)=>u.score-d.score),[n.map(({handler:u,params:d})=>[u,d])]}};var Ve=class{name="TrieRouter";#t;constructor(){this.#t=new Vt}add(e,t,r){let n=fe(t);if(n){for(let o=0,s=n.length;o<s;o++)this.#t.insert(e,n[o],r);return}this.#t.insert(e,t,r)}match(e,t){return this.#t.search(e,t)}};var Ge=class extends Bt{constructor(e={}){super(e),this.router=e.router??new We({routers:[new ye,new Ve]})}};var be=e=>{let t={origin:"*",allowMethods:["GET","HEAD","PUT","POST","DELETE","PATCH"],allowHeaders:[],exposeHeaders:[],...e},r=(o=>typeof o=="string"?o==="*"?()=>o:s=>o===s?s:null:typeof o=="function"?o:s=>o.includes(s)?s:null)(t.origin),n=(o=>typeof o=="function"?o:Array.isArray(o)?()=>o:()=>[])(t.allowMethods);return async function(s,i){function a(l,u){s.res.headers.set(l,u)}let c=await r(s.req.header("origin")||"",s);if(c&&a("Access-Control-Allow-Origin",c),t.credentials&&a("Access-Control-Allow-Credentials","true"),t.exposeHeaders?.length&&a("Access-Control-Expose-Headers",t.exposeHeaders.join(",")),s.req.method==="OPTIONS"){t.origin!=="*"&&a("Vary","Origin"),t.maxAge!=null&&a("Access-Control-Max-Age",t.maxAge.toString());let l=await n(s.req.header("origin")||"",s);l.length&&a("Access-Control-Allow-Methods",l.join(","));let u=t.allowHeaders;if(!u?.length){let d=s.req.header("Access-Control-Request-Headers");d&&(u=d.split(/\s*,\s*/))}return u?.length&&(a("Access-Control-Allow-Headers",u.join(",")),s.res.headers.append("Vary","Access-Control-Request-Headers")),s.res.headers.delete("Content-Length"),s.res.headers.delete("Content-Type"),new Response(null,{headers:s.res.headers,status:204,statusText:"No Content"})}await i(),t.origin!=="*"&&s.header("Vary","Origin",{append:!0})}};import ur from"process";import dr from"path";import{fileURLToPath as oo}from"url";import so from"child_process";import io,{constants as ao}from"fs/promises";import{promisify as jn}from"util";import Nn from"child_process";import Qe,{constants as er}from"fs/promises";import Jt from"process";import Ln from"os";import kn from"fs";import _n from"fs";import Kt from"fs";var Ke;function Cn(){try{return Kt.statSync("/.dockerenv"),!0}catch{return!1}}function On(){try{return Kt.readFileSync("/proc/self/cgroup","utf8").includes("docker")}catch{return!1}}function Xe(){return Ke===void 0&&(Ke=Cn()||On()),Ke}var Je,Tn=()=>{try{return _n.statSync("/run/.containerenv"),!0}catch{return!1}};function K(){return Je===void 0&&(Je=Tn()||Xe()),Je}var Xt=()=>{if(Jt.platform!=="linux")return!1;if(Ln.release().toLowerCase().includes("microsoft"))return!K();try{return kn.readFileSync("/proc/version","utf8").toLowerCase().includes("microsoft")?!K():!1}catch{return!1}},M=Jt.env.__IS_WSL_TEST__?Xt:Xt();import Yt from"process";import{Buffer as Un}from"buffer";import{promisify as Mn}from"util";import In from"child_process";import Ni,{constants as $i}from"fs/promises";var Hn=Mn(In.execFile),Ye=()=>`${Yt.env.SYSTEMROOT||Yt.env.windir||String.raw`C:\Windows`}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`;var T=async(e,t={})=>{let{powerShellPath:r,...n}=t,o=T.encodeCommand(e);return Hn(r??Ye(),[...T.argumentsPrefix,o],{encoding:"utf8",...n})};T.argumentsPrefix=["-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-EncodedCommand"];T.encodeCommand=e=>Un.from(e,"utf16le").toString("base64");T.escapeArgument=e=>`'${String(e).replaceAll("'","''")}'`;function Qt(e){for(let t of e.split(`
3
- `)){if(/^\s*#/.test(t))continue;let r=/^\s*root\s*=\s*(?<mountPoint>"[^"]*"|'[^']*'|[^#]*)/.exec(t);if(r)return r.groups.mountPoint.trim().replaceAll(/^["']|["']$/g,"")}}var $n=jn(Nn.execFile),Bn=(()=>{let e="/mnt/",t;return async function(){if(t)return t;let r="/etc/wsl.conf",n=!1;try{await Qe.access(r,er.F_OK),n=!0}catch{}if(!n)return e;let o=await Qe.readFile(r,{encoding:"utf8"}),s=Qt(o);return s===void 0?e:(t=s,t=t.endsWith("/")?t:`${t}/`,t)}})(),Dn=async()=>`${await Bn()}c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe`,ve=M?Dn:Ye,Zt,tr=async()=>(Zt??=(async()=>{try{let e=await ve();return await Qe.access(e,er.X_OK),!0}catch{return!1}})(),Zt),rr=async()=>{let e=await ve(),t=String.raw`(Get-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\Shell\Associations\UrlAssociations\http\UserChoice").ProgId`,{stdout:r}=await T(t,{powerShellPath:e});return r.trim()},nr=async e=>{if(/^[a-z]+:\/\//i.test(e))return e;try{let{stdout:t}=await $n("wslpath",["-aw",e],{encoding:"utf8"});return t.trim()}catch{return e}};function D(e,t,r){let n=o=>Object.defineProperty(e,t,{value:o,enumerable:!0,writable:!0});return Object.defineProperty(e,t,{configurable:!0,enumerable:!0,get(){let o=r();return n(o),o},set(o){n(o)}}),e}import{promisify as Zn}from"util";import ot from"process";import{execFile as eo}from"child_process";import{promisify as Fn}from"util";import qn from"process";import{execFile as zn}from"child_process";var Wn=Fn(zn);async function Ze(){if(qn.platform!=="darwin")throw new Error("macOS only");let{stdout:e}=await Wn("defaults",["read","com.apple.LaunchServices/com.apple.launchservices.secure","LSHandlers"]),r=/LSHandlerRoleAll = "(?!-)(?<id>[^"]+?)";\s+?LSHandlerURLScheme = (?:http|https);/.exec(e)?.groups.id??"com.apple.Safari";return r==="com.apple.safari"?"com.apple.Safari":r}import Vn from"process";import{promisify as Gn}from"util";import{execFile as Kn,execFileSync as oa}from"child_process";var Xn=Gn(Kn);async function or(e,{humanReadableOutput:t=!0,signal:r}={}){if(Vn.platform!=="darwin")throw new Error("macOS only");let n=t?[]:["-ss"],o={};r&&(o.signal=r);let{stdout:s}=await Xn("osascript",["-e",e,n],o);return s.trim()}async function et(e){return or(`tell application "Finder" to set app_path to application file id "${e}" as string
4
- tell application "System Events" to get value of property list item "CFBundleName" of property list file (app_path & ":Contents:Info.plist")`)}import{promisify as Jn}from"util";import{execFile as Yn}from"child_process";var Qn=Jn(Yn),xe={MSEdgeHTM:{name:"Edge",id:"com.microsoft.edge"},MSEdgeBHTML:{name:"Edge Beta",id:"com.microsoft.edge.beta"},MSEdgeDHTML:{name:"Edge Dev",id:"com.microsoft.edge.dev"},AppXq0fevzme2pys62n3e0fbqa7peapykr8v:{name:"Edge",id:"com.microsoft.edge.old"},ChromeHTML:{name:"Chrome",id:"com.google.chrome"},ChromeBHTML:{name:"Chrome Beta",id:"com.google.chrome.beta"},ChromeDHTML:{name:"Chrome Dev",id:"com.google.chrome.dev"},ChromiumHTM:{name:"Chromium",id:"org.chromium.Chromium"},BraveHTML:{name:"Brave",id:"com.brave.Browser"},BraveBHTML:{name:"Brave Beta",id:"com.brave.Browser.beta"},BraveDHTML:{name:"Brave Dev",id:"com.brave.Browser.dev"},BraveSSHTM:{name:"Brave Nightly",id:"com.brave.Browser.nightly"},FirefoxURL:{name:"Firefox",id:"org.mozilla.firefox"},OperaStable:{name:"Opera",id:"com.operasoftware.Opera"},VivaldiHTM:{name:"Vivaldi",id:"com.vivaldi.Vivaldi"},"IE.HTTP":{name:"Internet Explorer",id:"com.microsoft.ie"}},rt=new Map(Object.entries(xe)),tt=class extends Error{};async function nt(e=Qn){let{stdout:t}=await e("reg",["QUERY"," HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\Shell\\Associations\\UrlAssociations\\http\\UserChoice","/v","ProgId"]),r=/ProgId\s*REG_SZ\s*(?<id>\S+)/.exec(t);if(!r)throw new tt(`Cannot find Windows browser in stdout: ${JSON.stringify(t)}`);let{id:n}=r.groups,o=n.lastIndexOf("."),s=n.lastIndexOf("-"),i=o===-1?void 0:n.slice(0,o),a=s===-1?void 0:n.slice(0,s);return xe[n]??xe[i]??xe[a]??{name:n,id:n}}var to=Zn(eo),ro=e=>e.toLowerCase().replaceAll(/(?:^|\s|-)\S/g,t=>t.toUpperCase());async function st(){if(ot.platform==="darwin"){let e=await Ze();return{name:await et(e),id:e}}if(ot.platform==="linux"){let{stdout:e}=await to("xdg-mime",["query","default","x-scheme-handler/http"]),t=e.trim();return{name:ro(t.replace(/.desktop$/,"").replace("-"," ")),id:t}}if(ot.platform==="win32")return nt();throw new Error("Only macOS, Linux, and Windows are supported")}import it from"process";var no=!!(it.env.SSH_CONNECTION||it.env.SSH_CLIENT||it.env.SSH_TTY),sr=no;var Re=Symbol("fallbackAttempt"),at=import.meta.url?dr.dirname(oo(import.meta.url)):"",ir=dr.join(at,"xdg-open"),{platform:X,arch:ar}=ur,cr=async(e,t)=>{if(e.length===0)return;let r=[];for(let n of e)try{return await t(n)}catch(o){r.push(o)}throw new AggregateError(r,"Failed to open in all supported apps")},Ee=async e=>{e={wait:!1,background:!1,newInstance:!1,allowNonzeroExitCode:!1,...e};let t=e[Re]===!0;if(delete e[Re],Array.isArray(e.app))return cr(e.app,l=>Ee({...e,app:l,[Re]:!0}));let{name:r,arguments:n=[]}=e.app??{};if(n=[...n],Array.isArray(r))return cr(r,l=>Ee({...e,app:{name:l,arguments:n},[Re]:!0}));if(r==="browser"||r==="browserPrivate"){let l={"com.google.chrome":"chrome","google-chrome.desktop":"chrome","com.brave.browser":"brave","org.mozilla.firefox":"firefox","firefox.desktop":"firefox","com.microsoft.msedge":"edge","com.microsoft.edge":"edge","com.microsoft.edgemac":"edge","microsoft-edge.desktop":"edge","com.apple.safari":"safari"},u={chrome:"--incognito",brave:"--incognito",firefox:"--private-window",edge:"--inPrivate"},d;if(M){let h=await rr();d=rt.get(h)??{}}else d=await st();if(d.id in l){let h=l[d.id.toLowerCase()];if(r==="browserPrivate"){if(h==="safari")throw new Error("Safari doesn't support opening in private mode via command line");n.push(u[h])}return Ee({...e,app:{name:J[h],arguments:n}})}throw new Error(`${d.name} is not supported as a default browser`)}let o,s=[],i={},a=!1;if(M&&!K()&&!sr&&!r&&(a=await tr()),X==="darwin")o="open",e.wait&&s.push("--wait-apps"),e.background&&s.push("--background"),e.newInstance&&s.push("--new"),r&&s.push("-a",r);else if(X==="win32"||a){o=await ve(),s.push(...T.argumentsPrefix),M||(i.windowsVerbatimArguments=!0),M&&e.target&&(e.target=await nr(e.target));let l=["$ProgressPreference = 'SilentlyContinue';","Start"];e.wait&&l.push("-Wait"),r?(l.push(T.escapeArgument(r)),e.target&&n.push(e.target)):e.target&&l.push(T.escapeArgument(e.target)),n.length>0&&(n=n.map(u=>T.escapeArgument(u)),l.push("-ArgumentList",n.join(","))),e.target=T.encodeCommand(l.join(" ")),e.wait||(i.stdio="ignore")}else{if(r)o=r;else{let l=!at||at==="/",u=!1;try{await io.access(ir,ao.X_OK),u=!0}catch{}o=ur.versions.electron??(X==="android"||l||!u)?"xdg-open":ir}n.length>0&&s.push(...n),e.wait||(i.stdio="ignore",i.detached=!0)}X==="darwin"&&n.length>0&&s.push("--args",...n),e.target&&s.push(e.target);let c=so.spawn(o,s,i);return e.wait?new Promise((l,u)=>{c.once("error",u),c.once("close",d=>{if(!e.allowNonzeroExitCode&&d!==0){u(new Error(`Exited with code ${d}`));return}l(c)})}):t?new Promise((l,u)=>{c.once("error",u),c.once("spawn",()=>{c.once("close",d=>{if(c.off("error",u),d!==0){u(new Error(`Exited with code ${d}`));return}c.unref(),l(c)})})}):(c.unref(),new Promise((l,u)=>{c.once("error",u),c.once("spawn",()=>{c.off("error",u),l(c)})}))},co=(e,t)=>{if(typeof e!="string")throw new TypeError("Expected a `target`");return Ee({...t,target:e})};function lr(e){if(typeof e=="string"||Array.isArray(e))return e;let{[ar]:t}=e;if(!t)throw new Error(`${ar} is not supported`);return t}function se({[X]:e},{wsl:t}={}){if(t&&M)return lr(t);if(!e)throw new Error(`${X} is not supported`);return lr(e)}var J={browser:"browser",browserPrivate:"browserPrivate"};D(J,"chrome",()=>se({darwin:"google chrome",win32:"chrome",linux:["google-chrome","google-chrome-stable","chromium","chromium-browser"]},{wsl:{ia32:"/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe",x64:["/mnt/c/Program Files/Google/Chrome/Application/chrome.exe","/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe"]}}));D(J,"brave",()=>se({darwin:"brave browser",win32:"brave",linux:["brave-browser","brave"]},{wsl:{ia32:"/mnt/c/Program Files (x86)/BraveSoftware/Brave-Browser/Application/brave.exe",x64:["/mnt/c/Program Files/BraveSoftware/Brave-Browser/Application/brave.exe","/mnt/c/Program Files (x86)/BraveSoftware/Brave-Browser/Application/brave.exe"]}}));D(J,"firefox",()=>se({darwin:"firefox",win32:String.raw`C:\Program Files\Mozilla Firefox\firefox.exe`,linux:"firefox"},{wsl:"/mnt/c/Program Files/Mozilla Firefox/firefox.exe"}));D(J,"edge",()=>se({darwin:"microsoft edge",win32:"msedge",linux:["microsoft-edge","microsoft-edge-dev"]},{wsl:"/mnt/c/Program Files (x86)/Microsoft/Edge/Application/msedge.exe"}));D(J,"safari",()=>se({darwin:"Safari"}));var pr=co;function fr(e=""){return`<link rel="icon" type="image/svg+xml" href="${`${e.replace(/\/$/,"")}/favicon-black.svg?v=4`}" />`}import{existsSync as hr,readFileSync as lo}from"fs";import I from"path";import{fileURLToPath as uo}from"url";import{gunzipSync as po}from"zlib";var fo={".js":"application/javascript",".css":"text/css",".svg":"image/svg+xml",".png":"image/png",".ico":"image/x-icon",".webmanifest":"application/manifest+json"};function ho(){let e=I.dirname(uo(import.meta.url));for(let t of[I.resolve(e,"app"),I.resolve(e,"../app"),I.resolve(e,"../../dist/app")])if(hr(I.join(t,"inspector.js.gz")))return t;throw new Error("Inspector bundle not found (expected dist/app/inspector.js.gz)")}function mr(e,t="/inspector/assets"){let r=ho(),n=new Map;e.get(`${t}/*`,o=>{let s=o.req.path.slice(t.length),i=s.startsWith("/")?s.slice(1):s;if(!i||i.includes(".."))return o.notFound();let a=i==="inspector.js"||i==="inspector.css"?`${i}.gz`:i,c=I.resolve(r,a),l=r.endsWith(I.sep)?r:`${r}${I.sep}`;if(!c.startsWith(l)||!hr(c))return o.notFound();let u=I.extname(i),d=a.endsWith(".gz"),h=/(?:^|,)\s*gzip\s*(?:,|$)/i.test(o.req.header("accept-encoding")??""),f=lo(c),g=d&&!h?n.get(c)??mo(n,c,f):f,p=g.buffer.slice(g.byteOffset,g.byteOffset+g.byteLength);return o.body(p,200,{"Content-Type":fo[u]??"application/octet-stream",...d&&h?{"Content-Encoding":"gzip"}:{},...d?{Vary:"Accept-Encoding"}:{},"Cache-Control":"no-cache"})})}function mo(e,t,r){let n=po(r);return e.set(t,n),n}var gr={name:"@mcp-use/inspector",type:"module",version:"20.0.0-beta.33",description:"MCP Inspector - A tool for inspecting and debugging MCP servers",author:"",license:"MIT",homepage:"https://github.com/mcp-use/mcp-use#readme",repository:{type:"git",url:"git+https://github.com/mcp-use/mcp-use.git",directory:"libraries/typescript/packages/inspector"},bugs:{url:"https://github.com/mcp-use/mcp-use/issues"},keywords:["mcp","inspector","debug","tools"],exports:{".":{types:"./dist/server/index.d.ts",import:"./dist/server/index.js"},"./client":{types:"./dist/client/index.d.ts",import:"./dist/client/index.js"}},main:"./dist/server/index.js",types:"./dist/server/index.d.ts",bin:{"mcp-inspect":"./dist/cli.js"},files:["dist"],scripts:{dev:"rimraf node_modules/.vite && VITE_MANUFACT_CHAT_URL=${VITE_MANUFACT_CHAT_URL:-http://localhost:8000/api/v1/inspector/chat/stream} vite --strictPort","dev:client":"pnpm run dev","dev:server":"VITE_DEV=true tsx watch src/server/server.ts","dev:standalone":"tsx watch src/server/server.ts",clean:"rimraf dist",build:"npm run clean && npm run build:client-exports && npm run build:server && npm run build:app && npm run verify:package","build:app":"vite build --config vite.app.config.ts && node scripts/compress-app.mjs","watch:app":"vite build --watch --config vite.app.config.ts","preview:app":"vite preview --config vite.app.config.ts --host 127.0.0.1","serve:app":"pnpm build:app && pnpm preview:app","analyze:app":"ANALYZE=true vite build --config vite.app.config.ts","build:client-exports":"tsup --config tsup.client.ts","build:server":"tsup --config tsup.server.ts","verify:package":"node scripts/verify-package.mjs",prepublishOnly:"pnpm --filter @mcp-use/client build && pnpm build",start:"node dist/cli.js --port 3000",preview:"vite preview","type-check":"tsc --noEmit",lint:"eslint .","lint:fix":"eslint . --fix","test:e2e":"playwright test","test:e2e:ui":"playwright test --ui","test:e2e:debug":"playwright test --debug","test:e2e:builtin":"node tests/e2e/scripts/run-test-matrix.mjs builtin","test:e2e:prod":"node tests/e2e/scripts/run-test-matrix.mjs prod","test:e2e:mix":"node tests/e2e/scripts/run-test-matrix.mjs mix","test:e2e:prod:ui":"TEST_MODE=production playwright test --ui","test:e2e:codegen":"playwright codegen http://localhost:3000/inspector","test:e2e:report":"playwright show-report","test:e2e:python":"node tests/e2e/scripts/run-python-e2e.mjs","test:unit":"vitest run","test:unit:watch":"vitest","test:e2e:tunnel":"node tests/e2e/scripts/run-tunnel-test.mjs","install:pnpm":"pnpm install","install:npm":"npm install","lint:npm":"npm run lint:fix","lint:pnpm":"pnpm lint:fix"},engines:{node:">=22.22.2"},peerDependencies:{"@base-ui/react":"^1.6.0","@mcp-use/agent":"^2.0.0-alpha.0","@mcp-use/client":"^2.0.0-alpha.0","class-variance-authority":"^0.7.1",clsx:"^2.1.1",express:"^4.21.2 || ^5.0.0","lucide-react":"^0.562.0","markdown-to-jsx":"^9.7.4","mcp-use":"workspace:*",motion:"^12.34.2",react:"^18.0.0 || ^19.0.0","react-dom":"^18.0.0 || ^19.0.0","react-resizable-panels":"^4.6.4",sonner:"^2.0.7","tailwind-merge":"^3.5.0"},peerDependenciesMeta:{"@base-ui/react":{optional:!0},"@mcp-use/agent":{optional:!0},"@mcp-use/client":{optional:!0},"class-variance-authority":{optional:!0},clsx:{optional:!0},express:{optional:!0},"lucide-react":{optional:!0},"markdown-to-jsx":{optional:!0},motion:{optional:!0},react:{optional:!0},"react-dom":{optional:!0},"react-resizable-panels":{optional:!0},sonner:{optional:!0},"tailwind-merge":{optional:!0}},dependencies:{},publishConfig:{access:"public"},devDependencies:{"@base-ui/react":"^1.6.0","@hono/node-server":"^1.19.13","@mcp-use/agent":"workspace:*","@mcp-use/client":"workspace:*","@playwright/test":"^1.58.2","@tailwindcss/vite":"^4.2.0","@types/express":"^5.0.6","@vitejs/plugin-react":"^6.0.0","class-variance-authority":"^0.7.1",clsx:"^2.1.1",emulate:"0.5.0",eslint:"^9.39.2",express:"^5.2.1",hono:"^4.12.12","lucide-react":"^0.562.0","markdown-to-jsx":"^9.7.4",motion:"^12.34.2","oauth2-mock-server":"^8.2.2",open:"^11.0.0",react:"^19.2.3","react-dom":"^19.2.3","react-router":"^7.12.0","react-resizable-panels":"^4.6.4","rollup-plugin-visualizer":"^6.0.3",sonner:"^2.0.7","tailwind-merge":"^3.5.0",tailwindcss:"^4.2.0",tsup:"^8.5.1",tsx:"^4.21.0","tw-animate-css":"^1.4.0",typescript:"^5.9.3",vite:"^8.0.16",vitest:"^4.1.0","wait-on":"^9.0.4",zod:"^4.2.0"}};var wo=gr.version;function Se(){return wo}var wr=Se(),yo=`<!doctype html>
2
+ var dn=Object.create;var vt=Object.defineProperty;var fn=Object.getOwnPropertyDescriptor;var pn=Object.getOwnPropertyNames;var hn=Object.getPrototypeOf,mn=Object.prototype.hasOwnProperty;var Q=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var gn=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of pn(t))!mn.call(e,o)&&o!==r&&vt(e,o,{get:()=>t[o],enumerable:!(n=fn(t,o))||n.enumerable});return e};var wn=(e,t,r)=>(r=e!=null?dn(hn(e)):{},gn(t||!e||!e.__esModule?vt(r,"default",{value:e,enumerable:!0}):r,e));var Er=Q((pc,vr)=>{"use strict";vr.exports=class{constructor(t={}){this.points=t.points,this.duration=t.duration,this.blockDuration=t.blockDuration,this.execEvenly=t.execEvenly,this.execEvenlyMinDelayMs=t.execEvenlyMinDelayMs,this.keyPrefix=t.keyPrefix}get points(){return this._points}set points(t){if(Number.isFinite(t))this._points=t;else throw new Error("points must be set and must be a finite number")}get duration(){return this._duration}set duration(t){if(typeof t=="number"&&Number.isFinite(t)&&t>=0)this._duration=t;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(t){this._blockDuration=typeof t>"u"?0:t}get msBlockDuration(){return this.blockDuration*1e3}get execEvenly(){return this._execEvenly}set execEvenly(t){this._execEvenly=typeof t>"u"?!1:!!t}get execEvenlyMinDelayMs(){return this._execEvenlyMinDelayMs===void 0?this._getExecEvenlyMinDelayMsDefault():this._execEvenlyMinDelayMs}set execEvenlyMinDelayMs(t){this._execEvenlyMinDelayMs=t}_getExecEvenlyMinDelayMsDefault(){return this.points>0?Math.ceil(this.msDuration/this.points):0}get keyPrefix(){return this._keyPrefix}set keyPrefix(t){if(typeof t>"u"&&(t="rlflx"),typeof t!="string")throw new Error("keyPrefix must be string");this._keyPrefix=t}_getKeySecDuration(t={}){return t&&t.customDuration>=0?t.customDuration:this.duration}getKey(t){return this.keyPrefix.length>0?`${this.keyPrefix}:${t}`:t}parseKey(t){return this.keyPrefix.length>0?t.substring(this.keyPrefix.length+1):t}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 Sr=Q((mc,Rr)=>{"use strict";Rr.exports=class{constructor(t,r,n=null){this.value=t,this.expiresAt=r,this.timeoutId=n}get value(){return this._value}set value(t){this._value=parseInt(t,10)}get expiresAt(){return this._expiresAt}set expiresAt(t){t instanceof Date?this._expiresAt=t.getTime():this._expiresAt=t}get timeoutId(){return this._timeoutId}set timeoutId(t){this._timeoutId=t}}});var dt=Q((wc,Pr)=>{"use strict";Pr.exports=class{constructor(t,r,n,o){this.remainingPoints=typeof t>"u"?0:t,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(t){return this._msBeforeNext=t,this}get remainingPoints(){return this._remainingPoints}set remainingPoints(t){return this._remainingPoints=t,this}get consumedPoints(){return this._consumedPoints}set consumedPoints(t){return this._consumedPoints=t,this}get isFirstInDuration(){return this._isFirstInDuration}set isFirstInDuration(t){this._isFirstInDuration=!!t}_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 Cr=Q((bc,_r)=>{"use strict";var Ar=Sr(),ft=dt();_r.exports=class{constructor(){this._storage=new Map}incrby(t,r,n){let o=this._storage.get(t);if(o){let s=o.expiresAt?o.expiresAt-Date.now():-1;return!o.expiresAt||s>0?(o.value=o.value+r,new ft(0,s,o.value,!1)):this.set(t,r,n)}return this.set(t,r,n)}set(t,r,n){let o=n*1e3,s=this._storage.get(t);s&&s.timeoutId&&clearTimeout(s.timeoutId);let i=new Ar(r,o>0?Date.now()+o:null);return this._storage.set(t,i),o>0&&(i.timeoutId=setTimeout(()=>{this._storage.delete(t)},o),i.timeoutId.unref&&i.timeoutId.unref()),new ft(0,o===0?-1:o,i.value,!0)}get(t){let r=this._storage.get(t);if(r){let n=r.expiresAt?r.expiresAt-Date.now():-1;return new ft(0,n,r.value,!1)}return null}delete(t){let r=this._storage.get(t);return r?(r.timeoutId&&clearTimeout(r.timeoutId),this._storage.delete(t),!0):!1}_restoreRecord(t,r,n){let o=Date.now(),s=n!==null;if(s&&!Number.isFinite(n)||s&&n<=o)return;let i=s?n-o:0,a=this._storage.get(t);a&&a.timeoutId&&clearTimeout(a.timeoutId);let c=new Ar(r,n);this._storage.set(t,c),i>0&&(c.timeoutId=setTimeout(()=>{this._storage.delete(t)},i),c.timeoutId.unref&&c.timeoutId.unref())}}});var Mr=Q((xc,Tr)=>{"use strict";var Do=Er(),jo=Cr(),Or=dt(),pt=class extends Do{constructor(t={}){super(t),this._memoryStorage=new jo}consume(t,r=1,n={}){return new Promise((o,s)=>{let i=this.getKey(t),a=this._getKeySecDuration(n),c=this._memoryStorage.incrby(i,r,a);if(c.remainingPoints=Math.max(this.points-c.consumedPoints,0),c.consumedPoints>this.points)this.blockDuration>0&&c.consumedPoints<=this.points+r&&(c=this._memoryStorage.set(i,c.consumedPoints,this.blockDuration)),s(c);else if(this.execEvenly&&this.points>0&&c.msBeforeNext>0&&!c.isFirstInDuration){let l=Math.ceil(c.msBeforeNext/(c.remainingPoints+2));l<this.execEvenlyMinDelayMs&&(l=c.consumedPoints*this.execEvenlyMinDelayMs),c.msBeforeNext=Math.max(c.msBeforeNext-l,0),setTimeout(o,l,c)}else o(c)})}penalty(t,r=1,n={}){let o=this.getKey(t);return new Promise(s=>{let i=this._getKeySecDuration(n),a=this._memoryStorage.incrby(o,r,i);a.remainingPoints=Math.max(this.points-a.consumedPoints,0),s(a)})}reward(t,r=1,n={}){let o=this.getKey(t);return new Promise(s=>{let i=this._getKeySecDuration(n),a=this._memoryStorage.incrby(o,-r,i);a.remainingPoints=Math.max(this.points-a.consumedPoints,0),s(a)})}block(t,r){let n=r*1e3,o=this.points+1;return this._memoryStorage.set(this.getKey(t),o,r),Promise.resolve(new Or(0,n===0?-1:n,o))}set(t,r,n){let o=(n>=0?n:this.duration)*1e3;return this._memoryStorage.set(this.getKey(t),r,n),Promise.resolve(new Or(0,o===0?-1:o,r))}get(t){let r=this._memoryStorage.get(this.getKey(t));return r!==null&&(r.remainingPoints=Math.max(this.points-r.consumedPoints,0)),Promise.resolve(r)}delete(t){return Promise.resolve(this._memoryStorage.delete(this.getKey(t)))}dump(){let t=[];for(let[r,n]of this._memoryStorage._storage)t.push({key:this.parseKey(r),value:n.value,expiresAt:n.expiresAt});return{version:1,dumpedAt:Date.now(),storage:t}}restore(t,r=!1){if(!t||typeof t!="object"||t.version!==1)return;let n=r?{invalid:{count:0,keys:[]},expired:{count:0,keys:[]},restored:{count:0,keys:[]}}:{invalid:0,expired:0,restored:0},o=(s,i)=>{r?(n[s].count+=1,n[s].keys.push(i)):n[s]+=1};if(!Array.isArray(t.storage))return n;for(let s of t.storage){if(!s||typeof s!="object"){o("invalid","N/A");continue}let i=typeof s.key=="string"||typeof s.key=="number",a=Number.isFinite(s.value),c=s.expiresAt===null||Number.isFinite(s.expiresAt);if(!i||!a||!c){o("invalid",s.key);continue}if(s.expiresAt!==null&&s.expiresAt<=Date.now()){o("expired",s.key);continue}this._memoryStorage._restoreRecord(this.getKey(s.key),s.value,s.expiresAt),o("restored",s.key)}return n}};Tr.exports=pt});import{createServer as yn}from"http";import{Http2ServerRequest as Pt,constants as bn}from"http2";import{Http2ServerRequest as Ie}from"http2";import{Readable as Et}from"stream";import Mn from"crypto";var D=class extends Error{constructor(e,t){super(e,t),this.name="RequestError"}},xn=e=>e instanceof D?e:new D(e.message,{cause:e}),vn=global.Request,Z=class extends vn{constructor(e,t){typeof e=="object"&&K in e&&(e=e[K]()),typeof t?.body?.getReader<"u"&&(t.duplex??="half"),super(e,t)}},En=e=>{let t=[],r=e.rawHeaders;for(let n=0;n<r.length;n+=2){let{[n]:o,[n+1]:s}=r;o.charCodeAt(0)!==58&&t.push([o,s])}return new Headers(t)},At=Symbol("wrapBodyStream"),Rn=(e,t,r,n,o)=>{let s={method:e,headers:r,signal:o.signal};if(e==="TRACE"){s.method="GET";let i=new Z(t,s);return Object.defineProperty(i,"method",{get(){return"TRACE"}}),i}if(!(e==="GET"||e==="HEAD"))if("rawBody"in n&&n.rawBody instanceof Buffer)s.body=new ReadableStream({start(i){i.enqueue(n.rawBody),i.close()}});else if(n[At]){let i;s.body=new ReadableStream({async pull(a){try{i||=Et.toWeb(n).getReader();let{done:c,value:l}=await i.read();c?a.close():a.enqueue(l)}catch(c){a.error(c)}}})}else s.body=Et.toWeb(n);return new Z(t,s)},K=Symbol("getRequestCache"),Sn=Symbol("requestCache"),ce=Symbol("incomingKey"),le=Symbol("urlKey"),Pn=Symbol("headersKey"),W=Symbol("abortControllerKey"),An=Symbol("getAbortController"),ue={get method(){return this[ce].method||"GET"},get url(){return this[le]},get headers(){return this[Pn]||=En(this[ce])},[An](){return this[K](),this[W]},[K](){return this[W]||=new AbortController,this[Sn]||=Rn(this.method,this[le],this.headers,this[ce],this[W])}};["body","bodyUsed","cache","credentials","destination","integrity","mode","redirect","referrer","referrerPolicy","signal","keepalive"].forEach(e=>{Object.defineProperty(ue,e,{get(){return this[K]()[e]}})});["arrayBuffer","blob","clone","formData","json","text"].forEach(e=>{Object.defineProperty(ue,e,{value:function(){return this[K]()[e]()}})});Object.setPrototypeOf(ue,Z.prototype);var _n=(e,t)=>{let r=Object.create(ue);r[ce]=e;let n=e.url||"";if(n[0]!=="/"&&(n.startsWith("http://")||n.startsWith("https://"))){if(e instanceof Ie)throw new D("Absolute URL for :path is not allowed in HTTP/2");try{let a=new URL(n);r[le]=a.href}catch(a){throw new D("Invalid absolute URL",{cause:a})}return r}let o=(e instanceof Ie?e.authority:e.headers.host)||t;if(!o)throw new D("Missing host header");let s;if(e instanceof Ie){if(s=e.scheme,!(s==="http"||s==="https"))throw new D("Unsupported scheme")}else s=e.socket&&e.socket.encrypted?"https":"http";let i=new URL(`${s}://${o}${n}`);if(i.hostname.length!==o.length&&i.hostname!==o.replace(/:\d+$/,""))throw new D("Invalid host header");return r[le]=i.href,r},Rt=Symbol("responseCache"),z=Symbol("getResponseCache"),j=Symbol("cache"),Ne=global.Response,ee=class _t{#t;#e;[z](){return delete this[j],this[Rt]||=new Ne(this.#t,this.#e)}constructor(t,r){let n;if(this.#t=t,r instanceof _t){let o=r[Rt];if(o){this.#e=o,this[z]();return}else this.#e=r.#e,n=new Headers(r.#e.headers)}else this.#e=r;(typeof t=="string"||typeof t?.getReader<"u"||t instanceof Blob||t instanceof Uint8Array)&&(this[j]=[r?.status||200,t,n||r?.headers])}get headers(){let t=this[j];return t?(t[2]instanceof Headers||(t[2]=new Headers(t[2]||{"content-type":"text/plain; charset=UTF-8"})),t[2]):this[z]().headers}get status(){return this[j]?.[0]??this[z]().status}get ok(){let t=this.status;return t>=200&&t<300}};["body","bodyUsed","redirected","statusText","trailers","type","url"].forEach(e=>{Object.defineProperty(ee.prototype,e,{get(){return this[z]()[e]}})});["arrayBuffer","blob","clone","formData","json","text"].forEach(e=>{Object.defineProperty(ee.prototype,e,{value:function(){return this[z]()[e]()}})});Object.setPrototypeOf(ee,Ne);Object.setPrototypeOf(ee.prototype,Ne.prototype);async function Cn(e){return Promise.race([e,Promise.resolve().then(()=>Promise.resolve(void 0))])}function Ct(e,t,r){let n=a=>{e.cancel(a).catch(()=>{})};return t.on("close",n),t.on("error",n),(r??e.read()).then(i,o),e.closed.finally(()=>{t.off("close",n),t.off("error",n)});function o(a){a&&t.destroy(a)}function s(){e.read().then(i,o)}function i({done:a,value:c}){try{if(a)t.end();else if(!t.write(c))t.once("drain",s);else return e.read().then(i,o)}catch(l){o(l)}}}function On(e,t){if(e.locked)throw new TypeError("ReadableStream is locked.");return t.destroyed?void 0:Ct(e.getReader(),t)}var Le=e=>{let t={};e instanceof Headers||(e=new Headers(e??void 0));let r=[];for(let[n,o]of e)n==="set-cookie"?r.push(o):t[n]=o;return r.length>0&&(t["set-cookie"]=r),t["content-type"]??="text/plain; charset=UTF-8",t},Tn="x-hono-already-sent";typeof global.crypto>"u"&&(global.crypto=Mn);var He=Symbol("outgoingEnded"),St=Symbol("incomingDraining"),In=500,kn=64*1024*1024,ke=e=>{let t=e;if(e.destroyed||t[St])return;if(t[St]=!0,e instanceof Pt){try{e.stream?.close?.(bn.NGHTTP2_NO_ERROR)}catch{}return}let r=0,n=()=>{clearTimeout(s),e.off("data",i),e.off("end",n),e.off("error",n)},o=()=>{n();let a=e.socket;a&&!a.destroyed&&a.destroySoon()},s=setTimeout(o,In);s.unref?.();let i=a=>{r+=a.length,r>kn&&o()};e.on("data",i),e.on("end",n),e.on("error",n),e.resume()},Ln=()=>new Response(null,{status:400}),Ot=e=>new Response(null,{status:e instanceof Error&&(e.name==="TimeoutError"||e.constructor.name==="TimeoutError")?504:500}),Ue=(e,t)=>{let r=e instanceof Error?e:new Error("unknown error",{cause:e});r.code==="ERR_STREAM_PREMATURE_CLOSE"?console.info("The user aborted a request."):(console.error(e),t.headersSent||t.writeHead(500,{"Content-Type":"text/plain"}),t.end(`Error: ${r.message}`),t.destroy(r))},Tt=e=>{"flushHeaders"in e&&e.writable&&e.flushHeaders()},Mt=async(e,t)=>{let[r,n,o]=e[j],s=!1;if(!o)o={"content-type":"text/plain; charset=UTF-8"};else if(o instanceof Headers)s=o.has("content-length"),o=Le(o);else if(Array.isArray(o)){let i=new Headers(o);s=i.has("content-length"),o=Le(i)}else for(let i in o)if(i.length===14&&i.toLowerCase()==="content-length"){s=!0;break}s||(typeof n=="string"?o["Content-Length"]=Buffer.byteLength(n):n instanceof Uint8Array?o["Content-Length"]=n.byteLength:n instanceof Blob&&(o["Content-Length"]=n.size)),t.writeHead(r,o),typeof n=="string"||n instanceof Uint8Array?t.end(n):n instanceof Blob?t.end(new Uint8Array(await n.arrayBuffer())):(Tt(t),await On(n,t)?.catch(i=>Ue(i,t))),t[He]?.()},Un=e=>typeof e.then=="function",Nn=async(e,t,r={})=>{if(Un(e))if(r.errorHandler)try{e=await e}catch(o){let s=await r.errorHandler(o);if(!s)return;e=s}else e=await e.catch(Ot);if(j in e)return Mt(e,t);let n=Le(e.headers);if(e.body){let o=e.body.getReader(),s=[],i=!1,a;if(n["transfer-encoding"]!=="chunked"){let c=2;for(let l=0;l<c;l++){a||=o.read();let u=await Cn(a).catch(d=>{console.error(d),i=!0});if(!u){if(l===1){await new Promise(d=>setTimeout(d)),c=3;continue}break}if(a=void 0,u.value&&s.push(u.value),u.done){i=!0;break}}i&&!("content-length"in n)&&(n["content-length"]=s.reduce((l,u)=>l+u.length,0))}t.writeHead(e.status,n),s.forEach(c=>{t.write(c)}),i?t.end():(s.length===0&&Tt(t),await Ct(o,t,a))}else n[Tn]||(t.writeHead(e.status,n),t.end());t[He]?.()},Hn=(e,t={})=>{let r=t.autoCleanupIncoming??!0;return t.overrideGlobalObjects!==!1&&global.Request!==Z&&(Object.defineProperty(global,"Request",{value:Z}),Object.defineProperty(global,"Response",{value:ee})),async(n,o)=>{let s,i;try{i=_n(n,t.hostname);let a=!r||n.method==="GET"||n.method==="HEAD";if(a||(n[At]=!0,n.on("end",()=>{a=!0}),n instanceof Pt&&(o[He]=()=>{a||setTimeout(()=>{a||setTimeout(()=>{ke(n)})})}),o.on("finish",()=>{a||ke(n)})),o.on("close",()=>{i[W]&&(n.errored?i[W].abort(n.errored.toString()):o.writableFinished||i[W].abort("Client connection prematurely closed.")),a||setTimeout(()=>{a||setTimeout(()=>{ke(n)})})}),s=e(i,{incoming:n,outgoing:o}),j in s)return Mt(s,o)}catch(a){if(s)return Ue(a,o);if(t.errorHandler){if(s=await t.errorHandler(i?a:xn(a)),!s)return}else i?s=Ot(a):s=Ln()}try{return await Nn(s,o,t)}catch(a){return Ue(a,o)}}},Dn=e=>{let t=e.fetch,r=Hn(t,{hostname:e.hostname,overrideGlobalObjects:e.overrideGlobalObjects,autoCleanupIncoming:e.autoCleanupIncoming});return(e.createServer||yn)(e.serverOptions||{},r)},It=(e,t)=>{let r=Dn(e);return r.listen(e?.port??3e3,e.hostname,()=>{let n=r.address();t&&t(n)}),r};var De=(e,t,r)=>(n,o)=>{let s=-1;return i(0);async function i(a){if(a<=s)throw new Error("next() called multiple times");s=a;let c,l=!1,u;if(e[a]?(u=e[a][0][0],n.req.routeIndex=a):u=a===e.length&&o||void 0,u)try{c=await u(n,()=>i(a+1))}catch(d){if(d instanceof Error&&t)n.error=d,c=await t(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 kt=Symbol();var Lt=async(e,t=Object.create(null))=>{let{all:r=!1,dot:n=!1}=t,s=(e instanceof de?e.raw.headers:e.headers).get("Content-Type");return s?.startsWith("multipart/form-data")||s?.startsWith("application/x-www-form-urlencoded")?jn(e,{all:r,dot:n}):{}};async function jn(e,t){let r=await e.formData();return r?Bn(r,t):{}}function Bn(e,t){let r=Object.create(null);return e.forEach((n,o)=>{t.all||o.endsWith("[]")?$n(r,o,n):r[o]=n}),t.dot&&Object.entries(r).forEach(([n,o])=>{n.includes(".")&&(Fn(r,n,o),delete r[n])}),r}var $n=(e,t,r)=>{e[t]!==void 0?Array.isArray(e[t])?e[t].push(r):e[t]=[e[t],r]:t.endsWith("[]")?e[t]=[r]:e[t]=r},Fn=(e,t,r)=>{if(/(?:^|\.)__proto__\./.test(t))return;let n=e,o=t.split(".");o.forEach((s,i)=>{i===o.length-1?n[s]=r:((!n[s]||typeof n[s]!="object"||Array.isArray(n[s])||n[s]instanceof File)&&(n[s]=Object.create(null)),n=n[s])})};var Be=e=>{let t=e.split("/");return t[0]===""&&t.shift(),t},Ut=e=>{let{groups:t,path:r}=qn(e),n=Be(r);return zn(n,t)},qn=e=>{let t=[];return e=e.replace(/\{[^}]+\}/g,(r,n)=>{let o=`@${n}`;return t.push([o,r]),o}),{groups:t,path:e}},zn=(e,t)=>{for(let r=t.length-1;r>=0;r--){let[n]=t[r];for(let o=e.length-1;o>=0;o--)if(e[o].includes(n)){e[o]=e[o].replace(n,t[r][1]);break}}return e},fe={},Nt=(e,t)=>{if(e==="*")return"*";let r=e.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);if(r){let n=`${e}#${t}`;return fe[n]||(r[2]?fe[n]=t&&t[0]!==":"&&t[0]!=="*"?[n,r[1],new RegExp(`^${r[2]}(?=/${t})`)]:[e,r[1],new RegExp(`^${r[2]}$`)]:fe[n]=[e,r[1],!0]),fe[n]}return null},pe=(e,t)=>{try{return t(e)}catch{return e.replace(/(?:%[0-9A-Fa-f]{2})+/g,r=>{try{return t(r)}catch{return r}})}},Wn=e=>pe(e,decodeURI),$e=e=>{let t=e.url,r=t.indexOf("/",t.indexOf(":")+4),n=r;for(;n<t.length;n++){let o=t.charCodeAt(n);if(o===37){let s=t.indexOf("?",n),i=t.indexOf("#",n),a=s===-1?i===-1?void 0:i:i===-1?s:Math.min(s,i),c=t.slice(r,a);return Wn(c.includes("%25")?c.replace(/%25/g,"%2525"):c)}else if(o===63||o===35)break}return t.slice(r,n)};var Ht=e=>{let t=$e(e);return t.length>1&&t.at(-1)==="/"?t.slice(0,-1):t},N=(e,t,...r)=>(r.length&&(t=N(t,...r)),`${e?.[0]==="/"?"":"/"}${e}${t==="/"?"":`${e?.at(-1)==="/"?"":"/"}${t?.[0]==="/"?t.slice(1):t}`}`),he=e=>{if(e.charCodeAt(e.length-1)!==63||!e.includes(":"))return null;let t=e.split("/"),r=[],n="";return t.forEach(o=>{if(o!==""&&!/\:/.test(o))n+="/"+o;else if(/\:/.test(o))if(/\?/.test(o)){r.length===0&&n===""?r.push("/"):r.push(n);let s=o.replace("?","");n+="/"+s,r.push(n)}else n+="/"+o}),r.filter((o,s,i)=>i.indexOf(o)===s)},je=e=>/[%+]/.test(e)?(e.indexOf("+")!==-1&&(e=e.replace(/\+/g," ")),e.indexOf("%")!==-1?pe(e,Fe):e):e,Dt=(e,t,r)=>{let n;if(!r&&t&&!/[%+]/.test(t)){let i=e.indexOf("?",8);if(i===-1)return;for(e.startsWith(t,i+1)||(i=e.indexOf(`&${t}`,i+1));i!==-1;){let a=e.charCodeAt(i+t.length+1);if(a===61){let c=i+t.length+2,l=e.indexOf("&",c);return je(e.slice(c,l===-1?void 0:l))}else if(a==38||isNaN(a))return"";i=e.indexOf(`&${t}`,i+1)}if(n=/[%+]/.test(e),!n)return}let o={};n??=/[%+]/.test(e);let s=e.indexOf("?",8);for(;s!==-1;){let i=e.indexOf("&",s+1),a=e.indexOf("=",s);a>i&&i!==-1&&(a=-1);let c=e.slice(s+1,a===-1?i===-1?void 0:i:a);if(n&&(c=je(c)),s=i,c==="")continue;let l;a===-1?l="":(l=e.slice(a+1,i===-1?void 0:i),n&&(l=je(l))),r?(o[c]&&Array.isArray(o[c])||(o[c]=[]),o[c].push(l)):o[c]??=l}return t?o[t]:o},jt=Dt,Bt=(e,t)=>Dt(e,t,!0),Fe=decodeURIComponent;var $t=e=>pe(e,Fe),de=class{raw;#t;#e;routeIndex=0;path;bodyCache={};constructor(e,t="/",r=[[]]){this.raw=e,this.path=t,this.#e=r,this.#t={}}param(e){return e?this.#r(e):this.#s()}#r(e){let t=this.#e[0][this.routeIndex][1][e],r=this.#o(t);return r&&/\%/.test(r)?$t(r):r}#s(){let e={},t=Object.keys(this.#e[0][this.routeIndex][1]);for(let r of t){let n=this.#o(this.#e[0][this.routeIndex][1][r]);n!==void 0&&(e[r]=/\%/.test(n)?$t(n):n)}return e}#o(e){return this.#e[1]?this.#e[1][e]:e}query(e){return jt(this.url,e)}queries(e){return Bt(this.url,e)}header(e){if(e)return this.raw.headers.get(e)??void 0;let t={};return this.raw.headers.forEach((r,n)=>{t[n]=r}),t}async parseBody(e){return Lt(this,e)}#n=e=>{let{bodyCache:t,raw:r}=this,n=t[e];if(n)return n;let o=Object.keys(t)[0];return o?t[o].then(s=>(o==="json"&&(s=JSON.stringify(s)),new Response(s)[e]())):t[e]=r[e]()};json(){return this.#n("text").then(e=>JSON.parse(e))}text(){return this.#n("text")}arrayBuffer(){return this.#n("arrayBuffer")}bytes(){return this.#n("arrayBuffer").then(e=>new Uint8Array(e))}blob(){return this.#n("blob")}formData(){return this.#n("formData")}addValidatedData(e,t){this.#t[e]=t}valid(e){return this.#t[e]}get url(){return this.raw.url}get method(){return this.raw.method}get[kt](){return this.#e}get matchedRoutes(){return this.#e[0].map(([[,e]])=>e)}get routePath(){return this.#e[0].map(([[,e]])=>e)[this.routeIndex].path}};var Ft={Stringify:1,BeforeStream:2,Stream:3},Kn=(e,t)=>{let r=new String(e);return r.isEscaped=!0,r.callbacks=t,r};var qe=async(e,t,r,n,o)=>{typeof e=="object"&&!(e instanceof String)&&(e instanceof Promise||(e=e.toString()),e instanceof Promise&&(e=await e));let s=e.callbacks;if(!s?.length)return Promise.resolve(e);o?o[0]+=e:o=[e];let i=Promise.all(s.map(a=>a({phase:t,buffer:o,context:n}))).then(a=>Promise.all(a.filter(Boolean).map(c=>qe(c,t,!1,n,o))).then(()=>o[0]));return r?Kn(await i,s):i};var Vn="text/plain; charset=UTF-8",ze=(e,t)=>({"Content-Type":e,...t}),te=(e,t)=>new Response(e,t),We=class{#t;#e;env={};#r;finalized=!1;error;#s;#o;#n;#u;#c;#l;#a;#d;#f;constructor(e,t){this.#t=e,t&&(this.#o=t.executionCtx,this.env=t.env,this.#l=t.notFoundHandler,this.#f=t.path,this.#d=t.matchResult)}get req(){return this.#e??=new de(this.#t,this.#f,this.#d),this.#e}get event(){if(this.#o&&"respondWith"in this.#o)return this.#o;throw Error("This context has no FetchEvent")}get executionCtx(){if(this.#o)return this.#o;throw Error("This context has no ExecutionContext")}get res(){return this.#n||=te(null,{headers:this.#a??=new Headers})}set res(e){if(this.#n&&e){e=te(e.body,e);for(let[t,r]of this.#n.headers.entries())if(t!=="content-type")if(t==="set-cookie"){let n=this.#n.headers.getSetCookie();e.headers.delete("set-cookie");for(let o of n)e.headers.append("set-cookie",o)}else e.headers.set(t,r)}this.#n=e,this.finalized=!0}render=(...e)=>(this.#c??=t=>this.html(t),this.#c(...e));setLayout=e=>this.#u=e;getLayout=()=>this.#u;setRenderer=e=>{this.#c=e};header=(e,t,r)=>{this.finalized&&(this.#n=te(this.#n.body,this.#n));let n=this.#n?this.#n.headers:this.#a??=new Headers;t===void 0?n.delete(e):r?.append?n.append(e,t):n.set(e,t)};status=e=>{this.#s=e};set=(e,t)=>{this.#r??=new Map,this.#r.set(e,t)};get=e=>this.#r?this.#r.get(e):void 0;get var(){return this.#r?Object.fromEntries(this.#r):{}}#i(e,t,r){let n=this.#n?new Headers(this.#n.headers):this.#a??new Headers;if(typeof t=="object"&&"headers"in t){let s=t.headers instanceof Headers?t.headers:new Headers(t.headers);for(let[i,a]of s)i.toLowerCase()==="set-cookie"?n.append(i,a):n.set(i,a)}if(r)for(let[s,i]of Object.entries(r))if(typeof i=="string")n.set(s,i);else{n.delete(s);for(let a of i)n.append(s,a)}let o=typeof t=="number"?t:t?.status??this.#s;return te(e,{status:o,headers:n})}newResponse=(...e)=>this.#i(...e);body=(e,t,r)=>this.#i(e,t,r);text=(e,t,r)=>!this.#a&&!this.#s&&!t&&!r&&!this.finalized?new Response(e):this.#i(e,t,ze(Vn,r));json=(e,t,r)=>this.#i(JSON.stringify(e),t,ze("application/json",r));html=(e,t,r)=>{let n=o=>this.#i(o,t,ze("text/html; charset=UTF-8",r));return typeof e=="object"?qe(e,Ft.Stringify,!1,{}).then(n):n(e)};redirect=(e,t)=>{let r=String(e);return this.header("Location",/[^\x00-\xFF]/.test(r)?encodeURI(r):r),this.newResponse(null,t??302)};notFound=()=>(this.#l??=()=>te(),this.#l(this))};var y="ALL",qt="all",zt=["get","post","put","delete","options","patch"],me="Can not add a route since the matcher is already built.",ge=class extends Error{};var Wt="__COMPOSED_HANDLER";var Gn=e=>e.text("404 Not Found",404),Kt=(e,t)=>{if("getResponse"in e){let r=e.getResponse();return t.newResponse(r.body,r)}return console.error(e),t.text("Internal Server Error",500)},Vt=class Gt{get;post;put;delete;options;patch;all;on;use;router;getPath;_basePath="/";#t="/";routes=[];constructor(t={}){[...zt,qt].forEach(s=>{this[s]=(i,...a)=>(typeof i=="string"?this.#t=i:this.#s(s,this.#t,i),a.forEach(c=>{this.#s(s,this.#t,c)}),this)}),this.on=(s,i,...a)=>{for(let c of[i].flat()){this.#t=c;for(let l of[s].flat())a.map(u=>{this.#s(l.toUpperCase(),this.#t,u)})}return this},this.use=(s,...i)=>(typeof s=="string"?this.#t=s:(this.#t="*",i.unshift(s)),i.forEach(a=>{this.#s(y,this.#t,a)}),this);let{strict:n,...o}=t;Object.assign(this,o),this.getPath=n??!0?t.getPath??$e:Ht}#e(){let t=new Gt({router:this.router,getPath:this.getPath});return t.errorHandler=this.errorHandler,t.#r=this.#r,t.routes=this.routes,t}#r=Gn;errorHandler=Kt;route(t,r){let n=this.basePath(t);return r.routes.map(o=>{let s;r.errorHandler===Kt?s=o.handler:(s=async(i,a)=>(await De([],r.errorHandler)(i,()=>o.handler(i,a))).res,s[Wt]=o.handler),n.#s(o.method,o.path,s,o.basePath)}),this}basePath(t){let r=this.#e();return r._basePath=N(this._basePath,t),r}onError=t=>(this.errorHandler=t,this);notFound=t=>(this.#r=t,this);mount(t,r,n){let o,s;n&&(typeof n=="function"?s=n:(s=n.optionHandler,n.replaceRequest===!1?o=c=>c:o=n.replaceRequest));let i=s?c=>{let l=s(c);return Array.isArray(l)?l:[l]}:c=>{let l;try{l=c.executionCtx}catch{}return[c.env,l]};o||=(()=>{let c=N(this._basePath,t),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 a=async(c,l)=>{let u=await r(o(c.req.raw),...i(c));if(u)return u;await l()};return this.#s(y,N(t,"*"),a),this}#s(t,r,n,o){t=t.toUpperCase(),r=N(this._basePath,r);let s={basePath:o!==void 0?N(this._basePath,o):this._basePath,path:r,method:t,handler:n};this.router.add(t,r,[n,s]),this.routes.push(s)}#o(t,r){if(t instanceof Error)return this.errorHandler(t,r);throw t}#n(t,r,n,o){if(o==="HEAD")return(async()=>new Response(null,await this.#n(t,r,n,"GET")))();let s=this.getPath(t,{env:n}),i=this.router.match(o,s),a=new We(t,{path:s,matchResult:i,env:n,executionCtx:r,notFoundHandler:this.#r});if(i[0].length===1){let l;try{l=i[0][0][0][0](a,async()=>{a.res=await this.#r(a)})}catch(u){return this.#o(u,a)}return l instanceof Promise?l.then(u=>u||(a.finalized?a.res:this.#r(a))).catch(u=>this.#o(u,a)):l??this.#r(a)}let c=De(i[0],this.errorHandler,this.#r);return(async()=>{try{let l=await c(a);if(!l.finalized)throw new Error("Context is not finalized. Did you forget to return a Response object or `await next()`?");return l.res}catch(l){return this.#o(l,a)}})()}fetch=(t,...r)=>this.#n(t,r[1],r[0],t.method);request=(t,r,n,o)=>t instanceof Request?this.fetch(r?new Request(t,r):t,n,o):(t=t.toString(),this.fetch(new Request(/^https?:\/\//.test(t)?t:`http://localhost${N("/",t)}`,r),n,o));fire=()=>{addEventListener("fetch",t=>{t.respondWith(this.#n(t.request,t,void 0,t.request.method))})}};var we=[];function Ke(e,t){let r=this.buildAllMatchers(),n=((o,s)=>{let i=r[o]||r[y],a=i[2][s];if(a)return a;let c=s.match(i[0]);if(!c)return[[],we];let l=c.indexOf("",1);return[i[1][l],c]});return this.match=n,n(e,t)}var ye="[^/]+",re=".*",ne="(?:|/.*)",B=Symbol(),Xn=new Set(".\\+*[^]$()");function Yn(e,t){return e.length===1?t.length===1?e<t?-1:1:-1:t.length===1||e===re||e===ne?1:t===re||t===ne?-1:e===ye?1:t===ye?-1:e.length===t.length?e<t?-1:1:t.length-e.length}var Xt=class Ve{#t;#e;#r=Object.create(null);insert(t,r,n,o,s){if(t.length===0){if(this.#t!==void 0)throw B;if(s)return;this.#t=r;return}let[i,...a]=t,c=i==="*"?a.length===0?["","",re]:["","",ye]:i==="/*"?["","",ne]:i.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/),l;if(c){let u=c[1],d=c[2]||ye;if(u&&c[2]&&(d===".*"||(d=d.replace(/^\((?!\?:)(?=[^)]+\)$)/,"(?:"),/\((?!\?:)/.test(d))))throw B;if(l=this.#r[d],!l){if(Object.keys(this.#r).some(h=>h!==re&&h!==ne))throw B;if(s)return;l=this.#r[d]=new Ve,u!==""&&(l.#e=o.varIndex++)}!s&&u!==""&&n.push([u,l.#e])}else if(l=this.#r[i],!l){if(Object.keys(this.#r).some(u=>u.length>1&&u!==re&&u!==ne))throw B;if(s)return;l=this.#r[i]=new Ve}l.insert(a,r,n,o,s)}buildRegExpStr(){let r=Object.keys(this.#r).sort(Yn).map(n=>{let o=this.#r[n];return(typeof o.#e=="number"?`(${n})@${o.#e}`:Xn.has(n)?`\\${n}`:n)+o.buildRegExpStr()});return typeof this.#t=="number"&&r.unshift(`#${this.#t}`),r.length===0?"":r.length===1?r[0]:"(?:"+r.join("|")+")"}};var Yt=class{#t={varIndex:0};#e=new Xt;insert(e,t,r){let n=[],o=[];for(let i=0;;){let a=!1;if(e=e.replace(/\{[^}]+\}/g,c=>{let l=`@\\${i}`;return o[i]=[l,c],i++,a=!0,l}),!a)break}let s=e.match(/(?::[^\/]+)|(?:\/\*$)|./g)||[];for(let i=o.length-1;i>=0;i--){let[a]=o[i];for(let c=s.length-1;c>=0;c--)if(s[c].indexOf(a)!==-1){s[c]=s[c].replace(a,o[i][1]);break}}return this.#e.insert(s,t,n,this.#t,r),n}buildRegExp(){let e=this.#e.buildRegExpStr();if(e==="")return[/^$/,[],[]];let t=0,r=[],n=[];return e=e.replace(/#(\d+)|@(\d+)|\.\*\$/g,(o,s,i)=>s!==void 0?(r[++t]=Number(s),"$()"):(i!==void 0&&(n[Number(i)]=++t),"")),[new RegExp(`^${e}`),r,n]}};var Jn=[/^$/,[],Object.create(null)],Jt=Object.create(null);function Qt(e){return Jt[e]??=new RegExp(e==="*"?"":`^${e.replace(/\/\*$|([.\\+*[^\]$()])/g,(t,r)=>r?`\\${r}`:"(?:|/.*)")}$`)}function Qn(){Jt=Object.create(null)}function Zn(e){let t=new Yt,r=[];if(e.length===0)return Jn;let n=e.map(l=>[!/\*|\/:/.test(l[0]),...l]).sort(([l,u],[d,h])=>l?1:d?-1:u.length-h.length),o=Object.create(null);for(let l=0,u=-1,d=n.length;l<d;l++){let[h,p,g]=n[l];h?o[p]=[g.map(([w])=>[w,Object.create(null)]),we]:u++;let f;try{f=t.insert(p,u,h)}catch(w){throw w===B?new ge(p):w}h||(r[u]=g.map(([w,m])=>{let v=Object.create(null);for(m-=1;m>=0;m--){let[A,M]=f[m];v[A]=M}return[w,v]}))}let[s,i,a]=t.buildRegExp();for(let l=0,u=r.length;l<u;l++)for(let d=0,h=r[l].length;d<h;d++){let p=r[l][d]?.[1];if(!p)continue;let g=Object.keys(p);for(let f=0,w=g.length;f<w;f++)p[g[f]]=a[p[g[f]]]}let c=[];for(let l in i)c[l]=r[i[l]];return[s,c,o]}function V(e,t){if(e){for(let r of Object.keys(e).sort((n,o)=>o.length-n.length))if(Qt(r).test(t))return[...e[r]]}}var be=class{name="RegExpRouter";#t;#e;constructor(){this.#t={[y]:Object.create(null)},this.#e={[y]:Object.create(null)}}add(e,t,r){let n=this.#t,o=this.#e;if(!n||!o)throw new Error(me);n[e]||[n,o].forEach(a=>{a[e]=Object.create(null),Object.keys(a[y]).forEach(c=>{a[e][c]=[...a[y][c]]})}),t==="/*"&&(t="*");let s=(t.match(/\/:/g)||[]).length;if(/\*$/.test(t)){let a=Qt(t);e===y?Object.keys(n).forEach(c=>{n[c][t]||=V(n[c],t)||V(n[y],t)||[]}):n[e][t]||=V(n[e],t)||V(n[y],t)||[],Object.keys(n).forEach(c=>{(e===y||e===c)&&Object.keys(n[c]).forEach(l=>{a.test(l)&&n[c][l].push([r,s])})}),Object.keys(o).forEach(c=>{(e===y||e===c)&&Object.keys(o[c]).forEach(l=>a.test(l)&&o[c][l].push([r,s]))});return}let i=he(t)||[t];for(let a=0,c=i.length;a<c;a++){let l=i[a];Object.keys(o).forEach(u=>{(e===y||e===u)&&(o[u][l]||=[...V(n[u],l)||V(n[y],l)||[]],o[u][l].push([r,s-c+a+1]))})}}match=Ke;buildAllMatchers(){let e=Object.create(null);return Object.keys(this.#e).concat(Object.keys(this.#t)).forEach(t=>{e[t]||=this.#r(t)}),this.#t=this.#e=void 0,Qn(),e}#r(e){let t=[],r=e===y;return[this.#t,this.#e].forEach(n=>{let o=n[e]?Object.keys(n[e]).map(s=>[s,n[e][s]]):[];o.length!==0?(r||=!0,t.push(...o)):e!==y&&t.push(...Object.keys(n[y]).map(s=>[s,n[y][s]]))}),r?Zn(t):null}};var Ge=class{name="SmartRouter";#t=[];#e=[];constructor(e){this.#t=e.routers}add(e,t,r){if(!this.#e)throw new Error(me);this.#e.push([e,t,r])}match(e,t){if(!this.#e)throw new Error("Fatal error");let r=this.#t,n=this.#e,o=r.length,s=0,i;for(;s<o;s++){let a=r[s];try{for(let c=0,l=n.length;c<l;c++)a.add(...n[c]);i=a.match(e,t)}catch(c){if(c instanceof ge)continue;throw c}this.match=a.match.bind(a),this.#t=[a],this.#e=void 0;break}if(s===o)throw new Error("Fatal error");return this.name=`SmartRouter + ${this.activeRouter.name}`,i}get activeRouter(){if(this.#e||this.#t.length!==1)throw new Error("No active router has been determined yet.");return this.#t[0]}};var oe=Object.create(null),eo=e=>{for(let t in e)return!0;return!1},Zt=class er{#t;#e;#r;#s=0;#o=oe;constructor(t,r,n){if(this.#e=n||Object.create(null),this.#t=[],t&&r){let o=Object.create(null);o[t]={handler:r,possibleKeys:[],score:0},this.#t=[o]}this.#r=[]}insert(t,r,n){this.#s=++this.#s;let o=this,s=Ut(r),i=[];for(let a=0,c=s.length;a<c;a++){let l=s[a],u=s[a+1],d=Nt(l,u),h=Array.isArray(d)?d[0]:l;if(h in o.#e){o=o.#e[h],d&&i.push(d[1]);continue}o.#e[h]=new er,d&&(o.#r.push(d),i.push(d[1])),o=o.#e[h]}return o.#t.push({[t]:{handler:n,possibleKeys:i.filter((a,c,l)=>l.indexOf(a)===c),score:this.#s}}),o}#n(t,r,n,o,s){for(let i=0,a=r.#t.length;i<a;i++){let c=r.#t[i],l=c[n]||c[y],u={};if(l!==void 0&&(l.params=Object.create(null),t.push(l),o!==oe||s&&s!==oe))for(let d=0,h=l.possibleKeys.length;d<h;d++){let p=l.possibleKeys[d],g=u[l.score];l.params[p]=s?.[p]&&!g?s[p]:o[p]??s?.[p],u[l.score]=!0}}}search(t,r){let n=[];this.#o=oe;let s=[this],i=Be(r),a=[],c=i.length,l=null;for(let u=0;u<c;u++){let d=i[u],h=u===c-1,p=[];for(let f=0,w=s.length;f<w;f++){let m=s[f],v=m.#e[d];v&&(v.#o=m.#o,h?(v.#e["*"]&&this.#n(n,v.#e["*"],t,m.#o),this.#n(n,v,t,m.#o)):p.push(v));for(let A=0,M=m.#r.length;A<M;A++){let E=m.#r[A],b=m.#o===oe?{}:{...m.#o};if(E==="*"){let k=m.#e["*"];k&&(this.#n(n,k,t,m.#o),k.#o=b,p.push(k));continue}let[S,x,P]=E;if(!d&&!(P instanceof RegExp))continue;let R=m.#e[S];if(P instanceof RegExp){if(l===null){l=new Array(c);let q=r[0]==="/"?1:0;for(let O=0;O<c;O++)l[O]=q,q+=i[O].length+1}let k=r.substring(l[u]),J=P.exec(k);if(J){if(b[x]=J[0],this.#n(n,R,t,m.#o,b),eo(R.#e)){R.#o=b;let q=J[0].match(/\//)?.length??0;(a[q]||=[]).push(R)}continue}}(P===!0||P.test(d))&&(b[x]=d,h?(this.#n(n,R,t,b,m.#o),R.#e["*"]&&this.#n(n,R.#e["*"],t,b,m.#o)):(R.#o=b,p.push(R)))}}let g=a.shift();s=g?p.concat(g):p}return n.length>1&&n.sort((u,d)=>u.score-d.score),[n.map(({handler:u,params:d})=>[u,d])]}};var Xe=class{name="TrieRouter";#t;constructor(){this.#t=new Zt}add(e,t,r){let n=he(t);if(n){for(let o=0,s=n.length;o<s;o++)this.#t.insert(e,n[o],r);return}this.#t.insert(e,t,r)}match(e,t){return this.#t.search(e,t)}};var Ye=class extends Vt{constructor(e={}){super(e),this.router=e.router??new Ge({routers:[new be,new Xe]})}};var xe=e=>{let t={origin:"*",allowMethods:["GET","HEAD","PUT","POST","DELETE","PATCH"],allowHeaders:[],exposeHeaders:[],...e},r=(o=>typeof o=="string"?o==="*"?()=>o:s=>o===s?s:null:typeof o=="function"?o:s=>o.includes(s)?s:null)(t.origin),n=(o=>typeof o=="function"?o:Array.isArray(o)?()=>o:()=>[])(t.allowMethods);return async function(s,i){function a(l,u){s.res.headers.set(l,u)}let c=await r(s.req.header("origin")||"",s);if(c&&a("Access-Control-Allow-Origin",c),t.credentials&&a("Access-Control-Allow-Credentials","true"),t.exposeHeaders?.length&&a("Access-Control-Expose-Headers",t.exposeHeaders.join(",")),s.req.method==="OPTIONS"){t.origin!=="*"&&a("Vary","Origin"),t.maxAge!=null&&a("Access-Control-Max-Age",t.maxAge.toString());let l=await n(s.req.header("origin")||"",s);l.length&&a("Access-Control-Allow-Methods",l.join(","));let u=t.allowHeaders;if(!u?.length){let d=s.req.header("Access-Control-Request-Headers");d&&(u=d.split(/\s*,\s*/))}return u?.length&&(a("Access-Control-Allow-Headers",u.join(",")),s.res.headers.append("Vary","Access-Control-Request-Headers")),s.res.headers.delete("Content-Length"),s.res.headers.delete("Content-Type"),new Response(null,{headers:s.res.headers,status:204,statusText:"No Content"})}await i(),t.origin!=="*"&&s.header("Vary","Origin",{append:!0})}};import wr from"process";import yr from"path";import{fileURLToPath as ko}from"url";import Lo from"child_process";import Uo,{constants as No}from"fs/promises";import{promisify as fo}from"util";import po from"child_process";import tt,{constants as ar}from"fs/promises";import nr from"process";import so from"os";import io from"fs";import no from"fs";import tr from"fs";var Je;function to(){try{return tr.statSync("/.dockerenv"),!0}catch{return!1}}function ro(){try{return tr.readFileSync("/proc/self/cgroup","utf8").includes("docker")}catch{return!1}}function Qe(){return Je===void 0&&(Je=to()||ro()),Je}var Ze,oo=()=>{try{return no.statSync("/run/.containerenv"),!0}catch{return!1}};function G(){return Ze===void 0&&(Ze=oo()||Qe()),Ze}var rr=()=>{if(nr.platform!=="linux")return!1;if(so.release().toLowerCase().includes("microsoft"))return!G();try{return io.readFileSync("/proc/version","utf8").toLowerCase().includes("microsoft")?!G():!1}catch{return!1}},L=nr.env.__IS_WSL_TEST__?rr:rr();import or from"process";import{Buffer as ao}from"buffer";import{promisify as co}from"util";import lo from"child_process";import ga,{constants as wa}from"fs/promises";var uo=co(lo.execFile),et=()=>`${or.env.SYSTEMROOT||or.env.windir||String.raw`C:\Windows`}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`;var T=async(e,t={})=>{let{powerShellPath:r,...n}=t,o=T.encodeCommand(e);return uo(r??et(),[...T.argumentsPrefix,o],{encoding:"utf8",...n})};T.argumentsPrefix=["-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-EncodedCommand"];T.encodeCommand=e=>ao.from(e,"utf16le").toString("base64");T.escapeArgument=e=>`'${String(e).replaceAll("'","''")}'`;function sr(e){for(let t of e.split(`
3
+ `)){if(/^\s*#/.test(t))continue;let r=/^\s*root\s*=\s*(?<mountPoint>"[^"]*"|'[^']*'|[^#]*)/.exec(t);if(r)return r.groups.mountPoint.trim().replaceAll(/^["']|["']$/g,"")}}var ho=fo(po.execFile),mo=(()=>{let e="/mnt/",t;return async function(){if(t)return t;let r="/etc/wsl.conf",n=!1;try{await tt.access(r,ar.F_OK),n=!0}catch{}if(!n)return e;let o=await tt.readFile(r,{encoding:"utf8"}),s=sr(o);return s===void 0?e:(t=s,t=t.endsWith("/")?t:`${t}/`,t)}})(),go=async()=>`${await mo()}c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe`,ve=L?go:et,ir,cr=async()=>(ir??=(async()=>{try{let e=await ve();return await tt.access(e,ar.X_OK),!0}catch{return!1}})(),ir),lr=async()=>{let e=await ve(),t=String.raw`(Get-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\Shell\Associations\UrlAssociations\http\UserChoice").ProgId`,{stdout:r}=await T(t,{powerShellPath:e});return r.trim()},ur=async e=>{if(/^[a-z]+:\/\//i.test(e))return e;try{let{stdout:t}=await ho("wslpath",["-aw",e],{encoding:"utf8"});return t.trim()}catch{return e}};function $(e,t,r){let n=o=>Object.defineProperty(e,t,{value:o,enumerable:!0,writable:!0});return Object.defineProperty(e,t,{configurable:!0,enumerable:!0,get(){let o=r();return n(o),o},set(o){n(o)}}),e}import{promisify as Co}from"util";import at from"process";import{execFile as Oo}from"child_process";import{promisify as wo}from"util";import yo from"process";import{execFile as bo}from"child_process";var xo=wo(bo);async function rt(){if(yo.platform!=="darwin")throw new Error("macOS only");let{stdout:e}=await xo("defaults",["read","com.apple.LaunchServices/com.apple.launchservices.secure","LSHandlers"]),r=/LSHandlerRoleAll = "(?!-)(?<id>[^"]+?)";\s+?LSHandlerURLScheme = (?:http|https);/.exec(e)?.groups.id??"com.apple.Safari";return r==="com.apple.safari"?"com.apple.Safari":r}import vo from"process";import{promisify as Eo}from"util";import{execFile as Ro,execFileSync as Na}from"child_process";var So=Eo(Ro);async function dr(e,{humanReadableOutput:t=!0,signal:r}={}){if(vo.platform!=="darwin")throw new Error("macOS only");let n=t?[]:["-ss"],o={};r&&(o.signal=r);let{stdout:s}=await So("osascript",["-e",e,n],o);return s.trim()}async function nt(e){return dr(`tell application "Finder" to set app_path to application file id "${e}" as string
4
+ tell application "System Events" to get value of property list item "CFBundleName" of property list file (app_path & ":Contents:Info.plist")`)}import{promisify as Po}from"util";import{execFile as Ao}from"child_process";var _o=Po(Ao),Ee={MSEdgeHTM:{name:"Edge",id:"com.microsoft.edge"},MSEdgeBHTML:{name:"Edge Beta",id:"com.microsoft.edge.beta"},MSEdgeDHTML:{name:"Edge Dev",id:"com.microsoft.edge.dev"},AppXq0fevzme2pys62n3e0fbqa7peapykr8v:{name:"Edge",id:"com.microsoft.edge.old"},ChromeHTML:{name:"Chrome",id:"com.google.chrome"},ChromeBHTML:{name:"Chrome Beta",id:"com.google.chrome.beta"},ChromeDHTML:{name:"Chrome Dev",id:"com.google.chrome.dev"},ChromiumHTM:{name:"Chromium",id:"org.chromium.Chromium"},BraveHTML:{name:"Brave",id:"com.brave.Browser"},BraveBHTML:{name:"Brave Beta",id:"com.brave.Browser.beta"},BraveDHTML:{name:"Brave Dev",id:"com.brave.Browser.dev"},BraveSSHTM:{name:"Brave Nightly",id:"com.brave.Browser.nightly"},FirefoxURL:{name:"Firefox",id:"org.mozilla.firefox"},OperaStable:{name:"Opera",id:"com.operasoftware.Opera"},VivaldiHTM:{name:"Vivaldi",id:"com.vivaldi.Vivaldi"},"IE.HTTP":{name:"Internet Explorer",id:"com.microsoft.ie"}},st=new Map(Object.entries(Ee)),ot=class extends Error{};async function it(e=_o){let{stdout:t}=await e("reg",["QUERY"," HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\Shell\\Associations\\UrlAssociations\\http\\UserChoice","/v","ProgId"]),r=/ProgId\s*REG_SZ\s*(?<id>\S+)/.exec(t);if(!r)throw new ot(`Cannot find Windows browser in stdout: ${JSON.stringify(t)}`);let{id:n}=r.groups,o=n.lastIndexOf("."),s=n.lastIndexOf("-"),i=o===-1?void 0:n.slice(0,o),a=s===-1?void 0:n.slice(0,s);return Ee[n]??Ee[i]??Ee[a]??{name:n,id:n}}var To=Co(Oo),Mo=e=>e.toLowerCase().replaceAll(/(?:^|\s|-)\S/g,t=>t.toUpperCase());async function ct(){if(at.platform==="darwin"){let e=await rt();return{name:await nt(e),id:e}}if(at.platform==="linux"){let{stdout:e}=await To("xdg-mime",["query","default","x-scheme-handler/http"]),t=e.trim();return{name:Mo(t.replace(/.desktop$/,"").replace("-"," ")),id:t}}if(at.platform==="win32")return it();throw new Error("Only macOS, Linux, and Windows are supported")}import lt from"process";var Io=!!(lt.env.SSH_CONNECTION||lt.env.SSH_CLIENT||lt.env.SSH_TTY),fr=Io;var Re=Symbol("fallbackAttempt"),ut=import.meta.url?yr.dirname(ko(import.meta.url)):"",pr=yr.join(ut,"xdg-open"),{platform:X,arch:hr}=wr,mr=async(e,t)=>{if(e.length===0)return;let r=[];for(let n of e)try{return await t(n)}catch(o){r.push(o)}throw new AggregateError(r,"Failed to open in all supported apps")},Se=async e=>{e={wait:!1,background:!1,newInstance:!1,allowNonzeroExitCode:!1,...e};let t=e[Re]===!0;if(delete e[Re],Array.isArray(e.app))return mr(e.app,l=>Se({...e,app:l,[Re]:!0}));let{name:r,arguments:n=[]}=e.app??{};if(n=[...n],Array.isArray(r))return mr(r,l=>Se({...e,app:{name:l,arguments:n},[Re]:!0}));if(r==="browser"||r==="browserPrivate"){let l={"com.google.chrome":"chrome","google-chrome.desktop":"chrome","com.brave.browser":"brave","org.mozilla.firefox":"firefox","firefox.desktop":"firefox","com.microsoft.msedge":"edge","com.microsoft.edge":"edge","com.microsoft.edgemac":"edge","microsoft-edge.desktop":"edge","com.apple.safari":"safari"},u={chrome:"--incognito",brave:"--incognito",firefox:"--private-window",edge:"--inPrivate"},d;if(L){let h=await lr();d=st.get(h)??{}}else d=await ct();if(d.id in l){let h=l[d.id.toLowerCase()];if(r==="browserPrivate"){if(h==="safari")throw new Error("Safari doesn't support opening in private mode via command line");n.push(u[h])}return Se({...e,app:{name:Y[h],arguments:n}})}throw new Error(`${d.name} is not supported as a default browser`)}let o,s=[],i={},a=!1;if(L&&!G()&&!fr&&!r&&(a=await cr()),X==="darwin")o="open",e.wait&&s.push("--wait-apps"),e.background&&s.push("--background"),e.newInstance&&s.push("--new"),r&&s.push("-a",r);else if(X==="win32"||a){o=await ve(),s.push(...T.argumentsPrefix),L||(i.windowsVerbatimArguments=!0),L&&e.target&&(e.target=await ur(e.target));let l=["$ProgressPreference = 'SilentlyContinue';","Start"];e.wait&&l.push("-Wait"),r?(l.push(T.escapeArgument(r)),e.target&&n.push(e.target)):e.target&&l.push(T.escapeArgument(e.target)),n.length>0&&(n=n.map(u=>T.escapeArgument(u)),l.push("-ArgumentList",n.join(","))),e.target=T.encodeCommand(l.join(" ")),e.wait||(i.stdio="ignore")}else{if(r)o=r;else{let l=!ut||ut==="/",u=!1;try{await Uo.access(pr,No.X_OK),u=!0}catch{}o=wr.versions.electron??(X==="android"||l||!u)?"xdg-open":pr}n.length>0&&s.push(...n),e.wait||(i.stdio="ignore",i.detached=!0)}X==="darwin"&&n.length>0&&s.push("--args",...n),e.target&&s.push(e.target);let c=Lo.spawn(o,s,i);return e.wait?new Promise((l,u)=>{c.once("error",u),c.once("close",d=>{if(!e.allowNonzeroExitCode&&d!==0){u(new Error(`Exited with code ${d}`));return}l(c)})}):t?new Promise((l,u)=>{c.once("error",u),c.once("spawn",()=>{c.once("close",d=>{if(c.off("error",u),d!==0){u(new Error(`Exited with code ${d}`));return}c.unref(),l(c)})})}):(c.unref(),new Promise((l,u)=>{c.once("error",u),c.once("spawn",()=>{c.off("error",u),l(c)})}))},Ho=(e,t)=>{if(typeof e!="string")throw new TypeError("Expected a `target`");return Se({...t,target:e})};function gr(e){if(typeof e=="string"||Array.isArray(e))return e;let{[hr]:t}=e;if(!t)throw new Error(`${hr} is not supported`);return t}function se({[X]:e},{wsl:t}={}){if(t&&L)return gr(t);if(!e)throw new Error(`${X} is not supported`);return gr(e)}var Y={browser:"browser",browserPrivate:"browserPrivate"};$(Y,"chrome",()=>se({darwin:"google chrome",win32:"chrome",linux:["google-chrome","google-chrome-stable","chromium","chromium-browser"]},{wsl:{ia32:"/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe",x64:["/mnt/c/Program Files/Google/Chrome/Application/chrome.exe","/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe"]}}));$(Y,"brave",()=>se({darwin:"brave browser",win32:"brave",linux:["brave-browser","brave"]},{wsl:{ia32:"/mnt/c/Program Files (x86)/BraveSoftware/Brave-Browser/Application/brave.exe",x64:["/mnt/c/Program Files/BraveSoftware/Brave-Browser/Application/brave.exe","/mnt/c/Program Files (x86)/BraveSoftware/Brave-Browser/Application/brave.exe"]}}));$(Y,"firefox",()=>se({darwin:"firefox",win32:String.raw`C:\Program Files\Mozilla Firefox\firefox.exe`,linux:"firefox"},{wsl:"/mnt/c/Program Files/Mozilla Firefox/firefox.exe"}));$(Y,"edge",()=>se({darwin:"microsoft edge",win32:"msedge",linux:["microsoft-edge","microsoft-edge-dev"]},{wsl:"/mnt/c/Program Files (x86)/Microsoft/Edge/Application/msedge.exe"}));$(Y,"safari",()=>se({darwin:"Safari"}));var br=Ho;function xr(e=""){return`<link rel="icon" type="image/svg+xml" href="${`${e.replace(/\/$/,"")}/favicon-black.svg?v=4`}" />`}import{existsSync as Ur,readFileSync as $o}from"fs";import U from"path";import{fileURLToPath as Fo}from"url";import{gunzipSync as qo}from"zlib";var Ir=wn(Mr(),1),kr=600,Lr=120,Pe=60;function Ae(e){let t=new Ir.default({points:e.points,duration:e.durationSeconds});return async(r,n)=>{try{await t.consume(e.key)}catch(o){return r.header("Retry-After",String(Bo(o))),r.json({error:"Too Many Requests"},429)}await n()}}function Bo(e){return e&&typeof e=="object"&&"msBeforeNext"in e&&typeof e.msBeforeNext=="number"?Math.max(1,Math.ceil(e.msBeforeNext/1e3)):60}var zo={".js":"application/javascript",".css":"text/css",".svg":"image/svg+xml",".png":"image/png",".ico":"image/x-icon",".webmanifest":"application/manifest+json"};function Wo(){let e=U.dirname(Fo(import.meta.url));for(let t of[U.resolve(e,"app"),U.resolve(e,"../app"),U.resolve(e,"../../dist/app")])if(Ur(U.join(t,"inspector.js.gz")))return t;throw new Error("Inspector bundle not found (expected dist/app/inspector.js.gz)")}function Nr(e,t="/inspector/assets"){let r=Wo(),n=new Map;e.use(`${t}/*`,Ae({points:kr,durationSeconds:Pe,key:"inspector-assets"})),e.get(`${t}/*`,o=>{let s=o.req.path.slice(t.length),i=s.startsWith("/")?s.slice(1):s;if(!i||i.includes(".."))return o.notFound();let a=i==="inspector.js"||i==="inspector.css"?`${i}.gz`:i,c=U.resolve(r,a),l=r.endsWith(U.sep)?r:`${r}${U.sep}`;if(!c.startsWith(l)||!Ur(c))return o.notFound();let u=U.extname(i),d=a.endsWith(".gz"),h=/(?:^|,)\s*gzip\s*(?:,|$)/i.test(o.req.header("accept-encoding")??""),p=$o(c),g=d&&!h?n.get(c)??Ko(n,c,p):p,f=g.buffer.slice(g.byteOffset,g.byteOffset+g.byteLength);return o.body(f,200,{"Content-Type":zo[u]??"application/octet-stream",...d&&h?{"Content-Encoding":"gzip"}:{},...d?{Vary:"Accept-Encoding"}:{},"Cache-Control":"no-cache"})})}function Ko(e,t,r){let n=qo(r);return e.set(t,n),n}var Hr={name:"@mcp-use/inspector",type:"module",version:"20.0.0-beta.34",description:"MCP Inspector - A tool for inspecting and debugging MCP servers",author:"",license:"MIT",homepage:"https://github.com/mcp-use/mcp-use#readme",repository:{type:"git",url:"git+https://github.com/mcp-use/mcp-use.git",directory:"libraries/typescript/packages/inspector"},bugs:{url:"https://github.com/mcp-use/mcp-use/issues"},keywords:["mcp","inspector","debug","tools"],exports:{".":{types:"./dist/server/index.d.ts",import:"./dist/server/index.js"},"./client":{types:"./dist/client/index.d.ts",import:"./dist/client/index.js"}},main:"./dist/server/index.js",types:"./dist/server/index.d.ts",bin:{"mcp-inspect":"./dist/cli.js"},files:["dist"],scripts:{dev:"rimraf node_modules/.vite && VITE_MANUFACT_CHAT_URL=${VITE_MANUFACT_CHAT_URL:-http://localhost:8000/api/v1/inspector/chat/stream} vite --strictPort","dev:client":"pnpm run dev","dev:server":"VITE_DEV=true tsx watch src/server/server.ts","dev:standalone":"tsx watch src/server/server.ts",clean:"rimraf dist",build:"npm run clean && npm run build:client-exports && npm run build:server && npm run build:app && npm run verify:package","build:app":"vite build --config vite.app.config.ts && node scripts/compress-app.mjs","watch:app":"vite build --watch --config vite.app.config.ts","preview:app":"vite preview --config vite.app.config.ts --host 127.0.0.1","serve:app":"pnpm build:app && pnpm preview:app","analyze:app":"ANALYZE=true vite build --config vite.app.config.ts","build:client-exports":"tsup --config tsup.client.ts","build:server":"tsup --config tsup.server.ts","verify:package":"node scripts/verify-package.mjs",prepublishOnly:"pnpm --filter @mcp-use/client build && pnpm build",start:"node dist/cli.js --port 3000",preview:"vite preview","type-check":"tsc --noEmit",lint:"eslint .","lint:fix":"eslint . --fix","test:e2e":"playwright test","test:e2e:ui":"playwright test --ui","test:e2e:debug":"playwright test --debug","test:e2e:builtin":"node tests/e2e/scripts/run-test-matrix.mjs builtin","test:e2e:prod":"node tests/e2e/scripts/run-test-matrix.mjs prod","test:e2e:mix":"node tests/e2e/scripts/run-test-matrix.mjs mix","test:e2e:prod:ui":"TEST_MODE=production playwright test --ui","test:e2e:codegen":"playwright codegen http://localhost:3000/inspector","test:e2e:report":"playwright show-report","test:e2e:python":"node tests/e2e/scripts/run-python-e2e.mjs","test:unit":"vitest run","test:unit:watch":"vitest","test:e2e:tunnel":"node tests/e2e/scripts/run-tunnel-test.mjs","install:pnpm":"pnpm install","install:npm":"npm install","lint:npm":"npm run lint:fix","lint:pnpm":"pnpm lint:fix"},engines:{node:">=22.22.2"},peerDependencies:{"@base-ui/react":"^1.6.0","@mcp-use/agent":"^2.0.0-alpha.0","@mcp-use/client":"^2.0.0-alpha.0","class-variance-authority":"^0.7.1",clsx:"^2.1.1",express:"^4.21.2 || ^5.0.0","lucide-react":"^0.562.0","markdown-to-jsx":"^9.7.4","mcp-use":"workspace:*",motion:"^12.34.2",react:"^18.0.0 || ^19.0.0","react-dom":"^18.0.0 || ^19.0.0","react-resizable-panels":"^4.6.4",sonner:"^2.0.7","tailwind-merge":"^3.5.0"},peerDependenciesMeta:{"@base-ui/react":{optional:!0},"@mcp-use/agent":{optional:!0},"@mcp-use/client":{optional:!0},"class-variance-authority":{optional:!0},clsx:{optional:!0},express:{optional:!0},"lucide-react":{optional:!0},"markdown-to-jsx":{optional:!0},motion:{optional:!0},react:{optional:!0},"react-dom":{optional:!0},"react-resizable-panels":{optional:!0},sonner:{optional:!0},"tailwind-merge":{optional:!0}},dependencies:{},publishConfig:{access:"public"},devDependencies:{"@base-ui/react":"^1.6.0","@hono/node-server":"^1.19.13","@mcp-use/agent":"workspace:*","@mcp-use/client":"workspace:*","@playwright/test":"^1.58.2","@tailwindcss/vite":"^4.2.0","@types/express":"^5.0.6","@vitejs/plugin-react":"^6.0.0","class-variance-authority":"^0.7.1",clsx:"^2.1.1",emulate:"0.5.0",eslint:"^9.39.2",express:"^5.2.1",hono:"^4.12.12","lucide-react":"^0.562.0","markdown-to-jsx":"^9.7.4",motion:"^12.34.2","oauth2-mock-server":"^8.2.2",open:"^11.0.0",react:"^19.2.3","react-dom":"^19.2.3","react-router":"^7.12.0","react-resizable-panels":"^4.6.4","rate-limiter-flexible":"^11.2.0","rollup-plugin-visualizer":"^6.0.3",sonner:"^2.0.7","tailwind-merge":"^3.5.0",tailwindcss:"^4.2.0",tsup:"^8.5.1",tsx:"^4.21.0","tw-animate-css":"^1.4.0",typescript:"^5.9.3",vite:"^8.0.16",vitest:"^4.1.0","wait-on":"^9.0.4",zod:"^4.2.0"}};var Go=Hr.version;function _e(){return Go}var Dr=_e(),Xo=`<!doctype html>
5
5
  <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>
6
6
  <body><div>Signed in. You can close this window.</div>
7
7
  <script>try{if(window.opener&&!window.opener.closed)window.opener.postMessage({type:"manufact:oauth-complete"},"*")}catch(e){}try{window.close()}catch(e){}</script>
8
- </body></html>`;function bo(e,t,r){let n=[];e?.basePath!==void 0&&n.push(`<script>window.__MCP_BASE_PATH__ = ${JSON.stringify(e.basePath)};</script>`),e?.devMode&&n.push("<script>window.__MCP_DEV_MODE__ = true;</script>"),e?.sandboxOrigin&&n.push(`<script>window.__MCP_SANDBOX_ORIGIN__ = ${JSON.stringify(e.sandboxOrigin)};</script>`),e?.proxyUrl!==void 0&&n.push(`<script>window.__MCP_PROXY_URL__ = ${JSON.stringify(e.proxyUrl)};</script>`),e?.inspectorMode&&n.push(`<script>window.__MCP_INSPECTOR_MODE__ = ${JSON.stringify(e.inspectorMode)};</script>`),e?.manufactChatUrl&&n.push(`<script>window.__MANUFACT_CHAT_URL__ = ${JSON.stringify(e.manufactChatUrl)};</script>`),e?.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(`
8
+ </body></html>`;function Yo(e,t,r){let n=[];e?.basePath!==void 0&&n.push(`<script>window.__MCP_BASE_PATH__ = ${JSON.stringify(e.basePath)};</script>`),e?.devMode&&n.push("<script>window.__MCP_DEV_MODE__ = true;</script>"),e?.sandboxOrigin&&n.push(`<script>window.__MCP_SANDBOX_ORIGIN__ = ${JSON.stringify(e.sandboxOrigin)};</script>`),e?.proxyUrl!==void 0&&n.push(`<script>window.__MCP_PROXY_URL__ = ${JSON.stringify(e.proxyUrl)};</script>`),e?.inspectorMode&&n.push(`<script>window.__MCP_INSPECTOR_MODE__ = ${JSON.stringify(e.inspectorMode)};</script>`),e?.manufactChatUrl&&n.push(`<script>window.__MANUFACT_CHAT_URL__ = ${JSON.stringify(e.manufactChatUrl)};</script>`),e?.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(`
9
9
  `);return`<!doctype html>
10
10
  <html lang="en">
11
11
  <head>
12
12
  <meta charset="UTF-8" />
13
- ${fr(`${t}/inspector/assets`)}
13
+ ${xr(`${t}/inspector/assets`)}
14
14
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
15
15
  <link rel="preconnect" href="https://fonts.googleapis.com" />
16
16
  <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
@@ -57,7 +57,7 @@ tell application "System Events" to get value of property list item "CFBundleNam
57
57
  .mcp-boot-spinner, .mcp-boot-label { color: #a1a1aa; }
58
58
  }
59
59
  </style>
60
- <script>window.__INSPECTOR_VERSION__ = ${JSON.stringify(wr)};</script>
60
+ <script>window.__INSPECTOR_VERSION__ = ${JSON.stringify(Dr)};</script>
61
61
  ${o}
62
62
  </head>
63
63
  <body>
@@ -97,9 +97,9 @@ tell application "System Events" to get value of property list item "CFBundleNam
97
97
  </div>
98
98
  <script type="module" src="${r.jsUrl}"></script>
99
99
  </body>
100
- </html>`}function yr(e,t,r=""){let n=`${r}/inspector/assets`,o=encodeURIComponent(wr),s={jsUrl:`${n}/inspector.js?v=${o}`,cssUrl:`${n}/inspector.css?v=${o}`},i=u=>`${r}${u}`,a={...t,basePath:t?.basePath??r,proxyUrl:t?.proxyUrl!==void 0?t.proxyUrl:i("/inspector/api/proxy"),disableTelemetry:t?.disableTelemetry??process.env.MCP_USE_ANONYMIZED_TELEMETRY==="false"},c=u=>u.html(bo(a,r,s));mr(e,n),e.get(i("/inspector/oauth-popup-closed.html"),u=>u.html(yo)),e.get(i("/inspector"),c),e.get(`${i("/inspector")}/`,c);let l=i("/inspector/api/");e.get(i("/inspector/*"),u=>u.req.path.startsWith(l)?u.notFound():c(u)),e.post(i("/inspector/*"),u=>u.req.path.startsWith(l)?u.notFound():c(u)),r===""&&t?.rootRedirect!==!1&&e.get("/",u=>{let d=new URL(u.req.url);return u.redirect(`${i("/inspector")}${d.search}`)})}function vo(){let{process:e,Deno:t}=globalThis;return!(typeof t?.noColor=="boolean"?t.noColor:e!==void 0?"NO_COLOR"in e?.env:!1)}async function br(){let{navigator:e}=globalThis,t="cloudflare:workers";return!(e!==void 0&&e.userAgent==="Cloudflare-Workers"?await(async()=>{try{return"NO_COLOR"in((await import(t)).env??{})}catch{return!1}})():!vo())}var xo=e=>{let[t,r]=[",","."];return e.map(o=>o.replace(/(\d)(?=(\d\d\d)+(?!\d))/g,"$1"+t)).join(r)},Ro=e=>{let t=Date.now()-e;return xo([t<1e3?t+"ms":Math.round(t/1e3)+"s"])},Eo=async e=>{if(await br())switch(e/100|0){case 5:return`\x1B[31m${e}\x1B[0m`;case 4:return`\x1B[33m${e}\x1B[0m`;case 3:return`\x1B[36m${e}\x1B[0m`;case 2:return`\x1B[32m${e}\x1B[0m`}return`${e}`};async function vr(e,t,r,n,o=0,s){let i=t==="<--"?`${t} ${r} ${n}`:`${t} ${r} ${n} ${await Eo(o)} ${s}`;e(i)}var xr=(e=console.log)=>async function(r,n){let{method:o,url:s}=r.req,i=s.slice(s.indexOf("/",8));await vr(e,"<--",o,i);let a=Date.now();await n(),await vr(e,"-->",o,i,r.res.status,Ro(a))};import{lookup as So}from"dns/promises";import{Buffer as Po}from"buffer";import{isIP as Ao}from"net";var Co=new Set(["accept","authorization","content-type","dpop"]),Oo=new Set(["cache-control","content-type","dpop-nonce","expires","pragma","retry-after","www-authenticate"]),_o=[["registration_endpoint","registration"],["token_endpoint","token"],["revocation_endpoint","revocation"],["introspection_endpoint","introspection"]],Or=600*1e3,To=100,Lo=1440*60*1e3,ko=500;function pt(e,t={}){let{basePath:r="/oauth",allowedOrigins:n=[],allowLoopback:o=!1,timeoutMs:s=1e4,maxRequestBodyBytes:i=64*1024,maxResponseBodyBytes:a=1024*1024,callbackPath:c="/oauth/callback",enableLogging:l=!0,authenticate:u,validateServerUrl:d}=t,h=new Set(n.map(dt)),f=new Map,g=new Map;e.use(`${r}/*`,async(p,w)=>{let m=p.req.header("Origin");if(m&&!Do(m,p,h))return p.json({error:"Origin not allowed"},403);if(p.req.method==="OPTIONS")return Fo(m);await w(),m&&Ir(p.res.headers,m)}),e.get(`${r}/metadata`,async p=>{if(!await Cr(p,u))return p.json({error:"Unauthorized"},401);let w=await F(p.req.query("serverUrl"),o);if("error"in w)return p.json({error:w.error},400);let m=w.url;if(d&&!await d(m.toString(),p))return p.json({error:"MCP server URL not allowed"},403);let x=await F(p.req.query("url"),o);if("error"in x)return p.json({error:x.error},400);let C=x.url,L=k(m),R=Pr(f,L),b=Rr(m,C,R);if(!b&&R.authorizationServers.size===0)try{await Er(m,R,o,s,a),f.set(L,R),b=Rr(m,C,R)}catch{}if(!b)return p.json({error:"Metadata target is not bound to this MCP server"},403);try{ct(l,`GET ${C}`);let P=await Pe(C,{method:"GET",headers:{Accept:"application/json"},redirect:"manual",signal:AbortSignal.timeout(s)});if(Ce(P.status))return p.json({error:"OAuth metadata redirects are not allowed"},502);let v=await Ae(P,a);if(!P.ok)return p.body(v,P.status,{"Content-Type":P.headers.get("content-type")??"application/json"});let A=ut(v);return b.type==="protected-resource"?await Lr(A,m,R,o):await kr(A,b.issuer,R,o),R.updatedAt=Date.now(),f.set(L,R),Ar(f),p.body(v,200,{"Content-Type":P.headers.get("content-type")??"application/json"})}catch(P){return lt(p,P,l)}}),e.post(`${r}/proxy`,async p=>{if(!await Cr(p,u))return p.json({error:"Unauthorized"},401);let w;try{w=JSON.parse(await $o(p.req.raw,i))}catch(v){return p.json({error:v instanceof j?"Request body too large":"Invalid JSON request body"},v instanceof j?413:400)}let m=await F(w.serverUrl,o);if("error"in m)return p.json({error:m.error},400);let x=m.url;if(d&&!await d(x.toString(),p))return p.json({error:"MCP server URL not allowed"},403);let C=await F(w.url,o);if("error"in C)return p.json({error:C.error},400);let L=C.url;if(w.method!==void 0&&w.method!=="POST")return p.json({error:"Only OAuth endpoint POST is allowed"},405);let R=k(x),b=Pr(f,R);if(b.endpoints.size===0)try{await Er(x,b,o,s,a),f.set(R,b),Ar(f)}catch(v){return lt(p,v,l)}let P=b.endpoints.get(k(L));if(!P)return p.json({error:"OAuth endpoint is not bound to this MCP server"},403);try{let v=Uo(w.headers),A=Io(w.body,v);if(P==="registration"){let Fr=dt(p.req.header("Origin")??new URL(p.req.url).origin);A=Bo(A,v,new URL(c,Fr).toString())}else A=jo({body:A,headers:v,bindingKey:R,clients:g});if(new TextEncoder().encode(A??"").byteLength>i)return p.json({error:"OAuth request body too large"},413);ct(l,`POST ${P} ${L}`);let E=await Pe(L,{method:"POST",headers:v,body:A,redirect:"manual",signal:AbortSignal.timeout(s)});if(Ce(E.status))return p.json({error:"OAuth endpoint redirects are not allowed"},502);let U=await Ae(E,a),Q=Mo(E.headers),q=E.headers.get("content-type")??"",_=U;if(q.includes("json"))try{_=JSON.parse(U)}catch{}return P==="registration"&&E.ok&&_&&typeof _=="object"&&!Array.isArray(_)&&(_=Ho({responseBody:_,binding:b,bindingKey:R,clients:g})),p.json({status:E.status,statusText:E.statusText,headers:Q,body:_})}catch(v){return lt(p,v,l)}}),ct(l,`Mounted at ${r}/metadata and ${r}/proxy`)}async function F(e,t){if(typeof e!="string"||!e)return{error:"Missing or invalid URL"};let r;try{r=new URL(e)}catch{return{error:"Invalid URL"}}if(r.username||r.password||r.hash)return{error:"URL credentials and fragments are not allowed"};let n=qo(r.hostname);if(r.protocol!=="https:"&&!(t&&n&&r.protocol==="http:"))return{error:"HTTPS is required"};if(n)return t?{url:r}:{error:"Loopback URL not allowed"};if(zo(r.hostname))return{error:"Local network URL not allowed"};try{let o=Ao(r.hostname)?[r.hostname]:(await So(r.hostname,{all:!0,verbatim:!0})).map(({address:s})=>s);if(o.length===0||o.some(s=>!Hr(s)))return{error:"Private or non-routable URL not allowed"}}catch{return{error:"URL hostname could not be resolved"}}return{url:r}}async function ft(e,t=!1){return!("error"in await F(e,t))}function Rr(e,t,r){let n=k(t);if(_r(e).some(o=>k(o)===n))return{type:"protected-resource"};for(let o of r.authorizationServers)if(Tr(new URL(o)).some(s=>k(s)===n))return{type:"authorization-server",issuer:o}}function _r(e){let t=e.pathname==="/"?"":e.pathname;return[new URL(`/.well-known/oauth-protected-resource${t}`,e.origin),new URL("/.well-known/oauth-protected-resource",e.origin)]}function Tr(e){let t=e.pathname==="/"?"":e.pathname;return[new URL(`/.well-known/oauth-authorization-server${t}`,e.origin),new URL(`/.well-known/openid-configuration${t}`,e.origin),new URL(`${t||""}/.well-known/openid-configuration`,e.origin)]}async function Lr(e,t,r,n){if(typeof e.resource!="string"||k(new URL(e.resource))!==k(t))throw new O("Protected-resource metadata does not match serverUrl");if(!Array.isArray(e.authorization_servers)||e.authorization_servers.length===0)throw new O("Protected-resource metadata has no authorization servers");let o=new Set;for(let s of e.authorization_servers){let i=await F(s,n);if("error"in i)throw new O(`Unsafe authorization server: ${i.error}`);o.add(k(i.url))}r.authorizationServers=o,r.endpoints.clear(),r.tokenEndpointAuthMethods.clear()}async function kr(e,t,r,n){if(typeof e.issuer!="string"||k(new URL(e.issuer))!==t)throw new O("Authorization-server metadata issuer mismatch");r.endpoints.clear(),r.tokenEndpointAuthMethods=new Set(Array.isArray(e.token_endpoint_auth_methods_supported)?e.token_endpoint_auth_methods_supported.filter(o=>typeof o=="string"):[]);for(let[o,s]of _o){let i=e[o];if(i===void 0)continue;let a=await F(i,n);if("error"in a)throw new O(`Unsafe ${o}: ${a.error}`);r.endpoints.set(k(a.url),s)}}async function Er(e,t,r,n,o){for(let s of _r(e)){let i=await Pe(s,{method:"GET",headers:{Accept:"application/json"},redirect:"manual",signal:AbortSignal.timeout(n)});if(Ce(i.status))throw new O("OAuth metadata redirects are not allowed");if(i.ok){await Lr(ut(await Ae(i,o)),e,t,r);break}}if(t.authorizationServers.size===0)throw new O("Protected-resource metadata could not be discovered");for(let s of t.authorizationServers){let i=!1;for(let a of Tr(new URL(s))){let c=await Pe(a,{method:"GET",headers:{Accept:"application/json"},redirect:"manual",signal:AbortSignal.timeout(n)});if(Ce(c.status))throw new O("OAuth metadata redirects are not allowed");if(c.ok){await kr(ut(await Ae(c,o)),s,t,r),i=!0;break}}if(i)break}if(t.endpoints.size===0)throw new O("Authorization-server metadata could not be discovered");t.updatedAt=Date.now()}async function Pe(e,t){return fetch(e,t)}function Uo(e){let t=new Headers;if(!e||typeof e!="object"||Array.isArray(e))return t;for(let[r,n]of Object.entries(e)){let o=r.toLowerCase();Co.has(o)&&typeof n=="string"&&t.set(o,n)}return t}function Mo(e){let t={};return e.forEach((r,n)=>{Oo.has(n.toLowerCase())&&(t[n]=r)}),t}function Io(e,t){if(e==null)return;if(typeof e=="string"){if(!t.has("content-type"))try{JSON.parse(e),t.set("content-type","application/json")}catch{t.set("content-type","application/x-www-form-urlencoded")}return e}if((t.get("content-type")??"").includes("application/x-www-form-urlencoded")&&typeof e=="object"&&!Array.isArray(e)){let n=new URLSearchParams;for(let[o,s]of Object.entries(e))n.append(o,String(s));return n.toString()}return t.has("content-type")||t.set("content-type","application/json"),JSON.stringify(e)}function Ur(e,t){return`${e}\0${t}`}function Ho(e){let{responseBody:t,binding:r,bindingKey:n,clients:o}=e,s=t.client_id,i=t.client_secret;if(typeof s!="string"||typeof i!="string")return t;let a=t.token_endpoint_auth_method,c=a==="client_secret_post"||a==="client_secret_basic"?a:r.tokenEndpointAuthMethods.has("client_secret_basic")?"client_secret_basic":"client_secret_post",l=t.client_secret_expires_at,u=l===0?Number.POSITIVE_INFINITY:typeof l=="number"&&l>0?l*1e3:Date.now()+Lo;for(No(o),o.set(Ur(n,s),{clientSecret:i,authMethod:c,expiresAt:u});o.size>ko;){let h=o.keys().next().value;if(!h)break;o.delete(h)}let d={...t};return delete d.client_secret,delete d.client_secret_expires_at,d.token_endpoint_auth_method="none",d}function jo(e){let{body:t,headers:r,bindingKey:n,clients:o}=e;if(!t||!(r.get("content-type")??"").includes("application/x-www-form-urlencoded"))return t;let s=new URLSearchParams(t),i=s.get("client_id");if(!i)return t;let a=Ur(n,i),c=o.get(a);if(!c)return t;if(c.expiresAt<=Date.now())return o.delete(a),t;if(s.delete("client_secret"),c.authMethod==="client_secret_basic"){let l=Po.from(`${Sr(i)}:${Sr(c.clientSecret)}`,"utf8").toString("base64");r.set("authorization",`Basic ${l}`)}else r.delete("authorization"),s.set("client_id",i),s.set("client_secret",c.clientSecret);return s.toString()}function Sr(e){return new URLSearchParams({value:e}).toString().slice(6)}function No(e){let t=Date.now();for(let[r,n]of e)n.expiresAt<=t&&e.delete(r)}async function $o(e,t){let r=Number(e.headers.get("content-length"));if(Number.isFinite(r)&&r>t)throw new j;return Mr(e.body,t)}async function Ae(e,t){let r=Number(e.headers.get("content-length"));if(Number.isFinite(r)&&r>t)throw await e.body?.cancel(),new j;return Mr(e.body,t)}async function Mr(e,t){if(!e)return"";let r=e.getReader(),n=[],o=0;for(;;){let{done:a,value:c}=await r.read();if(a)break;if(o+=c.byteLength,o>t)throw await r.cancel(),new j;n.push(c)}let s=new Uint8Array(o),i=0;for(let a of n)s.set(a,i),i+=a.byteLength;return new TextDecoder().decode(s)}function ut(e){let t;try{t=JSON.parse(e)}catch{throw new O("OAuth metadata is not valid JSON")}if(!t||typeof t!="object"||Array.isArray(t))throw new O("OAuth metadata is not an object");return t}function Pr(e,t){let r=e.get(t);return r&&Date.now()-r.updatedAt<=Or?r:(e.delete(t),{authorizationServers:new Set,endpoints:new Map,tokenEndpointAuthMethods:new Set,updatedAt:Date.now()})}function Ar(e){let t=Date.now();for(let[r,n]of e)t-n.updatedAt>Or&&e.delete(r);for(;e.size>To;){let r=e.keys().next().value;if(!r)break;e.delete(r)}}function k(e){let t=new URL(e);return t.hash="",(t.protocol==="https:"&&t.port==="443"||t.protocol==="http:"&&t.port==="80")&&(t.port=""),t.toString().replace(/\/$/,"")}function Bo(e,t,r){if(!e||!(t.get("content-type")??"").includes("json"))return e;try{let o=JSON.parse(e);return!o||typeof o!="object"||Array.isArray(o)?e:JSON.stringify({...o,redirect_uris:[r]})}catch{return e}}function dt(e){let t=new URL(e);if(t.pathname!=="/"||t.search||t.hash)throw new Error(`OAuth proxy allowed origin must be an origin: ${e}`);return t.origin}function Do(e,t,r){try{let n=dt(e);if(n===new URL(t.req.url).origin||r.has(n))return!0;let o=new URL(n),i=t.req.header("x-forwarded-host")?.split(",")[0]?.trim()||t.req.header("host");if(!i||o.host!==i)return!1;let a=t.req.header("x-forwarded-proto")?.split(",")[0]?.trim();return!a||`${a}:`===o.protocol}catch{return!1}}function Fo(e){let t=new Headers;return e&&Ir(t,e),t.set("Access-Control-Allow-Methods","GET, POST, OPTIONS"),t.set("Access-Control-Allow-Headers","Accept, Authorization, Content-Type"),t.set("Access-Control-Max-Age","600"),new Response(null,{status:204,headers:t})}function Ir(e,t){e.set("Access-Control-Allow-Origin",t),e.append("Vary","Origin")}async function Cr(e,t){return t?t(e):!0}function Ce(e){return e>=300&&e<400}function qo(e){let t=e.toLowerCase().replace(/^\[|\]$/g,"");return t==="localhost"||t.endsWith(".localhost")||t==="::1"||t.startsWith("127.")}function zo(e){let t=e.toLowerCase();return t.endsWith(".local")||t.endsWith(".internal")||t.endsWith(".home.arpa")}function Hr(e){if(e.includes(":")){let s=e.toLowerCase();return s.startsWith("::ffff:")?Hr(s.slice(7)):!(s==="::"||s==="::1"||s.startsWith("fc")||s.startsWith("fd")||/^fe[89ab]/.test(s)||s.startsWith("ff")||s.startsWith("2001:db8:"))}let t=e.split(".").map(Number);if(t.length!==4||t.some(s=>!Number.isInteger(s)))return!1;let[r,n,o]=t;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 ct(e,t){e&&console.log(`[OAuth BFF] ${t}`)}function lt(e,t,r){let n=t instanceof Error?t.message:"Unknown error";return r&&console.error("[OAuth BFF]",n),t instanceof j?e.json({error:"Upstream response too large"},502):t instanceof O?e.json({error:t.message},502):t instanceof DOMException&&t.name==="TimeoutError"?e.json({error:"OAuth upstream timed out"},504):e.json({error:"OAuth upstream request failed"},502)}var j=class extends Error{},O=class extends Error{};var Wo=3;function Vo(e,t){return e.includes("text/event-stream")&&!t}function ht(e,t={}){let r=t.path||"/mcp/proxy",n=t.enableLogging!==!1;e.use(`${r}/*`,be({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&&e.use(`${r}/*`,xr()),e.all(`${r}/*`,async o=>{try{if(t.authenticate&&!await t.authenticate(o))return o.json({error:"Unauthorized"},401);let s=o.req.header("X-Target-URL");if(!s)return o.json({error:"X-Target-URL header is required",usage:"Set X-Target-URL header to the MCP server URL you want to proxy to"},400);if(!await ft(s,t.allowLoopback??!1))return o.json({error:"Invalid target URL",details:"Target is not allowed by the proxy network policy"},403);if(t.validateRequest&&!await t.validateRequest(s,o))return o.json({error:"Invalid target URL",details:"The requested target URL is not allowed"},403);try{new URL(s)}catch{return o.json({error:"Invalid target URL format",details:"The X-Target-URL must be a valid HTTP/HTTPS URL"},400)}let i=o.req.method,a={},c=o.req.header();for(let[f,g]of Object.entries(c)){let p=f.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-")&&(a[f]=g)}a["Accept-Encoding"]="identity";let l=i!=="GET"&&i!=="HEAD"?new Uint8Array(await o.req.arrayBuffer()).slice():void 0,u=s,d=i,h=l;for(let f=0;;f+=1){let g=await fetch(u,{method:d,headers:a,body:h,redirect:"manual"}),p=g.headers.get("location");if(!(g.status>=300&&g.status<400&&p))return Go(g);if(f>=Wo)return o.json({error:"Too many upstream redirects"},502);let w=new URL(p,u);if(!await ft(w.toString(),t.allowLoopback??!1)||t.validateRequest&&!await t.validateRequest(w.toString(),o))return o.json({error:"Redirect target is not allowed"},403);w.origin!==new URL(u).origin&&(Oe(a,"authorization"),Oe(a,"proxy-authorization")),(g.status===303||(g.status===301||g.status===302)&&d==="POST")&&(d="GET",h=void 0,Oe(a,"content-type"),Oe(a,"content-length")),u=w.toString()}}catch(s){let i=s instanceof Error?s.message:"Unknown error",a=o.req.header("X-Target-URL");return s instanceof Error&&(s.message.includes("ECONNREFUSED")||s.message.includes("fetch failed"))?console.warn(`[MCP Proxy] Connection refused to ${a||"unknown target"} - server may not be running`):console.error("[MCP Proxy] Request failed:",i,`
100
+ </html>`}function jr(e,t,r=""){let n=`${r}/inspector/assets`,o=encodeURIComponent(Dr),s={jsUrl:`${n}/inspector.js?v=${o}`,cssUrl:`${n}/inspector.css?v=${o}`},i=u=>`${r}${u}`,a={...t,basePath:t?.basePath??r,proxyUrl:t?.proxyUrl!==void 0?t.proxyUrl:i("/inspector/api/proxy"),disableTelemetry:t?.disableTelemetry??process.env.MCP_USE_ANONYMIZED_TELEMETRY==="false"},c=u=>u.html(Yo(a,r,s));Nr(e,n),e.get(i("/inspector/oauth-popup-closed.html"),u=>u.html(Xo)),e.get(i("/inspector"),c),e.get(`${i("/inspector")}/`,c);let l=i("/inspector/api/");e.get(i("/inspector/*"),u=>u.req.path.startsWith(l)?u.notFound():c(u)),e.post(i("/inspector/*"),u=>u.req.path.startsWith(l)?u.notFound():c(u)),r===""&&t?.rootRedirect!==!1&&e.get("/",u=>{let d=new URL(u.req.url);return u.redirect(`${i("/inspector")}${d.search}`)})}function Jo(){let{process:e,Deno:t}=globalThis;return!(typeof t?.noColor=="boolean"?t.noColor:e!==void 0?"NO_COLOR"in e?.env:!1)}async function Br(){let{navigator:e}=globalThis,t="cloudflare:workers";return!(e!==void 0&&e.userAgent==="Cloudflare-Workers"?await(async()=>{try{return"NO_COLOR"in((await import(t)).env??{})}catch{return!1}})():!Jo())}var Qo=e=>{let[t,r]=[",","."];return e.map(o=>o.replace(/(\d)(?=(\d\d\d)+(?!\d))/g,"$1"+t)).join(r)},Zo=e=>{let t=Date.now()-e;return Qo([t<1e3?t+"ms":Math.round(t/1e3)+"s"])},es=async e=>{if(await Br())switch(e/100|0){case 5:return`\x1B[31m${e}\x1B[0m`;case 4:return`\x1B[33m${e}\x1B[0m`;case 3:return`\x1B[36m${e}\x1B[0m`;case 2:return`\x1B[32m${e}\x1B[0m`}return`${e}`};async function $r(e,t,r,n,o=0,s){let i=t==="<--"?`${t} ${r} ${n}`:`${t} ${r} ${n} ${await es(o)} ${s}`;e(i)}var Fr=(e=console.log)=>async function(r,n){let{method:o,url:s}=r.req,i=s.slice(s.indexOf("/",8));await $r(e,"<--",o,i);let a=Date.now();await n(),await $r(e,"-->",o,i,r.res.status,Zo(a))};import{lookup as ts}from"dns/promises";import{Buffer as rs}from"buffer";import{isIP as ns}from"net";var os=new Set(["accept","authorization","content-type","dpop"]),ss=new Set(["cache-control","content-type","dpop-nonce","expires","pragma","retry-after","www-authenticate"]),is=[["registration_endpoint","registration"],["token_endpoint","token"],["revocation_endpoint","revocation"],["introspection_endpoint","introspection"]],Xr=600*1e3,as=100,cs=1440*60*1e3,ls=500;function yt(e,t={}){let{basePath:r="/oauth",allowedOrigins:n=[],allowLoopback:o=!1,timeoutMs:s=1e4,maxRequestBodyBytes:i=64*1024,maxResponseBodyBytes:a=1024*1024,callbackPath:c="/oauth/callback",enableLogging:l=!0,authenticate:u,validateServerUrl:d}=t,h=new Set(n.map(wt)),p=new Map,g=new Map;e.use(`${r}/*`,async(f,w)=>{let m=f.req.header("Origin");if(m&&!ys(m,f,h))return f.json({error:"Origin not allowed"},403);if(f.req.method==="OPTIONS")return bs(m);await w(),m&&rn(f.res.headers,m)}),e.get(`${r}/metadata`,async f=>{if(!await Gr(f,u))return f.json({error:"Unauthorized"},401);let w=await F(f.req.query("serverUrl"),o);if("error"in w)return f.json({error:w.error},400);let m=w.url;if(d&&!await d(m.toString(),f))return f.json({error:"MCP server URL not allowed"},403);let v=await F(f.req.query("url"),o);if("error"in v)return f.json({error:v.error},400);let A=v.url,M=I(m),E=Kr(p,M),b=qr(m,A,E);if(!b&&E.authorizationServers.size===0)try{await zr(m,E,o,s,a),p.set(M,E),b=qr(m,A,E)}catch{}if(!b)return f.json({error:"Metadata target is not bound to this MCP server"},403);try{ht(l,`GET ${A}`);let S=await Ce(A,{method:"GET",headers:{Accept:"application/json"},redirect:"manual",signal:AbortSignal.timeout(s)});if(Te(S.status))return f.json({error:"OAuth metadata redirects are not allowed"},502);let x=await Oe(S,a);if(!S.ok)return f.body(x,S.status,{"Content-Type":S.headers.get("content-type")??"application/json"});let P=gt(x);return b.type==="protected-resource"?await Qr(P,m,E,o):await Zr(P,b.issuer,E,o),E.updatedAt=Date.now(),p.set(M,E),Vr(p),f.body(x,200,{"Content-Type":S.headers.get("content-type")??"application/json"})}catch(S){return mt(f,S,l)}}),e.post(`${r}/proxy`,async f=>{if(!await Gr(f,u))return f.json({error:"Unauthorized"},401);let w;try{w=JSON.parse(await gs(f.req.raw,i))}catch(x){return f.json({error:x instanceof H?"Request body too large":"Invalid JSON request body"},x instanceof H?413:400)}let m=await F(w.serverUrl,o);if("error"in m)return f.json({error:m.error},400);let v=m.url;if(d&&!await d(v.toString(),f))return f.json({error:"MCP server URL not allowed"},403);let A=await F(w.url,o);if("error"in A)return f.json({error:A.error},400);let M=A.url;if(w.method!==void 0&&w.method!=="POST")return f.json({error:"Only OAuth endpoint POST is allowed"},405);let E=I(v),b=Kr(p,E);if(b.endpoints.size===0)try{await zr(v,b,o,s,a),p.set(E,b),Vr(p)}catch(x){return mt(f,x,l)}let S=b.endpoints.get(I(M));if(!S)return f.json({error:"OAuth endpoint is not bound to this MCP server"},403);try{let x=us(w.headers),P=fs(w.body,x);if(S==="registration"){let un=wt(f.req.header("Origin")??new URL(f.req.url).origin);P=ws(P,x,new URL(c,un).toString())}else P=hs({body:P,headers:x,bindingKey:E,clients:g});if(new TextEncoder().encode(P??"").byteLength>i)return f.json({error:"OAuth request body too large"},413);ht(l,`POST ${S} ${M}`);let R=await Ce(M,{method:"POST",headers:x,body:P,redirect:"manual",signal:AbortSignal.timeout(s)});if(Te(R.status))return f.json({error:"OAuth endpoint redirects are not allowed"},502);let k=await Oe(R,a),J=ds(R.headers),q=R.headers.get("content-type")??"",O=k;if(q.includes("json"))try{O=JSON.parse(k)}catch{}return S==="registration"&&R.ok&&O&&typeof O=="object"&&!Array.isArray(O)&&(O=ps({responseBody:O,binding:b,bindingKey:E,clients:g})),f.json({status:R.status,statusText:R.statusText,headers:J,body:O})}catch(x){return mt(f,x,l)}}),ht(l,`Mounted at ${r}/metadata and ${r}/proxy`)}async function F(e,t){if(typeof e!="string"||!e)return{error:"Missing or invalid URL"};let r;try{r=new URL(e)}catch{return{error:"Invalid URL"}}if(r.username||r.password||r.hash)return{error:"URL credentials and fragments are not allowed"};let n=xs(r.hostname);if(r.protocol!=="https:"&&!(t&&n&&r.protocol==="http:"))return{error:"HTTPS is required"};if(n)return t?{url:r}:{error:"Loopback URL not allowed"};if(vs(r.hostname))return{error:"Local network URL not allowed"};try{let o=ns(r.hostname)?[r.hostname]:(await ts(r.hostname,{all:!0,verbatim:!0})).map(({address:s})=>s);if(o.length===0||o.some(s=>!nn(s)))return{error:"Private or non-routable URL not allowed"}}catch{return{error:"URL hostname could not be resolved"}}return{url:r}}async function bt(e,t=!1){return!("error"in await F(e,t))}function qr(e,t,r){let n=I(t);if(Yr(e).some(o=>I(o)===n))return{type:"protected-resource"};for(let o of r.authorizationServers)if(Jr(new URL(o)).some(s=>I(s)===n))return{type:"authorization-server",issuer:o}}function Yr(e){let t=e.pathname==="/"?"":e.pathname;return[new URL(`/.well-known/oauth-protected-resource${t}`,e.origin),new URL("/.well-known/oauth-protected-resource",e.origin)]}function Jr(e){let t=e.pathname==="/"?"":e.pathname;return[new URL(`/.well-known/oauth-authorization-server${t}`,e.origin),new URL(`/.well-known/openid-configuration${t}`,e.origin),new URL(`${t||""}/.well-known/openid-configuration`,e.origin)]}async function Qr(e,t,r,n){if(typeof e.resource!="string"||I(new URL(e.resource))!==I(t))throw new _("Protected-resource metadata does not match serverUrl");if(!Array.isArray(e.authorization_servers)||e.authorization_servers.length===0)throw new _("Protected-resource metadata has no authorization servers");let o=new Set;for(let s of e.authorization_servers){let i=await F(s,n);if("error"in i)throw new _(`Unsafe authorization server: ${i.error}`);o.add(I(i.url))}r.authorizationServers=o,r.endpoints.clear(),r.tokenEndpointAuthMethods.clear()}async function Zr(e,t,r,n){if(typeof e.issuer!="string"||I(new URL(e.issuer))!==t)throw new _("Authorization-server metadata issuer mismatch");r.endpoints.clear(),r.tokenEndpointAuthMethods=new Set(Array.isArray(e.token_endpoint_auth_methods_supported)?e.token_endpoint_auth_methods_supported.filter(o=>typeof o=="string"):[]);for(let[o,s]of is){let i=e[o];if(i===void 0)continue;let a=await F(i,n);if("error"in a)throw new _(`Unsafe ${o}: ${a.error}`);r.endpoints.set(I(a.url),s)}}async function zr(e,t,r,n,o){for(let s of Yr(e)){let i=await Ce(s,{method:"GET",headers:{Accept:"application/json"},redirect:"manual",signal:AbortSignal.timeout(n)});if(Te(i.status))throw new _("OAuth metadata redirects are not allowed");if(i.ok){await Qr(gt(await Oe(i,o)),e,t,r);break}}if(t.authorizationServers.size===0)throw new _("Protected-resource metadata could not be discovered");for(let s of t.authorizationServers){let i=!1;for(let a of Jr(new URL(s))){let c=await Ce(a,{method:"GET",headers:{Accept:"application/json"},redirect:"manual",signal:AbortSignal.timeout(n)});if(Te(c.status))throw new _("OAuth metadata redirects are not allowed");if(c.ok){await Zr(gt(await Oe(c,o)),s,t,r),i=!0;break}}if(i)break}if(t.endpoints.size===0)throw new _("Authorization-server metadata could not be discovered");t.updatedAt=Date.now()}async function Ce(e,t){return fetch(e,t)}function us(e){let t=new Headers;if(!e||typeof e!="object"||Array.isArray(e))return t;for(let[r,n]of Object.entries(e)){let o=r.toLowerCase();os.has(o)&&typeof n=="string"&&t.set(o,n)}return t}function ds(e){let t={};return e.forEach((r,n)=>{ss.has(n.toLowerCase())&&(t[n]=r)}),t}function fs(e,t){if(e==null)return;if(typeof e=="string"){if(!t.has("content-type"))try{JSON.parse(e),t.set("content-type","application/json")}catch{t.set("content-type","application/x-www-form-urlencoded")}return e}if((t.get("content-type")??"").includes("application/x-www-form-urlencoded")&&typeof e=="object"&&!Array.isArray(e)){let n=new URLSearchParams;for(let[o,s]of Object.entries(e))n.append(o,String(s));return n.toString()}return t.has("content-type")||t.set("content-type","application/json"),JSON.stringify(e)}function en(e,t){return`${e}\0${t}`}function ps(e){let{responseBody:t,binding:r,bindingKey:n,clients:o}=e,s=t.client_id,i=t.client_secret;if(typeof s!="string"||typeof i!="string")return t;let a=t.token_endpoint_auth_method,c=a==="client_secret_post"||a==="client_secret_basic"?a:r.tokenEndpointAuthMethods.has("client_secret_basic")?"client_secret_basic":"client_secret_post",l=t.client_secret_expires_at,u=l===0?Number.POSITIVE_INFINITY:typeof l=="number"&&l>0?l*1e3:Date.now()+cs;for(ms(o),o.set(en(n,s),{clientSecret:i,authMethod:c,expiresAt:u});o.size>ls;){let h=o.keys().next().value;if(!h)break;o.delete(h)}let d={...t};return delete d.client_secret,delete d.client_secret_expires_at,d.token_endpoint_auth_method="none",d}function hs(e){let{body:t,headers:r,bindingKey:n,clients:o}=e;if(!t||!(r.get("content-type")??"").includes("application/x-www-form-urlencoded"))return t;let s=new URLSearchParams(t),i=s.get("client_id");if(!i)return t;let a=en(n,i),c=o.get(a);if(!c)return t;if(c.expiresAt<=Date.now())return o.delete(a),t;if(s.delete("client_secret"),c.authMethod==="client_secret_basic"){let l=rs.from(`${Wr(i)}:${Wr(c.clientSecret)}`,"utf8").toString("base64");r.set("authorization",`Basic ${l}`)}else r.delete("authorization"),s.set("client_id",i),s.set("client_secret",c.clientSecret);return s.toString()}function Wr(e){return new URLSearchParams({value:e}).toString().slice(6)}function ms(e){let t=Date.now();for(let[r,n]of e)n.expiresAt<=t&&e.delete(r)}async function gs(e,t){let r=Number(e.headers.get("content-length"));if(Number.isFinite(r)&&r>t)throw new H;return tn(e.body,t)}async function Oe(e,t){let r=Number(e.headers.get("content-length"));if(Number.isFinite(r)&&r>t)throw await e.body?.cancel(),new H;return tn(e.body,t)}async function tn(e,t){if(!e)return"";let r=e.getReader(),n=[],o=0;for(;;){let{done:a,value:c}=await r.read();if(a)break;if(o+=c.byteLength,o>t)throw await r.cancel(),new H;n.push(c)}let s=new Uint8Array(o),i=0;for(let a of n)s.set(a,i),i+=a.byteLength;return new TextDecoder().decode(s)}function gt(e){let t;try{t=JSON.parse(e)}catch{throw new _("OAuth metadata is not valid JSON")}if(!t||typeof t!="object"||Array.isArray(t))throw new _("OAuth metadata is not an object");return t}function Kr(e,t){let r=e.get(t);return r&&Date.now()-r.updatedAt<=Xr?r:(e.delete(t),{authorizationServers:new Set,endpoints:new Map,tokenEndpointAuthMethods:new Set,updatedAt:Date.now()})}function Vr(e){let t=Date.now();for(let[r,n]of e)t-n.updatedAt>Xr&&e.delete(r);for(;e.size>as;){let r=e.keys().next().value;if(!r)break;e.delete(r)}}function I(e){let t=new URL(e);return t.hash="",(t.protocol==="https:"&&t.port==="443"||t.protocol==="http:"&&t.port==="80")&&(t.port=""),t.toString().replace(/\/$/,"")}function ws(e,t,r){if(!e||!(t.get("content-type")??"").includes("json"))return e;try{let o=JSON.parse(e);return!o||typeof o!="object"||Array.isArray(o)?e:JSON.stringify({...o,redirect_uris:[r]})}catch{return e}}function wt(e){let t=new URL(e);if(t.pathname!=="/"||t.search||t.hash)throw new Error(`OAuth proxy allowed origin must be an origin: ${e}`);return t.origin}function ys(e,t,r){try{let n=wt(e);if(n===new URL(t.req.url).origin||r.has(n))return!0;let o=new URL(n),i=t.req.header("x-forwarded-host")?.split(",")[0]?.trim()||t.req.header("host");if(!i||o.host!==i)return!1;let a=t.req.header("x-forwarded-proto")?.split(",")[0]?.trim();return!a||`${a}:`===o.protocol}catch{return!1}}function bs(e){let t=new Headers;return e&&rn(t,e),t.set("Access-Control-Allow-Methods","GET, POST, OPTIONS"),t.set("Access-Control-Allow-Headers","Accept, Authorization, Content-Type"),t.set("Access-Control-Max-Age","600"),new Response(null,{status:204,headers:t})}function rn(e,t){e.set("Access-Control-Allow-Origin",t),e.append("Vary","Origin")}async function Gr(e,t){return t?t(e):!0}function Te(e){return e>=300&&e<400}function xs(e){let t=e.toLowerCase().replace(/^\[|\]$/g,"");return t==="localhost"||t.endsWith(".localhost")||t==="::1"||t.startsWith("127.")}function vs(e){let t=e.toLowerCase();return t.endsWith(".local")||t.endsWith(".internal")||t.endsWith(".home.arpa")}function nn(e){if(e.includes(":")){let s=e.toLowerCase();return s.startsWith("::ffff:")?nn(s.slice(7)):!(s==="::"||s==="::1"||s.startsWith("fc")||s.startsWith("fd")||/^fe[89ab]/.test(s)||s.startsWith("ff")||s.startsWith("2001:db8:"))}let t=e.split(".").map(Number);if(t.length!==4||t.some(s=>!Number.isInteger(s)))return!1;let[r,n,o]=t;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 ht(e,t){e&&console.log(`[OAuth BFF] ${t}`)}function mt(e,t,r){let n=t instanceof Error?t.message:"Unknown error";return r&&console.error("[OAuth BFF]",n),t instanceof H?e.json({error:"Upstream response too large"},502):t instanceof _?e.json({error:t.message},502):t instanceof DOMException&&t.name==="TimeoutError"?e.json({error:"OAuth upstream timed out"},504):e.json({error:"OAuth upstream request failed"},502)}var H=class extends Error{},_=class extends Error{};var Es=3;function Rs(e,t){return e.includes("text/event-stream")&&!t}function xt(e,t={}){let r=t.path||"/mcp/proxy",n=t.enableLogging!==!1;e.use(`${r}/*`,xe({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&&e.use(`${r}/*`,Fr()),e.all(`${r}/*`,async o=>{try{if(t.authenticate&&!await t.authenticate(o))return o.json({error:"Unauthorized"},401);let s=o.req.header("X-Target-URL");if(!s)return o.json({error:"X-Target-URL header is required",usage:"Set X-Target-URL header to the MCP server URL you want to proxy to"},400);if(!await bt(s,t.allowLoopback??!1))return o.json({error:"Invalid target URL",details:"Target is not allowed by the proxy network policy"},403);if(t.validateRequest&&!await t.validateRequest(s,o))return o.json({error:"Invalid target URL",details:"The requested target URL is not allowed"},403);try{new URL(s)}catch{return o.json({error:"Invalid target URL format",details:"The X-Target-URL must be a valid HTTP/HTTPS URL"},400)}let i=o.req.method,a={},c=o.req.header();for(let[p,g]of Object.entries(c)){let f=p.toLowerCase();!f.startsWith("x-proxy-")&&!f.startsWith("x-target-")&&!f.startsWith("x-mcp-")&&!f.startsWith("x-forwarded-")&&!f.startsWith("cf-")&&f!=="x-original-host"&&f!=="host"&&f!=="origin"&&f!=="referer"&&f!=="cookie"&&f!=="proxy-authorization"&&f!=="accept-encoding"&&f!=="cdn-loop"&&!f.startsWith("sec-fetch-")&&(a[p]=g)}a["Accept-Encoding"]="identity";let l=i!=="GET"&&i!=="HEAD"?new Uint8Array(await o.req.arrayBuffer()).slice():void 0,u=s,d=i,h=l;for(let p=0;;p+=1){let g=await fetch(u,{method:d,headers:a,body:h,redirect:"manual"}),f=g.headers.get("location");if(!(g.status>=300&&g.status<400&&f))return Ss(g);if(p>=Es)return o.json({error:"Too many upstream redirects"},502);let w=new URL(f,u);if(!await bt(w.toString(),t.allowLoopback??!1)||t.validateRequest&&!await t.validateRequest(w.toString(),o))return o.json({error:"Redirect target is not allowed"},403);w.origin!==new URL(u).origin&&(Me(a,"authorization"),Me(a,"proxy-authorization")),(g.status===303||(g.status===301||g.status===302)&&d==="POST")&&(d="GET",h=void 0,Me(a,"content-type"),Me(a,"content-length")),u=w.toString()}}catch(s){let i=s instanceof Error?s.message:"Unknown error",a=o.req.header("X-Target-URL");return s instanceof Error&&(s.message.includes("ECONNREFUSED")||s.message.includes("fetch failed"))?console.warn(`[MCP Proxy] Connection refused to ${a||"unknown target"} - server may not be running`):console.error("[MCP Proxy] Request failed:",i,`
101
101
  Target URL:`,a||"unknown",`
102
- Error:`,s),o.json({error:"Proxy request failed",details:i,targetUrl:a||"unknown"},500)}})}function Oe(e,t){for(let r of Object.keys(e))r.toLowerCase()===t&&delete e[r]}async function Go(e){let t={};if(e.headers.forEach((o,s)=>{let i=s.toLowerCase();i!=="content-encoding"&&i!=="transfer-encoding"&&i!=="content-length"&&i!=="set-cookie"&&(t[s]=o)}),Vo(e.headers.get("content-type")||"",e.headers.get("content-length")))return new Response(e.body,{status:e.status,statusText:e.statusText,headers:t});if([204,205,304].includes(e.status))return new Response(null,{status:e.status,statusText:e.statusText,headers:t});let n=await e.arrayBuffer();return t["Content-Length"]=String(n.byteLength),new Response(n,{status:e.status,statusText:e.statusText,headers:t})}function jr(e,t,r=""){let n=i=>`${r}${i}`,o=t?.oauthProxyAllowLoopback??!1,s=t?.oauth!==!1;if(e.get(n("/inspector/health"),i=>i.json({status:"ok",protocol:"mcp-use-inspector-preview",version:1,capabilities:["view-preview"]})),ht(e,{path:n("/inspector/api/proxy"),allowLoopback:o}),s&&pt(e,{basePath:n("/inspector/api/oauth"),callbackPath:n("/inspector/oauth/callback"),enableLogging:!0,allowedOrigins:t?.oauthProxyAllowedOrigins??[],allowLoopback:o}),t?.autoConnectUrl!==void 0){let i=t.autoConnectUrl;e.get(n("/inspector/config.json"),a=>a.json({autoConnectUrl:i??null}))}}function Nr(e){try{let t=new URL(e);return t.protocol==="http:"||t.protocol==="https:"}catch{return!1}}async function $r(e=8080,t=100){let r=await import("net");for(let n=e;n<e+t;n++)try{return await new Promise((o,s)=>{let i=r.createServer();i.listen(n,()=>{i.close(()=>o())}),i.on("error",a=>s(a))}),n}catch{continue}throw new Error(`No available port found after trying ${t} ports starting from ${e}`)}var S=process.argv.slice(2),Y,Br=8080,Dr=!1;for(let e=0;e<S.length;e++)if(S[e]==="--url"){(e+1>=S.length||S[e+1].startsWith("-"))&&(console.error("Error: --url requires a value"),process.exit(1));let t=S[e+1];Nr(t)||(console.error(`Error: Invalid URL format: ${t}`),console.error("URL must start with http://, https://, ws://, or wss://"),process.exit(1)),Y=t,e++}else if(S[e]==="--port"){(e+1>=S.length||S[e+1].startsWith("-"))&&(console.error("Error: --port requires a value"),process.exit(1));let t=Number.parseInt(S[e+1],10);(Number.isNaN(t)||t<1||t>65535)&&(console.error(`Error: Port must be a number between 1 and 65535, got: ${S[e+1]}`),process.exit(1)),Br=t,e++}else S[e]==="--no-open"?Dr=!0:S[e]==="--version"||S[e]==="-v"?(console.log(Se()),process.exit(0)):S[e]==="--help"||S[e]==="-h"?(console.log(`
102
+ Error:`,s),o.json({error:"Proxy request failed",details:i,targetUrl:a||"unknown"},500)}})}function Me(e,t){for(let r of Object.keys(e))r.toLowerCase()===t&&delete e[r]}async function Ss(e){let t={};if(e.headers.forEach((o,s)=>{let i=s.toLowerCase();i!=="content-encoding"&&i!=="transfer-encoding"&&i!=="content-length"&&i!=="set-cookie"&&(t[s]=o)}),Rs(e.headers.get("content-type")||"",e.headers.get("content-length")))return new Response(e.body,{status:e.status,statusText:e.statusText,headers:t});if([204,205,304].includes(e.status))return new Response(null,{status:e.status,statusText:e.statusText,headers:t});let n=await e.arrayBuffer();return t["Content-Length"]=String(n.byteLength),new Response(n,{status:e.status,statusText:e.statusText,headers:t})}function on(e,t,r=""){let n=i=>`${r}${i}`,o=t?.oauthProxyAllowLoopback??!1,s=t?.oauth!==!1;if(e.use(n("/inspector/api/*"),Ae({points:Lr,durationSeconds:Pe,key:"inspector-api"})),e.get(n("/inspector/health"),i=>i.json({status:"ok",protocol:"mcp-use-inspector-preview",version:1,capabilities:["view-preview"]})),xt(e,{path:n("/inspector/api/proxy"),allowLoopback:o}),s&&yt(e,{basePath:n("/inspector/api/oauth"),callbackPath:n("/inspector/oauth/callback"),enableLogging:!0,allowedOrigins:t?.oauthProxyAllowedOrigins??[],allowLoopback:o}),t?.autoConnectUrl!==void 0){let i=t.autoConnectUrl;e.get(n("/inspector/config.json"),a=>a.json({autoConnectUrl:i??null}))}}function sn(e){try{let t=new URL(e);return t.protocol==="http:"||t.protocol==="https:"}catch{return!1}}async function an(e=8080,t=100){let r=await import("net");for(let n=e;n<e+t;n++)try{return await new Promise((o,s)=>{let i=r.createServer();i.listen(n,()=>{i.close(()=>o())}),i.on("error",a=>s(a))}),n}catch{continue}throw new Error(`No available port found after trying ${t} ports starting from ${e}`)}var C=process.argv.slice(2),ie,cn=8080,ln=!1;for(let e=0;e<C.length;e++)if(C[e]==="--url"){(e+1>=C.length||C[e+1].startsWith("-"))&&(console.error("Error: --url requires a value"),process.exit(1));let t=C[e+1];sn(t)||(console.error("Error: Invalid URL format."),console.error("URL must start with http://, https://, ws://, or wss://"),process.exit(1)),ie=t,e++}else if(C[e]==="--port"){(e+1>=C.length||C[e+1].startsWith("-"))&&(console.error("Error: --port requires a value"),process.exit(1));let t=Number.parseInt(C[e+1],10);(Number.isNaN(t)||t<1||t>65535)&&(console.error("Error: Port must be a number between 1 and 65535."),process.exit(1)),cn=t,e++}else C[e]==="--no-open"?ln=!0:C[e]==="--version"||C[e]==="-v"?(console.log(_e()),process.exit(0)):C[e]==="--help"||C[e]==="-h"?(console.log(`
103
103
  MCP Inspector - Inspect and debug MCP servers
104
104
 
105
105
  Usage:
@@ -116,4 +116,4 @@ Examples:
116
116
  npx @mcp-use/inspector --url http://localhost:3000/mcp
117
117
  npx @mcp-use/inspector --url http://localhost:3000/mcp --port 9000
118
118
  npx @mcp-use/inspector
119
- `),process.exit(0)):(console.error(`Error: Unknown option: ${S[e]}`),console.error("Run with --help to see available options."),process.exit(1));var ie=new Ge;ie.use("*",be({origin:"*",exposeHeaders:["*"]}));jr(ie,{autoConnectUrl:Y,oauthProxyAllowedOrigins:[],oauthProxyAllowLoopback:!0});yr(ie,{inspectorMode:"standalone",manufactChatUrl:process.env.MANUFACT_CHAT_URL});async function Ko(){try{let e=await $r(Br);if(Pt({fetch:ie.fetch,port:e}),console.log(`\u{1F680} MCP Inspector running on http://localhost:${e}`),Y&&console.log(`\u{1F4E1} Auto-connecting to: ${Y}`),!Dr){let t=new URL(`http://localhost:${e}/inspector`);Y&&t.searchParams.set("autoConnect",Y);try{await pr(t.toString()),console.log("\u{1F310} Browser opened")}catch{console.log(`\u{1F310} Please open ${t} in your browser`)}}return{port:e,fetch:ie.fetch}}catch(e){console.error("Failed to start server:",e),process.exit(1)}}Ko();
119
+ `),process.exit(0)):(console.error("Error: Unknown option."),console.error("Run with --help to see available options."),process.exit(1));var ae=new Ye;ae.use("*",xe({origin:"*",exposeHeaders:["*"]}));on(ae,{autoConnectUrl:ie,oauthProxyAllowedOrigins:[],oauthProxyAllowLoopback:!0});jr(ae,{inspectorMode:"standalone",manufactChatUrl:process.env.MANUFACT_CHAT_URL});async function Ps(){try{let e=await an(cn);if(It({fetch:ae.fetch,port:e}),console.log("MCP Inspector started."),ie&&console.log("Auto-connect configured."),!ln){let t=new URL(`http://localhost:${e}/inspector`);ie&&t.searchParams.set("autoConnect",ie);try{await br(t.toString()),console.log("Browser opened.")}catch{console.log("Browser could not be opened automatically.")}}return{port:e,fetch:ae.fetch}}catch(e){let t=e instanceof Error?e.name:"UnknownError";console.error(`Failed to start server (${t}).`),process.exit(1)}}Ps();
@@ -1,13 +1,13 @@
1
- var ne=(e,t,r)=>(n,o)=>{let s=-1;return i(0);async function i(a){if(a<=s)throw new Error("next() called multiple times");s=a;let c,l=!1,u;if(e[a]?(u=e[a][0][0],n.req.routeIndex=a):u=a===e.length&&o||void 0,u)try{c=await u(n,()=>i(a+1))}catch(p){if(p instanceof Error&&t)n.error=p,c=await t(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 Pe=Symbol();var Oe=async(e,t=Object.create(null))=>{let{all:r=!1,dot:n=!1}=t,s=(e instanceof F?e.raw.headers:e.headers).get("Content-Type");return s?.startsWith("multipart/form-data")||s?.startsWith("application/x-www-form-urlencoded")?Pt(e,{all:r,dot:n}):{}};async function Pt(e,t){let r=await e.formData();return r?Ot(r,t):{}}function Ot(e,t){let r=Object.create(null);return e.forEach((n,o)=>{t.all||o.endsWith("[]")?Ct(r,o,n):r[o]=n}),t.dot&&Object.entries(r).forEach(([n,o])=>{n.includes(".")&&(_t(r,n,o),delete r[n])}),r}var Ct=(e,t,r)=>{e[t]!==void 0?Array.isArray(e[t])?e[t].push(r):e[t]=[e[t],r]:t.endsWith("[]")?e[t]=[r]:e[t]=r},_t=(e,t,r)=>{if(/(?:^|\.)__proto__\./.test(t))return;let n=e,o=t.split(".");o.forEach((s,i)=>{i===o.length-1?n[s]=r:((!n[s]||typeof n[s]!="object"||Array.isArray(n[s])||n[s]instanceof File)&&(n[s]=Object.create(null)),n=n[s])})};var se=e=>{let t=e.split("/");return t[0]===""&&t.shift(),t},Ce=e=>{let{groups:t,path:r}=St(e),n=se(r);return Tt(n,t)},St=e=>{let t=[];return e=e.replace(/\{[^}]+\}/g,(r,n)=>{let o=`@${n}`;return t.push([o,r]),o}),{groups:t,path:e}},Tt=(e,t)=>{for(let r=t.length-1;r>=0;r--){let[n]=t[r];for(let o=e.length-1;o>=0;o--)if(e[o].includes(n)){e[o]=e[o].replace(n,t[r][1]);break}}return e},W={},_e=(e,t)=>{if(e==="*")return"*";let r=e.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);if(r){let n=`${e}#${t}`;return W[n]||(r[2]?W[n]=t&&t[0]!==":"&&t[0]!=="*"?[n,r[1],new RegExp(`^${r[2]}(?=/${t})`)]:[e,r[1],new RegExp(`^${r[2]}$`)]:W[n]=[e,r[1],!0]),W[n]}return null},V=(e,t)=>{try{return t(e)}catch{return e.replace(/(?:%[0-9A-Fa-f]{2})+/g,r=>{try{return t(r)}catch{return r}})}},kt=e=>V(e,decodeURI),ie=e=>{let t=e.url,r=t.indexOf("/",t.indexOf(":")+4),n=r;for(;n<t.length;n++){let o=t.charCodeAt(n);if(o===37){let s=t.indexOf("?",n),i=t.indexOf("#",n),a=s===-1?i===-1?void 0:i:i===-1?s:Math.min(s,i),c=t.slice(r,a);return kt(c.includes("%25")?c.replace(/%25/g,"%2525"):c)}else if(o===63||o===35)break}return t.slice(r,n)};var Se=e=>{let t=ie(e);return t.length>1&&t.at(-1)==="/"?t.slice(0,-1):t},L=(e,t,...r)=>(r.length&&(t=L(t,...r)),`${e?.[0]==="/"?"":"/"}${e}${t==="/"?"":`${e?.at(-1)==="/"?"":"/"}${t?.[0]==="/"?t.slice(1):t}`}`),K=e=>{if(e.charCodeAt(e.length-1)!==63||!e.includes(":"))return null;let t=e.split("/"),r=[],n="";return t.forEach(o=>{if(o!==""&&!/\:/.test(o))n+="/"+o;else if(/\:/.test(o))if(/\?/.test(o)){r.length===0&&n===""?r.push("/"):r.push(n);let s=o.replace("?","");n+="/"+s,r.push(n)}else n+="/"+o}),r.filter((o,s,i)=>i.indexOf(o)===s)},oe=e=>/[%+]/.test(e)?(e.indexOf("+")!==-1&&(e=e.replace(/\+/g," ")),e.indexOf("%")!==-1?V(e,ae):e):e,Te=(e,t,r)=>{let n;if(!r&&t&&!/[%+]/.test(t)){let i=e.indexOf("?",8);if(i===-1)return;for(e.startsWith(t,i+1)||(i=e.indexOf(`&${t}`,i+1));i!==-1;){let a=e.charCodeAt(i+t.length+1);if(a===61){let c=i+t.length+2,l=e.indexOf("&",c);return oe(e.slice(c,l===-1?void 0:l))}else if(a==38||isNaN(a))return"";i=e.indexOf(`&${t}`,i+1)}if(n=/[%+]/.test(e),!n)return}let o={};n??=/[%+]/.test(e);let s=e.indexOf("?",8);for(;s!==-1;){let i=e.indexOf("&",s+1),a=e.indexOf("=",s);a>i&&i!==-1&&(a=-1);let c=e.slice(s+1,a===-1?i===-1?void 0:i:a);if(n&&(c=oe(c)),s=i,c==="")continue;let l;a===-1?l="":(l=e.slice(a+1,i===-1?void 0:i),n&&(l=oe(l))),r?(o[c]&&Array.isArray(o[c])||(o[c]=[]),o[c].push(l)):o[c]??=l}return t?o[t]:o},ke=Te,Ue=(e,t)=>Te(e,t,!0),ae=decodeURIComponent;var Le=e=>V(e,ae),F=class{raw;#t;#e;routeIndex=0;path;bodyCache={};constructor(e,t="/",r=[[]]){this.raw=e,this.path=t,this.#e=r,this.#t={}}param(e){return e?this.#r(e):this.#s()}#r(e){let t=this.#e[0][this.routeIndex][1][e],r=this.#o(t);return r&&/\%/.test(r)?Le(r):r}#s(){let e={},t=Object.keys(this.#e[0][this.routeIndex][1]);for(let r of t){let n=this.#o(this.#e[0][this.routeIndex][1][r]);n!==void 0&&(e[r]=/\%/.test(n)?Le(n):n)}return e}#o(e){return this.#e[1]?this.#e[1][e]:e}query(e){return ke(this.url,e)}queries(e){return Ue(this.url,e)}header(e){if(e)return this.raw.headers.get(e)??void 0;let t={};return this.raw.headers.forEach((r,n)=>{t[n]=r}),t}async parseBody(e){return Oe(this,e)}#n=e=>{let{bodyCache:t,raw:r}=this,n=t[e];if(n)return n;let o=Object.keys(t)[0];return o?t[o].then(s=>(o==="json"&&(s=JSON.stringify(s)),new Response(s)[e]())):t[e]=r[e]()};json(){return this.#n("text").then(e=>JSON.parse(e))}text(){return this.#n("text")}arrayBuffer(){return this.#n("arrayBuffer")}bytes(){return this.#n("arrayBuffer").then(e=>new Uint8Array(e))}blob(){return this.#n("blob")}formData(){return this.#n("formData")}addValidatedData(e,t){this.#t[e]=t}valid(e){return this.#t[e]}get url(){return this.raw.url}get method(){return this.raw.method}get[Pe](){return this.#e}get matchedRoutes(){return this.#e[0].map(([[,e]])=>e)}get routePath(){return this.#e[0].map(([[,e]])=>e)[this.routeIndex].path}};var Me={Stringify:1,BeforeStream:2,Stream:3},Ut=(e,t)=>{let r=new String(e);return r.isEscaped=!0,r.callbacks=t,r};var ce=async(e,t,r,n,o)=>{typeof e=="object"&&!(e instanceof String)&&(e instanceof Promise||(e=e.toString()),e instanceof Promise&&(e=await e));let s=e.callbacks;if(!s?.length)return Promise.resolve(e);o?o[0]+=e:o=[e];let i=Promise.all(s.map(a=>a({phase:t,buffer:o,context:n}))).then(a=>Promise.all(a.filter(Boolean).map(c=>ce(c,t,!1,n,o))).then(()=>o[0]));return r?Ut(await i,s):i};var Lt="text/plain; charset=UTF-8",le=(e,t)=>({"Content-Type":e,...t}),D=(e,t)=>new Response(e,t),ue=class{#t;#e;env={};#r;finalized=!1;error;#s;#o;#n;#u;#c;#l;#a;#d;#p;constructor(e,t){this.#t=e,t&&(this.#o=t.executionCtx,this.env=t.env,this.#l=t.notFoundHandler,this.#p=t.path,this.#d=t.matchResult)}get req(){return this.#e??=new F(this.#t,this.#p,this.#d),this.#e}get event(){if(this.#o&&"respondWith"in this.#o)return this.#o;throw Error("This context has no FetchEvent")}get executionCtx(){if(this.#o)return this.#o;throw Error("This context has no ExecutionContext")}get res(){return this.#n||=D(null,{headers:this.#a??=new Headers})}set res(e){if(this.#n&&e){e=D(e.body,e);for(let[t,r]of this.#n.headers.entries())if(t!=="content-type")if(t==="set-cookie"){let n=this.#n.headers.getSetCookie();e.headers.delete("set-cookie");for(let o of n)e.headers.append("set-cookie",o)}else e.headers.set(t,r)}this.#n=e,this.finalized=!0}render=(...e)=>(this.#c??=t=>this.html(t),this.#c(...e));setLayout=e=>this.#u=e;getLayout=()=>this.#u;setRenderer=e=>{this.#c=e};header=(e,t,r)=>{this.finalized&&(this.#n=D(this.#n.body,this.#n));let n=this.#n?this.#n.headers:this.#a??=new Headers;t===void 0?n.delete(e):r?.append?n.append(e,t):n.set(e,t)};status=e=>{this.#s=e};set=(e,t)=>{this.#r??=new Map,this.#r.set(e,t)};get=e=>this.#r?this.#r.get(e):void 0;get var(){return this.#r?Object.fromEntries(this.#r):{}}#i(e,t,r){let n=this.#n?new Headers(this.#n.headers):this.#a??new Headers;if(typeof t=="object"&&"headers"in t){let s=t.headers instanceof Headers?t.headers:new Headers(t.headers);for(let[i,a]of s)i.toLowerCase()==="set-cookie"?n.append(i,a):n.set(i,a)}if(r)for(let[s,i]of Object.entries(r))if(typeof i=="string")n.set(s,i);else{n.delete(s);for(let a of i)n.append(s,a)}let o=typeof t=="number"?t:t?.status??this.#s;return D(e,{status:o,headers:n})}newResponse=(...e)=>this.#i(...e);body=(e,t,r)=>this.#i(e,t,r);text=(e,t,r)=>!this.#a&&!this.#s&&!t&&!r&&!this.finalized?new Response(e):this.#i(e,t,le(Lt,r));json=(e,t,r)=>this.#i(JSON.stringify(e),t,le("application/json",r));html=(e,t,r)=>{let n=o=>this.#i(o,t,le("text/html; charset=UTF-8",r));return typeof e=="object"?ce(e,Me.Stringify,!1,{}).then(n):n(e)};redirect=(e,t)=>{let r=String(e);return this.header("Location",/[^\x00-\xFF]/.test(r)?encodeURI(r):r),this.newResponse(null,t??302)};notFound=()=>(this.#l??=()=>D(),this.#l(this))};var y="ALL",Ie="all",je=["get","post","put","delete","options","patch"],G="Can not add a route since the matcher is already built.",J=class extends Error{};var He="__COMPOSED_HANDLER";var Mt=e=>e.text("404 Not Found",404),$e=(e,t)=>{if("getResponse"in e){let r=e.getResponse();return t.newResponse(r.body,r)}return console.error(e),t.text("Internal Server Error",500)},Ne=class De{get;post;put;delete;options;patch;all;on;use;router;getPath;_basePath="/";#t="/";routes=[];constructor(t={}){[...je,Ie].forEach(s=>{this[s]=(i,...a)=>(typeof i=="string"?this.#t=i:this.#s(s,this.#t,i),a.forEach(c=>{this.#s(s,this.#t,c)}),this)}),this.on=(s,i,...a)=>{for(let c of[i].flat()){this.#t=c;for(let l of[s].flat())a.map(u=>{this.#s(l.toUpperCase(),this.#t,u)})}return this},this.use=(s,...i)=>(typeof s=="string"?this.#t=s:(this.#t="*",i.unshift(s)),i.forEach(a=>{this.#s(y,this.#t,a)}),this);let{strict:n,...o}=t;Object.assign(this,o),this.getPath=n??!0?t.getPath??ie:Se}#e(){let t=new De({router:this.router,getPath:this.getPath});return t.errorHandler=this.errorHandler,t.#r=this.#r,t.routes=this.routes,t}#r=Mt;errorHandler=$e;route(t,r){let n=this.basePath(t);return r.routes.map(o=>{let s;r.errorHandler===$e?s=o.handler:(s=async(i,a)=>(await ne([],r.errorHandler)(i,()=>o.handler(i,a))).res,s[He]=o.handler),n.#s(o.method,o.path,s,o.basePath)}),this}basePath(t){let r=this.#e();return r._basePath=L(this._basePath,t),r}onError=t=>(this.errorHandler=t,this);notFound=t=>(this.#r=t,this);mount(t,r,n){let o,s;n&&(typeof n=="function"?s=n:(s=n.optionHandler,n.replaceRequest===!1?o=c=>c:o=n.replaceRequest));let i=s?c=>{let l=s(c);return Array.isArray(l)?l:[l]}:c=>{let l;try{l=c.executionCtx}catch{}return[c.env,l]};o||=(()=>{let c=L(this._basePath,t),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 a=async(c,l)=>{let u=await r(o(c.req.raw),...i(c));if(u)return u;await l()};return this.#s(y,L(t,"*"),a),this}#s(t,r,n,o){t=t.toUpperCase(),r=L(this._basePath,r);let s={basePath:o!==void 0?L(this._basePath,o):this._basePath,path:r,method:t,handler:n};this.router.add(t,r,[n,s]),this.routes.push(s)}#o(t,r){if(t instanceof Error)return this.errorHandler(t,r);throw t}#n(t,r,n,o){if(o==="HEAD")return(async()=>new Response(null,await this.#n(t,r,n,"GET")))();let s=this.getPath(t,{env:n}),i=this.router.match(o,s),a=new ue(t,{path:s,matchResult:i,env:n,executionCtx:r,notFoundHandler:this.#r});if(i[0].length===1){let l;try{l=i[0][0][0][0](a,async()=>{a.res=await this.#r(a)})}catch(u){return this.#o(u,a)}return l instanceof Promise?l.then(u=>u||(a.finalized?a.res:this.#r(a))).catch(u=>this.#o(u,a)):l??this.#r(a)}let c=ne(i[0],this.errorHandler,this.#r);return(async()=>{try{let l=await c(a);if(!l.finalized)throw new Error("Context is not finalized. Did you forget to return a Response object or `await next()`?");return l.res}catch(l){return this.#o(l,a)}})()}fetch=(t,...r)=>this.#n(t,r[1],r[0],t.method);request=(t,r,n,o)=>t instanceof Request?this.fetch(r?new Request(t,r):t,n,o):(t=t.toString(),this.fetch(new Request(/^https?:\/\//.test(t)?t:`http://localhost${L("/",t)}`,r),n,o));fire=()=>{addEventListener("fetch",t=>{t.respondWith(this.#n(t.request,t,void 0,t.request.method))})}};var X=[];function de(e,t){let r=this.buildAllMatchers(),n=((o,s)=>{let i=r[o]||r[y],a=i[2][s];if(a)return a;let c=s.match(i[0]);if(!c)return[[],X];let l=c.indexOf("",1);return[i[1][l],c]});return this.match=n,n(e,t)}var Y="[^/]+",B=".*",z="(?:|/.*)",I=Symbol(),It=new Set(".\\+*[^]$()");function jt(e,t){return e.length===1?t.length===1?e<t?-1:1:-1:t.length===1||e===B||e===z?1:t===B||t===z?-1:e===Y?1:t===Y?-1:e.length===t.length?e<t?-1:1:t.length-e.length}var Be=class pe{#t;#e;#r=Object.create(null);insert(t,r,n,o,s){if(t.length===0){if(this.#t!==void 0)throw I;if(s)return;this.#t=r;return}let[i,...a]=t,c=i==="*"?a.length===0?["","",B]:["","",Y]:i==="/*"?["","",z]:i.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/),l;if(c){let u=c[1],p=c[2]||Y;if(u&&c[2]&&(p===".*"||(p=p.replace(/^\((?!\?:)(?=[^)]+\)$)/,"(?:"),/\((?!\?:)/.test(p))))throw I;if(l=this.#r[p],!l){if(Object.keys(this.#r).some(g=>g!==B&&g!==z))throw I;if(s)return;l=this.#r[p]=new pe,u!==""&&(l.#e=o.varIndex++)}!s&&u!==""&&n.push([u,l.#e])}else if(l=this.#r[i],!l){if(Object.keys(this.#r).some(u=>u.length>1&&u!==B&&u!==z))throw I;if(s)return;l=this.#r[i]=new pe}l.insert(a,r,n,o,s)}buildRegExpStr(){let r=Object.keys(this.#r).sort(jt).map(n=>{let o=this.#r[n];return(typeof o.#e=="number"?`(${n})@${o.#e}`:It.has(n)?`\\${n}`:n)+o.buildRegExpStr()});return typeof this.#t=="number"&&r.unshift(`#${this.#t}`),r.length===0?"":r.length===1?r[0]:"(?:"+r.join("|")+")"}};var ze=class{#t={varIndex:0};#e=new Be;insert(e,t,r){let n=[],o=[];for(let i=0;;){let a=!1;if(e=e.replace(/\{[^}]+\}/g,c=>{let l=`@\\${i}`;return o[i]=[l,c],i++,a=!0,l}),!a)break}let s=e.match(/(?::[^\/]+)|(?:\/\*$)|./g)||[];for(let i=o.length-1;i>=0;i--){let[a]=o[i];for(let c=s.length-1;c>=0;c--)if(s[c].indexOf(a)!==-1){s[c]=s[c].replace(a,o[i][1]);break}}return this.#e.insert(s,t,n,this.#t,r),n}buildRegExp(){let e=this.#e.buildRegExpStr();if(e==="")return[/^$/,[],[]];let t=0,r=[],n=[];return e=e.replace(/#(\d+)|@(\d+)|\.\*\$/g,(o,s,i)=>s!==void 0?(r[++t]=Number(s),"$()"):(i!==void 0&&(n[Number(i)]=++t),"")),[new RegExp(`^${e}`),r,n]}};var Ht=[/^$/,[],Object.create(null)],qe=Object.create(null);function Fe(e){return qe[e]??=new RegExp(e==="*"?"":`^${e.replace(/\/\*$|([.\\+*[^\]$()])/g,(t,r)=>r?`\\${r}`:"(?:|/.*)")}$`)}function $t(){qe=Object.create(null)}function Nt(e){let t=new ze,r=[];if(e.length===0)return Ht;let n=e.map(l=>[!/\*|\/:/.test(l[0]),...l]).sort(([l,u],[p,g])=>l?1:p?-1:u.length-g.length),o=Object.create(null);for(let l=0,u=-1,p=n.length;l<p;l++){let[g,h,m]=n[l];g?o[h]=[m.map(([w])=>[w,Object.create(null)]),X]:u++;let d;try{d=t.insert(h,u,g)}catch(w){throw w===I?new J(h):w}g||(r[u]=m.map(([w,f])=>{let R=Object.create(null);for(f-=1;f>=0;f--){let[O,S]=d[f];R[O]=S}return[w,R]}))}let[s,i,a]=t.buildRegExp();for(let l=0,u=r.length;l<u;l++)for(let p=0,g=r[l].length;p<g;p++){let h=r[l][p]?.[1];if(!h)continue;let m=Object.keys(h);for(let d=0,w=m.length;d<w;d++)h[m[d]]=a[h[m[d]]]}let c=[];for(let l in i)c[l]=r[i[l]];return[s,c,o]}function $(e,t){if(e){for(let r of Object.keys(e).sort((n,o)=>o.length-n.length))if(Fe(r).test(t))return[...e[r]]}}var Q=class{name="RegExpRouter";#t;#e;constructor(){this.#t={[y]:Object.create(null)},this.#e={[y]:Object.create(null)}}add(e,t,r){let n=this.#t,o=this.#e;if(!n||!o)throw new Error(G);n[e]||[n,o].forEach(a=>{a[e]=Object.create(null),Object.keys(a[y]).forEach(c=>{a[e][c]=[...a[y][c]]})}),t==="/*"&&(t="*");let s=(t.match(/\/:/g)||[]).length;if(/\*$/.test(t)){let a=Fe(t);e===y?Object.keys(n).forEach(c=>{n[c][t]||=$(n[c],t)||$(n[y],t)||[]}):n[e][t]||=$(n[e],t)||$(n[y],t)||[],Object.keys(n).forEach(c=>{(e===y||e===c)&&Object.keys(n[c]).forEach(l=>{a.test(l)&&n[c][l].push([r,s])})}),Object.keys(o).forEach(c=>{(e===y||e===c)&&Object.keys(o[c]).forEach(l=>a.test(l)&&o[c][l].push([r,s]))});return}let i=K(t)||[t];for(let a=0,c=i.length;a<c;a++){let l=i[a];Object.keys(o).forEach(u=>{(e===y||e===u)&&(o[u][l]||=[...$(n[u],l)||$(n[y],l)||[]],o[u][l].push([r,s-c+a+1]))})}}match=de;buildAllMatchers(){let e=Object.create(null);return Object.keys(this.#e).concat(Object.keys(this.#t)).forEach(t=>{e[t]||=this.#r(t)}),this.#t=this.#e=void 0,$t(),e}#r(e){let t=[],r=e===y;return[this.#t,this.#e].forEach(n=>{let o=n[e]?Object.keys(n[e]).map(s=>[s,n[e][s]]):[];o.length!==0?(r||=!0,t.push(...o)):e!==y&&t.push(...Object.keys(n[y]).map(s=>[s,n[y][s]]))}),r?Nt(t):null}};var he=class{name="SmartRouter";#t=[];#e=[];constructor(e){this.#t=e.routers}add(e,t,r){if(!this.#e)throw new Error(G);this.#e.push([e,t,r])}match(e,t){if(!this.#e)throw new Error("Fatal error");let r=this.#t,n=this.#e,o=r.length,s=0,i;for(;s<o;s++){let a=r[s];try{for(let c=0,l=n.length;c<l;c++)a.add(...n[c]);i=a.match(e,t)}catch(c){if(c instanceof J)continue;throw c}this.match=a.match.bind(a),this.#t=[a],this.#e=void 0;break}if(s===o)throw new Error("Fatal error");return this.name=`SmartRouter + ${this.activeRouter.name}`,i}get activeRouter(){if(this.#e||this.#t.length!==1)throw new Error("No active router has been determined yet.");return this.#t[0]}};var q=Object.create(null),Dt=e=>{for(let t in e)return!0;return!1},We=class Ve{#t;#e;#r;#s=0;#o=q;constructor(t,r,n){if(this.#e=n||Object.create(null),this.#t=[],t&&r){let o=Object.create(null);o[t]={handler:r,possibleKeys:[],score:0},this.#t=[o]}this.#r=[]}insert(t,r,n){this.#s=++this.#s;let o=this,s=Ce(r),i=[];for(let a=0,c=s.length;a<c;a++){let l=s[a],u=s[a+1],p=_e(l,u),g=Array.isArray(p)?p[0]:l;if(g in o.#e){o=o.#e[g],p&&i.push(p[1]);continue}o.#e[g]=new Ve,p&&(o.#r.push(p),i.push(p[1])),o=o.#e[g]}return o.#t.push({[t]:{handler:n,possibleKeys:i.filter((a,c,l)=>l.indexOf(a)===c),score:this.#s}}),o}#n(t,r,n,o,s){for(let i=0,a=r.#t.length;i<a;i++){let c=r.#t[i],l=c[n]||c[y],u={};if(l!==void 0&&(l.params=Object.create(null),t.push(l),o!==q||s&&s!==q))for(let p=0,g=l.possibleKeys.length;p<g;p++){let h=l.possibleKeys[p],m=u[l.score];l.params[h]=s?.[h]&&!m?s[h]:o[h]??s?.[h],u[l.score]=!0}}}search(t,r){let n=[];this.#o=q;let s=[this],i=se(r),a=[],c=i.length,l=null;for(let u=0;u<c;u++){let p=i[u],g=u===c-1,h=[];for(let d=0,w=s.length;d<w;d++){let f=s[d],R=f.#e[p];R&&(R.#o=f.#o,g?(R.#e["*"]&&this.#n(n,R.#e["*"],t,f.#o),this.#n(n,R,t,f.#o)):h.push(R));for(let O=0,S=f.#r.length;O<S;O++){let v=f.#r[O],b=f.#o===q?{}:{...f.#o};if(v==="*"){let k=f.#e["*"];k&&(this.#n(n,k,t,f.#o),k.#o=b,h.push(k));continue}let[A,x,P]=v;if(!p&&!(P instanceof RegExp))continue;let E=f.#e[A];if(P instanceof RegExp){if(l===null){l=new Array(c);let H=r[0]==="/"?1:0;for(let _=0;_<c;_++)l[_]=H,H+=i[_].length+1}let k=r.substring(l[u]),N=P.exec(k);if(N){if(b[x]=N[0],this.#n(n,E,t,f.#o,b),Dt(E.#e)){E.#o=b;let H=N[0].match(/\//)?.length??0;(a[H]||=[]).push(E)}continue}}(P===!0||P.test(p))&&(b[x]=p,g?(this.#n(n,E,t,b,f.#o),E.#e["*"]&&this.#n(n,E.#e["*"],t,b,f.#o)):(E.#o=b,h.push(E)))}}let m=a.shift();s=m?h.concat(m):h}return n.length>1&&n.sort((u,p)=>u.score-p.score),[n.map(({handler:u,params:p})=>[u,p])]}};var fe=class{name="TrieRouter";#t;constructor(){this.#t=new We}add(e,t,r){let n=K(t);if(n){for(let o=0,s=n.length;o<s;o++)this.#t.insert(e,n[o],r);return}this.#t.insert(e,t,r)}match(e,t){return this.#t.search(e,t)}};var ge=class extends Ne{constructor(e={}){super(e),this.router=e.router??new he({routers:[new Q,new fe]})}};import{Readable as Pr}from"stream";function Ke(e=""){return`<link rel="icon" type="image/svg+xml" href="${`${e.replace(/\/$/,"")}/favicon-black.svg?v=4`}" />`}import{existsSync as Ge,readFileSync as Bt}from"fs";import U from"path";import{fileURLToPath as zt}from"url";import{gunzipSync as qt}from"zlib";var Ft={".js":"application/javascript",".css":"text/css",".svg":"image/svg+xml",".png":"image/png",".ico":"image/x-icon",".webmanifest":"application/manifest+json"};function Wt(){let e=U.dirname(zt(import.meta.url));for(let t of[U.resolve(e,"app"),U.resolve(e,"../app"),U.resolve(e,"../../dist/app")])if(Ge(U.join(t,"inspector.js.gz")))return t;throw new Error("Inspector bundle not found (expected dist/app/inspector.js.gz)")}function Je(e,t="/inspector/assets"){let r=Wt(),n=new Map;e.get(`${t}/*`,o=>{let s=o.req.path.slice(t.length),i=s.startsWith("/")?s.slice(1):s;if(!i||i.includes(".."))return o.notFound();let a=i==="inspector.js"||i==="inspector.css"?`${i}.gz`:i,c=U.resolve(r,a),l=r.endsWith(U.sep)?r:`${r}${U.sep}`;if(!c.startsWith(l)||!Ge(c))return o.notFound();let u=U.extname(i),p=a.endsWith(".gz"),g=/(?:^|,)\s*gzip\s*(?:,|$)/i.test(o.req.header("accept-encoding")??""),h=Bt(c),m=p&&!g?n.get(c)??Vt(n,c,h):h,d=m.buffer.slice(m.byteOffset,m.byteOffset+m.byteLength);return o.body(d,200,{"Content-Type":Ft[u]??"application/octet-stream",...p&&g?{"Content-Encoding":"gzip"}:{},...p?{Vary:"Accept-Encoding"}:{},"Cache-Control":"no-cache"})})}function Vt(e,t,r){let n=qt(r);return e.set(t,n),n}var Xe={name:"@mcp-use/inspector",type:"module",version:"20.0.0-beta.33",description:"MCP Inspector - A tool for inspecting and debugging MCP servers",author:"",license:"MIT",homepage:"https://github.com/mcp-use/mcp-use#readme",repository:{type:"git",url:"git+https://github.com/mcp-use/mcp-use.git",directory:"libraries/typescript/packages/inspector"},bugs:{url:"https://github.com/mcp-use/mcp-use/issues"},keywords:["mcp","inspector","debug","tools"],exports:{".":{types:"./dist/server/index.d.ts",import:"./dist/server/index.js"},"./client":{types:"./dist/client/index.d.ts",import:"./dist/client/index.js"}},main:"./dist/server/index.js",types:"./dist/server/index.d.ts",bin:{"mcp-inspect":"./dist/cli.js"},files:["dist"],scripts:{dev:"rimraf node_modules/.vite && VITE_MANUFACT_CHAT_URL=${VITE_MANUFACT_CHAT_URL:-http://localhost:8000/api/v1/inspector/chat/stream} vite --strictPort","dev:client":"pnpm run dev","dev:server":"VITE_DEV=true tsx watch src/server/server.ts","dev:standalone":"tsx watch src/server/server.ts",clean:"rimraf dist",build:"npm run clean && npm run build:client-exports && npm run build:server && npm run build:app && npm run verify:package","build:app":"vite build --config vite.app.config.ts && node scripts/compress-app.mjs","watch:app":"vite build --watch --config vite.app.config.ts","preview:app":"vite preview --config vite.app.config.ts --host 127.0.0.1","serve:app":"pnpm build:app && pnpm preview:app","analyze:app":"ANALYZE=true vite build --config vite.app.config.ts","build:client-exports":"tsup --config tsup.client.ts","build:server":"tsup --config tsup.server.ts","verify:package":"node scripts/verify-package.mjs",prepublishOnly:"pnpm --filter @mcp-use/client build && pnpm build",start:"node dist/cli.js --port 3000",preview:"vite preview","type-check":"tsc --noEmit",lint:"eslint .","lint:fix":"eslint . --fix","test:e2e":"playwright test","test:e2e:ui":"playwright test --ui","test:e2e:debug":"playwright test --debug","test:e2e:builtin":"node tests/e2e/scripts/run-test-matrix.mjs builtin","test:e2e:prod":"node tests/e2e/scripts/run-test-matrix.mjs prod","test:e2e:mix":"node tests/e2e/scripts/run-test-matrix.mjs mix","test:e2e:prod:ui":"TEST_MODE=production playwright test --ui","test:e2e:codegen":"playwright codegen http://localhost:3000/inspector","test:e2e:report":"playwright show-report","test:e2e:python":"node tests/e2e/scripts/run-python-e2e.mjs","test:unit":"vitest run","test:unit:watch":"vitest","test:e2e:tunnel":"node tests/e2e/scripts/run-tunnel-test.mjs","install:pnpm":"pnpm install","install:npm":"npm install","lint:npm":"npm run lint:fix","lint:pnpm":"pnpm lint:fix"},engines:{node:">=22.22.2"},peerDependencies:{"@base-ui/react":"^1.6.0","@mcp-use/agent":"^2.0.0-alpha.0","@mcp-use/client":"^2.0.0-alpha.0","class-variance-authority":"^0.7.1",clsx:"^2.1.1",express:"^4.21.2 || ^5.0.0","lucide-react":"^0.562.0","markdown-to-jsx":"^9.7.4","mcp-use":"workspace:*",motion:"^12.34.2",react:"^18.0.0 || ^19.0.0","react-dom":"^18.0.0 || ^19.0.0","react-resizable-panels":"^4.6.4",sonner:"^2.0.7","tailwind-merge":"^3.5.0"},peerDependenciesMeta:{"@base-ui/react":{optional:!0},"@mcp-use/agent":{optional:!0},"@mcp-use/client":{optional:!0},"class-variance-authority":{optional:!0},clsx:{optional:!0},express:{optional:!0},"lucide-react":{optional:!0},"markdown-to-jsx":{optional:!0},motion:{optional:!0},react:{optional:!0},"react-dom":{optional:!0},"react-resizable-panels":{optional:!0},sonner:{optional:!0},"tailwind-merge":{optional:!0}},dependencies:{},publishConfig:{access:"public"},devDependencies:{"@base-ui/react":"^1.6.0","@hono/node-server":"^1.19.13","@mcp-use/agent":"workspace:*","@mcp-use/client":"workspace:*","@playwright/test":"^1.58.2","@tailwindcss/vite":"^4.2.0","@types/express":"^5.0.6","@vitejs/plugin-react":"^6.0.0","class-variance-authority":"^0.7.1",clsx:"^2.1.1",emulate:"0.5.0",eslint:"^9.39.2",express:"^5.2.1",hono:"^4.12.12","lucide-react":"^0.562.0","markdown-to-jsx":"^9.7.4",motion:"^12.34.2","oauth2-mock-server":"^8.2.2",open:"^11.0.0",react:"^19.2.3","react-dom":"^19.2.3","react-router":"^7.12.0","react-resizable-panels":"^4.6.4","rollup-plugin-visualizer":"^6.0.3",sonner:"^2.0.7","tailwind-merge":"^3.5.0",tailwindcss:"^4.2.0",tsup:"^8.5.1",tsx:"^4.21.0","tw-animate-css":"^1.4.0",typescript:"^5.9.3",vite:"^8.0.16",vitest:"^4.1.0","wait-on":"^9.0.4",zod:"^4.2.0"}};var Gt=Xe.version;function Ye(){return Gt}var Qe=Ye(),Jt=`<!doctype html>
1
+ var Kt=Object.create;var Me=Object.defineProperty;var Vt=Object.getOwnPropertyDescriptor;var Gt=Object.getOwnPropertyNames;var Jt=Object.getPrototypeOf,Yt=Object.prototype.hasOwnProperty;var $=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports);var Xt=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Gt(e))!Yt.call(t,o)&&o!==r&&Me(t,o,{get:()=>e[o],enumerable:!(n=Vt(e,o))||n.enumerable});return t};var Qt=(t,e,r)=>(r=t!=null?Kt(Jt(t)):{},Xt(e||!t||!t.__esModule?Me(r,"default",{value:t,enumerable:!0}):r,t));var rt=$((Lo,tt)=>{"use strict";tt.exports=class{constructor(e={}){this.points=e.points,this.duration=e.duration,this.blockDuration=e.blockDuration,this.execEvenly=e.execEvenly,this.execEvenlyMinDelayMs=e.execEvenlyMinDelayMs,this.keyPrefix=e.keyPrefix}get points(){return this._points}set points(e){if(Number.isFinite(e))this._points=e;else throw new Error("points must be set and must be a finite number")}get duration(){return this._duration}set duration(e){if(typeof e=="number"&&Number.isFinite(e)&&e>=0)this._duration=e;else throw new Error("duration must be set and must be a finite, non-negative number")}get msDuration(){return this.duration*1e3}get blockDuration(){return this._blockDuration}set blockDuration(e){this._blockDuration=typeof e>"u"?0:e}get msBlockDuration(){return this.blockDuration*1e3}get execEvenly(){return this._execEvenly}set execEvenly(e){this._execEvenly=typeof e>"u"?!1:!!e}get execEvenlyMinDelayMs(){return this._execEvenlyMinDelayMs===void 0?this._getExecEvenlyMinDelayMsDefault():this._execEvenlyMinDelayMs}set execEvenlyMinDelayMs(e){this._execEvenlyMinDelayMs=e}_getExecEvenlyMinDelayMsDefault(){return this.points>0?Math.ceil(this.msDuration/this.points):0}get keyPrefix(){return this._keyPrefix}set keyPrefix(e){if(typeof e>"u"&&(e="rlflx"),typeof e!="string")throw new Error("keyPrefix must be string");this._keyPrefix=e}_getKeySecDuration(e={}){return e&&e.customDuration>=0?e.customDuration:this.duration}getKey(e){return this.keyPrefix.length>0?`${this.keyPrefix}:${e}`:e}parseKey(e){return this.keyPrefix.length>0?e.substring(this.keyPrefix.length+1):e}consume(){throw new Error("You have to implement the method 'consume'!")}penalty(){throw new Error("You have to implement the method 'penalty'!")}reward(){throw new Error("You have to implement the method 'reward'!")}get(){throw new Error("You have to implement the method 'get'!")}set(){throw new Error("You have to implement the method 'set'!")}block(){throw new Error("You have to implement the method 'block'!")}delete(){throw new Error("You have to implement the method 'delete'!")}}});var ot=$((jo,nt)=>{"use strict";nt.exports=class{constructor(e,r,n=null){this.value=e,this.expiresAt=r,this.timeoutId=n}get value(){return this._value}set value(e){this._value=parseInt(e,10)}get expiresAt(){return this._expiresAt}set expiresAt(e){e instanceof Date?this._expiresAt=e.getTime():this._expiresAt=e}get timeoutId(){return this._timeoutId}set timeoutId(e){this._timeoutId=e}}});var xe=$((Do,st)=>{"use strict";st.exports=class{constructor(e,r,n,o){this.remainingPoints=typeof e>"u"?0:e,this.msBeforeNext=typeof r>"u"?0:r,this.consumedPoints=typeof n>"u"?0:n,this.isFirstInDuration=typeof o>"u"?!1:o}get msBeforeNext(){return this._msBeforeNext}set msBeforeNext(e){return this._msBeforeNext=e,this}get remainingPoints(){return this._remainingPoints}set remainingPoints(e){return this._remainingPoints=e,this}get consumedPoints(){return this._consumedPoints}set consumedPoints(e){return this._consumedPoints=e,this}get isFirstInDuration(){return this._isFirstInDuration}set isFirstInDuration(e){this._isFirstInDuration=!!e}_getDecoratedProperties(){return{remainingPoints:this.remainingPoints,msBeforeNext:this.msBeforeNext,consumedPoints:this.consumedPoints,isFirstInDuration:this.isFirstInDuration}}[Symbol.for("nodejs.util.inspect.custom")](){return this._getDecoratedProperties()}toString(){return JSON.stringify(this._getDecoratedProperties())}toJSON(){return this._getDecoratedProperties()}}});var ct=$(($o,at)=>{"use strict";var it=ot(),be=xe();at.exports=class{constructor(){this._storage=new Map}incrby(e,r,n){let o=this._storage.get(e);if(o){let s=o.expiresAt?o.expiresAt-Date.now():-1;return!o.expiresAt||s>0?(o.value=o.value+r,new be(0,s,o.value,!1)):this.set(e,r,n)}return this.set(e,r,n)}set(e,r,n){let o=n*1e3,s=this._storage.get(e);s&&s.timeoutId&&clearTimeout(s.timeoutId);let i=new it(r,o>0?Date.now()+o:null);return this._storage.set(e,i),o>0&&(i.timeoutId=setTimeout(()=>{this._storage.delete(e)},o),i.timeoutId.unref&&i.timeoutId.unref()),new be(0,o===0?-1:o,i.value,!0)}get(e){let r=this._storage.get(e);if(r){let n=r.expiresAt?r.expiresAt-Date.now():-1;return new be(0,n,r.value,!1)}return null}delete(e){let r=this._storage.get(e);return r?(r.timeoutId&&clearTimeout(r.timeoutId),this._storage.delete(e),!0):!1}_restoreRecord(e,r,n){let o=Date.now(),s=n!==null;if(s&&!Number.isFinite(n)||s&&n<=o)return;let i=s?n-o:0,a=this._storage.get(e);a&&a.timeoutId&&clearTimeout(a.timeoutId);let c=new it(r,n);this._storage.set(e,c),i>0&&(c.timeoutId=setTimeout(()=>{this._storage.delete(e)},i),c.timeoutId.unref&&c.timeoutId.unref())}}});var dt=$((Bo,ut)=>{"use strict";var mr=rt(),gr=ct(),lt=xe(),Re=class extends mr{constructor(e={}){super(e),this._memoryStorage=new gr}consume(e,r=1,n={}){return new Promise((o,s)=>{let i=this.getKey(e),a=this._getKeySecDuration(n),c=this._memoryStorage.incrby(i,r,a);if(c.remainingPoints=Math.max(this.points-c.consumedPoints,0),c.consumedPoints>this.points)this.blockDuration>0&&c.consumedPoints<=this.points+r&&(c=this._memoryStorage.set(i,c.consumedPoints,this.blockDuration)),s(c);else if(this.execEvenly&&this.points>0&&c.msBeforeNext>0&&!c.isFirstInDuration){let l=Math.ceil(c.msBeforeNext/(c.remainingPoints+2));l<this.execEvenlyMinDelayMs&&(l=c.consumedPoints*this.execEvenlyMinDelayMs),c.msBeforeNext=Math.max(c.msBeforeNext-l,0),setTimeout(o,l,c)}else o(c)})}penalty(e,r=1,n={}){let o=this.getKey(e);return new Promise(s=>{let i=this._getKeySecDuration(n),a=this._memoryStorage.incrby(o,r,i);a.remainingPoints=Math.max(this.points-a.consumedPoints,0),s(a)})}reward(e,r=1,n={}){let o=this.getKey(e);return new Promise(s=>{let i=this._getKeySecDuration(n),a=this._memoryStorage.incrby(o,-r,i);a.remainingPoints=Math.max(this.points-a.consumedPoints,0),s(a)})}block(e,r){let n=r*1e3,o=this.points+1;return this._memoryStorage.set(this.getKey(e),o,r),Promise.resolve(new lt(0,n===0?-1:n,o))}set(e,r,n){let o=(n>=0?n:this.duration)*1e3;return this._memoryStorage.set(this.getKey(e),r,n),Promise.resolve(new lt(0,o===0?-1:o,r))}get(e){let r=this._memoryStorage.get(this.getKey(e));return r!==null&&(r.remainingPoints=Math.max(this.points-r.consumedPoints,0)),Promise.resolve(r)}delete(e){return Promise.resolve(this._memoryStorage.delete(this.getKey(e)))}dump(){let e=[];for(let[r,n]of this._memoryStorage._storage)e.push({key:this.parseKey(r),value:n.value,expiresAt:n.expiresAt});return{version:1,dumpedAt:Date.now(),storage:e}}restore(e,r=!1){if(!e||typeof e!="object"||e.version!==1)return;let n=r?{invalid:{count:0,keys:[]},expired:{count:0,keys:[]},restored:{count:0,keys:[]}}:{invalid:0,expired:0,restored:0},o=(s,i)=>{r?(n[s].count+=1,n[s].keys.push(i)):n[s]+=1};if(!Array.isArray(e.storage))return n;for(let s of e.storage){if(!s||typeof s!="object"){o("invalid","N/A");continue}let i=typeof s.key=="string"||typeof s.key=="number",a=Number.isFinite(s.value),c=s.expiresAt===null||Number.isFinite(s.expiresAt);if(!i||!a||!c){o("invalid",s.key);continue}if(s.expiresAt!==null&&s.expiresAt<=Date.now()){o("expired",s.key);continue}this._memoryStorage._restoreRecord(this.getKey(s.key),s.value,s.expiresAt),o("restored",s.key)}return n}};ut.exports=Re});var ie=(t,e,r)=>(n,o)=>{let s=-1;return i(0);async function i(a){if(a<=s)throw new Error("next() called multiple times");s=a;let c,l=!1,u;if(t[a]?(u=t[a][0][0],n.req.routeIndex=a):u=a===t.length&&o||void 0,u)try{c=await u(n,()=>i(a+1))}catch(h){if(h instanceof Error&&e)n.error=h,c=await e(h,n),l=!0;else throw h}else n.finalized===!1&&r&&(c=await r(n));return c&&(n.finalized===!1||l)&&(n.res=c),n}};var Te=Symbol();var ke=async(t,e=Object.create(null))=>{let{all:r=!1,dot:n=!1}=e,s=(t instanceof W?t.raw.headers:t.headers).get("Content-Type");return s?.startsWith("multipart/form-data")||s?.startsWith("application/x-www-form-urlencoded")?Zt(t,{all:r,dot:n}):{}};async function Zt(t,e){let r=await t.formData();return r?er(r,e):{}}function er(t,e){let r=Object.create(null);return t.forEach((n,o)=>{e.all||o.endsWith("[]")?tr(r,o,n):r[o]=n}),e.dot&&Object.entries(r).forEach(([n,o])=>{n.includes(".")&&(rr(r,n,o),delete r[n])}),r}var tr=(t,e,r)=>{t[e]!==void 0?Array.isArray(t[e])?t[e].push(r):t[e]=[t[e],r]:e.endsWith("[]")?t[e]=[r]:t[e]=r},rr=(t,e,r)=>{if(/(?:^|\.)__proto__\./.test(e))return;let n=t,o=e.split(".");o.forEach((s,i)=>{i===o.length-1?n[s]=r:((!n[s]||typeof n[s]!="object"||Array.isArray(n[s])||n[s]instanceof File)&&(n[s]=Object.create(null)),n=n[s])})};var ce=t=>{let e=t.split("/");return e[0]===""&&e.shift(),e},Le=t=>{let{groups:e,path:r}=nr(t),n=ce(r);return or(n,e)},nr=t=>{let e=[];return t=t.replace(/\{[^}]+\}/g,(r,n)=>{let o=`@${n}`;return e.push([o,r]),o}),{groups:e,path:t}},or=(t,e)=>{for(let r=e.length-1;r>=0;r--){let[n]=e[r];for(let o=t.length-1;o>=0;o--)if(t[o].includes(n)){t[o]=t[o].replace(n,e[r][1]);break}}return t},K={},Ue=(t,e)=>{if(t==="*")return"*";let r=t.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);if(r){let n=`${t}#${e}`;return K[n]||(r[2]?K[n]=e&&e[0]!==":"&&e[0]!=="*"?[n,r[1],new RegExp(`^${r[2]}(?=/${e})`)]:[t,r[1],new RegExp(`^${r[2]}$`)]:K[n]=[t,r[1],!0]),K[n]}return null},V=(t,e)=>{try{return e(t)}catch{return t.replace(/(?:%[0-9A-Fa-f]{2})+/g,r=>{try{return e(r)}catch{return r}})}},sr=t=>V(t,decodeURI),le=t=>{let e=t.url,r=e.indexOf("/",e.indexOf(":")+4),n=r;for(;n<e.length;n++){let o=e.charCodeAt(n);if(o===37){let s=e.indexOf("?",n),i=e.indexOf("#",n),a=s===-1?i===-1?void 0:i:i===-1?s:Math.min(s,i),c=e.slice(r,a);return sr(c.includes("%25")?c.replace(/%25/g,"%2525"):c)}else if(o===63||o===35)break}return e.slice(r,n)};var je=t=>{let e=le(t);return e.length>1&&e.at(-1)==="/"?e.slice(0,-1):e},k=(t,e,...r)=>(r.length&&(e=k(e,...r)),`${t?.[0]==="/"?"":"/"}${t}${e==="/"?"":`${t?.at(-1)==="/"?"":"/"}${e?.[0]==="/"?e.slice(1):e}`}`),G=t=>{if(t.charCodeAt(t.length-1)!==63||!t.includes(":"))return null;let e=t.split("/"),r=[],n="";return e.forEach(o=>{if(o!==""&&!/\:/.test(o))n+="/"+o;else if(/\:/.test(o))if(/\?/.test(o)){r.length===0&&n===""?r.push("/"):r.push(n);let s=o.replace("?","");n+="/"+s,r.push(n)}else n+="/"+o}),r.filter((o,s,i)=>i.indexOf(o)===s)},ae=t=>/[%+]/.test(t)?(t.indexOf("+")!==-1&&(t=t.replace(/\+/g," ")),t.indexOf("%")!==-1?V(t,ue):t):t,Ne=(t,e,r)=>{let n;if(!r&&e&&!/[%+]/.test(e)){let i=t.indexOf("?",8);if(i===-1)return;for(t.startsWith(e,i+1)||(i=t.indexOf(`&${e}`,i+1));i!==-1;){let a=t.charCodeAt(i+e.length+1);if(a===61){let c=i+e.length+2,l=t.indexOf("&",c);return ae(t.slice(c,l===-1?void 0:l))}else if(a==38||isNaN(a))return"";i=t.indexOf(`&${e}`,i+1)}if(n=/[%+]/.test(t),!n)return}let o={};n??=/[%+]/.test(t);let s=t.indexOf("?",8);for(;s!==-1;){let i=t.indexOf("&",s+1),a=t.indexOf("=",s);a>i&&i!==-1&&(a=-1);let c=t.slice(s+1,a===-1?i===-1?void 0:i:a);if(n&&(c=ae(c)),s=i,c==="")continue;let l;a===-1?l="":(l=t.slice(a+1,i===-1?void 0:i),n&&(l=ae(l))),r?(o[c]&&Array.isArray(o[c])||(o[c]=[]),o[c].push(l)):o[c]??=l}return e?o[e]:o},De=Ne,He=(t,e)=>Ne(t,e,!0),ue=decodeURIComponent;var $e=t=>V(t,ue),W=class{raw;#t;#e;routeIndex=0;path;bodyCache={};constructor(t,e="/",r=[[]]){this.raw=t,this.path=e,this.#e=r,this.#t={}}param(t){return t?this.#r(t):this.#s()}#r(t){let e=this.#e[0][this.routeIndex][1][t],r=this.#o(e);return r&&/\%/.test(r)?$e(r):r}#s(){let t={},e=Object.keys(this.#e[0][this.routeIndex][1]);for(let r of e){let n=this.#o(this.#e[0][this.routeIndex][1][r]);n!==void 0&&(t[r]=/\%/.test(n)?$e(n):n)}return t}#o(t){return this.#e[1]?this.#e[1][t]:t}query(t){return De(this.url,t)}queries(t){return He(this.url,t)}header(t){if(t)return this.raw.headers.get(t)??void 0;let e={};return this.raw.headers.forEach((r,n)=>{e[n]=r}),e}async parseBody(t){return ke(this,t)}#n=t=>{let{bodyCache:e,raw:r}=this,n=e[t];if(n)return n;let o=Object.keys(e)[0];return o?e[o].then(s=>(o==="json"&&(s=JSON.stringify(s)),new Response(s)[t]())):e[t]=r[t]()};json(){return this.#n("text").then(t=>JSON.parse(t))}text(){return this.#n("text")}arrayBuffer(){return this.#n("arrayBuffer")}bytes(){return this.#n("arrayBuffer").then(t=>new Uint8Array(t))}blob(){return this.#n("blob")}formData(){return this.#n("formData")}addValidatedData(t,e){this.#t[t]=e}valid(t){return this.#t[t]}get url(){return this.raw.url}get method(){return this.raw.method}get[Te](){return this.#e}get matchedRoutes(){return this.#e[0].map(([[,t]])=>t)}get routePath(){return this.#e[0].map(([[,t]])=>t)[this.routeIndex].path}};var Be={Stringify:1,BeforeStream:2,Stream:3},ir=(t,e)=>{let r=new String(t);return r.isEscaped=!0,r.callbacks=e,r};var de=async(t,e,r,n,o)=>{typeof t=="object"&&!(t instanceof String)&&(t instanceof Promise||(t=t.toString()),t instanceof Promise&&(t=await t));let s=t.callbacks;if(!s?.length)return Promise.resolve(t);o?o[0]+=t:o=[t];let i=Promise.all(s.map(a=>a({phase:e,buffer:o,context:n}))).then(a=>Promise.all(a.filter(Boolean).map(c=>de(c,e,!1,n,o))).then(()=>o[0]));return r?ir(await i,s):i};var ar="text/plain; charset=UTF-8",he=(t,e)=>({"Content-Type":t,...e}),B=(t,e)=>new Response(t,e),pe=class{#t;#e;env={};#r;finalized=!1;error;#s;#o;#n;#u;#c;#l;#a;#d;#h;constructor(t,e){this.#t=t,e&&(this.#o=e.executionCtx,this.env=e.env,this.#l=e.notFoundHandler,this.#h=e.path,this.#d=e.matchResult)}get req(){return this.#e??=new W(this.#t,this.#h,this.#d),this.#e}get event(){if(this.#o&&"respondWith"in this.#o)return this.#o;throw Error("This context has no FetchEvent")}get executionCtx(){if(this.#o)return this.#o;throw Error("This context has no ExecutionContext")}get res(){return this.#n||=B(null,{headers:this.#a??=new Headers})}set res(t){if(this.#n&&t){t=B(t.body,t);for(let[e,r]of this.#n.headers.entries())if(e!=="content-type")if(e==="set-cookie"){let n=this.#n.headers.getSetCookie();t.headers.delete("set-cookie");for(let o of n)t.headers.append("set-cookie",o)}else t.headers.set(e,r)}this.#n=t,this.finalized=!0}render=(...t)=>(this.#c??=e=>this.html(e),this.#c(...t));setLayout=t=>this.#u=t;getLayout=()=>this.#u;setRenderer=t=>{this.#c=t};header=(t,e,r)=>{this.finalized&&(this.#n=B(this.#n.body,this.#n));let n=this.#n?this.#n.headers:this.#a??=new Headers;e===void 0?n.delete(t):r?.append?n.append(t,e):n.set(t,e)};status=t=>{this.#s=t};set=(t,e)=>{this.#r??=new Map,this.#r.set(t,e)};get=t=>this.#r?this.#r.get(t):void 0;get var(){return this.#r?Object.fromEntries(this.#r):{}}#i(t,e,r){let n=this.#n?new Headers(this.#n.headers):this.#a??new Headers;if(typeof e=="object"&&"headers"in e){let s=e.headers instanceof Headers?e.headers:new Headers(e.headers);for(let[i,a]of s)i.toLowerCase()==="set-cookie"?n.append(i,a):n.set(i,a)}if(r)for(let[s,i]of Object.entries(r))if(typeof i=="string")n.set(s,i);else{n.delete(s);for(let a of i)n.append(s,a)}let o=typeof e=="number"?e:e?.status??this.#s;return B(t,{status:o,headers:n})}newResponse=(...t)=>this.#i(...t);body=(t,e,r)=>this.#i(t,e,r);text=(t,e,r)=>!this.#a&&!this.#s&&!e&&!r&&!this.finalized?new Response(t):this.#i(t,e,he(ar,r));json=(t,e,r)=>this.#i(JSON.stringify(t),e,he("application/json",r));html=(t,e,r)=>{let n=o=>this.#i(o,e,he("text/html; charset=UTF-8",r));return typeof t=="object"?de(t,Be.Stringify,!1,{}).then(n):n(t)};redirect=(t,e)=>{let r=String(t);return this.header("Location",/[^\x00-\xFF]/.test(r)?encodeURI(r):r),this.newResponse(null,e??302)};notFound=()=>(this.#l??=()=>B(),this.#l(this))};var w="ALL",Fe="all",qe=["get","post","put","delete","options","patch"],J="Can not add a route since the matcher is already built.",Y=class extends Error{};var ze="__COMPOSED_HANDLER";var cr=t=>t.text("404 Not Found",404),We=(t,e)=>{if("getResponse"in t){let r=t.getResponse();return e.newResponse(r.body,r)}return console.error(t),e.text("Internal Server Error",500)},Ke=class Ve{get;post;put;delete;options;patch;all;on;use;router;getPath;_basePath="/";#t="/";routes=[];constructor(e={}){[...qe,Fe].forEach(s=>{this[s]=(i,...a)=>(typeof i=="string"?this.#t=i:this.#s(s,this.#t,i),a.forEach(c=>{this.#s(s,this.#t,c)}),this)}),this.on=(s,i,...a)=>{for(let c of[i].flat()){this.#t=c;for(let l of[s].flat())a.map(u=>{this.#s(l.toUpperCase(),this.#t,u)})}return this},this.use=(s,...i)=>(typeof s=="string"?this.#t=s:(this.#t="*",i.unshift(s)),i.forEach(a=>{this.#s(w,this.#t,a)}),this);let{strict:n,...o}=e;Object.assign(this,o),this.getPath=n??!0?e.getPath??le:je}#e(){let e=new Ve({router:this.router,getPath:this.getPath});return e.errorHandler=this.errorHandler,e.#r=this.#r,e.routes=this.routes,e}#r=cr;errorHandler=We;route(e,r){let n=this.basePath(e);return r.routes.map(o=>{let s;r.errorHandler===We?s=o.handler:(s=async(i,a)=>(await ie([],r.errorHandler)(i,()=>o.handler(i,a))).res,s[ze]=o.handler),n.#s(o.method,o.path,s,o.basePath)}),this}basePath(e){let r=this.#e();return r._basePath=k(this._basePath,e),r}onError=e=>(this.errorHandler=e,this);notFound=e=>(this.#r=e,this);mount(e,r,n){let o,s;n&&(typeof n=="function"?s=n:(s=n.optionHandler,n.replaceRequest===!1?o=c=>c:o=n.replaceRequest));let i=s?c=>{let l=s(c);return Array.isArray(l)?l:[l]}:c=>{let l;try{l=c.executionCtx}catch{}return[c.env,l]};o||=(()=>{let c=k(this._basePath,e),l=c==="/"?0:c.length;return u=>{let h=new URL(u.url);return h.pathname=this.getPath(u).slice(l)||"/",new Request(h,u)}})();let a=async(c,l)=>{let u=await r(o(c.req.raw),...i(c));if(u)return u;await l()};return this.#s(w,k(e,"*"),a),this}#s(e,r,n,o){e=e.toUpperCase(),r=k(this._basePath,r);let s={basePath:o!==void 0?k(this._basePath,o):this._basePath,path:r,method:e,handler:n};this.router.add(e,r,[n,s]),this.routes.push(s)}#o(e,r){if(e instanceof Error)return this.errorHandler(e,r);throw e}#n(e,r,n,o){if(o==="HEAD")return(async()=>new Response(null,await this.#n(e,r,n,"GET")))();let s=this.getPath(e,{env:n}),i=this.router.match(o,s),a=new pe(e,{path:s,matchResult:i,env:n,executionCtx:r,notFoundHandler:this.#r});if(i[0].length===1){let l;try{l=i[0][0][0][0](a,async()=>{a.res=await this.#r(a)})}catch(u){return this.#o(u,a)}return l instanceof Promise?l.then(u=>u||(a.finalized?a.res:this.#r(a))).catch(u=>this.#o(u,a)):l??this.#r(a)}let c=ie(i[0],this.errorHandler,this.#r);return(async()=>{try{let l=await c(a);if(!l.finalized)throw new Error("Context is not finalized. Did you forget to return a Response object or `await next()`?");return l.res}catch(l){return this.#o(l,a)}})()}fetch=(e,...r)=>this.#n(e,r[1],r[0],e.method);request=(e,r,n,o)=>e instanceof Request?this.fetch(r?new Request(e,r):e,n,o):(e=e.toString(),this.fetch(new Request(/^https?:\/\//.test(e)?e:`http://localhost${k("/",e)}`,r),n,o));fire=()=>{addEventListener("fetch",e=>{e.respondWith(this.#n(e.request,e,void 0,e.request.method))})}};var X=[];function fe(t,e){let r=this.buildAllMatchers(),n=((o,s)=>{let i=r[o]||r[w],a=i[2][s];if(a)return a;let c=s.match(i[0]);if(!c)return[[],X];let l=c.indexOf("",1);return[i[1][l],c]});return this.match=n,n(t,e)}var Q="[^/]+",F=".*",q="(?:|/.*)",U=Symbol(),lr=new Set(".\\+*[^]$()");function ur(t,e){return t.length===1?e.length===1?t<e?-1:1:-1:e.length===1||t===F||t===q?1:e===F||e===q?-1:t===Q?1:e===Q?-1:t.length===e.length?t<e?-1:1:e.length-t.length}var Ge=class me{#t;#e;#r=Object.create(null);insert(e,r,n,o,s){if(e.length===0){if(this.#t!==void 0)throw U;if(s)return;this.#t=r;return}let[i,...a]=e,c=i==="*"?a.length===0?["","",F]:["","",Q]:i==="/*"?["","",q]:i.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/),l;if(c){let u=c[1],h=c[2]||Q;if(u&&c[2]&&(h===".*"||(h=h.replace(/^\((?!\?:)(?=[^)]+\)$)/,"(?:"),/\((?!\?:)/.test(h))))throw U;if(l=this.#r[h],!l){if(Object.keys(this.#r).some(m=>m!==F&&m!==q))throw U;if(s)return;l=this.#r[h]=new me,u!==""&&(l.#e=o.varIndex++)}!s&&u!==""&&n.push([u,l.#e])}else if(l=this.#r[i],!l){if(Object.keys(this.#r).some(u=>u.length>1&&u!==F&&u!==q))throw U;if(s)return;l=this.#r[i]=new me}l.insert(a,r,n,o,s)}buildRegExpStr(){let r=Object.keys(this.#r).sort(ur).map(n=>{let o=this.#r[n];return(typeof o.#e=="number"?`(${n})@${o.#e}`:lr.has(n)?`\\${n}`:n)+o.buildRegExpStr()});return typeof this.#t=="number"&&r.unshift(`#${this.#t}`),r.length===0?"":r.length===1?r[0]:"(?:"+r.join("|")+")"}};var Je=class{#t={varIndex:0};#e=new Ge;insert(t,e,r){let n=[],o=[];for(let i=0;;){let a=!1;if(t=t.replace(/\{[^}]+\}/g,c=>{let l=`@\\${i}`;return o[i]=[l,c],i++,a=!0,l}),!a)break}let s=t.match(/(?::[^\/]+)|(?:\/\*$)|./g)||[];for(let i=o.length-1;i>=0;i--){let[a]=o[i];for(let c=s.length-1;c>=0;c--)if(s[c].indexOf(a)!==-1){s[c]=s[c].replace(a,o[i][1]);break}}return this.#e.insert(s,e,n,this.#t,r),n}buildRegExp(){let t=this.#e.buildRegExpStr();if(t==="")return[/^$/,[],[]];let e=0,r=[],n=[];return t=t.replace(/#(\d+)|@(\d+)|\.\*\$/g,(o,s,i)=>s!==void 0?(r[++e]=Number(s),"$()"):(i!==void 0&&(n[Number(i)]=++e),"")),[new RegExp(`^${t}`),r,n]}};var dr=[/^$/,[],Object.create(null)],Ye=Object.create(null);function Xe(t){return Ye[t]??=new RegExp(t==="*"?"":`^${t.replace(/\/\*$|([.\\+*[^\]$()])/g,(e,r)=>r?`\\${r}`:"(?:|/.*)")}$`)}function hr(){Ye=Object.create(null)}function pr(t){let e=new Je,r=[];if(t.length===0)return dr;let n=t.map(l=>[!/\*|\/:/.test(l[0]),...l]).sort(([l,u],[h,m])=>l?1:h?-1:u.length-m.length),o=Object.create(null);for(let l=0,u=-1,h=n.length;l<h;l++){let[m,p,g]=n[l];m?o[p]=[g.map(([y])=>[y,Object.create(null)]),X]:u++;let d;try{d=e.insert(p,u,m)}catch(y){throw y===U?new Y(p):y}m||(r[u]=g.map(([y,f])=>{let R=Object.create(null);for(f-=1;f>=0;f--){let[A,C]=d[f];R[A]=C}return[y,R]}))}let[s,i,a]=e.buildRegExp();for(let l=0,u=r.length;l<u;l++)for(let h=0,m=r[l].length;h<m;h++){let p=r[l][h]?.[1];if(!p)continue;let g=Object.keys(p);for(let d=0,y=g.length;d<y;d++)p[g[d]]=a[p[g[d]]]}let c=[];for(let l in i)c[l]=r[i[l]];return[s,c,o]}function D(t,e){if(t){for(let r of Object.keys(t).sort((n,o)=>o.length-n.length))if(Xe(r).test(e))return[...t[r]]}}var Z=class{name="RegExpRouter";#t;#e;constructor(){this.#t={[w]:Object.create(null)},this.#e={[w]:Object.create(null)}}add(t,e,r){let n=this.#t,o=this.#e;if(!n||!o)throw new Error(J);n[t]||[n,o].forEach(a=>{a[t]=Object.create(null),Object.keys(a[w]).forEach(c=>{a[t][c]=[...a[w][c]]})}),e==="/*"&&(e="*");let s=(e.match(/\/:/g)||[]).length;if(/\*$/.test(e)){let a=Xe(e);t===w?Object.keys(n).forEach(c=>{n[c][e]||=D(n[c],e)||D(n[w],e)||[]}):n[t][e]||=D(n[t],e)||D(n[w],e)||[],Object.keys(n).forEach(c=>{(t===w||t===c)&&Object.keys(n[c]).forEach(l=>{a.test(l)&&n[c][l].push([r,s])})}),Object.keys(o).forEach(c=>{(t===w||t===c)&&Object.keys(o[c]).forEach(l=>a.test(l)&&o[c][l].push([r,s]))});return}let i=G(e)||[e];for(let a=0,c=i.length;a<c;a++){let l=i[a];Object.keys(o).forEach(u=>{(t===w||t===u)&&(o[u][l]||=[...D(n[u],l)||D(n[w],l)||[]],o[u][l].push([r,s-c+a+1]))})}}match=fe;buildAllMatchers(){let t=Object.create(null);return Object.keys(this.#e).concat(Object.keys(this.#t)).forEach(e=>{t[e]||=this.#r(e)}),this.#t=this.#e=void 0,hr(),t}#r(t){let e=[],r=t===w;return[this.#t,this.#e].forEach(n=>{let o=n[t]?Object.keys(n[t]).map(s=>[s,n[t][s]]):[];o.length!==0?(r||=!0,e.push(...o)):t!==w&&e.push(...Object.keys(n[w]).map(s=>[s,n[w][s]]))}),r?pr(e):null}};var ge=class{name="SmartRouter";#t=[];#e=[];constructor(t){this.#t=t.routers}add(t,e,r){if(!this.#e)throw new Error(J);this.#e.push([t,e,r])}match(t,e){if(!this.#e)throw new Error("Fatal error");let r=this.#t,n=this.#e,o=r.length,s=0,i;for(;s<o;s++){let a=r[s];try{for(let c=0,l=n.length;c<l;c++)a.add(...n[c]);i=a.match(t,e)}catch(c){if(c instanceof Y)continue;throw c}this.match=a.match.bind(a),this.#t=[a],this.#e=void 0;break}if(s===o)throw new Error("Fatal error");return this.name=`SmartRouter + ${this.activeRouter.name}`,i}get activeRouter(){if(this.#e||this.#t.length!==1)throw new Error("No active router has been determined yet.");return this.#t[0]}};var z=Object.create(null),fr=t=>{for(let e in t)return!0;return!1},Qe=class Ze{#t;#e;#r;#s=0;#o=z;constructor(e,r,n){if(this.#e=n||Object.create(null),this.#t=[],e&&r){let o=Object.create(null);o[e]={handler:r,possibleKeys:[],score:0},this.#t=[o]}this.#r=[]}insert(e,r,n){this.#s=++this.#s;let o=this,s=Le(r),i=[];for(let a=0,c=s.length;a<c;a++){let l=s[a],u=s[a+1],h=Ue(l,u),m=Array.isArray(h)?h[0]:l;if(m in o.#e){o=o.#e[m],h&&i.push(h[1]);continue}o.#e[m]=new Ze,h&&(o.#r.push(h),i.push(h[1])),o=o.#e[m]}return o.#t.push({[e]:{handler:n,possibleKeys:i.filter((a,c,l)=>l.indexOf(a)===c),score:this.#s}}),o}#n(e,r,n,o,s){for(let i=0,a=r.#t.length;i<a;i++){let c=r.#t[i],l=c[n]||c[w],u={};if(l!==void 0&&(l.params=Object.create(null),e.push(l),o!==z||s&&s!==z))for(let h=0,m=l.possibleKeys.length;h<m;h++){let p=l.possibleKeys[h],g=u[l.score];l.params[p]=s?.[p]&&!g?s[p]:o[p]??s?.[p],u[l.score]=!0}}}search(e,r){let n=[];this.#o=z;let s=[this],i=ce(r),a=[],c=i.length,l=null;for(let u=0;u<c;u++){let h=i[u],m=u===c-1,p=[];for(let d=0,y=s.length;d<y;d++){let f=s[d],R=f.#e[h];R&&(R.#o=f.#o,m?(R.#e["*"]&&this.#n(n,R.#e["*"],e,f.#o),this.#n(n,R,e,f.#o)):p.push(R));for(let A=0,C=f.#r.length;A<C;A++){let v=f.#r[A],x=f.#o===z?{}:{...f.#o};if(v==="*"){let M=f.#e["*"];M&&(this.#n(n,M,e,f.#o),M.#o=x,p.push(M));continue}let[_,b,P]=v;if(!h&&!(P instanceof RegExp))continue;let E=f.#e[_];if(P instanceof RegExp){if(l===null){l=new Array(c);let N=r[0]==="/"?1:0;for(let O=0;O<c;O++)l[O]=N,N+=i[O].length+1}let M=r.substring(l[u]),H=P.exec(M);if(H){if(x[b]=H[0],this.#n(n,E,e,f.#o,x),fr(E.#e)){E.#o=x;let N=H[0].match(/\//)?.length??0;(a[N]||=[]).push(E)}continue}}(P===!0||P.test(h))&&(x[b]=h,m?(this.#n(n,E,e,x,f.#o),E.#e["*"]&&this.#n(n,E.#e["*"],e,x,f.#o)):(E.#o=x,p.push(E)))}}let g=a.shift();s=g?p.concat(g):p}return n.length>1&&n.sort((u,h)=>u.score-h.score),[n.map(({handler:u,params:h})=>[u,h])]}};var ye=class{name="TrieRouter";#t;constructor(){this.#t=new Qe}add(t,e,r){let n=G(e);if(n){for(let o=0,s=n.length;o<s;o++)this.#t.insert(t,n[o],r);return}this.#t.insert(t,e,r)}match(t,e){return this.#t.search(t,e)}};var we=class extends Ke{constructor(t={}){super(t),this.router=t.router??new ge({routers:[new Z,new ye]})}};import{Readable as rn}from"stream";function et(t=""){return`<link rel="icon" type="image/svg+xml" href="${`${t.replace(/\/$/,"")}/favicon-black.svg?v=4`}" />`}import{existsSync as mt,readFileSync as wr}from"fs";import T from"path";import{fileURLToPath as xr}from"url";import{gunzipSync as br}from"zlib";var ht=Qt(dt(),1),pt=600,ft=120,ee=60;function te(t){let e=new ht.default({points:t.points,duration:t.durationSeconds});return async(r,n)=>{try{await e.consume(t.key)}catch(o){return r.header("Retry-After",String(yr(o))),r.json({error:"Too Many Requests"},429)}await n()}}function yr(t){return t&&typeof t=="object"&&"msBeforeNext"in t&&typeof t.msBeforeNext=="number"?Math.max(1,Math.ceil(t.msBeforeNext/1e3)):60}var Rr={".js":"application/javascript",".css":"text/css",".svg":"image/svg+xml",".png":"image/png",".ico":"image/x-icon",".webmanifest":"application/manifest+json"};function vr(){let t=T.dirname(xr(import.meta.url));for(let e of[T.resolve(t,"app"),T.resolve(t,"../app"),T.resolve(t,"../../dist/app")])if(mt(T.join(e,"inspector.js.gz")))return e;throw new Error("Inspector bundle not found (expected dist/app/inspector.js.gz)")}function gt(t,e="/inspector/assets"){let r=vr(),n=new Map;t.use(`${e}/*`,te({points:pt,durationSeconds:ee,key:"inspector-assets"})),t.get(`${e}/*`,o=>{let s=o.req.path.slice(e.length),i=s.startsWith("/")?s.slice(1):s;if(!i||i.includes(".."))return o.notFound();let a=i==="inspector.js"||i==="inspector.css"?`${i}.gz`:i,c=T.resolve(r,a),l=r.endsWith(T.sep)?r:`${r}${T.sep}`;if(!c.startsWith(l)||!mt(c))return o.notFound();let u=T.extname(i),h=a.endsWith(".gz"),m=/(?:^|,)\s*gzip\s*(?:,|$)/i.test(o.req.header("accept-encoding")??""),p=wr(c),g=h&&!m?n.get(c)??Er(n,c,p):p,d=g.buffer.slice(g.byteOffset,g.byteOffset+g.byteLength);return o.body(d,200,{"Content-Type":Rr[u]??"application/octet-stream",...h&&m?{"Content-Encoding":"gzip"}:{},...h?{Vary:"Accept-Encoding"}:{},"Cache-Control":"no-cache"})})}function Er(t,e,r){let n=br(r);return t.set(e,n),n}var yt={name:"@mcp-use/inspector",type:"module",version:"20.0.0-beta.34",description:"MCP Inspector - A tool for inspecting and debugging MCP servers",author:"",license:"MIT",homepage:"https://github.com/mcp-use/mcp-use#readme",repository:{type:"git",url:"git+https://github.com/mcp-use/mcp-use.git",directory:"libraries/typescript/packages/inspector"},bugs:{url:"https://github.com/mcp-use/mcp-use/issues"},keywords:["mcp","inspector","debug","tools"],exports:{".":{types:"./dist/server/index.d.ts",import:"./dist/server/index.js"},"./client":{types:"./dist/client/index.d.ts",import:"./dist/client/index.js"}},main:"./dist/server/index.js",types:"./dist/server/index.d.ts",bin:{"mcp-inspect":"./dist/cli.js"},files:["dist"],scripts:{dev:"rimraf node_modules/.vite && VITE_MANUFACT_CHAT_URL=${VITE_MANUFACT_CHAT_URL:-http://localhost:8000/api/v1/inspector/chat/stream} vite --strictPort","dev:client":"pnpm run dev","dev:server":"VITE_DEV=true tsx watch src/server/server.ts","dev:standalone":"tsx watch src/server/server.ts",clean:"rimraf dist",build:"npm run clean && npm run build:client-exports && npm run build:server && npm run build:app && npm run verify:package","build:app":"vite build --config vite.app.config.ts && node scripts/compress-app.mjs","watch:app":"vite build --watch --config vite.app.config.ts","preview:app":"vite preview --config vite.app.config.ts --host 127.0.0.1","serve:app":"pnpm build:app && pnpm preview:app","analyze:app":"ANALYZE=true vite build --config vite.app.config.ts","build:client-exports":"tsup --config tsup.client.ts","build:server":"tsup --config tsup.server.ts","verify:package":"node scripts/verify-package.mjs",prepublishOnly:"pnpm --filter @mcp-use/client build && pnpm build",start:"node dist/cli.js --port 3000",preview:"vite preview","type-check":"tsc --noEmit",lint:"eslint .","lint:fix":"eslint . --fix","test:e2e":"playwright test","test:e2e:ui":"playwright test --ui","test:e2e:debug":"playwright test --debug","test:e2e:builtin":"node tests/e2e/scripts/run-test-matrix.mjs builtin","test:e2e:prod":"node tests/e2e/scripts/run-test-matrix.mjs prod","test:e2e:mix":"node tests/e2e/scripts/run-test-matrix.mjs mix","test:e2e:prod:ui":"TEST_MODE=production playwright test --ui","test:e2e:codegen":"playwright codegen http://localhost:3000/inspector","test:e2e:report":"playwright show-report","test:e2e:python":"node tests/e2e/scripts/run-python-e2e.mjs","test:unit":"vitest run","test:unit:watch":"vitest","test:e2e:tunnel":"node tests/e2e/scripts/run-tunnel-test.mjs","install:pnpm":"pnpm install","install:npm":"npm install","lint:npm":"npm run lint:fix","lint:pnpm":"pnpm lint:fix"},engines:{node:">=22.22.2"},peerDependencies:{"@base-ui/react":"^1.6.0","@mcp-use/agent":"^2.0.0-alpha.0","@mcp-use/client":"^2.0.0-alpha.0","class-variance-authority":"^0.7.1",clsx:"^2.1.1",express:"^4.21.2 || ^5.0.0","lucide-react":"^0.562.0","markdown-to-jsx":"^9.7.4","mcp-use":"workspace:*",motion:"^12.34.2",react:"^18.0.0 || ^19.0.0","react-dom":"^18.0.0 || ^19.0.0","react-resizable-panels":"^4.6.4",sonner:"^2.0.7","tailwind-merge":"^3.5.0"},peerDependenciesMeta:{"@base-ui/react":{optional:!0},"@mcp-use/agent":{optional:!0},"@mcp-use/client":{optional:!0},"class-variance-authority":{optional:!0},clsx:{optional:!0},express:{optional:!0},"lucide-react":{optional:!0},"markdown-to-jsx":{optional:!0},motion:{optional:!0},react:{optional:!0},"react-dom":{optional:!0},"react-resizable-panels":{optional:!0},sonner:{optional:!0},"tailwind-merge":{optional:!0}},dependencies:{},publishConfig:{access:"public"},devDependencies:{"@base-ui/react":"^1.6.0","@hono/node-server":"^1.19.13","@mcp-use/agent":"workspace:*","@mcp-use/client":"workspace:*","@playwright/test":"^1.58.2","@tailwindcss/vite":"^4.2.0","@types/express":"^5.0.6","@vitejs/plugin-react":"^6.0.0","class-variance-authority":"^0.7.1",clsx:"^2.1.1",emulate:"0.5.0",eslint:"^9.39.2",express:"^5.2.1",hono:"^4.12.12","lucide-react":"^0.562.0","markdown-to-jsx":"^9.7.4",motion:"^12.34.2","oauth2-mock-server":"^8.2.2",open:"^11.0.0",react:"^19.2.3","react-dom":"^19.2.3","react-router":"^7.12.0","react-resizable-panels":"^4.6.4","rate-limiter-flexible":"^11.2.0","rollup-plugin-visualizer":"^6.0.3",sonner:"^2.0.7","tailwind-merge":"^3.5.0",tailwindcss:"^4.2.0",tsup:"^8.5.1",tsx:"^4.21.0","tw-animate-css":"^1.4.0",typescript:"^5.9.3",vite:"^8.0.16",vitest:"^4.1.0","wait-on":"^9.0.4",zod:"^4.2.0"}};var Pr=yt.version;function wt(){return Pr}var xt=wt(),Ar=`<!doctype html>
2
2
  <html lang="en"><head><meta charset="utf-8"><title>Signed in</title><meta name="robots" content="noindex"><style>html,body{margin:0;height:100%;display:flex;align-items:center;justify-content:center;font-family:-apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif;color:#4b5563;background:#fff}</style></head>
3
3
  <body><div>Signed in. You can close this window.</div>
4
4
  <script>try{if(window.opener&&!window.opener.closed)window.opener.postMessage({type:"manufact:oauth-complete"},"*")}catch(e){}try{window.close()}catch(e){}</script>
5
- </body></html>`;function Xt(e,t,r){let n=[];e?.basePath!==void 0&&n.push(`<script>window.__MCP_BASE_PATH__ = ${JSON.stringify(e.basePath)};</script>`),e?.devMode&&n.push("<script>window.__MCP_DEV_MODE__ = true;</script>"),e?.sandboxOrigin&&n.push(`<script>window.__MCP_SANDBOX_ORIGIN__ = ${JSON.stringify(e.sandboxOrigin)};</script>`),e?.proxyUrl!==void 0&&n.push(`<script>window.__MCP_PROXY_URL__ = ${JSON.stringify(e.proxyUrl)};</script>`),e?.inspectorMode&&n.push(`<script>window.__MCP_INSPECTOR_MODE__ = ${JSON.stringify(e.inspectorMode)};</script>`),e?.manufactChatUrl&&n.push(`<script>window.__MANUFACT_CHAT_URL__ = ${JSON.stringify(e.manufactChatUrl)};</script>`),e?.disableTelemetry&&n.push('<script>window.__MCP_USE_ANONYMIZED_TELEMETRY__ = false;try{localStorage.setItem("MCP_USE_ANONYMIZED_TELEMETRY","false");}catch(e){}</script>'),process.env.MCP_USE_DEV_CLI==="1"&&n.push("<script>window.__MCP_DEV_CLI__ = true;</script>");let o=n.join(`
5
+ </body></html>`;function Sr(t,e,r){let n=[];t?.basePath!==void 0&&n.push(`<script>window.__MCP_BASE_PATH__ = ${JSON.stringify(t.basePath)};</script>`),t?.devMode&&n.push("<script>window.__MCP_DEV_MODE__ = true;</script>"),t?.sandboxOrigin&&n.push(`<script>window.__MCP_SANDBOX_ORIGIN__ = ${JSON.stringify(t.sandboxOrigin)};</script>`),t?.proxyUrl!==void 0&&n.push(`<script>window.__MCP_PROXY_URL__ = ${JSON.stringify(t.proxyUrl)};</script>`),t?.inspectorMode&&n.push(`<script>window.__MCP_INSPECTOR_MODE__ = ${JSON.stringify(t.inspectorMode)};</script>`),t?.manufactChatUrl&&n.push(`<script>window.__MANUFACT_CHAT_URL__ = ${JSON.stringify(t.manufactChatUrl)};</script>`),t?.disableTelemetry&&n.push('<script>window.__MCP_USE_ANONYMIZED_TELEMETRY__ = false;try{localStorage.setItem("MCP_USE_ANONYMIZED_TELEMETRY","false");}catch(e){}</script>'),process.env.MCP_USE_DEV_CLI==="1"&&n.push("<script>window.__MCP_DEV_CLI__ = true;</script>");let o=n.join(`
6
6
  `);return`<!doctype html>
7
7
  <html lang="en">
8
8
  <head>
9
9
  <meta charset="UTF-8" />
10
- ${Ke(`${t}/inspector/assets`)}
10
+ ${et(`${e}/inspector/assets`)}
11
11
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
12
12
  <link rel="preconnect" href="https://fonts.googleapis.com" />
13
13
  <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
@@ -54,7 +54,7 @@ var ne=(e,t,r)=>(n,o)=>{let s=-1;return i(0);async function i(a){if(a<=s)throw n
54
54
  .mcp-boot-spinner, .mcp-boot-label { color: #a1a1aa; }
55
55
  }
56
56
  </style>
57
- <script>window.__INSPECTOR_VERSION__ = ${JSON.stringify(Qe)};</script>
57
+ <script>window.__INSPECTOR_VERSION__ = ${JSON.stringify(xt)};</script>
58
58
  ${o}
59
59
  </head>
60
60
  <body>
@@ -94,6 +94,6 @@ var ne=(e,t,r)=>(n,o)=>{let s=-1;return i(0);async function i(a){if(a<=s)throw n
94
94
  </div>
95
95
  <script type="module" src="${r.jsUrl}"></script>
96
96
  </body>
97
- </html>`}function Ze(e,t,r=""){let n=`${r}/inspector/assets`,o=encodeURIComponent(Qe),s={jsUrl:`${n}/inspector.js?v=${o}`,cssUrl:`${n}/inspector.css?v=${o}`},i=u=>`${r}${u}`,a={...t,basePath:t?.basePath??r,proxyUrl:t?.proxyUrl!==void 0?t.proxyUrl:i("/inspector/api/proxy"),disableTelemetry:t?.disableTelemetry??process.env.MCP_USE_ANONYMIZED_TELEMETRY==="false"},c=u=>u.html(Xt(a,r,s));Je(e,n),e.get(i("/inspector/oauth-popup-closed.html"),u=>u.html(Jt)),e.get(i("/inspector"),c),e.get(`${i("/inspector")}/`,c);let l=i("/inspector/api/");e.get(i("/inspector/*"),u=>u.req.path.startsWith(l)?u.notFound():c(u)),e.post(i("/inspector/*"),u=>u.req.path.startsWith(l)?u.notFound():c(u)),r===""&&t?.rootRedirect!==!1&&e.get("/",u=>{let p=new URL(u.req.url);return u.redirect(`${i("/inspector")}${p.search}`)})}var et=e=>{let t={origin:"*",allowMethods:["GET","HEAD","PUT","POST","DELETE","PATCH"],allowHeaders:[],exposeHeaders:[],...e},r=(o=>typeof o=="string"?o==="*"?()=>o:s=>o===s?s:null:typeof o=="function"?o:s=>o.includes(s)?s:null)(t.origin),n=(o=>typeof o=="function"?o:Array.isArray(o)?()=>o:()=>[])(t.allowMethods);return async function(s,i){function a(l,u){s.res.headers.set(l,u)}let c=await r(s.req.header("origin")||"",s);if(c&&a("Access-Control-Allow-Origin",c),t.credentials&&a("Access-Control-Allow-Credentials","true"),t.exposeHeaders?.length&&a("Access-Control-Expose-Headers",t.exposeHeaders.join(",")),s.req.method==="OPTIONS"){t.origin!=="*"&&a("Vary","Origin"),t.maxAge!=null&&a("Access-Control-Max-Age",t.maxAge.toString());let l=await n(s.req.header("origin")||"",s);l.length&&a("Access-Control-Allow-Methods",l.join(","));let u=t.allowHeaders;if(!u?.length){let p=s.req.header("Access-Control-Request-Headers");p&&(u=p.split(/\s*,\s*/))}return u?.length&&(a("Access-Control-Allow-Headers",u.join(",")),s.res.headers.append("Vary","Access-Control-Request-Headers")),s.res.headers.delete("Content-Length"),s.res.headers.delete("Content-Type"),new Response(null,{headers:s.res.headers,status:204,statusText:"No Content"})}await i(),t.origin!=="*"&&s.header("Vary","Origin",{append:!0})}};function Yt(){let{process:e,Deno:t}=globalThis;return!(typeof t?.noColor=="boolean"?t.noColor:e!==void 0?"NO_COLOR"in e?.env:!1)}async function tt(){let{navigator:e}=globalThis,t="cloudflare:workers";return!(e!==void 0&&e.userAgent==="Cloudflare-Workers"?await(async()=>{try{return"NO_COLOR"in((await import(t)).env??{})}catch{return!1}})():!Yt())}var Qt=e=>{let[t,r]=[",","."];return e.map(o=>o.replace(/(\d)(?=(\d\d\d)+(?!\d))/g,"$1"+t)).join(r)},Zt=e=>{let t=Date.now()-e;return Qt([t<1e3?t+"ms":Math.round(t/1e3)+"s"])},er=async e=>{if(await tt())switch(e/100|0){case 5:return`\x1B[31m${e}\x1B[0m`;case 4:return`\x1B[33m${e}\x1B[0m`;case 3:return`\x1B[36m${e}\x1B[0m`;case 2:return`\x1B[32m${e}\x1B[0m`}return`${e}`};async function rt(e,t,r,n,o=0,s){let i=t==="<--"?`${t} ${r} ${n}`:`${t} ${r} ${n} ${await er(o)} ${s}`;e(i)}var nt=(e=console.log)=>async function(r,n){let{method:o,url:s}=r.req,i=s.slice(s.indexOf("/",8));await rt(e,"<--",o,i);let a=Date.now();await n(),await rt(e,"-->",o,i,r.res.status,Zt(a))};import{lookup as tr}from"dns/promises";import{Buffer as rr}from"buffer";import{isIP as nr}from"net";var or=new Set(["accept","authorization","content-type","dpop"]),sr=new Set(["cache-control","content-type","dpop-nonce","expires","pragma","retry-after","www-authenticate"]),ir=[["registration_endpoint","registration"],["token_endpoint","token"],["revocation_endpoint","revocation"],["introspection_endpoint","introspection"]],ut=600*1e3,ar=100,cr=1440*60*1e3,lr=500;function xe(e,t={}){let{basePath:r="/oauth",allowedOrigins:n=[],allowLoopback:o=!1,timeoutMs:s=1e4,maxRequestBodyBytes:i=64*1024,maxResponseBodyBytes:a=1024*1024,callbackPath:c="/oauth/callback",enableLogging:l=!0,authenticate:u,validateServerUrl:p}=t,g=new Set(n.map(be)),h=new Map,m=new Map;e.use(`${r}/*`,async(d,w)=>{let f=d.req.header("Origin");if(f&&!yr(f,d,g))return d.json({error:"Origin not allowed"},403);if(d.req.method==="OPTIONS")return br(f);await w(),f&&wt(d.res.headers,f)}),e.get(`${r}/metadata`,async d=>{if(!await lt(d,u))return d.json({error:"Unauthorized"},401);let w=await j(d.req.query("serverUrl"),o);if("error"in w)return d.json({error:w.error},400);let f=w.url;if(p&&!await p(f.toString(),d))return d.json({error:"MCP server URL not allowed"},403);let R=await j(d.req.query("url"),o);if("error"in R)return d.json({error:R.error},400);let O=R.url,S=T(f),v=at(h,S),b=ot(f,O,v);if(!b&&v.authorizationServers.size===0)try{await st(f,v,o,s,a),h.set(S,v),b=ot(f,O,v)}catch{}if(!b)return d.json({error:"Metadata target is not bound to this MCP server"},403);try{me(l,`GET ${O}`);let A=await Z(O,{method:"GET",headers:{Accept:"application/json"},redirect:"manual",signal:AbortSignal.timeout(s)});if(te(A.status))return d.json({error:"OAuth metadata redirects are not allowed"},502);let x=await ee(A,a);if(!A.ok)return d.body(x,A.status,{"Content-Type":A.headers.get("content-type")??"application/json"});let P=ye(x);return b.type==="protected-resource"?await ht(P,f,v,o):await ft(P,b.issuer,v,o),v.updatedAt=Date.now(),h.set(S,v),ct(h),d.body(x,200,{"Content-Type":A.headers.get("content-type")??"application/json"})}catch(A){return we(d,A,l)}}),e.post(`${r}/proxy`,async d=>{if(!await lt(d,u))return d.json({error:"Unauthorized"},401);let w;try{w=JSON.parse(await mr(d.req.raw,i))}catch(x){return d.json({error:x instanceof M?"Request body too large":"Invalid JSON request body"},x instanceof M?413:400)}let f=await j(w.serverUrl,o);if("error"in f)return d.json({error:f.error},400);let R=f.url;if(p&&!await p(R.toString(),d))return d.json({error:"MCP server URL not allowed"},403);let O=await j(w.url,o);if("error"in O)return d.json({error:O.error},400);let S=O.url;if(w.method!==void 0&&w.method!=="POST")return d.json({error:"Only OAuth endpoint POST is allowed"},405);let v=T(R),b=at(h,v);if(b.endpoints.size===0)try{await st(R,b,o,s,a),h.set(v,b),ct(h)}catch(x){return we(d,x,l)}let A=b.endpoints.get(T(S));if(!A)return d.json({error:"OAuth endpoint is not bound to this MCP server"},403);try{let x=ur(w.headers),P=pr(w.body,x);if(A==="registration"){let At=be(d.req.header("Origin")??new URL(d.req.url).origin);P=wr(P,x,new URL(c,At).toString())}else P=fr({body:P,headers:x,bindingKey:v,clients:m});if(new TextEncoder().encode(P??"").byteLength>i)return d.json({error:"OAuth request body too large"},413);me(l,`POST ${A} ${S}`);let E=await Z(S,{method:"POST",headers:x,body:P,redirect:"manual",signal:AbortSignal.timeout(s)});if(te(E.status))return d.json({error:"OAuth endpoint redirects are not allowed"},502);let k=await ee(E,a),N=dr(E.headers),H=E.headers.get("content-type")??"",_=k;if(H.includes("json"))try{_=JSON.parse(k)}catch{}return A==="registration"&&E.ok&&_&&typeof _=="object"&&!Array.isArray(_)&&(_=hr({responseBody:_,binding:b,bindingKey:v,clients:m})),d.json({status:E.status,statusText:E.statusText,headers:N,body:_})}catch(x){return we(d,x,l)}}),me(l,`Mounted at ${r}/metadata and ${r}/proxy`)}async function j(e,t){if(typeof e!="string"||!e)return{error:"Missing or invalid URL"};let r;try{r=new URL(e)}catch{return{error:"Invalid URL"}}if(r.username||r.password||r.hash)return{error:"URL credentials and fragments are not allowed"};let n=xr(r.hostname);if(r.protocol!=="https:"&&!(t&&n&&r.protocol==="http:"))return{error:"HTTPS is required"};if(n)return t?{url:r}:{error:"Loopback URL not allowed"};if(Rr(r.hostname))return{error:"Local network URL not allowed"};try{let o=nr(r.hostname)?[r.hostname]:(await tr(r.hostname,{all:!0,verbatim:!0})).map(({address:s})=>s);if(o.length===0||o.some(s=>!yt(s)))return{error:"Private or non-routable URL not allowed"}}catch{return{error:"URL hostname could not be resolved"}}return{url:r}}async function Re(e,t=!1){return!("error"in await j(e,t))}function ot(e,t,r){let n=T(t);if(dt(e).some(o=>T(o)===n))return{type:"protected-resource"};for(let o of r.authorizationServers)if(pt(new URL(o)).some(s=>T(s)===n))return{type:"authorization-server",issuer:o}}function dt(e){let t=e.pathname==="/"?"":e.pathname;return[new URL(`/.well-known/oauth-protected-resource${t}`,e.origin),new URL("/.well-known/oauth-protected-resource",e.origin)]}function pt(e){let t=e.pathname==="/"?"":e.pathname;return[new URL(`/.well-known/oauth-authorization-server${t}`,e.origin),new URL(`/.well-known/openid-configuration${t}`,e.origin),new URL(`${t||""}/.well-known/openid-configuration`,e.origin)]}async function ht(e,t,r,n){if(typeof e.resource!="string"||T(new URL(e.resource))!==T(t))throw new C("Protected-resource metadata does not match serverUrl");if(!Array.isArray(e.authorization_servers)||e.authorization_servers.length===0)throw new C("Protected-resource metadata has no authorization servers");let o=new Set;for(let s of e.authorization_servers){let i=await j(s,n);if("error"in i)throw new C(`Unsafe authorization server: ${i.error}`);o.add(T(i.url))}r.authorizationServers=o,r.endpoints.clear(),r.tokenEndpointAuthMethods.clear()}async function ft(e,t,r,n){if(typeof e.issuer!="string"||T(new URL(e.issuer))!==t)throw new C("Authorization-server metadata issuer mismatch");r.endpoints.clear(),r.tokenEndpointAuthMethods=new Set(Array.isArray(e.token_endpoint_auth_methods_supported)?e.token_endpoint_auth_methods_supported.filter(o=>typeof o=="string"):[]);for(let[o,s]of ir){let i=e[o];if(i===void 0)continue;let a=await j(i,n);if("error"in a)throw new C(`Unsafe ${o}: ${a.error}`);r.endpoints.set(T(a.url),s)}}async function st(e,t,r,n,o){for(let s of dt(e)){let i=await Z(s,{method:"GET",headers:{Accept:"application/json"},redirect:"manual",signal:AbortSignal.timeout(n)});if(te(i.status))throw new C("OAuth metadata redirects are not allowed");if(i.ok){await ht(ye(await ee(i,o)),e,t,r);break}}if(t.authorizationServers.size===0)throw new C("Protected-resource metadata could not be discovered");for(let s of t.authorizationServers){let i=!1;for(let a of pt(new URL(s))){let c=await Z(a,{method:"GET",headers:{Accept:"application/json"},redirect:"manual",signal:AbortSignal.timeout(n)});if(te(c.status))throw new C("OAuth metadata redirects are not allowed");if(c.ok){await ft(ye(await ee(c,o)),s,t,r),i=!0;break}}if(i)break}if(t.endpoints.size===0)throw new C("Authorization-server metadata could not be discovered");t.updatedAt=Date.now()}async function Z(e,t){return fetch(e,t)}function ur(e){let t=new Headers;if(!e||typeof e!="object"||Array.isArray(e))return t;for(let[r,n]of Object.entries(e)){let o=r.toLowerCase();or.has(o)&&typeof n=="string"&&t.set(o,n)}return t}function dr(e){let t={};return e.forEach((r,n)=>{sr.has(n.toLowerCase())&&(t[n]=r)}),t}function pr(e,t){if(e==null)return;if(typeof e=="string"){if(!t.has("content-type"))try{JSON.parse(e),t.set("content-type","application/json")}catch{t.set("content-type","application/x-www-form-urlencoded")}return e}if((t.get("content-type")??"").includes("application/x-www-form-urlencoded")&&typeof e=="object"&&!Array.isArray(e)){let n=new URLSearchParams;for(let[o,s]of Object.entries(e))n.append(o,String(s));return n.toString()}return t.has("content-type")||t.set("content-type","application/json"),JSON.stringify(e)}function gt(e,t){return`${e}\0${t}`}function hr(e){let{responseBody:t,binding:r,bindingKey:n,clients:o}=e,s=t.client_id,i=t.client_secret;if(typeof s!="string"||typeof i!="string")return t;let a=t.token_endpoint_auth_method,c=a==="client_secret_post"||a==="client_secret_basic"?a:r.tokenEndpointAuthMethods.has("client_secret_basic")?"client_secret_basic":"client_secret_post",l=t.client_secret_expires_at,u=l===0?Number.POSITIVE_INFINITY:typeof l=="number"&&l>0?l*1e3:Date.now()+cr;for(gr(o),o.set(gt(n,s),{clientSecret:i,authMethod:c,expiresAt:u});o.size>lr;){let g=o.keys().next().value;if(!g)break;o.delete(g)}let p={...t};return delete p.client_secret,delete p.client_secret_expires_at,p.token_endpoint_auth_method="none",p}function fr(e){let{body:t,headers:r,bindingKey:n,clients:o}=e;if(!t||!(r.get("content-type")??"").includes("application/x-www-form-urlencoded"))return t;let s=new URLSearchParams(t),i=s.get("client_id");if(!i)return t;let a=gt(n,i),c=o.get(a);if(!c)return t;if(c.expiresAt<=Date.now())return o.delete(a),t;if(s.delete("client_secret"),c.authMethod==="client_secret_basic"){let l=rr.from(`${it(i)}:${it(c.clientSecret)}`,"utf8").toString("base64");r.set("authorization",`Basic ${l}`)}else r.delete("authorization"),s.set("client_id",i),s.set("client_secret",c.clientSecret);return s.toString()}function it(e){return new URLSearchParams({value:e}).toString().slice(6)}function gr(e){let t=Date.now();for(let[r,n]of e)n.expiresAt<=t&&e.delete(r)}async function mr(e,t){let r=Number(e.headers.get("content-length"));if(Number.isFinite(r)&&r>t)throw new M;return mt(e.body,t)}async function ee(e,t){let r=Number(e.headers.get("content-length"));if(Number.isFinite(r)&&r>t)throw await e.body?.cancel(),new M;return mt(e.body,t)}async function mt(e,t){if(!e)return"";let r=e.getReader(),n=[],o=0;for(;;){let{done:a,value:c}=await r.read();if(a)break;if(o+=c.byteLength,o>t)throw await r.cancel(),new M;n.push(c)}let s=new Uint8Array(o),i=0;for(let a of n)s.set(a,i),i+=a.byteLength;return new TextDecoder().decode(s)}function ye(e){let t;try{t=JSON.parse(e)}catch{throw new C("OAuth metadata is not valid JSON")}if(!t||typeof t!="object"||Array.isArray(t))throw new C("OAuth metadata is not an object");return t}function at(e,t){let r=e.get(t);return r&&Date.now()-r.updatedAt<=ut?r:(e.delete(t),{authorizationServers:new Set,endpoints:new Map,tokenEndpointAuthMethods:new Set,updatedAt:Date.now()})}function ct(e){let t=Date.now();for(let[r,n]of e)t-n.updatedAt>ut&&e.delete(r);for(;e.size>ar;){let r=e.keys().next().value;if(!r)break;e.delete(r)}}function T(e){let t=new URL(e);return t.hash="",(t.protocol==="https:"&&t.port==="443"||t.protocol==="http:"&&t.port==="80")&&(t.port=""),t.toString().replace(/\/$/,"")}function wr(e,t,r){if(!e||!(t.get("content-type")??"").includes("json"))return e;try{let o=JSON.parse(e);return!o||typeof o!="object"||Array.isArray(o)?e:JSON.stringify({...o,redirect_uris:[r]})}catch{return e}}function be(e){let t=new URL(e);if(t.pathname!=="/"||t.search||t.hash)throw new Error(`OAuth proxy allowed origin must be an origin: ${e}`);return t.origin}function yr(e,t,r){try{let n=be(e);if(n===new URL(t.req.url).origin||r.has(n))return!0;let o=new URL(n),i=t.req.header("x-forwarded-host")?.split(",")[0]?.trim()||t.req.header("host");if(!i||o.host!==i)return!1;let a=t.req.header("x-forwarded-proto")?.split(",")[0]?.trim();return!a||`${a}:`===o.protocol}catch{return!1}}function br(e){let t=new Headers;return e&&wt(t,e),t.set("Access-Control-Allow-Methods","GET, POST, OPTIONS"),t.set("Access-Control-Allow-Headers","Accept, Authorization, Content-Type"),t.set("Access-Control-Max-Age","600"),new Response(null,{status:204,headers:t})}function wt(e,t){e.set("Access-Control-Allow-Origin",t),e.append("Vary","Origin")}async function lt(e,t){return t?t(e):!0}function te(e){return e>=300&&e<400}function xr(e){let t=e.toLowerCase().replace(/^\[|\]$/g,"");return t==="localhost"||t.endsWith(".localhost")||t==="::1"||t.startsWith("127.")}function Rr(e){let t=e.toLowerCase();return t.endsWith(".local")||t.endsWith(".internal")||t.endsWith(".home.arpa")}function yt(e){if(e.includes(":")){let s=e.toLowerCase();return s.startsWith("::ffff:")?yt(s.slice(7)):!(s==="::"||s==="::1"||s.startsWith("fc")||s.startsWith("fd")||/^fe[89ab]/.test(s)||s.startsWith("ff")||s.startsWith("2001:db8:"))}let t=e.split(".").map(Number);if(t.length!==4||t.some(s=>!Number.isInteger(s)))return!1;let[r,n,o]=t;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 me(e,t){e&&console.log(`[OAuth BFF] ${t}`)}function we(e,t,r){let n=t instanceof Error?t.message:"Unknown error";return r&&console.error("[OAuth BFF]",n),t instanceof M?e.json({error:"Upstream response too large"},502):t instanceof C?e.json({error:t.message},502):t instanceof DOMException&&t.name==="TimeoutError"?e.json({error:"OAuth upstream timed out"},504):e.json({error:"OAuth upstream request failed"},502)}var M=class extends Error{},C=class extends Error{};var vr=3;function Er(e,t){return e.includes("text/event-stream")&&!t}function ve(e,t={}){let r=t.path||"/mcp/proxy",n=t.enableLogging!==!1;e.use(`${r}/*`,et({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&&e.use(`${r}/*`,nt()),e.all(`${r}/*`,async o=>{try{if(t.authenticate&&!await t.authenticate(o))return o.json({error:"Unauthorized"},401);let s=o.req.header("X-Target-URL");if(!s)return o.json({error:"X-Target-URL header is required",usage:"Set X-Target-URL header to the MCP server URL you want to proxy to"},400);if(!await Re(s,t.allowLoopback??!1))return o.json({error:"Invalid target URL",details:"Target is not allowed by the proxy network policy"},403);if(t.validateRequest&&!await t.validateRequest(s,o))return o.json({error:"Invalid target URL",details:"The requested target URL is not allowed"},403);try{new URL(s)}catch{return o.json({error:"Invalid target URL format",details:"The X-Target-URL must be a valid HTTP/HTTPS URL"},400)}let i=o.req.method,a={},c=o.req.header();for(let[h,m]of Object.entries(c)){let d=h.toLowerCase();!d.startsWith("x-proxy-")&&!d.startsWith("x-target-")&&!d.startsWith("x-mcp-")&&!d.startsWith("x-forwarded-")&&!d.startsWith("cf-")&&d!=="x-original-host"&&d!=="host"&&d!=="origin"&&d!=="referer"&&d!=="cookie"&&d!=="proxy-authorization"&&d!=="accept-encoding"&&d!=="cdn-loop"&&!d.startsWith("sec-fetch-")&&(a[h]=m)}a["Accept-Encoding"]="identity";let l=i!=="GET"&&i!=="HEAD"?new Uint8Array(await o.req.arrayBuffer()).slice():void 0,u=s,p=i,g=l;for(let h=0;;h+=1){let m=await fetch(u,{method:p,headers:a,body:g,redirect:"manual"}),d=m.headers.get("location");if(!(m.status>=300&&m.status<400&&d))return Ar(m);if(h>=vr)return o.json({error:"Too many upstream redirects"},502);let w=new URL(d,u);if(!await Re(w.toString(),t.allowLoopback??!1)||t.validateRequest&&!await t.validateRequest(w.toString(),o))return o.json({error:"Redirect target is not allowed"},403);w.origin!==new URL(u).origin&&(re(a,"authorization"),re(a,"proxy-authorization")),(m.status===303||(m.status===301||m.status===302)&&p==="POST")&&(p="GET",g=void 0,re(a,"content-type"),re(a,"content-length")),u=w.toString()}}catch(s){let i=s instanceof Error?s.message:"Unknown error",a=o.req.header("X-Target-URL");return s instanceof Error&&(s.message.includes("ECONNREFUSED")||s.message.includes("fetch failed"))?console.warn(`[MCP Proxy] Connection refused to ${a||"unknown target"} - server may not be running`):console.error("[MCP Proxy] Request failed:",i,`
97
+ </html>`}function bt(t,e,r=""){let n=`${r}/inspector/assets`,o=encodeURIComponent(xt),s={jsUrl:`${n}/inspector.js?v=${o}`,cssUrl:`${n}/inspector.css?v=${o}`},i=u=>`${r}${u}`,a={...e,basePath:e?.basePath??r,proxyUrl:e?.proxyUrl!==void 0?e.proxyUrl:i("/inspector/api/proxy"),disableTelemetry:e?.disableTelemetry??process.env.MCP_USE_ANONYMIZED_TELEMETRY==="false"},c=u=>u.html(Sr(a,r,s));gt(t,n),t.get(i("/inspector/oauth-popup-closed.html"),u=>u.html(Ar)),t.get(i("/inspector"),c),t.get(`${i("/inspector")}/`,c);let l=i("/inspector/api/");t.get(i("/inspector/*"),u=>u.req.path.startsWith(l)?u.notFound():c(u)),t.post(i("/inspector/*"),u=>u.req.path.startsWith(l)?u.notFound():c(u)),r===""&&e?.rootRedirect!==!1&&t.get("/",u=>{let h=new URL(u.req.url);return u.redirect(`${i("/inspector")}${h.search}`)})}var Rt=t=>{let e={origin:"*",allowMethods:["GET","HEAD","PUT","POST","DELETE","PATCH"],allowHeaders:[],exposeHeaders:[],...t},r=(o=>typeof o=="string"?o==="*"?()=>o:s=>o===s?s:null:typeof o=="function"?o:s=>o.includes(s)?s:null)(e.origin),n=(o=>typeof o=="function"?o:Array.isArray(o)?()=>o:()=>[])(e.allowMethods);return async function(s,i){function a(l,u){s.res.headers.set(l,u)}let c=await r(s.req.header("origin")||"",s);if(c&&a("Access-Control-Allow-Origin",c),e.credentials&&a("Access-Control-Allow-Credentials","true"),e.exposeHeaders?.length&&a("Access-Control-Expose-Headers",e.exposeHeaders.join(",")),s.req.method==="OPTIONS"){e.origin!=="*"&&a("Vary","Origin"),e.maxAge!=null&&a("Access-Control-Max-Age",e.maxAge.toString());let l=await n(s.req.header("origin")||"",s);l.length&&a("Access-Control-Allow-Methods",l.join(","));let u=e.allowHeaders;if(!u?.length){let h=s.req.header("Access-Control-Request-Headers");h&&(u=h.split(/\s*,\s*/))}return u?.length&&(a("Access-Control-Allow-Headers",u.join(",")),s.res.headers.append("Vary","Access-Control-Request-Headers")),s.res.headers.delete("Content-Length"),s.res.headers.delete("Content-Type"),new Response(null,{headers:s.res.headers,status:204,statusText:"No Content"})}await i(),e.origin!=="*"&&s.header("Vary","Origin",{append:!0})}};function Or(){let{process:t,Deno:e}=globalThis;return!(typeof e?.noColor=="boolean"?e.noColor:t!==void 0?"NO_COLOR"in t?.env:!1)}async function vt(){let{navigator:t}=globalThis,e="cloudflare:workers";return!(t!==void 0&&t.userAgent==="Cloudflare-Workers"?await(async()=>{try{return"NO_COLOR"in((await import(e)).env??{})}catch{return!1}})():!Or())}var Cr=t=>{let[e,r]=[",","."];return t.map(o=>o.replace(/(\d)(?=(\d\d\d)+(?!\d))/g,"$1"+e)).join(r)},Ir=t=>{let e=Date.now()-t;return Cr([e<1e3?e+"ms":Math.round(e/1e3)+"s"])},Mr=async t=>{if(await vt())switch(t/100|0){case 5:return`\x1B[31m${t}\x1B[0m`;case 4:return`\x1B[33m${t}\x1B[0m`;case 3:return`\x1B[36m${t}\x1B[0m`;case 2:return`\x1B[32m${t}\x1B[0m`}return`${t}`};async function Et(t,e,r,n,o=0,s){let i=e==="<--"?`${e} ${r} ${n}`:`${e} ${r} ${n} ${await Mr(o)} ${s}`;t(i)}var _t=(t=console.log)=>async function(r,n){let{method:o,url:s}=r.req,i=s.slice(s.indexOf("/",8));await Et(t,"<--",o,i);let a=Date.now();await n(),await Et(t,"-->",o,i,r.res.status,Ir(a))};import{lookup as Tr}from"dns/promises";import{Buffer as kr}from"buffer";import{isIP as Lr}from"net";var Ur=new Set(["accept","authorization","content-type","dpop"]),jr=new Set(["cache-control","content-type","dpop-nonce","expires","pragma","retry-after","www-authenticate"]),Nr=[["registration_endpoint","registration"],["token_endpoint","token"],["revocation_endpoint","revocation"],["introspection_endpoint","introspection"]],Mt=600*1e3,Dr=100,Hr=1440*60*1e3,$r=500;function Ae(t,e={}){let{basePath:r="/oauth",allowedOrigins:n=[],allowLoopback:o=!1,timeoutMs:s=1e4,maxRequestBodyBytes:i=64*1024,maxResponseBodyBytes:a=1024*1024,callbackPath:c="/oauth/callback",enableLogging:l=!0,authenticate:u,validateServerUrl:h}=e,m=new Set(n.map(Pe)),p=new Map,g=new Map;t.use(`${r}/*`,async(d,y)=>{let f=d.req.header("Origin");if(f&&!Jr(f,d,m))return d.json({error:"Origin not allowed"},403);if(d.req.method==="OPTIONS")return Yr(f);await y(),f&&Dt(d.res.headers,f)}),t.get(`${r}/metadata`,async d=>{if(!await It(d,u))return d.json({error:"Unauthorized"},401);let y=await j(d.req.query("serverUrl"),o);if("error"in y)return d.json({error:y.error},400);let f=y.url;if(h&&!await h(f.toString(),d))return d.json({error:"MCP server URL not allowed"},403);let R=await j(d.req.query("url"),o);if("error"in R)return d.json({error:R.error},400);let A=R.url,C=I(f),v=Ot(p,C),x=Pt(f,A,v);if(!x&&v.authorizationServers.size===0)try{await At(f,v,o,s,a),p.set(C,v),x=Pt(f,A,v)}catch{}if(!x)return d.json({error:"Metadata target is not bound to this MCP server"},403);try{ve(l,`GET ${A}`);let _=await re(A,{method:"GET",headers:{Accept:"application/json"},redirect:"manual",signal:AbortSignal.timeout(s)});if(oe(_.status))return d.json({error:"OAuth metadata redirects are not allowed"},502);let b=await ne(_,a);if(!_.ok)return d.body(b,_.status,{"Content-Type":_.headers.get("content-type")??"application/json"});let P=_e(b);return x.type==="protected-resource"?await Lt(P,f,v,o):await Ut(P,x.issuer,v,o),v.updatedAt=Date.now(),p.set(C,v),Ct(p),d.body(b,200,{"Content-Type":_.headers.get("content-type")??"application/json"})}catch(_){return Ee(d,_,l)}}),t.post(`${r}/proxy`,async d=>{if(!await It(d,u))return d.json({error:"Unauthorized"},401);let y;try{y=JSON.parse(await Vr(d.req.raw,i))}catch(b){return d.json({error:b instanceof L?"Request body too large":"Invalid JSON request body"},b instanceof L?413:400)}let f=await j(y.serverUrl,o);if("error"in f)return d.json({error:f.error},400);let R=f.url;if(h&&!await h(R.toString(),d))return d.json({error:"MCP server URL not allowed"},403);let A=await j(y.url,o);if("error"in A)return d.json({error:A.error},400);let C=A.url;if(y.method!==void 0&&y.method!=="POST")return d.json({error:"Only OAuth endpoint POST is allowed"},405);let v=I(R),x=Ot(p,v);if(x.endpoints.size===0)try{await At(R,x,o,s,a),p.set(v,x),Ct(p)}catch(b){return Ee(d,b,l)}let _=x.endpoints.get(I(C));if(!_)return d.json({error:"OAuth endpoint is not bound to this MCP server"},403);try{let b=Br(y.headers),P=qr(y.body,b);if(_==="registration"){let Wt=Pe(d.req.header("Origin")??new URL(d.req.url).origin);P=Gr(P,b,new URL(c,Wt).toString())}else P=Wr({body:P,headers:b,bindingKey:v,clients:g});if(new TextEncoder().encode(P??"").byteLength>i)return d.json({error:"OAuth request body too large"},413);ve(l,`POST ${_} ${C}`);let E=await re(C,{method:"POST",headers:b,body:P,redirect:"manual",signal:AbortSignal.timeout(s)});if(oe(E.status))return d.json({error:"OAuth endpoint redirects are not allowed"},502);let M=await ne(E,a),H=Fr(E.headers),N=E.headers.get("content-type")??"",O=M;if(N.includes("json"))try{O=JSON.parse(M)}catch{}return _==="registration"&&E.ok&&O&&typeof O=="object"&&!Array.isArray(O)&&(O=zr({responseBody:O,binding:x,bindingKey:v,clients:g})),d.json({status:E.status,statusText:E.statusText,headers:H,body:O})}catch(b){return Ee(d,b,l)}}),ve(l,`Mounted at ${r}/metadata and ${r}/proxy`)}async function j(t,e){if(typeof t!="string"||!t)return{error:"Missing or invalid URL"};let r;try{r=new URL(t)}catch{return{error:"Invalid URL"}}if(r.username||r.password||r.hash)return{error:"URL credentials and fragments are not allowed"};let n=Xr(r.hostname);if(r.protocol!=="https:"&&!(e&&n&&r.protocol==="http:"))return{error:"HTTPS is required"};if(n)return e?{url:r}:{error:"Loopback URL not allowed"};if(Qr(r.hostname))return{error:"Local network URL not allowed"};try{let o=Lr(r.hostname)?[r.hostname]:(await Tr(r.hostname,{all:!0,verbatim:!0})).map(({address:s})=>s);if(o.length===0||o.some(s=>!Ht(s)))return{error:"Private or non-routable URL not allowed"}}catch{return{error:"URL hostname could not be resolved"}}return{url:r}}async function Se(t,e=!1){return!("error"in await j(t,e))}function Pt(t,e,r){let n=I(e);if(Tt(t).some(o=>I(o)===n))return{type:"protected-resource"};for(let o of r.authorizationServers)if(kt(new URL(o)).some(s=>I(s)===n))return{type:"authorization-server",issuer:o}}function Tt(t){let e=t.pathname==="/"?"":t.pathname;return[new URL(`/.well-known/oauth-protected-resource${e}`,t.origin),new URL("/.well-known/oauth-protected-resource",t.origin)]}function kt(t){let e=t.pathname==="/"?"":t.pathname;return[new URL(`/.well-known/oauth-authorization-server${e}`,t.origin),new URL(`/.well-known/openid-configuration${e}`,t.origin),new URL(`${e||""}/.well-known/openid-configuration`,t.origin)]}async function Lt(t,e,r,n){if(typeof t.resource!="string"||I(new URL(t.resource))!==I(e))throw new S("Protected-resource metadata does not match serverUrl");if(!Array.isArray(t.authorization_servers)||t.authorization_servers.length===0)throw new S("Protected-resource metadata has no authorization servers");let o=new Set;for(let s of t.authorization_servers){let i=await j(s,n);if("error"in i)throw new S(`Unsafe authorization server: ${i.error}`);o.add(I(i.url))}r.authorizationServers=o,r.endpoints.clear(),r.tokenEndpointAuthMethods.clear()}async function Ut(t,e,r,n){if(typeof t.issuer!="string"||I(new URL(t.issuer))!==e)throw new S("Authorization-server metadata issuer mismatch");r.endpoints.clear(),r.tokenEndpointAuthMethods=new Set(Array.isArray(t.token_endpoint_auth_methods_supported)?t.token_endpoint_auth_methods_supported.filter(o=>typeof o=="string"):[]);for(let[o,s]of Nr){let i=t[o];if(i===void 0)continue;let a=await j(i,n);if("error"in a)throw new S(`Unsafe ${o}: ${a.error}`);r.endpoints.set(I(a.url),s)}}async function At(t,e,r,n,o){for(let s of Tt(t)){let i=await re(s,{method:"GET",headers:{Accept:"application/json"},redirect:"manual",signal:AbortSignal.timeout(n)});if(oe(i.status))throw new S("OAuth metadata redirects are not allowed");if(i.ok){await Lt(_e(await ne(i,o)),t,e,r);break}}if(e.authorizationServers.size===0)throw new S("Protected-resource metadata could not be discovered");for(let s of e.authorizationServers){let i=!1;for(let a of kt(new URL(s))){let c=await re(a,{method:"GET",headers:{Accept:"application/json"},redirect:"manual",signal:AbortSignal.timeout(n)});if(oe(c.status))throw new S("OAuth metadata redirects are not allowed");if(c.ok){await Ut(_e(await ne(c,o)),s,e,r),i=!0;break}}if(i)break}if(e.endpoints.size===0)throw new S("Authorization-server metadata could not be discovered");e.updatedAt=Date.now()}async function re(t,e){return fetch(t,e)}function Br(t){let e=new Headers;if(!t||typeof t!="object"||Array.isArray(t))return e;for(let[r,n]of Object.entries(t)){let o=r.toLowerCase();Ur.has(o)&&typeof n=="string"&&e.set(o,n)}return e}function Fr(t){let e={};return t.forEach((r,n)=>{jr.has(n.toLowerCase())&&(e[n]=r)}),e}function qr(t,e){if(t==null)return;if(typeof t=="string"){if(!e.has("content-type"))try{JSON.parse(t),e.set("content-type","application/json")}catch{e.set("content-type","application/x-www-form-urlencoded")}return t}if((e.get("content-type")??"").includes("application/x-www-form-urlencoded")&&typeof t=="object"&&!Array.isArray(t)){let n=new URLSearchParams;for(let[o,s]of Object.entries(t))n.append(o,String(s));return n.toString()}return e.has("content-type")||e.set("content-type","application/json"),JSON.stringify(t)}function jt(t,e){return`${t}\0${e}`}function zr(t){let{responseBody:e,binding:r,bindingKey:n,clients:o}=t,s=e.client_id,i=e.client_secret;if(typeof s!="string"||typeof i!="string")return e;let a=e.token_endpoint_auth_method,c=a==="client_secret_post"||a==="client_secret_basic"?a:r.tokenEndpointAuthMethods.has("client_secret_basic")?"client_secret_basic":"client_secret_post",l=e.client_secret_expires_at,u=l===0?Number.POSITIVE_INFINITY:typeof l=="number"&&l>0?l*1e3:Date.now()+Hr;for(Kr(o),o.set(jt(n,s),{clientSecret:i,authMethod:c,expiresAt:u});o.size>$r;){let m=o.keys().next().value;if(!m)break;o.delete(m)}let h={...e};return delete h.client_secret,delete h.client_secret_expires_at,h.token_endpoint_auth_method="none",h}function Wr(t){let{body:e,headers:r,bindingKey:n,clients:o}=t;if(!e||!(r.get("content-type")??"").includes("application/x-www-form-urlencoded"))return e;let s=new URLSearchParams(e),i=s.get("client_id");if(!i)return e;let a=jt(n,i),c=o.get(a);if(!c)return e;if(c.expiresAt<=Date.now())return o.delete(a),e;if(s.delete("client_secret"),c.authMethod==="client_secret_basic"){let l=kr.from(`${St(i)}:${St(c.clientSecret)}`,"utf8").toString("base64");r.set("authorization",`Basic ${l}`)}else r.delete("authorization"),s.set("client_id",i),s.set("client_secret",c.clientSecret);return s.toString()}function St(t){return new URLSearchParams({value:t}).toString().slice(6)}function Kr(t){let e=Date.now();for(let[r,n]of t)n.expiresAt<=e&&t.delete(r)}async function Vr(t,e){let r=Number(t.headers.get("content-length"));if(Number.isFinite(r)&&r>e)throw new L;return Nt(t.body,e)}async function ne(t,e){let r=Number(t.headers.get("content-length"));if(Number.isFinite(r)&&r>e)throw await t.body?.cancel(),new L;return Nt(t.body,e)}async function Nt(t,e){if(!t)return"";let r=t.getReader(),n=[],o=0;for(;;){let{done:a,value:c}=await r.read();if(a)break;if(o+=c.byteLength,o>e)throw await r.cancel(),new L;n.push(c)}let s=new Uint8Array(o),i=0;for(let a of n)s.set(a,i),i+=a.byteLength;return new TextDecoder().decode(s)}function _e(t){let e;try{e=JSON.parse(t)}catch{throw new S("OAuth metadata is not valid JSON")}if(!e||typeof e!="object"||Array.isArray(e))throw new S("OAuth metadata is not an object");return e}function Ot(t,e){let r=t.get(e);return r&&Date.now()-r.updatedAt<=Mt?r:(t.delete(e),{authorizationServers:new Set,endpoints:new Map,tokenEndpointAuthMethods:new Set,updatedAt:Date.now()})}function Ct(t){let e=Date.now();for(let[r,n]of t)e-n.updatedAt>Mt&&t.delete(r);for(;t.size>Dr;){let r=t.keys().next().value;if(!r)break;t.delete(r)}}function I(t){let e=new URL(t);return e.hash="",(e.protocol==="https:"&&e.port==="443"||e.protocol==="http:"&&e.port==="80")&&(e.port=""),e.toString().replace(/\/$/,"")}function Gr(t,e,r){if(!t||!(e.get("content-type")??"").includes("json"))return t;try{let o=JSON.parse(t);return!o||typeof o!="object"||Array.isArray(o)?t:JSON.stringify({...o,redirect_uris:[r]})}catch{return t}}function Pe(t){let e=new URL(t);if(e.pathname!=="/"||e.search||e.hash)throw new Error(`OAuth proxy allowed origin must be an origin: ${t}`);return e.origin}function Jr(t,e,r){try{let n=Pe(t);if(n===new URL(e.req.url).origin||r.has(n))return!0;let o=new URL(n),i=e.req.header("x-forwarded-host")?.split(",")[0]?.trim()||e.req.header("host");if(!i||o.host!==i)return!1;let a=e.req.header("x-forwarded-proto")?.split(",")[0]?.trim();return!a||`${a}:`===o.protocol}catch{return!1}}function Yr(t){let e=new Headers;return t&&Dt(e,t),e.set("Access-Control-Allow-Methods","GET, POST, OPTIONS"),e.set("Access-Control-Allow-Headers","Accept, Authorization, Content-Type"),e.set("Access-Control-Max-Age","600"),new Response(null,{status:204,headers:e})}function Dt(t,e){t.set("Access-Control-Allow-Origin",e),t.append("Vary","Origin")}async function It(t,e){return e?e(t):!0}function oe(t){return t>=300&&t<400}function Xr(t){let e=t.toLowerCase().replace(/^\[|\]$/g,"");return e==="localhost"||e.endsWith(".localhost")||e==="::1"||e.startsWith("127.")}function Qr(t){let e=t.toLowerCase();return e.endsWith(".local")||e.endsWith(".internal")||e.endsWith(".home.arpa")}function Ht(t){if(t.includes(":")){let s=t.toLowerCase();return s.startsWith("::ffff:")?Ht(s.slice(7)):!(s==="::"||s==="::1"||s.startsWith("fc")||s.startsWith("fd")||/^fe[89ab]/.test(s)||s.startsWith("ff")||s.startsWith("2001:db8:"))}let e=t.split(".").map(Number);if(e.length!==4||e.some(s=>!Number.isInteger(s)))return!1;let[r,n,o]=e;return!(r===0||r===10||r===127||r===100&&n>=64&&n<=127||r===169&&n===254||r===172&&n>=16&&n<=31||r===192&&n===0&&o===0||r===192&&n===0&&o===2||r===192&&n===168||r===198&&(n===18||n===19)||r===198&&n===51&&o===100||r===203&&n===0&&o===113||r>=224)}function ve(t,e){t&&console.log(`[OAuth BFF] ${e}`)}function Ee(t,e,r){let n=e instanceof Error?e.message:"Unknown error";return r&&console.error("[OAuth BFF]",n),e instanceof L?t.json({error:"Upstream response too large"},502):e instanceof S?t.json({error:e.message},502):e instanceof DOMException&&e.name==="TimeoutError"?t.json({error:"OAuth upstream timed out"},504):t.json({error:"OAuth upstream request failed"},502)}var L=class extends Error{},S=class extends Error{};var Zr=3;function en(t,e){return t.includes("text/event-stream")&&!e}function Oe(t,e={}){let r=e.path||"/mcp/proxy",n=e.enableLogging!==!1;t.use(`${r}/*`,Rt({origin:"*",allowHeaders:["Authorization","Content-Type","Accept","X-Target-URL","X-MCP-Target","Mcp-Session-Id","mcp-session-id","mcp-protocol-version","X-Server-Id","X-Requested-With"],exposeHeaders:["*"]})),n&&t.use(`${r}/*`,_t()),t.all(`${r}/*`,async o=>{try{if(e.authenticate&&!await e.authenticate(o))return o.json({error:"Unauthorized"},401);let s=o.req.header("X-Target-URL");if(!s)return o.json({error:"X-Target-URL header is required",usage:"Set X-Target-URL header to the MCP server URL you want to proxy to"},400);if(!await Se(s,e.allowLoopback??!1))return o.json({error:"Invalid target URL",details:"Target is not allowed by the proxy network policy"},403);if(e.validateRequest&&!await e.validateRequest(s,o))return o.json({error:"Invalid target URL",details:"The requested target URL is not allowed"},403);try{new URL(s)}catch{return o.json({error:"Invalid target URL format",details:"The X-Target-URL must be a valid HTTP/HTTPS URL"},400)}let i=o.req.method,a={},c=o.req.header();for(let[p,g]of Object.entries(c)){let d=p.toLowerCase();!d.startsWith("x-proxy-")&&!d.startsWith("x-target-")&&!d.startsWith("x-mcp-")&&!d.startsWith("x-forwarded-")&&!d.startsWith("cf-")&&d!=="x-original-host"&&d!=="host"&&d!=="origin"&&d!=="referer"&&d!=="cookie"&&d!=="proxy-authorization"&&d!=="accept-encoding"&&d!=="cdn-loop"&&!d.startsWith("sec-fetch-")&&(a[p]=g)}a["Accept-Encoding"]="identity";let l=i!=="GET"&&i!=="HEAD"?new Uint8Array(await o.req.arrayBuffer()).slice():void 0,u=s,h=i,m=l;for(let p=0;;p+=1){let g=await fetch(u,{method:h,headers:a,body:m,redirect:"manual"}),d=g.headers.get("location");if(!(g.status>=300&&g.status<400&&d))return tn(g);if(p>=Zr)return o.json({error:"Too many upstream redirects"},502);let y=new URL(d,u);if(!await Se(y.toString(),e.allowLoopback??!1)||e.validateRequest&&!await e.validateRequest(y.toString(),o))return o.json({error:"Redirect target is not allowed"},403);y.origin!==new URL(u).origin&&(se(a,"authorization"),se(a,"proxy-authorization")),(g.status===303||(g.status===301||g.status===302)&&h==="POST")&&(h="GET",m=void 0,se(a,"content-type"),se(a,"content-length")),u=y.toString()}}catch(s){let i=s instanceof Error?s.message:"Unknown error",a=o.req.header("X-Target-URL");return s instanceof Error&&(s.message.includes("ECONNREFUSED")||s.message.includes("fetch failed"))?console.warn(`[MCP Proxy] Connection refused to ${a||"unknown target"} - server may not be running`):console.error("[MCP Proxy] Request failed:",i,`
98
98
  Target URL:`,a||"unknown",`
99
- Error:`,s),o.json({error:"Proxy request failed",details:i,targetUrl:a||"unknown"},500)}})}function re(e,t){for(let r of Object.keys(e))r.toLowerCase()===t&&delete e[r]}async function Ar(e){let t={};if(e.headers.forEach((o,s)=>{let i=s.toLowerCase();i!=="content-encoding"&&i!=="transfer-encoding"&&i!=="content-length"&&i!=="set-cookie"&&(t[s]=o)}),Er(e.headers.get("content-type")||"",e.headers.get("content-length")))return new Response(e.body,{status:e.status,statusText:e.statusText,headers:t});if([204,205,304].includes(e.status))return new Response(null,{status:e.status,statusText:e.statusText,headers:t});let n=await e.arrayBuffer();return t["Content-Length"]=String(n.byteLength),new Response(n,{status:e.status,statusText:e.statusText,headers:t})}function Ee(e,t,r=""){let n=i=>`${r}${i}`,o=t?.oauthProxyAllowLoopback??!1,s=t?.oauth!==!1;if(e.get(n("/inspector/health"),i=>i.json({status:"ok",protocol:"mcp-use-inspector-preview",version:1,capabilities:["view-preview"]})),ve(e,{path:n("/inspector/api/proxy"),allowLoopback:o}),s&&xe(e,{basePath:n("/inspector/api/oauth"),callbackPath:n("/inspector/oauth/callback"),enableLogging:!0,allowedOrigins:t?.oauthProxyAllowedOrigins??[],allowLoopback:o}),t?.autoConnectUrl!==void 0){let i=t.autoConnectUrl;e.get(n("/inspector/config.json"),a=>a.json({autoConnectUrl:i??null}))}}function Or(e,t){if(Ur(e)){let o=e,s=t,i=Rt(s?.basePath);if(Et(o)){vt(o,s,i);return}let a=bt(s,i),c=xt(a);o.use(Cr(c,a.routes.map(l=>l.path)));return}let r=e,n=Rt(r?.basePath);return xt(bt(r,n))}function bt(e,t){let r=new ge;return vt(r,e,t),r}function vt(e,t,r){let n={oauthProxyAllowedOrigins:t?.oauthProxyAllowedOrigins??[],oauthProxyAllowLoopback:t?.oauthProxyAllowLoopback??!0};t?.autoConnectUrl!==void 0?n.autoConnectUrl=t.autoConnectUrl:e.get(`${r}/inspector/config.json`,o=>{let s=new URL(o.req.url);return o.json({autoConnectUrl:`${s.origin}${r}`})}),Ee(e,n,r),Ze(e,{devMode:t?.devMode??!0,sandboxOrigin:t?.sandboxOrigin,inspectorMode:"embedded",rootRedirect:!1,basePath:r,proxyUrl:`${r}/inspector/api/proxy`,manufactChatUrl:t?.manufactChatUrl},r)}function xt(e){return t=>Promise.resolve(e.fetch(t))}function Cr(e,t){let r=new Set(t.filter(o=>!o.includes("*"))),n=t.filter(o=>o.endsWith("/*")).map(o=>o.slice(0,-1));return(o,s,i)=>{let a=new URL(o.originalUrl||o.url||"",_r(o));if(!r.has(a.pathname)&&!n.some(l=>a.pathname.startsWith(l))){i();return}let c=Sr(o,a);e(c).then(l=>kr(s,l)).catch(i)}}function _r(e){let r=Ae(e.headers["x-forwarded-proto"])||e.protocol||"http",o=Ae(e.headers["x-forwarded-host"])||Ae(e.headers.host)||"localhost";return`${r}://${o}`}function Ae(e){return Array.isArray(e)?e[0]??"":(e??"").split(",")[0].trim()}function Sr(e,t){let r={method:e.method,headers:e.headers};return e.method!=="GET"&&e.method!=="HEAD"&&(e.body!==void 0?r.body=Tr(e.body):(r.body=Pr.toWeb(e),r.duplex="half")),new globalThis.Request(t,r)}function Tr(e){return typeof e=="string"||e instanceof ArrayBuffer||ArrayBuffer.isView(e)||e instanceof Blob||e instanceof FormData||e instanceof URLSearchParams||e instanceof ReadableStream?e:JSON.stringify(e)}async function kr(e,t){e.status(t.status),t.headers.forEach((o,s)=>{s!=="set-cookie"&&e.setHeader(s,o)});let r=t.headers.getSetCookie();if(r.length>0&&e.setHeader("set-cookie",r),!t.body){e.end();return}let n=t.body.getReader();for(;;){let{done:o,value:s}=await n.read();if(o)break;e.write(s)}e.end()}function Ur(e){return!e||typeof e!="object"&&typeof e!="function"?!1:typeof e.use=="function"||Et(e)}function Et(e){return!!e&&typeof e=="object"&&typeof e.fetch=="function"&&typeof e.route=="function"}function Rt(e){if(e===void 0)return"/mcp";let t=e.trim().replace(/\/{2,}/g,"/").replace(/\/+$/,"");return t===""||t==="/"?"":(t.startsWith("/")||(t=`/${t}`),t)}export{Or as mountInspector,Ee as registerInspectorProxyRoutes};
99
+ Error:`,s),o.json({error:"Proxy request failed",details:i,targetUrl:a||"unknown"},500)}})}function se(t,e){for(let r of Object.keys(t))r.toLowerCase()===e&&delete t[r]}async function tn(t){let e={};if(t.headers.forEach((o,s)=>{let i=s.toLowerCase();i!=="content-encoding"&&i!=="transfer-encoding"&&i!=="content-length"&&i!=="set-cookie"&&(e[s]=o)}),en(t.headers.get("content-type")||"",t.headers.get("content-length")))return new Response(t.body,{status:t.status,statusText:t.statusText,headers:e});if([204,205,304].includes(t.status))return new Response(null,{status:t.status,statusText:t.statusText,headers:e});let n=await t.arrayBuffer();return e["Content-Length"]=String(n.byteLength),new Response(n,{status:t.status,statusText:t.statusText,headers:e})}function Ce(t,e,r=""){let n=i=>`${r}${i}`,o=e?.oauthProxyAllowLoopback??!1,s=e?.oauth!==!1;if(t.use(n("/inspector/api/*"),te({points:ft,durationSeconds:ee,key:"inspector-api"})),t.get(n("/inspector/health"),i=>i.json({status:"ok",protocol:"mcp-use-inspector-preview",version:1,capabilities:["view-preview"]})),Oe(t,{path:n("/inspector/api/proxy"),allowLoopback:o}),s&&Ae(t,{basePath:n("/inspector/api/oauth"),callbackPath:n("/inspector/oauth/callback"),enableLogging:!0,allowedOrigins:e?.oauthProxyAllowedOrigins??[],allowLoopback:o}),e?.autoConnectUrl!==void 0){let i=e.autoConnectUrl;t.get(n("/inspector/config.json"),a=>a.json({autoConnectUrl:i??null}))}}function nn(t,e){if(un(t)){let o=t,s=e,i=Ft(s?.basePath);if(zt(o)){qt(o,s,i);return}let a=$t(s,i),c=Bt(a);o.use(on(c,a.routes.map(l=>l.path)));return}let r=t,n=Ft(r?.basePath);return Bt($t(r,n))}function $t(t,e){let r=new we;return qt(r,t,e),r}function qt(t,e,r){let n={oauthProxyAllowedOrigins:e?.oauthProxyAllowedOrigins??[],oauthProxyAllowLoopback:e?.oauthProxyAllowLoopback??!0};e?.autoConnectUrl!==void 0?n.autoConnectUrl=e.autoConnectUrl:t.get(`${r}/inspector/config.json`,o=>{let s=new URL(o.req.url);return o.json({autoConnectUrl:`${s.origin}${r}`})}),Ce(t,n,r),bt(t,{devMode:e?.devMode??!0,sandboxOrigin:e?.sandboxOrigin,inspectorMode:"embedded",rootRedirect:!1,basePath:r,proxyUrl:`${r}/inspector/api/proxy`,manufactChatUrl:e?.manufactChatUrl},r)}function Bt(t){return e=>Promise.resolve(t.fetch(e))}function on(t,e){let r=new Set(e.filter(o=>!o.includes("*"))),n=e.filter(o=>o.endsWith("/*")).map(o=>o.slice(0,-1));return(o,s,i)=>{let a=new URL(o.originalUrl||o.url||"",sn(o));if(!r.has(a.pathname)&&!n.some(l=>a.pathname.startsWith(l))){i();return}let c=an(o,a);t(c).then(l=>ln(s,l)).catch(i)}}function sn(t){let r=Ie(t.headers["x-forwarded-proto"])||t.protocol||"http",o=Ie(t.headers["x-forwarded-host"])||Ie(t.headers.host)||"localhost";return`${r}://${o}`}function Ie(t){return Array.isArray(t)?t[0]??"":(t??"").split(",")[0].trim()}function an(t,e){let r={method:t.method,headers:t.headers};return t.method!=="GET"&&t.method!=="HEAD"&&(t.body!==void 0?r.body=cn(t.body):(r.body=rn.toWeb(t),r.duplex="half")),new globalThis.Request(e,r)}function cn(t){return typeof t=="string"||t instanceof ArrayBuffer||ArrayBuffer.isView(t)||t instanceof Blob||t instanceof FormData||t instanceof URLSearchParams||t instanceof ReadableStream?t:JSON.stringify(t)}async function ln(t,e){t.status(e.status),e.headers.forEach((o,s)=>{s!=="set-cookie"&&t.setHeader(s,o)});let r=e.headers.getSetCookie();if(r.length>0&&t.setHeader("set-cookie",r),!e.body){t.end();return}let n=e.body.getReader();for(;;){let{done:o,value:s}=await n.read();if(o)break;t.write(s)}t.end()}function un(t){return!t||typeof t!="object"&&typeof t!="function"?!1:typeof t.use=="function"||zt(t)}function zt(t){return!!t&&typeof t=="object"&&typeof t.fetch=="function"&&typeof t.route=="function"}function Ft(t){if(t===void 0)return"/mcp";let e=t.trim(),r=[],n=!1;for(let s of e)s==="/"?(n||r.push(s),n=!0):(r.push(s),n=!1);for(;r.length>0&&r[r.length-1]==="/";)r.pop();let o=r.join("");return o===""||o==="/"?"":(o.startsWith("/")||(o=`/${o}`),o)}export{nn as mountInspector,Ce as registerInspectorProxyRoutes};
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@mcp-use/inspector",
3
3
  "type": "module",
4
- "version": "20.0.0-beta.33",
4
+ "version": "20.0.0-beta.34",
5
5
  "description": "MCP Inspector - A tool for inspecting and debugging MCP servers",
6
6
  "author": "",
7
7
  "license": "MIT",
@@ -56,7 +56,7 @@
56
56
  "react-resizable-panels": "^4.6.4",
57
57
  "sonner": "^2.0.7",
58
58
  "tailwind-merge": "^3.5.0",
59
- "mcp-use": "2.0.0-beta.41"
59
+ "mcp-use": "2.0.0-beta.42"
60
60
  },
61
61
  "peerDependenciesMeta": {
62
62
  "@base-ui/react": {
@@ -128,6 +128,7 @@
128
128
  "react-dom": "^19.2.3",
129
129
  "react-router": "^7.12.0",
130
130
  "react-resizable-panels": "^4.6.4",
131
+ "rate-limiter-flexible": "^11.2.0",
131
132
  "rollup-plugin-visualizer": "^6.0.3",
132
133
  "sonner": "^2.0.7",
133
134
  "tailwind-merge": "^3.5.0",
@@ -140,8 +141,8 @@
140
141
  "vitest": "^4.1.0",
141
142
  "wait-on": "^9.0.4",
142
143
  "zod": "^4.2.0",
143
- "@mcp-use/client": "2.0.0-beta.12",
144
- "@mcp-use/agent": "2.0.0-beta.13"
144
+ "@mcp-use/client": "2.0.0-beta.13",
145
+ "@mcp-use/agent": "2.0.0-beta.14"
145
146
  },
146
147
  "scripts": {
147
148
  "dev": "rimraf node_modules/.vite && VITE_MANUFACT_CHAT_URL=${VITE_MANUFACT_CHAT_URL:-http://localhost:8000/api/v1/inspector/chat/stream} vite --strictPort",