mcp-use 2.0.0-beta.57 → 2.0.0-beta.59

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/dist/bin.js CHANGED
@@ -1,2 +1,2 @@
1
1
  #!/usr/bin/env node
2
- var{main}=await import("@mcp-use/cli");main(process.argv.slice(2),{frameworkVersion:"2.0.0-beta.57"}).then(code=>{process.exitCode=code},error=>{console.error(error instanceof Error?error.message:String(error)),process.exitCode=1});
2
+ var{main}=await import("@mcp-use/cli");main(process.argv.slice(2),{frameworkVersion:"2.0.0-beta.59"}).then(code=>{process.exitCode=code},error=>{console.error(error instanceof Error?error.message:String(error)),process.exitCode=1});
@@ -1,2 +1,2 @@
1
1
  var EVENT="mcp_use_sdk_event",ENDPOINT="https://eu.i.posthog.com/i/v0/e/",TOKEN="phc_lyTtbYwvkdSbrcMQNPiKiiRWrrM1seyKIMjycSvItEI",CONTENT=/(^|_)(arguments?|args|body|command|headers?|location|message|organization|path|query|response|secret|subject|token|uri|url|user_agent)(_|$)/i,RESERVED=new Set("feature action sdk_generation telemetry_schema_version sdk_package sdk_version server_id runtime_id identity_stability distinct_id validation_run_id is_validation".split(" ")),runtimeId=crypto.randomUUID(),once=new Set,pending=new Set,identities=new Map;function hasControl(value){return[...value].some(character=>{let code=character.charCodeAt(0);return code<32||code===127})}function env(name){return typeof process>"u"?void 0:process.env?.[name]}function safeEnv(name){let value=env(name);return value!==void 0&&value.length>0&&value.length<=128&&!hasControl(value)?value:void 0}function disabled(){if(env("MCP_USE_ANONYMIZED_TELEMETRY")==="false")return!0;try{return globalThis.__MCP_USE_ANONYMIZED_TELEMETRY__===!1||typeof localStorage<"u"&&localStorage.getItem("MCP_USE_ANONYMIZED_TELEMETRY")==="false"}catch{return!1}}function isUsageDisabled(){return disabled()}function clean(properties){return Object.fromEntries(Object.entries(properties).filter(([key,value])=>key.length>128||hasControl(key)||key.startsWith("$")||RESERVED.has(key)||CONTENT.test(key)||value===void 0?!1:typeof value=="string"?value.length<=128&&!hasControl(value):typeof value=="boolean"||typeof value=="number"&&Number.isFinite(value)))}async function identity(serverRoot){let projectId=safeEnv("MCP_USE_TELEMETRY_PROJECT_ID");if(projectId!==void 0)return{id:projectId,stability:"project"};if(serverRoot===void 0||typeof process>"u")return{id:runtimeId,stability:"process"};let existing=identities.get(serverRoot);if(existing!==void 0)return existing;let resolving=(async()=>{try{let fs=await import("fs/promises"),directory=`${serverRoot}/.mcp-use`,file=`${directory}/usage.json`,read=async()=>{try{let value=JSON.parse(await fs.readFile(file,"utf8"));if(typeof value=="object"&&value!==null&&"schemaVersion"in value&&value.schemaVersion===1&&"serverId"in value&&typeof value.serverId=="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(value.serverId))return value.serverId}catch{}},stored=await read();if(stored!==void 0)return{id:stored,stability:"server"};await fs.mkdir(directory,{recursive:!0,mode:448});let created=crypto.randomUUID();try{return await fs.writeFile(file,`${JSON.stringify({schemaVersion:1,serverId:created})}
2
- `,{flag:"wx",mode:384}),{id:created,stability:"server"}}catch{let raced=await read();if(raced!==void 0)return{id:raced,stability:"server"}}}catch{}return{id:runtimeId,stability:"process"}})();return identities.set(serverRoot,resolving),resolving}function capture(feature,action,properties,options,resolveIdentity){let validationId=safeEnv("MCP_USE_TELEMETRY_VALIDATION_ID");if(disabled()||env("NODE_ENV")==="test"&&validationId===void 0||pending.size>=16)return;if(options.onceKey!==void 0){if(once.has(options.onceKey))return;once.add(options.onceKey)}let rate=Math.max(0,Math.min(1,options.sampleRate??1));if(validationId===void 0&&Math.random()>=rate)return;let request=(async()=>{try{let resolvedIdentity=await resolveIdentity(),body=JSON.stringify({api_key:TOKEN,event:EVENT,properties:{...clean(properties),feature,action,sdk_generation:"v2",telemetry_schema_version:2,sdk_package:"mcp-use",sdk_version:"2.0.0-beta.57",server_id:resolvedIdentity.id,runtime_id:runtimeId,identity_stability:resolvedIdentity.stability,distinct_id:resolvedIdentity.id,sample_rate:validationId===void 0?rate:1,$process_person_profile:!1,$geoip_disable:!0,...validationId!==void 0&&{is_validation:!0,validation_run_id:validationId}}});await fetch(ENDPOINT,{method:"POST",headers:{"content-type":"application/json"},keepalive:!0,body})}catch{return}})();pending.add(request),request.then(()=>pending.delete(request))}function recordUsage(feature,action,properties={},options={}){capture(feature,action,properties,options,()=>identity(options.serverRoot))}async function flushUsage(){await Promise.all([...pending])}export{isUsageDisabled,recordUsage,flushUsage};
2
+ `,{flag:"wx",mode:384}),{id:created,stability:"server"}}catch{let raced=await read();if(raced!==void 0)return{id:raced,stability:"server"}}}catch{}return{id:runtimeId,stability:"process"}})();return identities.set(serverRoot,resolving),resolving}function capture(feature,action,properties,options,resolveIdentity){let validationId=safeEnv("MCP_USE_TELEMETRY_VALIDATION_ID");if(disabled()||env("NODE_ENV")==="test"&&validationId===void 0||pending.size>=16)return;if(options.onceKey!==void 0){if(once.has(options.onceKey))return;once.add(options.onceKey)}let rate=Math.max(0,Math.min(1,options.sampleRate??1));if(validationId===void 0&&Math.random()>=rate)return;let request=(async()=>{try{let resolvedIdentity=await resolveIdentity(),body=JSON.stringify({api_key:TOKEN,event:EVENT,properties:{...clean(properties),feature,action,sdk_generation:"v2",telemetry_schema_version:2,sdk_package:"mcp-use",sdk_version:"2.0.0-beta.59",server_id:resolvedIdentity.id,runtime_id:runtimeId,identity_stability:resolvedIdentity.stability,distinct_id:resolvedIdentity.id,sample_rate:validationId===void 0?rate:1,$process_person_profile:!1,$geoip_disable:!0,...validationId!==void 0&&{is_validation:!0,validation_run_id:validationId}}});await fetch(ENDPOINT,{method:"POST",headers:{"content-type":"application/json"},keepalive:!0,body})}catch{return}})();pending.add(request),request.then(()=>pending.delete(request))}function recordUsage(feature,action,properties={},options={}){capture(feature,action,properties,options,()=>identity(options.serverRoot))}async function flushUsage(){await Promise.all([...pending])}export{isUsageDisabled,recordUsage,flushUsage};
package/dist/compat-v1.js CHANGED
@@ -1,11 +1,19 @@
1
- import{a as vt,b as Rt}from"./chunk-ZBN5QPYD.js";import{a as ke,b as _e,c as $,d as Ue}from"./chunk-4TTKTNKI.js";function ir(e){return{content:[{type:"text",text:e}],_meta:{mimeType:"text/plain"}}}function ar(e){return{content:[{type:"text",text:e}],_meta:{mimeType:"text/markdown"}}}function ur(e){return{content:[{type:"text",text:e}],_meta:{mimeType:"text/html"}}}function dr(e){return{content:[{type:"text",text:e}],_meta:{mimeType:"text/xml"}}}function cr(e){return{content:[{type:"text",text:e}],_meta:{mimeType:"text/css"}}}function lr(e){return{content:[{type:"text",text:e}],_meta:{mimeType:"text/javascript"}}}function pr(e,t="image/png"){return{content:[{type:"image",data:e,mimeType:t}],_meta:{mimeType:t,isImage:!0}}}function fr(e,t="audio/wav"){return{content:[{type:"audio",data:e,mimeType:t}],_meta:{mimeType:t,isAudio:!0}}}function mr(e,t){return{content:[{type:"text",text:e}],_meta:{mimeType:t,isBinary:!0}}}function hr(e,t,n){if(typeof t=="object"&&t!==null&&"content"in t){let o=t,s,i;if(o._meta&&typeof o._meta=="object"){let a=o._meta;typeof a.mimeType=="string"&&(i=a.mimeType)}let u=o.content?.[0];return u?.type==="text"&&"text"in u&&(s=u.text),{content:[{type:"resource",resource:{uri:e,...i!==void 0&&{mimeType:i},text:s??""}}]}}let r=t;return{content:[{type:"resource",resource:{uri:e,...r!==void 0&&r!==""&&{mimeType:r},text:n??""}}]}}function gr(e){return{isError:!0,content:[{type:"text",text:e}]}}function yr(e){return Array.isArray(e)?Ie(e):{content:[{type:"text",text:JSON.stringify(e,null,2)}],structuredContent:e,_meta:{mimeType:"application/json"}}}function Ie(e){return{content:[{type:"text",text:JSON.stringify(e,null,2)}],structuredContent:e}}function Tt(e){let t=e.props??e.data??{},{output:n,message:r,metadata:o}=e,i={content:r?[{type:"text",text:r}]:Array.isArray(n?.content)&&n.content.length>0?n.content:[{type:"text",text:""}]};return o!==void 0&&Object.keys(o).length>0&&(i._meta=o),n?.structuredContent!==void 0?i.structuredContent=n.structuredContent:Object.keys(t).length>0&&(i.structuredContent=t),i}function wr(...e){let t=e.filter(s=>s.structuredContent!==void 0),n=t.length>0?t.map(s=>s.structuredContent).reduce((s,i)=>({...s,...typeof i=="object"&&i!==null?i:{}}),{}):void 0,r=e.filter(s=>s._meta!==void 0),o=r.length>0?r.map(s=>s._meta).reduce((s,i)=>({...s,...i!==void 0?i:{}}),{}):void 0;return{content:e.flatMap(s=>s.content),...n!==void 0&&Object.keys(n).length>0&&{structuredContent:n},...o!==void 0&&Object.keys(o).length>0&&{_meta:o}}}import{localhostAllowedHostnames as Nn,localhostAllowedOrigins as Ms,McpServer as bs,ResourceTemplate as xs,CLIENT_CAPABILITIES_META_KEY as Os,CLIENT_INFO_META_KEY as As,PROTOCOL_VERSION_META_KEY as Cs,isJSONRPCRequest as Bn,isInputRequiredResult as Hn}from"@modelcontextprotocol/server";import{createServer as Es}from"#mcp-use-node-http";import{Hono as qn}from"hono";var Mt="public, max-age=31536000, immutable",vr="public, max-age=300";function je(e){return/^([a-z][a-z\d+.-]*):/i.exec(e)?.[1]?.toLowerCase()}function Rr(e,t){return`${e==="/"?"":e}/_mcp-use/public/${t.split("/").map(r=>encodeURIComponent(r)).join("/")}`}function Le(e){return je(e)===void 0}function Tr(e){return e[0]}function Mr(e,t){if(e.startsWith("/")||e.includes("\\")||e.includes("?")||e.includes("#")||e.split("/").some(n=>n===""||n===".."))throw new TypeError(`${t} must be an http(s) URL, image data URL, or safe path relative to public/`)}function xt(e,t){let n=e.indexOf(",");if(n<0)throw new TypeError(`${t} must be a valid image data URL`);let r=e.slice(5,n),o=e.slice(n+1),s=r.split(";"),i=s[0]?.toLowerCase()??"";if(!i.startsWith("image/"))throw new TypeError(`${t} data URL must use an image MIME type`);try{if(s.includes("base64")){let u=atob(o);return{mimeType:i,bytes:Uint8Array.from(u,a=>a.charCodeAt(0))}}return{mimeType:i,bytes:new TextEncoder().encode(decodeURIComponent(o))}}catch{throw new TypeError(`${t} must be a valid image data URL`)}}function bt(e,t){if(typeof e!="string"||e.length===0)throw new TypeError(`${t} must be a non-empty string`);let n=je(e);if(n===void 0)return Mr(e,t),e;if(n==="data")return xt(e,t),e;if(n!=="http"&&n!=="https")throw new TypeError(`${t} must be an http(s) URL, image data URL, or safe path relative to public/`);try{new URL(e)}catch{throw new TypeError(`${t} must be a valid absolute http(s) URL`)}return e}function Ot(e){let t;if(e.websiteUrl!==void 0){if(typeof e.websiteUrl!="string"||e.websiteUrl.length===0)throw new TypeError("websiteUrl must be a non-empty absolute http(s) URL");let u;try{u=new URL(e.websiteUrl)}catch{throw new TypeError("websiteUrl must be a non-empty absolute http(s) URL")}if(u.protocol!=="http:"&&u.protocol!=="https:")throw new TypeError("websiteUrl must be a non-empty absolute http(s) URL");t=e.websiteUrl}let n;if(e.icons!==void 0){if(!Array.isArray(e.icons))throw new TypeError("icons must be an array of MCP Icon objects");n=Object.freeze(e.icons.map((u,a)=>{if(typeof u!="object"||u===null)throw new TypeError(`icons[${a}] must be an MCP Icon object`);let d=u,c=bt(d.src,`icons[${a}].src`),l=d.mimeType;if(l!==void 0&&(typeof l!="string"||!l.toLowerCase().startsWith("image/")))throw new TypeError(`icons[${a}].mimeType must be an image MIME type when provided`);let p=d.sizes;if(p!==void 0&&(!Array.isArray(p)||p.some(h=>typeof h!="string"||h.length===0)))throw new TypeError(`icons[${a}].sizes must be an array of non-empty strings when provided`);let g=p===void 0?void 0:p.map(h=>h),f=d.theme;if(f!==void 0&&f!=="light"&&f!=="dark")throw new TypeError(`icons[${a}].theme must be "light" or "dark" when provided`);return Object.freeze({src:c,...l!==void 0&&{mimeType:l},...g!==void 0&&{sizes:Object.freeze(g)},...f!==void 0&&{theme:f}})}))}let r=e.favicon===void 0?void 0:bt(e.favicon,"favicon"),o=r===void 0?Tr(n??[]):void 0,s=r??o?.src,i=o?.mimeType??n?.find(u=>u.src===r)?.mimeType;return Object.freeze({...s!==void 0&&{favicon:s},...i!==void 0&&{faviconMimeType:i},...n!==void 0&&{icons:n},...t!==void 0&&{websiteUrl:t}})}function At(e,t,n){if(e!==void 0)return e.map(r=>({...r,src:t!==void 0&&Le(r.src)?`${$(t)}${Rr(n,r.src)}`:r.src,...r.sizes!==void 0&&{sizes:[...r.sizes]}}))}function Ct(e){return e.favicon!==void 0&&Le(e.favicon)||e.icons?.some(t=>Le(t.src))===!0}function Et(e,t){let n=e.favicon;if(n!==void 0)return async r=>{if(r.method!=="GET"&&r.method!=="HEAD")return new Response("Method Not Allowed",{status:405,headers:{Allow:"GET, HEAD"}});if(new URL(r.url).pathname!=="/favicon.ico")return new Response("Not Found",{status:404});let o=je(n);if(o==="http"||o==="https")return new Response(null,{status:307,headers:{Location:n,"Cache-Control":vr}});if(o==="data"){let d=xt(n,"favicon");return new Response(r.method==="HEAD"?null:d.bytes.buffer,{status:200,headers:{"Content-Type":e.faviconMimeType??d.mimeType,"Cache-Control":Mt,"X-Content-Type-Options":"nosniff"}})}let{join:s}=await import("path"),i=t.dev?s(t.projectRoot,"public"):s(t.projectRoot,".mcp-use/build/views/public"),u=await vt(i,n);if(u===null)return new Response("Not Found",{status:404,headers:{"Cache-Control":"no-store"}});let a=await Rt(u,{...t.deferCors===!0&&{deferCors:!0},...r.method==="HEAD"&&{head:!0}});return a.headers.set("Cache-Control",Mt),a.headers.set("X-Content-Type-Options","nosniff"),e.faviconMimeType!==void 0&&a.headers.set("Content-Type",e.faviconMimeType),a}}function Pt(e){if(e.basePath!==void 0){if(typeof e.basePath!="string")throw new TypeError("basePath must be an absolute URL pathname without empty segments, trailing slash, query, fragment, or whitespace");let{basePath:t}=e;if(!t.startsWith("/")||t.includes("?")||t.includes("#")||/\s/.test(t)||t.includes("//")||t.length>1&&t.endsWith("/"))throw new TypeError("basePath must be an absolute URL pathname without empty segments, trailing slash, query, fragment, or whitespace")}if(e.port!==void 0&&(typeof e.port!="number"||!Number.isInteger(e.port)||e.port<0||e.port>65535))throw new TypeError("port must be an integer between 0 and 65535")}var br="127.0.0.1";function St(e,t,n=process.env){if(e!==void 0)return e;let r=n.HOST?.trim();return r!==void 0&&r!==""?r:t??br}function kt(e,t,n=process.env){if(e!==void 0)return e;let r=xr(n.PORT);return r!==void 0?r:t??3e3}function xr(e){if(e===void 0||e.trim()==="")return;let t=Number(e);return Number.isInteger(t)&&t>=0&&t<=65535?t:void 0}var _t=new WeakSet,Ut=new WeakMap;function It(e){return e.body!==null&&_t.add(e),e}function Lt(e,t){return It(t),Ut.set(e,t),t}function Ne(e,t){if(e.body===null)return!1;if(_t.has(e))return!0;let n=t===void 0?void 0:Ut.get(t);return n!==void 0&&n.body!==null&&n.body===e.body}function jt(e,t){return Ne(e)?It(t):t}function Ht(e,t){return async(n,r,o)=>{typeof o=="function"&&(o=void 0);let s=!1,i=new AbortController;r.on("close",()=>{s||i.abort()}),r.destroyed===!0&&i.abort();let u,a;try{u=await Or(n,o,{signal:i.signal}),a=await e.fetch(u,{...n.auth!==void 0&&{authInfo:n.auth},...o!==void 0&&{parsedBody:o}})}catch(f){try{t?.onerror?.(f instanceof Error?f:new Error(String(f)))}catch{}a=Cr(Ar(o))}let d={};for(let[f,h]of a.headers)d[f]=h;if(r.writeHead(a.status,d),a.body===null){s=!0,r.end();return}if(Ne(a,u)){try{let f=new Uint8Array(await a.arrayBuffer());s=!0,r.end(f)}catch{s=!0,r.end()}return}let c,l=()=>{c?.(),c=void 0},p=()=>new Promise(f=>{c=f});r.on("drain",l);let g=new Promise(f=>{i.signal.addEventListener("abort",()=>f(),{once:!0})});try{for await(let f of a.body){if(i.signal.aborted)break;let h=f instanceof Uint8Array?f:new Uint8Array(f);r.write(h)===!1&&await Promise.race([p(),g])}}catch{}s=!0,r.end()}}async function Or(e,t,n){let r=(e.method??"GET").toUpperCase(),s=`http://${Nt(e.headers.host)??Nt(e.headers[":authority"])??"localhost"}${e.url??"/"}`,i=new Headers;for(let[a,d]of Object.entries(e.headers))if(!(d===void 0||a.startsWith(":")))if(Array.isArray(d))for(let c of d)i.append(a,c);else i.set(a,d);let u;if(r!=="GET"&&r!=="HEAD")if(t===void 0){let a=new TextDecoder,d="";for await(let c of e)d+=typeof c=="string"?c:a.decode(c,{stream:!0});d+=a.decode(),d.length>0&&(u=d)}else{let a=JSON.stringify(t);i.delete("content-encoding"),i.delete("transfer-encoding"),a===void 0?i.delete("content-length"):(u=a,i.set("content-length",String(new TextEncoder().encode(a).byteLength)))}return new Request(s,{method:r,headers:i,...n?.signal!==void 0&&{signal:n.signal},...u!==void 0&&{body:u}})}function Nt(e){return Array.isArray(e)?e[0]:e}function Ar(e){if(e===null||typeof e!="object"||Array.isArray(e))return null;let{method:t,id:n}=e;return typeof t!="string"?null:typeof n=="string"||typeof n=="number"?n:null}function Cr(e){return Response.json({jsonrpc:"2.0",error:{code:-32603,message:"Internal server error"},id:e},{status:500})}import{CLIENT_CAPABILITIES_META_KEY as _r,CLIENT_INFO_META_KEY as Ur,inputRequired as Be,inputResponse as Ir}from"@modelcontextprotocol/server";import{HonoRequest as Lr}from"hono/request";import{hostHeaderValidationResponse as Er,originValidationResponse as Pr}from"@modelcontextprotocol/server";var qt=new WeakMap;function T(e){let t=qt.get(e);return t===void 0&&(t={},qt.set(e,t)),t}function ae(e){return new URL(e.url).pathname}function Dt(e,t){return ae(e)===t}function He(e,t){let n=ae(e);return n===t||n.startsWith(`${t}/`)}function G(e,t){let n=t.replace(/^\/+/,"");return e==="/"?`/${n}`:`${e}/${n}`}function qe(e){if(e.method!=="GET"&&e.method!=="HEAD")return!1;let t=e.headers.get("accept");return t===null?!1:t.split(",").some(n=>{let[r,...o]=n.split(";");return r?.trim().toLowerCase()!=="text/html"?!1:!o.some(s=>{let[i,u]=s.trim().toLowerCase().split("=");return i==="q"&&Number(u)===0})})}function $t(){return async(e,t)=>{let n=T(e);if(n.parsedBody!==void 0||!(e.headers.get("content-type")??"").includes("application/json"))return t();try{n.parsedBody=await e.clone().json()}catch{return new Response("Invalid JSON",{status:400})}return t()}}function Vt(e){return async(t,n)=>Er(t,e)??n()}function Bt(e,t=!0){return async(n,r)=>t&&(n.method==="GET"||n.method==="HEAD")?r():Pr(n,e)??r()}import{CLIENT_CAPABILITIES_META_KEY as Sr}from"@modelcontextprotocol/server";var De="io.modelcontextprotocol/ui",ue="text/html;profile=mcp-app",Ft="ui://views/";var de="ui/resourceUri";function Y(e){return`${Ft}${e}.html`}var kr=new WeakMap;function $e(e,t){kr.set(e,t)}function Ve(e){if(typeof e!="object"||e===null)return;let t=e.params;if(typeof t!="object"||t===null)return;let n=t._meta;if(typeof n!="object"||n===null)return;let r=n[Sr];if(!(typeof r!="object"||r===null))return r}function ce(e){let t=e?.extensions;if(t===void 0)return!1;let n=t[De];if(typeof n!="object"||n===null)return!1;let r=n.mimeTypes;return Array.isArray(r)?r.includes(ue):!1}function jr(e){if(e===void 0||e.extra===void 0||e.expiresAt===void 0)throw new Error("OAuth callback did not receive mapped AuthInfo.extra")}function _(e){return typeof e=="string"?e:void 0}function Wt(e){return typeof e=="string"||typeof e=="number"&&Number.isFinite(e)?e:void 0}function Nr(e){if(e===void 0)return;let t=_(e["openai/locale"])??_(e["webplus/i18n"]),n=_(e["openai/userAgent"]),r=_(e["openai/subject"]),o=_(e["openai/session"]),s=_(e["openai/organization"]),i=e["openai/userLocation"],u;if(typeof i=="object"&&i!==null&&!Array.isArray(i)){let a=i,d={city:_(a.city),region:_(a.region),country:_(a.country),timezone:_(a.timezone),latitude:Wt(a.latitude),longitude:Wt(a.longitude)},c=Object.entries(d).filter(l=>l[1]!==void 0);c.length>0&&(u=Object.fromEntries(c))}if(!(t===void 0&&n===void 0&&u===void 0&&r===void 0&&o===void 0&&s===void 0))return{...t!==void 0&&{locale:t},...n!==void 0&&{userAgent:n},...u!==void 0&&{location:u},...r!==void 0&&{subject:r},...o!==void 0&&{conversationId:o},...s!==void 0&&{organizationId:s}}}function Hr(e){let t=e.mcpReq.envelope,n={...t?.[_r]??{}},r={...t?.[Ur]??{}},o=Nr(e.mcpReq._meta);return{can(s){return Object.hasOwn(n,s)},capabilities(){return{...n}},extension(s){let i=n.extensions?.[s];return i===void 0?void 0:{...i}},info(){return{...r}},user(){return o===void 0?void 0:{...o,...o.location!==void 0&&{location:{...o.location}}}},supportsViews(){return ce(n)}}}function qr(e){return async function(n,r,o){let s,i;if(typeof o=="string")s=Be.elicitUrl({message:r,url:o});else if(o!==void 0)i=o,s=Be.elicit({message:r,requestedSchema:o});else throw new TypeError("ctx.elicit(key, message, value) requires a form schema or URL string");let u=Ir(e,n);if(u.kind==="elicit"){if(u.action!=="accept")return{status:u.action};if(i===void 0)return{status:"accept"};if(u.content!==void 0){let a=await i["~standard"].validate(u.content);if(a.issues===void 0)return{status:"accept",data:a.value}}}return{status:"required",result:Be({inputRequests:{[n]:s}})}}}function we(e){let t=e.http?.req,n=t===void 0?void 0:T(t).honoContext,r=n?.req??(t===void 0?void 0:new Lr(t)),o={signal:e.mcpReq.signal,...r!==void 0&&{request:r},...e.mcpReq.inputResponses!==void 0&&{inputResponses:e.mcpReq.inputResponses},client:Hr(e),elicit:qr(e.mcpReq.inputResponses),requestState:()=>e.mcpReq.requestState(),async sendNotification(s,i){await e.mcpReq.notify({method:s,...i!==void 0&&{params:i}})},async reportProgress(s,i,u){let a=e.mcpReq._meta?.progressToken;return a===void 0?!1:(await e.mcpReq.notify({method:"notifications/progress",params:{progressToken:a,progress:s,...i!==void 0&&{total:i},...u!==void 0&&{message:u}}}),!0)},async sendLog(s,i,u){await e.mcpReq.notify({method:"notifications/message",params:{level:s,data:i,...u!==void 0&&{logger:u}}})}};return n!==void 0?Object.assign(n,o):{...o,...r!==void 0&&{req:r}}}function zt(e){let t=e.http?.authInfo;return jr(t),Object.assign(we(e),{auth:{user:t.extra.user,payload:t.extra.payload,accessToken:t.token,scopes:[...t.scopes],permissions:[...t.extra.permissions],...t.clientId.length>0&&{clientId:t.clientId},expiresAt:t.expiresAt,...t.resource!==void 0&&{resource:t.resource}}})}function Dr(e){return"contents"in e&&Array.isArray(e.contents)}function $r(e){return"messages"in e&&Array.isArray(e.messages)}function Fe(e,t){if(Dr(e))return e;let n=e._meta&&typeof e._meta=="object"&&typeof e._meta.mimeType=="string"?e._meta.mimeType:void 0,r=[];for(let o of e.content??[]){let s=Vr(o,t,n);s!==void 0&&r.push(s)}return r.length===0&&e.structuredContent!==void 0&&r.push({uri:t,mimeType:"application/json",text:JSON.stringify(e.structuredContent)}),r.length===0&&r.push({uri:t,mimeType:"text/plain",text:""}),{contents:r}}function Vr(e,t,n){if(e.type==="text")return{uri:t,mimeType:n??"text/plain",text:e.text};if(e.type==="image"||e.type==="audio")return{uri:t,mimeType:e.mimeType,blob:e.data};if(e.type==="resource")return{...e.resource}}function Jt(e){if($r(e))return e;let t=(e.content??[]).map(n=>({role:"user",content:n}));return t.length===0&&e.structuredContent!==void 0&&t.push({role:"user",content:{type:"text",text:JSON.stringify(e.structuredContent)}}),t.length===0&&t.push({role:"user",content:{type:"text",text:""}}),{messages:t}}var Br=["GET","HEAD","POST","OPTIONS"],Fr=["Content-Type","Authorization","mcp-protocol-version","mcp-method","mcp-name"];function Wr(e,t){return e===void 0?t:typeof e=="function"?e(t):e==="*"?"*":Array.isArray(e)?t!==null&&e.includes(t)?t:null:e}function zr(e,t){if(t.headers.has("Access-Control-Allow-Origin"))return;let n=t.headers.get("Origin"),r=Wr(e.origin,n);if(r===null)return;let o={"Access-Control-Allow-Origin":r,"Access-Control-Allow-Methods":e.methods.join(", "),"Access-Control-Allow-Headers":e.allowedHeaders.join(", ")};return e.credentials&&(o["Access-Control-Allow-Credentials"]="true"),r!=="*"&&(o.Vary="Origin"),o}function Jr(e,t){if(e.headers.has("Access-Control-Allow-Origin"))return e;let n=new Headers(e.headers);return new Headers(t).forEach((o,s)=>{n.set(s,o)}),jt(e,new Response(e.body,{status:e.status,statusText:e.statusText,headers:n}))}function Kt(e){if(!(e.enabled!==!1))return async(r,o)=>o();let n={...e.origin!==void 0&&{origin:e.origin},methods:e.methods??Br,allowedHeaders:e.allowedHeaders??Fr,credentials:e.credentials??!1};return async(r,o)=>{let s=zr(n,r);if(s===void 0)return o();if(r.method==="OPTIONS")return new Response(null,{status:204,headers:s});let i=await o();return Jr(i,s)}}function Gt(e){return e!==void 0&&e.enabled!==!1}import{CallToolResultSchema as Kr,GetPromptResultSchema as Gr,ListPromptsResultSchema as Yr,ListResourcesResultSchema as Xr,ListToolsResultSchema as Zr,ReadResourceResultSchema as Qr}from"@modelcontextprotocol/core";import{isInputRequiredResult as eo}from"@modelcontextprotocol/server";var to=["tools/call","tools/list","resources/read","resources/list","prompts/get","prompts/list"];function Xt(e,t){if(typeof e!="object"||e===null||Array.isArray(e))throw new TypeError("[mcp-use] MCP middleware received an invalid downstream request");return{...e,params:t}}function Zt(e,t){let n=ao(e),r=t;if(n!=="*"&&!no(n))throw new TypeError(`Unsupported MCP middleware pattern "${e}". Use an exact MCP method or "mcp:*".`);return n==="*"?{pattern:n,handler:async(o,s)=>{let i=!1,u;if(await r(o,async()=>{u=await s(),i=!0}),!i)throw new Error(`Wildcard MCP middleware "${n}" must call next()`);return u}}:{pattern:n,handler:(o,s)=>r(o,s)}}function Qt(e,t){let{pattern:n,phase:r}=io(e),o=t;return{pattern:n,phase:r,handler:(s,i)=>o(s,i)}}function le(e,t){if(e==="*")return!0;if(e.endsWith("/*")){let n=e.slice(0,-1);return t.startsWith(n)}return e===t}function no(e){return to.some(t=>t===e)}function ro(e,t,n){let r=e.filter(o=>le(o.pattern,t));return r.length===0?o=>n():o=>{let s=-1,i=u=>u<=s?Promise.reject(new Error("next() called multiple times")):(s=u,u===r.length?n():r[u].handler(o,()=>i(u+1)));return i(0)}}function oo(e){return Object.freeze({method:e.method,params:Object.freeze({...e.params}),...e.request!==void 0&&{request:e.request},...e.req!==void 0&&{req:e.req},...e.session!==void 0&&{session:Object.freeze({...e.session})},...e.auth!==void 0&&{auth:e.auth},state:new Map(e.state)})}async function en(e,t,n,r,o){Yt(t,n,"before",r);let i=await ro(e,n,o)(r);return so(n,i),Yt(t,n,"complete",r,i),i}function so(e,t){if((e==="tools/call"||e==="resources/read"||e==="prompts/get")&&eo(t))return;let n=(()=>{switch(e){case"tools/call":return ze(e,t,"content"),Kr.safeParse(t);case"tools/list":return We(e,t),Zr.safeParse({tools:t});case"resources/read":return ze(e,t,"contents"),Qr.safeParse(t);case"resources/list":return We(e,t),Xr.safeParse({resources:t});case"prompts/get":return ze(e,t,"messages"),Gr.safeParse(t);case"prompts/list":return We(e,t),Yr.safeParse({prompts:t});default:throw new TypeError(`Unsupported MCP middleware method "${e}"`)}})();if(!n.success)throw new TypeError(`[mcp-use] ${e} middleware returned an invalid result: ${n.error.message}`)}function We(e,t){if(!Array.isArray(t))throw new TypeError(`[mcp-use] ${e} middleware returned an invalid result: expected an array`)}function ze(e,t,n){if(typeof t!="object"||t===null||!Array.isArray(t[n]))throw new TypeError(`[mcp-use] ${e} middleware returned an invalid result: expected a ${n} array`)}function Yt(e,t,n,r,o){let s=oo(r);for(let i of e)if(!(i.phase!==n||!le(i.pattern,t)))try{i.handler(s,o)}catch(u){console.error(`[mcp-use] MCP event listener for "${i.pattern}" (${n}) threw:`,u)}}function io(e){let t=e.startsWith("mcp:")?e.slice(4):e;return t.endsWith(":complete")?{pattern:t.slice(0,-9),phase:"complete"}:{pattern:t,phase:"before"}}function ao(e){return e.startsWith("mcp:")?e.slice(4):e}import{CLIENT_INFO_META_KEY as uo,isJSONRPCRequest as co}from"@modelcontextprotocol/server";function lo(){return typeof process>"u"||process.env?.NO_COLOR!==void 0?!1:process.stdout?.isTTY===!0}function I(e,t){return n=>lo()?`\x1B[${e}m${n}\x1B[${t}m`:n}var Ke=I(1,22),ve=I(2,22),Ge=I(31,39),on=I(32,39),U=I(33,39),po=I(34,39),sn=I(35,39),pe=I(36,39),fo=I(90,39);function mo(e){let t=typeof process>"u"?void 0:process.env?.MCP_USE_LOG_LEVEL?.toLowerCase();return t==="info"||t==="debug"||t==="trace"?t:e??"info"}function an(e){if(e!==void 0)return typeof e.version=="string"&&e.version!==""?`${e.name}/${e.version}`:e.name}var un={initialize:e=>({subject:an(e.clientInfo)}),ping:()=>({}),"server/discover":()=>({}),"completion/complete":e=>({subject:e.ref.type==="ref/prompt"?e.ref.name:e.ref.uri,input:e.argument}),"logging/setLevel":e=>({subject:e.level}),"prompts/get":e=>({subject:e.name,input:e.arguments}),"prompts/list":()=>({}),"resources/list":()=>({}),"resources/templates/list":()=>({}),"resources/read":e=>({subject:e.uri}),"resources/subscribe":e=>({subject:e.uri}),"resources/unsubscribe":e=>({subject:e.uri}),"subscriptions/listen":()=>({}),"tools/call":e=>({subject:e.name,input:e.arguments}),"tools/list":()=>({}),"sampling/createMessage":()=>({}),"elicitation/create":()=>({}),"roots/list":()=>({})};function ho(e){return Object.prototype.hasOwnProperty.call(un,e)}function go(e){if(!ho(e.method))return{};try{let t=un[e.method],n=t(e.params);return typeof n.subject=="string"||n.subject===void 0?n:{}}catch{return{}}}var tn=80;function nn(e){let t;try{t=JSON.stringify(e)??String(e)}catch{t=String(e)}return t.length>tn?`${t.slice(0,tn)}...`:t}function yo(e){let t=e.params?._meta;if(t===void 0)return;let n=t[uo];if(!(typeof n!="object"||n===null||typeof n.name!="string"))return an(n)}function Re(e){return e.replace(/[\u0000-\u001F\u007F-\u009F]+/g," ")}function wo(e){return e.startsWith("tools/")?pe:e.startsWith("resources/")?on:e.startsWith("prompts/")?sn:e==="initialize"||e==="ping"?fo:po}var vo=new Set(["authorization","proxy-authorization","cookie","set-cookie","x-api-key"]);function rn(e){return Object.fromEntries(Object.entries(e).map(([t,n])=>[t,vo.has(t.toLowerCase())?"[REDACTED]":n]))}async function Ro(e){if(!e.body)return{errorMessage:null};let t;try{t=await e.clone().text()}catch{return{errorMessage:null}}if(!t)return{errorMessage:null};let n=(e.headers.get("content-type")??"").includes("text/event-stream"),r=[],o=i=>{try{r.push(JSON.parse(i))}catch{}};if(n){for(let i of t.split(/\r?\n/))if(i.startsWith("data:")){let u=i.slice(5).trim();u&&o(u)}}else o(t);let s;for(let i of r){if(i===null||typeof i!="object")continue;let u=i;if(typeof u.error?.message=="string")return{errorMessage:u.error.message};if(u.result?.isError===!0){let d=(Array.isArray(u.result.content)?u.result.content:[]).find(c=>c?.type==="text"&&typeof c.text=="string");return{errorMessage:d?String(d.text):"tool error"}}"result"in u&&(s=u.result)}return{errorMessage:null,result:s}}function To(e){if(e===null||typeof e!="object")return e;let{structuredContent:t,content:n}=e;if(t!==void 0)return t;if(Array.isArray(n)){let[r]=n;if(n.length===1&&r?.type==="text")return r.text}return n}function Te(e){function t(n){return typeof n=="string"&&n.length>100?`${n.slice(0,100)}...`:Array.isArray(n)?n.map(t):n!==null&&typeof n=="object"?Object.fromEntries(Object.entries(n).map(([r,o])=>[r,t(o)])):n}try{return JSON.stringify(t(e),null,2)}catch{return String(e)}}var Je=1e4;async function Mo(e,t,n,r){console.log(`
1
+ import{a as vt,b as Rt}from"./chunk-ZBN5QPYD.js";import{a as ke,b as _e,c as $,d as Ue}from"./chunk-4TTKTNKI.js";function ir(e){return{content:[{type:"text",text:e}],_meta:{mimeType:"text/plain"}}}function ar(e){return{content:[{type:"text",text:e}],_meta:{mimeType:"text/markdown"}}}function ur(e){return{content:[{type:"text",text:e}],_meta:{mimeType:"text/html"}}}function dr(e){return{content:[{type:"text",text:e}],_meta:{mimeType:"text/xml"}}}function cr(e){return{content:[{type:"text",text:e}],_meta:{mimeType:"text/css"}}}function lr(e){return{content:[{type:"text",text:e}],_meta:{mimeType:"text/javascript"}}}function pr(e,t="image/png"){return{content:[{type:"image",data:e,mimeType:t}],_meta:{mimeType:t,isImage:!0}}}function fr(e,t="audio/wav"){return{content:[{type:"audio",data:e,mimeType:t}],_meta:{mimeType:t,isAudio:!0}}}function mr(e,t){return{content:[{type:"text",text:e}],_meta:{mimeType:t,isBinary:!0}}}function hr(e,t,n){if(typeof t=="object"&&t!==null&&"content"in t){let o=t,s,i;if(o._meta&&typeof o._meta=="object"){let a=o._meta;typeof a.mimeType=="string"&&(i=a.mimeType)}let u=o.content?.[0];return u?.type==="text"&&"text"in u&&(s=u.text),{content:[{type:"resource",resource:{uri:e,...i!==void 0&&{mimeType:i},text:s??""}}]}}let r=t;return{content:[{type:"resource",resource:{uri:e,...r!==void 0&&r!==""&&{mimeType:r},text:n??""}}]}}function gr(e){return{isError:!0,content:[{type:"text",text:e}]}}function yr(e){return Array.isArray(e)?Ie(e):{content:[{type:"text",text:JSON.stringify(e,null,2)}],structuredContent:e,_meta:{mimeType:"application/json"}}}function Ie(e){return{content:[{type:"text",text:JSON.stringify(e,null,2)}],structuredContent:e}}function Tt(e){let t=e.props??e.data??{},{output:n,message:r,metadata:o}=e,i={content:r?[{type:"text",text:r}]:Array.isArray(n?.content)&&n.content.length>0?n.content:[{type:"text",text:""}]};return o!==void 0&&Object.keys(o).length>0&&(i._meta=o),n?.structuredContent!==void 0?i.structuredContent=n.structuredContent:Object.keys(t).length>0&&(i.structuredContent=t),i}function wr(...e){let t=e.filter(s=>s.structuredContent!==void 0),n=t.length>0?t.map(s=>s.structuredContent).reduce((s,i)=>({...s,...typeof i=="object"&&i!==null?i:{}}),{}):void 0,r=e.filter(s=>s._meta!==void 0),o=r.length>0?r.map(s=>s._meta).reduce((s,i)=>({...s,...i!==void 0?i:{}}),{}):void 0;return{content:e.flatMap(s=>s.content),...n!==void 0&&Object.keys(n).length>0&&{structuredContent:n},...o!==void 0&&Object.keys(o).length>0&&{_meta:o}}}import{localhostAllowedHostnames as Nn,localhostAllowedOrigins as bs,McpServer as Ms,ResourceTemplate as xs,CLIENT_CAPABILITIES_META_KEY as Os,CLIENT_INFO_META_KEY as As,PROTOCOL_VERSION_META_KEY as Cs,isJSONRPCRequest as Bn,isInputRequiredResult as Hn}from"@modelcontextprotocol/server";import{createServer as Es}from"#mcp-use-node-http";import{Hono as qn}from"hono";var bt="public, max-age=31536000, immutable",vr="public, max-age=300";function je(e){return/^([a-z][a-z\d+.-]*):/i.exec(e)?.[1]?.toLowerCase()}function Rr(e,t){return`${e==="/"?"":e}/_mcp-use/public/${t.split("/").map(r=>encodeURIComponent(r)).join("/")}`}function Le(e){return je(e)===void 0}function Tr(e){return e[0]}function br(e,t){if(e.startsWith("/")||e.includes("\\")||e.includes("?")||e.includes("#")||e.split("/").some(n=>n===""||n===".."))throw new TypeError(`${t} must be an http(s) URL, image data URL, or safe path relative to public/`)}function xt(e,t){let n=e.indexOf(",");if(n<0)throw new TypeError(`${t} must be a valid image data URL`);let r=e.slice(5,n),o=e.slice(n+1),s=r.split(";"),i=s[0]?.toLowerCase()??"";if(!i.startsWith("image/"))throw new TypeError(`${t} data URL must use an image MIME type`);try{if(s.includes("base64")){let u=atob(o);return{mimeType:i,bytes:Uint8Array.from(u,a=>a.charCodeAt(0))}}return{mimeType:i,bytes:new TextEncoder().encode(decodeURIComponent(o))}}catch{throw new TypeError(`${t} must be a valid image data URL`)}}function Mt(e,t){if(typeof e!="string"||e.length===0)throw new TypeError(`${t} must be a non-empty string`);let n=je(e);if(n===void 0)return br(e,t),e;if(n==="data")return xt(e,t),e;if(n!=="http"&&n!=="https")throw new TypeError(`${t} must be an http(s) URL, image data URL, or safe path relative to public/`);try{new URL(e)}catch{throw new TypeError(`${t} must be a valid absolute http(s) URL`)}return e}function Ot(e){let t;if(e.websiteUrl!==void 0){if(typeof e.websiteUrl!="string"||e.websiteUrl.length===0)throw new TypeError("websiteUrl must be a non-empty absolute http(s) URL");let u;try{u=new URL(e.websiteUrl)}catch{throw new TypeError("websiteUrl must be a non-empty absolute http(s) URL")}if(u.protocol!=="http:"&&u.protocol!=="https:")throw new TypeError("websiteUrl must be a non-empty absolute http(s) URL");t=e.websiteUrl}let n;if(e.icons!==void 0){if(!Array.isArray(e.icons))throw new TypeError("icons must be an array of MCP Icon objects");n=Object.freeze(e.icons.map((u,a)=>{if(typeof u!="object"||u===null)throw new TypeError(`icons[${a}] must be an MCP Icon object`);let d=u,c=Mt(d.src,`icons[${a}].src`),l=d.mimeType;if(l!==void 0&&(typeof l!="string"||!l.toLowerCase().startsWith("image/")))throw new TypeError(`icons[${a}].mimeType must be an image MIME type when provided`);let p=d.sizes;if(p!==void 0&&(!Array.isArray(p)||p.some(h=>typeof h!="string"||h.length===0)))throw new TypeError(`icons[${a}].sizes must be an array of non-empty strings when provided`);let g=p===void 0?void 0:p.map(h=>h),f=d.theme;if(f!==void 0&&f!=="light"&&f!=="dark")throw new TypeError(`icons[${a}].theme must be "light" or "dark" when provided`);return Object.freeze({src:c,...l!==void 0&&{mimeType:l},...g!==void 0&&{sizes:Object.freeze(g)},...f!==void 0&&{theme:f}})}))}let r=e.favicon===void 0?void 0:Mt(e.favicon,"favicon"),o=r===void 0?Tr(n??[]):void 0,s=r??o?.src,i=o?.mimeType??n?.find(u=>u.src===r)?.mimeType;return Object.freeze({...s!==void 0&&{favicon:s},...i!==void 0&&{faviconMimeType:i},...n!==void 0&&{icons:n},...t!==void 0&&{websiteUrl:t}})}function At(e,t,n){if(e!==void 0)return e.map(r=>({...r,src:t!==void 0&&Le(r.src)?`${$(t)}${Rr(n,r.src)}`:r.src,...r.sizes!==void 0&&{sizes:[...r.sizes]}}))}function Ct(e){return e.favicon!==void 0&&Le(e.favicon)||e.icons?.some(t=>Le(t.src))===!0}function Et(e,t){let n=e.favicon;if(n!==void 0)return async r=>{if(r.method!=="GET"&&r.method!=="HEAD")return new Response("Method Not Allowed",{status:405,headers:{Allow:"GET, HEAD"}});if(new URL(r.url).pathname!=="/favicon.ico")return new Response("Not Found",{status:404});let o=je(n);if(o==="http"||o==="https")return new Response(null,{status:307,headers:{Location:n,"Cache-Control":vr}});if(o==="data"){let d=xt(n,"favicon");return new Response(r.method==="HEAD"?null:d.bytes.buffer,{status:200,headers:{"Content-Type":e.faviconMimeType??d.mimeType,"Cache-Control":bt,"X-Content-Type-Options":"nosniff"}})}let{join:s}=await import("path"),i=t.dev?s(t.projectRoot,"public"):s(t.projectRoot,".mcp-use/build/views/public"),u=await vt(i,n);if(u===null)return new Response("Not Found",{status:404,headers:{"Cache-Control":"no-store"}});let a=await Rt(u,{...t.deferCors===!0&&{deferCors:!0},...r.method==="HEAD"&&{head:!0}});return a.headers.set("Cache-Control",bt),a.headers.set("X-Content-Type-Options","nosniff"),e.faviconMimeType!==void 0&&a.headers.set("Content-Type",e.faviconMimeType),a}}function Pt(e){if(e.basePath!==void 0){if(typeof e.basePath!="string")throw new TypeError("basePath must be an absolute URL pathname without empty segments, trailing slash, query, fragment, or whitespace");let{basePath:t}=e;if(!t.startsWith("/")||t.includes("?")||t.includes("#")||/\s/.test(t)||t.includes("//")||t.length>1&&t.endsWith("/"))throw new TypeError("basePath must be an absolute URL pathname without empty segments, trailing slash, query, fragment, or whitespace")}if(e.port!==void 0&&(typeof e.port!="number"||!Number.isInteger(e.port)||e.port<0||e.port>65535))throw new TypeError("port must be an integer between 0 and 65535")}var Mr="127.0.0.1";function St(e,t,n=process.env){if(e!==void 0)return e;let r=n.HOST?.trim();return r!==void 0&&r!==""?r:t??Mr}function kt(e,t,n=process.env){if(e!==void 0)return e;let r=xr(n.PORT);return r!==void 0?r:t??3e3}function xr(e){if(e===void 0||e.trim()==="")return;let t=Number(e);return Number.isInteger(t)&&t>=0&&t<=65535?t:void 0}var _t=new WeakSet,Ut=new WeakMap;function It(e){return e.body!==null&&_t.add(e),e}function Lt(e,t){return It(t),Ut.set(e,t),t}function Ne(e,t){if(e.body===null)return!1;if(_t.has(e))return!0;let n=t===void 0?void 0:Ut.get(t);return n!==void 0&&n.body!==null&&n.body===e.body}function jt(e,t){return Ne(e)?It(t):t}function Ht(e,t){return async(n,r,o)=>{typeof o=="function"&&(o=void 0);let s=!1,i=new AbortController;r.on("close",()=>{s||i.abort()}),r.destroyed===!0&&i.abort();let u,a;try{u=await Or(n,o,{signal:i.signal}),a=await e.fetch(u,{...n.auth!==void 0&&{authInfo:n.auth},...o!==void 0&&{parsedBody:o}})}catch(f){try{t?.onerror?.(f instanceof Error?f:new Error(String(f)))}catch{}a=Cr(Ar(o))}let d={};for(let[f,h]of a.headers)d[f]=h;if(r.writeHead(a.status,d),a.body===null){s=!0,r.end();return}if(Ne(a,u)){try{let f=new Uint8Array(await a.arrayBuffer());s=!0,r.end(f)}catch{s=!0,r.end()}return}let c,l=()=>{c?.(),c=void 0},p=()=>new Promise(f=>{c=f});r.on("drain",l);let g=new Promise(f=>{i.signal.addEventListener("abort",()=>f(),{once:!0})});try{for await(let f of a.body){if(i.signal.aborted)break;let h=f instanceof Uint8Array?f:new Uint8Array(f);r.write(h)===!1&&await Promise.race([p(),g])}}catch{}s=!0,r.end()}}async function Or(e,t,n){let r=(e.method??"GET").toUpperCase(),s=`http://${Nt(e.headers.host)??Nt(e.headers[":authority"])??"localhost"}${e.url??"/"}`,i=new Headers;for(let[a,d]of Object.entries(e.headers))if(!(d===void 0||a.startsWith(":")))if(Array.isArray(d))for(let c of d)i.append(a,c);else i.set(a,d);let u;if(r!=="GET"&&r!=="HEAD")if(t===void 0){let a=new TextDecoder,d="";for await(let c of e)d+=typeof c=="string"?c:a.decode(c,{stream:!0});d+=a.decode(),d.length>0&&(u=d)}else{let a=JSON.stringify(t);i.delete("content-encoding"),i.delete("transfer-encoding"),a===void 0?i.delete("content-length"):(u=a,i.set("content-length",String(new TextEncoder().encode(a).byteLength)))}return new Request(s,{method:r,headers:i,...n?.signal!==void 0&&{signal:n.signal},...u!==void 0&&{body:u}})}function Nt(e){return Array.isArray(e)?e[0]:e}function Ar(e){if(e===null||typeof e!="object"||Array.isArray(e))return null;let{method:t,id:n}=e;return typeof t!="string"?null:typeof n=="string"||typeof n=="number"?n:null}function Cr(e){return Response.json({jsonrpc:"2.0",error:{code:-32603,message:"Internal server error"},id:e},{status:500})}import{CLIENT_CAPABILITIES_META_KEY as _r,CLIENT_INFO_META_KEY as Ur,inputRequired as Be,inputResponse as Ir}from"@modelcontextprotocol/server";import{HonoRequest as Lr}from"hono/request";import{hostHeaderValidationResponse as Er,originValidationResponse as Pr}from"@modelcontextprotocol/server";var qt=new WeakMap;function T(e){let t=qt.get(e);return t===void 0&&(t={},qt.set(e,t)),t}function ae(e){return new URL(e.url).pathname}function Dt(e,t){return ae(e)===t}function He(e,t){let n=ae(e);return n===t||n.startsWith(`${t}/`)}function G(e,t){let n=t.replace(/^\/+/,"");return e==="/"?`/${n}`:`${e}/${n}`}function qe(e){if(e.method!=="GET"&&e.method!=="HEAD")return!1;let t=e.headers.get("accept");return t===null?!1:t.split(",").some(n=>{let[r,...o]=n.split(";");return r?.trim().toLowerCase()!=="text/html"?!1:!o.some(s=>{let[i,u]=s.trim().toLowerCase().split("=");return i==="q"&&Number(u)===0})})}function $t(){return async(e,t)=>{let n=T(e);if(n.parsedBody!==void 0||!(e.headers.get("content-type")??"").includes("application/json"))return t();try{n.parsedBody=await e.clone().json()}catch{return new Response("Invalid JSON",{status:400})}return t()}}function Vt(e){return async(t,n)=>Er(t,e)??n()}function Bt(e,t=!0){return async(n,r)=>t&&(n.method==="GET"||n.method==="HEAD")?r():Pr(n,e)??r()}import{CLIENT_CAPABILITIES_META_KEY as Sr}from"@modelcontextprotocol/server";var De="io.modelcontextprotocol/ui",ue="text/html;profile=mcp-app",Ft="ui://views/";var de="ui/resourceUri";function Y(e){return`${Ft}${e}.html`}var kr=new WeakMap;function $e(e,t){kr.set(e,t)}function Ve(e){if(typeof e!="object"||e===null)return;let t=e.params;if(typeof t!="object"||t===null)return;let n=t._meta;if(typeof n!="object"||n===null)return;let r=n[Sr];if(!(typeof r!="object"||r===null))return r}function ce(e){let t=e?.extensions;if(t===void 0)return!1;let n=t[De];if(typeof n!="object"||n===null)return!1;let r=n.mimeTypes;return Array.isArray(r)?r.includes(ue):!1}function jr(e){if(e===void 0||e.extra===void 0||e.expiresAt===void 0)throw new Error("OAuth callback did not receive mapped AuthInfo.extra")}function _(e){return typeof e=="string"?e:void 0}function Wt(e){return typeof e=="string"||typeof e=="number"&&Number.isFinite(e)?e:void 0}function Nr(e){if(e===void 0)return;let t=_(e["openai/locale"])??_(e["webplus/i18n"]),n=_(e["openai/userAgent"]),r=_(e["openai/subject"]),o=_(e["openai/session"]),s=_(e["openai/organization"]),i=e["openai/userLocation"],u;if(typeof i=="object"&&i!==null&&!Array.isArray(i)){let a=i,d={city:_(a.city),region:_(a.region),country:_(a.country),timezone:_(a.timezone),latitude:Wt(a.latitude),longitude:Wt(a.longitude)},c=Object.entries(d).filter(l=>l[1]!==void 0);c.length>0&&(u=Object.fromEntries(c))}if(!(t===void 0&&n===void 0&&u===void 0&&r===void 0&&o===void 0&&s===void 0))return{...t!==void 0&&{locale:t},...n!==void 0&&{userAgent:n},...u!==void 0&&{location:u},...r!==void 0&&{subject:r},...o!==void 0&&{conversationId:o},...s!==void 0&&{organizationId:s}}}function Hr(e){let t=e.mcpReq.envelope,n={...t?.[_r]??{}},r={...t?.[Ur]??{}},o=Nr(e.mcpReq._meta);return{can(s){return Object.hasOwn(n,s)},capabilities(){return{...n}},extension(s){let i=n.extensions?.[s];return i===void 0?void 0:{...i}},info(){return{...r}},user(){return o===void 0?void 0:{...o,...o.location!==void 0&&{location:{...o.location}}}},supportsViews(){return ce(n)}}}function qr(e){return async function(n,r,o){let s,i;if(typeof o=="string")s=Be.elicitUrl({message:r,url:o});else if(o!==void 0)i=o,s=Be.elicit({message:r,requestedSchema:o});else throw new TypeError("ctx.elicit(key, message, value) requires a form schema or URL string");let u=Ir(e,n);if(u.kind==="elicit"){if(u.action!=="accept")return{status:u.action};if(i===void 0)return{status:"accept"};if(u.content!==void 0){let a=await i["~standard"].validate(u.content);if(a.issues===void 0)return{status:"accept",data:a.value}}}return{status:"required",result:Be({inputRequests:{[n]:s}})}}}function we(e){let t=e.http?.req,n=t===void 0?void 0:T(t).honoContext,r=n?.req??(t===void 0?void 0:new Lr(t)),o={signal:e.mcpReq.signal,...r!==void 0&&{request:r},...e.mcpReq.inputResponses!==void 0&&{inputResponses:e.mcpReq.inputResponses},client:Hr(e),elicit:qr(e.mcpReq.inputResponses),requestState:()=>e.mcpReq.requestState(),async sendNotification(s,i){await e.mcpReq.notify({method:s,...i!==void 0&&{params:i}})},async reportProgress(s,i,u){let a=e.mcpReq._meta?.progressToken;return a===void 0?!1:(await e.mcpReq.notify({method:"notifications/progress",params:{progressToken:a,progress:s,...i!==void 0&&{total:i},...u!==void 0&&{message:u}}}),!0)},async sendLog(s,i,u){await e.mcpReq.notify({method:"notifications/message",params:{level:s,data:i,...u!==void 0&&{logger:u}}})}};return n!==void 0?Object.assign(n,o):{...o,...r!==void 0&&{req:r}}}function zt(e){let t=e.http?.authInfo;return jr(t),Object.assign(we(e),{auth:{user:t.extra.user,payload:t.extra.payload,accessToken:t.token,scopes:[...t.scopes],permissions:[...t.extra.permissions],...t.clientId.length>0&&{clientId:t.clientId},expiresAt:t.expiresAt,...t.resource!==void 0&&{resource:t.resource}}})}function Dr(e){return"contents"in e&&Array.isArray(e.contents)}function $r(e){return"messages"in e&&Array.isArray(e.messages)}function Fe(e,t){if(Dr(e))return e;let n=e._meta&&typeof e._meta=="object"&&typeof e._meta.mimeType=="string"?e._meta.mimeType:void 0,r=[];for(let o of e.content??[]){let s=Vr(o,t,n);s!==void 0&&r.push(s)}return r.length===0&&e.structuredContent!==void 0&&r.push({uri:t,mimeType:"application/json",text:JSON.stringify(e.structuredContent)}),r.length===0&&r.push({uri:t,mimeType:"text/plain",text:""}),{contents:r}}function Vr(e,t,n){if(e.type==="text")return{uri:t,mimeType:n??"text/plain",text:e.text};if(e.type==="image"||e.type==="audio")return{uri:t,mimeType:e.mimeType,blob:e.data};if(e.type==="resource")return{...e.resource}}function Jt(e){if($r(e))return e;let t=(e.content??[]).map(n=>({role:"user",content:n}));return t.length===0&&e.structuredContent!==void 0&&t.push({role:"user",content:{type:"text",text:JSON.stringify(e.structuredContent)}}),t.length===0&&t.push({role:"user",content:{type:"text",text:""}}),{messages:t}}var Br=["GET","HEAD","POST","OPTIONS"],Fr=["Content-Type","Authorization","mcp-protocol-version","mcp-method","mcp-name"];function Wr(e,t){return e===void 0?t:typeof e=="function"?e(t):e==="*"?"*":Array.isArray(e)?t!==null&&e.includes(t)?t:null:e}function zr(e,t){if(t.headers.has("Access-Control-Allow-Origin"))return;let n=t.headers.get("Origin"),r=Wr(e.origin,n);if(r===null)return;let o={"Access-Control-Allow-Origin":r,"Access-Control-Allow-Methods":e.methods.join(", "),"Access-Control-Allow-Headers":e.allowedHeaders.join(", ")};return e.credentials&&(o["Access-Control-Allow-Credentials"]="true"),r!=="*"&&(o.Vary="Origin"),o}function Jr(e,t){if(e.headers.has("Access-Control-Allow-Origin"))return e;let n=new Headers(e.headers);return new Headers(t).forEach((o,s)=>{n.set(s,o)}),jt(e,new Response(e.body,{status:e.status,statusText:e.statusText,headers:n}))}function Kt(e){if(!(e.enabled!==!1))return async(r,o)=>o();let n={...e.origin!==void 0&&{origin:e.origin},methods:e.methods??Br,allowedHeaders:e.allowedHeaders??Fr,credentials:e.credentials??!1};return async(r,o)=>{let s=zr(n,r);if(s===void 0)return o();if(r.method==="OPTIONS")return new Response(null,{status:204,headers:s});let i=await o();return Jr(i,s)}}function Gt(e){return e!==void 0&&e.enabled!==!1}import{CallToolResultSchema as Kr,GetPromptResultSchema as Gr,ListPromptsResultSchema as Yr,ListResourcesResultSchema as Xr,ListToolsResultSchema as Zr,ReadResourceResultSchema as Qr}from"@modelcontextprotocol/core";import{isInputRequiredResult as eo}from"@modelcontextprotocol/server";var to=["tools/call","tools/list","resources/read","resources/list","prompts/get","prompts/list"];function Xt(e,t){if(typeof e!="object"||e===null||Array.isArray(e))throw new TypeError("[mcp-use] MCP middleware received an invalid downstream request");return{...e,params:t}}function Zt(e,t){let n=ao(e),r=t;if(n!=="*"&&!no(n))throw new TypeError(`Unsupported MCP middleware pattern "${e}". Use an exact MCP method or "mcp:*".`);return n==="*"?{pattern:n,handler:async(o,s)=>{let i=!1,u;if(await r(o,async()=>{u=await s(),i=!0}),!i)throw new Error(`Wildcard MCP middleware "${n}" must call next()`);return u}}:{pattern:n,handler:(o,s)=>r(o,s)}}function Qt(e,t){let{pattern:n,phase:r}=io(e),o=t;return{pattern:n,phase:r,handler:(s,i)=>o(s,i)}}function le(e,t){if(e==="*")return!0;if(e.endsWith("/*")){let n=e.slice(0,-1);return t.startsWith(n)}return e===t}function no(e){return to.some(t=>t===e)}function ro(e,t,n){let r=e.filter(o=>le(o.pattern,t));return r.length===0?o=>n():o=>{let s=-1,i=u=>u<=s?Promise.reject(new Error("next() called multiple times")):(s=u,u===r.length?n():r[u].handler(o,()=>i(u+1)));return i(0)}}function oo(e){return Object.freeze({method:e.method,params:Object.freeze({...e.params}),...e.request!==void 0&&{request:e.request},...e.req!==void 0&&{req:e.req},...e.session!==void 0&&{session:Object.freeze({...e.session})},...e.auth!==void 0&&{auth:e.auth},state:new Map(e.state)})}async function en(e,t,n,r,o){Yt(t,n,"before",r);let i=await ro(e,n,o)(r);return so(n,i),Yt(t,n,"complete",r,i),i}function so(e,t){if((e==="tools/call"||e==="resources/read"||e==="prompts/get")&&eo(t))return;let n=(()=>{switch(e){case"tools/call":return ze(e,t,"content"),Kr.safeParse(t);case"tools/list":return We(e,t),Zr.safeParse({tools:t});case"resources/read":return ze(e,t,"contents"),Qr.safeParse(t);case"resources/list":return We(e,t),Xr.safeParse({resources:t});case"prompts/get":return ze(e,t,"messages"),Gr.safeParse(t);case"prompts/list":return We(e,t),Yr.safeParse({prompts:t});default:throw new TypeError(`Unsupported MCP middleware method "${e}"`)}})();if(!n.success)throw new TypeError(`[mcp-use] ${e} middleware returned an invalid result: ${n.error.message}`)}function We(e,t){if(!Array.isArray(t))throw new TypeError(`[mcp-use] ${e} middleware returned an invalid result: expected an array`)}function ze(e,t,n){if(typeof t!="object"||t===null||!Array.isArray(t[n]))throw new TypeError(`[mcp-use] ${e} middleware returned an invalid result: expected a ${n} array`)}function Yt(e,t,n,r,o){let s=oo(r);for(let i of e)if(!(i.phase!==n||!le(i.pattern,t)))try{i.handler(s,o)}catch(u){console.error(`[mcp-use] MCP event listener for "${i.pattern}" (${n}) threw:`,u)}}function io(e){let t=e.startsWith("mcp:")?e.slice(4):e;return t.endsWith(":complete")?{pattern:t.slice(0,-9),phase:"complete"}:{pattern:t,phase:"before"}}function ao(e){return e.startsWith("mcp:")?e.slice(4):e}import{CLIENT_INFO_META_KEY as uo,isJSONRPCRequest as co}from"@modelcontextprotocol/server";function lo(){return typeof process>"u"||process.env?.NO_COLOR!==void 0?!1:process.stdout?.isTTY===!0}function I(e,t){return n=>lo()?`\x1B[${e}m${n}\x1B[${t}m`:n}var Ke=I(1,22),ve=I(2,22),Ge=I(31,39),on=I(32,39),U=I(33,39),po=I(34,39),sn=I(35,39),pe=I(36,39),fo=I(90,39);function mo(e){let t=typeof process>"u"?void 0:process.env?.MCP_USE_LOG_LEVEL?.toLowerCase();return t==="info"||t==="debug"||t==="trace"?t:e??"info"}function an(e){if(e!==void 0)return typeof e.version=="string"&&e.version!==""?`${e.name}/${e.version}`:e.name}var un={initialize:e=>({subject:an(e.clientInfo)}),ping:()=>({}),"server/discover":()=>({}),"completion/complete":e=>({subject:e.ref.type==="ref/prompt"?e.ref.name:e.ref.uri,input:e.argument}),"logging/setLevel":e=>({subject:e.level}),"prompts/get":e=>({subject:e.name,input:e.arguments}),"prompts/list":()=>({}),"resources/list":()=>({}),"resources/templates/list":()=>({}),"resources/read":e=>({subject:e.uri}),"resources/subscribe":e=>({subject:e.uri}),"resources/unsubscribe":e=>({subject:e.uri}),"subscriptions/listen":()=>({}),"tools/call":e=>({subject:e.name,input:e.arguments}),"tools/list":()=>({}),"sampling/createMessage":()=>({}),"elicitation/create":()=>({}),"roots/list":()=>({})};function ho(e){return Object.prototype.hasOwnProperty.call(un,e)}function go(e){if(!ho(e.method))return{};try{let t=un[e.method],n=t(e.params);return typeof n.subject=="string"||n.subject===void 0?n:{}}catch{return{}}}var tn=80;function nn(e){let t;try{t=JSON.stringify(e)??String(e)}catch{t=String(e)}return t.length>tn?`${t.slice(0,tn)}...`:t}function yo(e){let t=e.params?._meta;if(t===void 0)return;let n=t[uo];if(!(typeof n!="object"||n===null||typeof n.name!="string"))return an(n)}function Re(e){return e.replace(/[\u0000-\u001F\u007F-\u009F]+/g," ")}function wo(e){return e.startsWith("tools/")?pe:e.startsWith("resources/")?on:e.startsWith("prompts/")?sn:e==="initialize"||e==="ping"?fo:po}var vo=new Set(["authorization","proxy-authorization","cookie","set-cookie","x-api-key"]);function rn(e){return Object.fromEntries(Object.entries(e).map(([t,n])=>[t,vo.has(t.toLowerCase())?"[REDACTED]":n]))}async function Ro(e){if(!e.body)return{errorMessage:null};let t;try{t=await e.clone().text()}catch{return{errorMessage:null}}if(!t)return{errorMessage:null};let n=(e.headers.get("content-type")??"").includes("text/event-stream"),r=[],o=i=>{try{r.push(JSON.parse(i))}catch{}};if(n){for(let i of t.split(/\r?\n/))if(i.startsWith("data:")){let u=i.slice(5).trim();u&&o(u)}}else o(t);let s;for(let i of r){if(i===null||typeof i!="object")continue;let u=i;if(typeof u.error?.message=="string")return{errorMessage:u.error.message};if(u.result?.isError===!0){let d=(Array.isArray(u.result.content)?u.result.content:[]).find(c=>c?.type==="text"&&typeof c.text=="string");return{errorMessage:d?String(d.text):"tool error"}}"result"in u&&(s=u.result)}return{errorMessage:null,result:s}}function To(e){if(e===null||typeof e!="object")return e;let{structuredContent:t,content:n}=e;if(t!==void 0)return t;if(Array.isArray(n)){let[r]=n;if(n.length===1&&r?.type==="text")return r.text}return n}function Te(e){function t(n){return typeof n=="string"&&n.length>100?`${n.slice(0,100)}...`:Array.isArray(n)?n.map(t):n!==null&&typeof n=="object"?Object.fromEntries(Object.entries(n).map(([r,o])=>[r,t(o)])):n}try{return JSON.stringify(t(e),null,2)}catch{return String(e)}}var Je=1e4;async function bo(e,t,n,r){console.log(`
2
2
  ${pe("=".repeat(80))}`),console.log(Ke(pe("[TRACE] Request Details"))),console.log(pe("-".repeat(80))),Object.keys(t).length>0&&(console.log(U("Request Headers:")),console.log(Te(rn(t)))),n!==void 0&&(console.log(U("Request Body:")),console.log(typeof n=="string"?n:Te(n)));let o={};if(e.headers.forEach((s,i)=>{o[i]=s}),Object.keys(o).length>0&&(console.log(U("Response Headers:")),console.log(Te(rn(o)))),!r)console.log(`${U("Response Body:")} (streaming \u2014 not dumped)`);else if(e.body===null)console.log(`${U("Response Body:")} (no body)`);else try{let s=await e.clone().text();if(s.length===0)console.log(`${U("Response Body:")} (empty)`);else{console.log(U("Response Body:"));try{console.log(Te(JSON.parse(s)))}catch{console.log(s.length>Je?`${s.slice(0,Je)}
3
3
  ... (truncated, ${s.length-Je} more characters)`:s)}}}catch{console.log(`${U("Response Body:")} (unable to read)`)}console.log(`${pe("=".repeat(80))}
4
- `)}function bo(e){let t=String(e);return e>=500?sn(t):e>=400?Ge(t):e>=300?U(t):on(t)}function xo(e,t){return e!=="GET"&&e!=="HEAD"?!1:t.endsWith("/favicon.ico")}function dn(e={}){return e.enabled===!1?(t,n)=>n():async(t,n)=>{let r=mo(e.level),o=Date.now(),s=t.method,i=new URL(t.url).pathname;if(xo(s,i))return n();let u={};r==="trace"&&t.headers.forEach((h,R)=>{u[R]=h});let a;if(s!=="GET"&&s!=="HEAD"){let h=T(t).parsedBody;if(h!==void 0)a=h;else try{a=await t.clone().json()}catch{}}let d=await n(),c=Date.now()-o,l=new Date().toISOString().substring(11,19),p=co(a)?a:void 0,g=p?.method==="subscriptions/listen",f=[[ve(l),Ke(s),i,bo(d.status),ve(`in ${c}ms`)].join(" ")];if(p!==void 0){let h=Re(p.method),R=[` ${wo(h)(h)}`],H=go(p);H.subject!==void 0&&R.push(Ke(Re(H.subject)));let F=r!=="info";F&&H.input!==void 0&&R.push(nn(H.input));let O=g?{errorMessage:null}:await Ro(d);if(F&&p.method==="tools/call"&&O.errorMessage===null&&O.result!==void 0&&R.push(ve("->"),nn(To(O.result))),p.method!=="initialize"){let q=yo(p);q!==void 0&&R.push(ve(Re(q)))}O.errorMessage!==null?R.push(Ge(`ERROR ${Re(O.errorMessage)}`)):d.status>=400&&R.push(Ge(`ERROR (HTTP ${d.status})`)),f.push(R.join(" "))}return console.log(f.join(`
5
- `)),r==="trace"&&await Mo(d,u,a,!g),d}}import{createMcpHandler as Oo}from"@modelcontextprotocol/server";function cn(e,t={}){let{path:n="/mcp",handler:r,authInfo:o}=t,s=r?.legacy??"stateless",i=Oo(e,{legacy:"stateless",...r});return{handler:i,fetch:async a=>{if(!Dt(a,n))return new Response("Not Found",{status:404});if(s==="stateless"){let f=a.method.toUpperCase();if(f==="GET"||f==="DELETE"||f==="HEAD")return new Response(null,{status:204})}let d=T(a),c=d.parsedBody;if(c===void 0)try{c=await a.clone().json()}catch{}let l=Ve(c);l!==void 0&&$e(a,l);let p=o?.(a)??d.authInfo,g=await i.fetch(a,{...c!==void 0&&{parsedBody:c},...p!==void 0&&{authInfo:p}});return g.headers.get("content-type")?.toLowerCase().includes("application/json")?Lt(a,g):g}}}import{completable as ln}from"@modelcontextprotocol/server";function Ye(e){let t=e.map(String);return n=>{let r=String(n??"").toLowerCase();return t.filter(o=>o.toLowerCase().startsWith(r))}}function Ao(e,t){return typeof t=="function"?ln(e,(n,r)=>t(String(n??""),r)):ln(e,Ye(t))}function pn(e){let t=Object.create(null);for(let[n,r]of Object.entries(e))r!==void 0&&(t[n]=Array.isArray(r)?Ye(r):r);return t}import{fromJsonSchema as Co}from"@modelcontextprotocol/server";var Eo=["get","put","post","delete","options","head","patch","trace"];function gn(e,t){let n=Po(t.spec,t),r=Uo(n),o=n.length>0?Fo(t):void 0;for(let[s,i]of n.entries()){let u=r[s];if(u===void 0||o===void 0)continue;let a=No(i);e.tool({name:u,description:Io(i),inputSchema:jo(t.spec,i,a)},async d=>$o(i,d,t,a,o))}}function Po(e,t){let n=[];for(let[r,o]of Object.entries(e.paths??{})){let s=X(e,o);if(s===void 0||me(s))continue;let i=fn(e,s.parameters);for(let u of Eo){let a=s[u];if(a===void 0)continue;let d=X(e,a);if(d===void 0||me(d))continue;let c=fn(e,d.parameters),l=d.requestBody===void 0?void 0:X(e,d.requestBody),p={method:u,path:r,operation:d,parameters:So(i,c),...l!==void 0&&!me(l)&&{requestBody:l}};ko(p,t)&&n.push(p)}}return n}function fn(e,t){let n=[];for(let r of t??[]){let o=X(e,r);o!==void 0&&!me(o)&&n.push(o)}return n}function So(e,t){let n=new Map;for(let r of[...e,...t])n.set(`${r.in}:${r.name}`,r);return[...n.values()]}function ko(e,t){if(t.tags?.length){let n=new Set(e.operation.tags??[]);if(!t.tags.some(r=>n.has(r)))return!1}return!(t.exclude??[]).some(n=>_o(e,n))}function _o(e,t){if(t.method&&t.method.toLowerCase()!==e.method||t.operationId&&!mn(t.operationId,e.operation.operationId??"")||t.path&&!mn(t.path,e.path))return!1;if(t.tags?.length){let n=new Set(e.operation.tags??[]);if(!t.tags.some(r=>n.has(r)))return!1}return!0}function mn(e,t){return typeof e=="string"?e===t:(e.lastIndex=0,e.test(t))}function Uo(e){let t=new Map;return e.map(n=>{let r=Lo(n.operation.operationId??`${n.method}_${n.path.replace(/[{}]/g,"").replace(/\//g,"_")}`),o=t.get(r)??0;if(t.set(r,o+1),o===0)return r;let s=`_${o+1}`;return`${r.slice(0,64-s.length)}${s}`})}function Io(e){return[e.operation.summary,e.operation.description,`HTTP: ${e.method.toUpperCase()} ${e.path}`].filter(t=>!!t).join(`
4
+ `)}function Mo(e){let t=String(e);return e>=500?sn(t):e>=400?Ge(t):e>=300?U(t):on(t)}function xo(e,t){return e!=="GET"&&e!=="HEAD"?!1:t.endsWith("/favicon.ico")}function dn(e={}){return e.enabled===!1?(t,n)=>n():async(t,n)=>{let r=mo(e.level),o=Date.now(),s=t.method,i=new URL(t.url).pathname;if(xo(s,i))return n();let u={};r==="trace"&&t.headers.forEach((h,R)=>{u[R]=h});let a;if(s!=="GET"&&s!=="HEAD"){let h=T(t).parsedBody;if(h!==void 0)a=h;else try{a=await t.clone().json()}catch{}}let d=await n(),c=Date.now()-o,l=new Date().toISOString().substring(11,19),p=co(a)?a:void 0,g=p?.method==="subscriptions/listen",f=[[ve(l),Ke(s),i,Mo(d.status),ve(`in ${c}ms`)].join(" ")];if(p!==void 0){let h=Re(p.method),R=[` ${wo(h)(h)}`],H=go(p);H.subject!==void 0&&R.push(Ke(Re(H.subject)));let F=r!=="info";F&&H.input!==void 0&&R.push(nn(H.input));let O=g?{errorMessage:null}:await Ro(d);if(F&&p.method==="tools/call"&&O.errorMessage===null&&O.result!==void 0&&R.push(ve("->"),nn(To(O.result))),p.method!=="initialize"){let q=yo(p);q!==void 0&&R.push(ve(Re(q)))}O.errorMessage!==null?R.push(Ge(`ERROR ${Re(O.errorMessage)}`)):d.status>=400&&R.push(Ge(`ERROR (HTTP ${d.status})`)),f.push(R.join(" "))}return console.log(f.join(`
5
+ `)),r==="trace"&&await bo(d,u,a,!g),d}}import{createMcpHandler as Oo}from"@modelcontextprotocol/server";function cn(e,t={}){let{path:n="/mcp",handler:r,authInfo:o}=t,s=r?.legacy??"stateless",i=Oo(e,{legacy:"stateless",...r});return{handler:i,fetch:async a=>{if(!Dt(a,n))return new Response("Not Found",{status:404});if(s==="stateless"){let f=a.method.toUpperCase();if(f==="GET"||f==="DELETE"||f==="HEAD")return new Response(null,{status:204})}let d=T(a),c=d.parsedBody;if(c===void 0)try{c=await a.clone().json()}catch{}let l=Ve(c);l!==void 0&&$e(a,l);let p=o?.(a)??d.authInfo,g=await i.fetch(a,{...c!==void 0&&{parsedBody:c},...p!==void 0&&{authInfo:p}});return g.headers.get("content-type")?.toLowerCase().includes("application/json")?Lt(a,g):g}}}import{completable as ln}from"@modelcontextprotocol/server";function Ye(e){let t=e.map(String);return n=>{let r=String(n??"").toLowerCase();return t.filter(o=>o.toLowerCase().startsWith(r))}}function Ao(e,t){return typeof t=="function"?ln(e,(n,r)=>t(String(n??""),r)):ln(e,Ye(t))}function pn(e){let t=Object.create(null);for(let[n,r]of Object.entries(e))r!==void 0&&(t[n]=Array.isArray(r)?Ye(r):r);return t}import{fromJsonSchema as Co}from"@modelcontextprotocol/server";var Eo=["get","put","post","delete","options","head","patch","trace"];function gn(e,t){let n=Po(t.spec,t),r=Uo(n),o=n.length>0?Fo(t):void 0;for(let[s,i]of n.entries()){let u=r[s];if(u===void 0||o===void 0)continue;let a=No(i);e.tool({name:u,description:Io(i),inputSchema:jo(t.spec,i,a)},async d=>$o(i,d,t,a,o))}}function Po(e,t){let n=[];for(let[r,o]of Object.entries(e.paths??{})){let s=X(e,o);if(s===void 0||me(s))continue;let i=fn(e,s.parameters);for(let u of Eo){let a=s[u];if(a===void 0)continue;let d=X(e,a);if(d===void 0||me(d))continue;let c=fn(e,d.parameters),l=d.requestBody===void 0?void 0:X(e,d.requestBody),p={method:u,path:r,operation:d,parameters:So(i,c),...l!==void 0&&!me(l)&&{requestBody:l}};ko(p,t)&&n.push(p)}}return n}function fn(e,t){let n=[];for(let r of t??[]){let o=X(e,r);o!==void 0&&!me(o)&&n.push(o)}return n}function So(e,t){let n=new Map;for(let r of[...e,...t])n.set(`${r.in}:${r.name}`,r);return[...n.values()]}function ko(e,t){if(t.tags?.length){let n=new Set(e.operation.tags??[]);if(!t.tags.some(r=>n.has(r)))return!1}return!(t.exclude??[]).some(n=>_o(e,n))}function _o(e,t){if(t.method&&t.method.toLowerCase()!==e.method||t.operationId&&!mn(t.operationId,e.operation.operationId??"")||t.path&&!mn(t.path,e.path))return!1;if(t.tags?.length){let n=new Set(e.operation.tags??[]);if(!t.tags.some(r=>n.has(r)))return!1}return!0}function mn(e,t){return typeof e=="string"?e===t:(e.lastIndex=0,e.test(t))}function Uo(e){let t=new Map;return e.map(n=>{let r=Lo(n.operation.operationId??`${n.method}_${n.path.replace(/[{}]/g,"").replace(/\//g,"_")}`),o=t.get(r)??0;if(t.set(r,o+1),o===0)return r;let s=`_${o+1}`;return`${r.slice(0,64-s.length)}${s}`})}function Io(e){return[e.operation.summary,e.operation.description,`HTTP: ${e.method.toUpperCase()} ${e.path}`].filter(t=>!!t).join(`
6
6
 
7
- `)}function Lo(e){return e.trim().replace(/[^a-zA-Z0-9_-]+/g,"_").replace(/_+/g,"_").replace(/^_/,"").replace(/_$/,"").slice(0,64)||"openapi_tool"}function jo(e,t,n){let r={},o=[];for(let{parameter:a,inputName:d}of n.parameters){let c=hn(e,a.schema??{});r[d]={...c,description:a.description??`${a.in} parameter`},(a.required||a.in==="path")&&o.push(d)}let s=yn(t.requestBody);s!==void 0&&n.bodyInputName!==void 0&&(r[n.bodyInputName]=hn(e,s),t.requestBody?.required&&o.push(n.bodyInputName));let i=qo(e),u={type:"object",properties:r,additionalProperties:!1,...o.length>0&&{required:o},...i!==void 0&&{$defs:i}};return Co(u)}function No(e){let t=e.parameters.filter(i=>i.in!=="cookie"),n=yn(e.requestBody)===void 0?void 0:"body",r=new Map;for(let i of t)r.set(i.name,(r.get(i.name)??0)+1);let o=new Set(n===void 0?[]:[n]);return{parameters:t.map(i=>{let a=(r.get(i.name)??0)>1||i.name===n?`${i.name}_${i.in}`:i.name;return{parameter:i,inputName:Ho(a,o)}}),...n!==void 0&&{bodyInputName:n}}}function Ho(e,t){let n=e,r=2;for(;t.has(n);)n=`${e}_${r}`,r+=1;return t.add(n),n}function qo(e){let t=Z(e.components?.schemas);if(t===void 0)return;let n={};for(let[r,o]of Object.entries(t))n[r]=fe(e,o,new Set);return n}function hn(e,t){let n=fe(e,t,new Set);return Z(n)??{}}function fe(e,t,n){if(Array.isArray(t))return t.map(u=>fe(e,u,n));let r=Z(t);if(r===void 0)return t;let o=typeof r.$ref=="string"?r.$ref:void 0,s={};for(let[u,a]of Object.entries(r))u!=="$ref"&&(u==="nullable"&&typeof a=="boolean"||(s[u]=fe(e,a,n)));let i=s;if(o!==void 0){let u=Do(e,o);if(u!==void 0)i={$ref:u,...s};else if(!n.has(o)){let a=X(e,{$ref:o});if(a!==void 0){let d=new Set(n);d.add(o),i={...Z(fe(e,a,d))??{},...s}}}}return r.nullable===!0?{anyOf:[i,{type:"null"}]}:i}function Do(e,t){let n="#/components/schemas/";if(t.startsWith(n))return X(e,{$ref:t})===void 0?void 0:`#/$defs/${t.slice(n.length)}`}function yn(e){let t=e?.content;if(t!==void 0)return t["application/json"]?.schema??t["application/*+json"]?.schema??Object.entries(t).find(([n])=>n.includes("+json"))?.[1].schema}async function $o(e,t,n,r,o){let s=n.fetch??globalThis.fetch,i=Vo(e,t,r.parameters,o),u=Bo(r.parameters,t,n),a=r.bodyInputName,d=a===void 0||t[a]===void 0?void 0:JSON.stringify(t[a]);d!==void 0&&!Jo(u,"content-type")&&(u["content-type"]="application/json");let c=await s(i,{method:e.method.toUpperCase(),headers:u,...d!==void 0&&{body:d}}),l=c.headers.get("content-type")??"";if(!c.ok)return{content:[{type:"text",text:await c.text()}],isError:!0};if(l.includes("application/json")||l.includes("+json")){let p=await c.text();try{let g=JSON.parse(p);return{content:[{type:"text",text:JSON.stringify(g)}],structuredContent:g}}catch{return{content:[{type:"text",text:p}]}}}return{content:[{type:"text",text:await c.text()}]}}function Vo(e,t,n,r){let o=e.path.replace(/{([^}]+)}/g,(i,u)=>{let a=n.find(({parameter:d})=>d.in==="path"&&d.name===u);return encodeURIComponent(String(a===void 0?"":t[a.inputName]??""))}),s=new URL(o.replace(/^\/+/,""),zo(r));for(let{parameter:i,inputName:u}of n){if(i.in!=="query")continue;let a=t[u];a==null||a===""||Wo(s,i.name,a)}return s.toString()}function Bo(e,t,n){let r={...n.headers??{}};for(let{parameter:o,inputName:s}of e){if(o.in!=="header")continue;let i=t[s];i==null||i===""||(r[o.name]=String(i))}return n.auth?.type==="bearer"&&n.auth.token&&(r.authorization=`Bearer ${n.auth.token}`),n.auth?.type==="header"&&n.auth.value&&(r[n.auth.name]=n.auth.value),r}function Fo(e){let t=e.baseUrl??e.spec.servers?.[0]?.url;if(t===void 0||t.trim()==="")throw new Error("MCPServer.fromOpenAPI requires options.baseUrl or spec.servers[0].url");return t}function Wo(e,t,n){if(Array.isArray(n)){for(let r of n)r!=null&&r!==""&&e.searchParams.append(t,String(r));return}e.searchParams.set(t,String(n))}function zo(e){return e.endsWith("/")?e:`${e}/`}function Jo(e,t){return Object.keys(e).some(n=>n.toLowerCase()===t)}function me(e){let t=Z(e);return t!==void 0&&typeof t.$ref=="string"}function X(e,t){if(!me(t))return t;if(!t.$ref.startsWith("#/"))return;let n=t.$ref.slice(2).split("/").map(o=>o.replace(/~1/g,"/").replace(/~0/g,"~")),r=e;for(let o of n){let s=Z(r);if(s===void 0||!(o in s))return;r=s[o]}return r}function Z(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:void 0}import{OAuthError as va,OAuthErrorCode as Ra,bearerAuthChallengeResponse as Ta,getOAuthProtectedResourceMetadataUrl as On,oauthMetadataResponse as Ma,requireBearerAuth as An,verifyBearerToken as ba}from"@modelcontextprotocol/server";import{getOAuthProtectedResourceMetadataUrl as da,oauthMetadataResponse as es,requireBearerAuth as ca}from"@modelcontextprotocol/server";function L(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function W(e){let t=e.hostname.toLowerCase();return t==="localhost"||t.endsWith(".localhost")||t==="[::1]"||/^127(?:\.\d{1,3}){3}$/.test(t)}function z(e,t){let n;try{n=new URL(e)}catch{throw new Error(`${t} must be an absolute URL`)}if(n.origin==="null"||n.username!==""||n.password!=="")throw new Error(`${t} must be an absolute URL without credentials`);return n}function J(e,t){if(e.protocol!=="https:"&&!(e.protocol==="http:"&&W(e)))throw new Error(`${t} must use HTTPS, or HTTP for localhost`)}import{OAuthError as Ko,OAuthErrorCode as Go}from"@modelcontextprotocol/server";function w(e,t){let n=new Ko(Go.InvalidToken,e);return t!==void 0&&(n.cause=t),n}function wn(e){let t=e.provider,n=et(e.basePath);if(t.resource!==void 0)return Xe(t.resource,n);if(e.mcpUrl!==void 0)return Xe(Tn(Rn(e.mcpUrl,"MCP_URL"),n),n)}function vn(e,t){let n=Rn(e,"listen origin");if(!W(n))throw new Error("OAuth listen origin must be localhost or a loopback address");return Xe(Tn(n,et(t)),t)}function Xe(e,t){let n=et(t),r=z(e,"OAuth resource");if(r.search!==""||r.hash!=="")throw new Error("OAuth resource must not include a query string or fragment");if(J(r,"OAuth resource"),Mn(r.pathname)!==n)throw new Error(`OAuth resource path must exactly match basePath (${n})`);return r.pathname=n,r}function Ze(e,t){let n=Qe(t),r=e.createTokenVerifier(new URL(n.href));if(r===null||typeof r!="object"||typeof r.verifyAccessToken!="function")throw new TypeError("OAuth provider createTokenVerifier must return an OAuthTokenVerifier");return{async verifyAccessToken(o){let s=await r.verifyAccessToken(o);Zo(s),Yo(s,n);let i;try{i=e.mapAuthInfo(s)}catch(u){throw w("Token identity mapping failed",u)}return Qo(i),{...s,scopes:[...s.scopes],extra:{...s.extra,...i}}}}}function Yo(e,t){if(e.resource===void 0)throw w("Token verifier did not return a validated protected resource");if(Xo(e.resource).href!==Qe(t).href)throw w("Token resource does not match the protected resource")}function Xo(e){if(!(e instanceof URL))throw w("Token resource must be an absolute HTTPS URL, or HTTP URL for localhost");let t=e;if(!/^https?:$/.test(t.protocol)||t.username!==""||t.password!==""||t.search!==""||t.hash!==""||t.protocol==="http:"&&!W(t))throw w("Token resource must be an absolute HTTPS URL, or HTTP URL for localhost");return Qe(t)}function Qe(e){let t=new URL(e);return t.pathname=t.pathname==="/"?"/":t.pathname.replace(/\/+$/,""),t}function Me(e){return{oauthMetadata:e.oauthMetadata,...e.requiredScopes!==void 0&&{requiredScopes:[...e.requiredScopes]},...e.scopesSupported!==void 0&&{scopesSupported:[...e.scopesSupported]},...e.resourceName!==void 0&&{resourceName:e.resourceName},...e.serviceDocumentationUrl!==void 0&&{serviceDocumentationUrl:e.serviceDocumentationUrl}}}function Zo(e){if(e===null||typeof e!="object"||typeof e.token!="string"||e.token.length===0||typeof e.clientId!="string"||!Array.isArray(e.scopes)||!e.scopes.every(t=>typeof t=="string")||typeof e.expiresAt!="number"||!Number.isFinite(e.expiresAt)||e.expiresAt<=Date.now()/1e3)throw w("Token verifier returned invalid authentication information")}function Qo(e){if(e===null||typeof e!="object"||!("user"in e)||e.user===void 0||!L(e.payload)||!Array.isArray(e.permissions)||!e.permissions.every(t=>typeof t=="string"))throw w("Token identity mapping must return user, payload, and string permissions")}function Rn(e,t){let n=z(e,t);if(n.pathname!=="/"||n.search!==""||n.hash!==""||n.username!==""||n.password!=="")throw new Error(`${t} must be an absolute origin without a path`);return n}function Tn(e,t){let n=new URL(e.origin);return n.pathname=t,n}function et(e){if(!e.startsWith("/")||e.includes("?")||e.includes("#"))throw new Error("basePath must be an absolute URL pathname");return Mn(e)}function Mn(e){if(e==="/")return"/";let t=e.length;for(;t>0&&e.charCodeAt(t-1)===47;)t--;return e.slice(0,t)}function tt(e,t){let n=Me(e);return async(r,o)=>{let s=es(r,{oauthMetadata:n.oauthMetadata,resourceServerUrl:t,...n.scopesSupported!==void 0&&{scopesSupported:[...n.scopesSupported]},...n.resourceName!==void 0&&{resourceName:n.resourceName},...n.serviceDocumentationUrl!==void 0&&{serviceDocumentationUrl:n.serviceDocumentationUrl}});return s!==void 0?s:o()}}function bn(e){return T(e).authInfo}function x(e){if(e===null||typeof e!="object"||typeof e.createTokenVerifier!="function"||typeof e.mapAuthInfo!="function")throw new TypeError("oauthCustomProvider requires createTokenVerifier, oauthMetadata, and mapAuthInfo");if(ts(e.oauthMetadata),e.resource!==void 0&&ns(e.resource),xn(e.requiredScopes,"requiredScopes"),xn(e.scopesSupported,"scopesSupported"),e.resourceName!==void 0&&(typeof e.resourceName!="string"||e.resourceName.trim().length===0))throw new TypeError("resourceName must be a non-empty string");if(e.serviceDocumentationUrl!==void 0){if(!(e.serviceDocumentationUrl instanceof URL))throw new TypeError("serviceDocumentationUrl must be a URL");J(e.serviceDocumentationUrl,"serviceDocumentationUrl")}return{createTokenVerifier:e.createTokenVerifier,oauthMetadata:e.oauthMetadata,mapAuthInfo:e.mapAuthInfo,...e.resource!==void 0&&{resource:e.resource},...e.requiredScopes!==void 0&&{requiredScopes:[...e.requiredScopes]},...e.scopesSupported!==void 0&&{scopesSupported:[...e.scopesSupported]},...e.resourceName!==void 0&&{resourceName:e.resourceName},...e.serviceDocumentationUrl!==void 0&&{serviceDocumentationUrl:e.serviceDocumentationUrl}}}function ts(e){if(e===null||typeof e!="object"||!("issuer"in e)||typeof e.issuer!="string")throw new TypeError("oauthMetadata must include a string issuer");J(z(e.issuer,"oauthMetadata.issuer"),"oauthMetadata.issuer")}function ns(e){J(z(e,"resource"),"resource")}function xn(e,t){if(e!==void 0&&(!Array.isArray(e)||!e.every(n=>typeof n=="string")))throw new TypeError(`${t} must be an array of strings`)}function Cn(e){return e.inputSchema??e.schema}var rs="mcp_use_sdk_event",os="https://eu.i.posthog.com/i/v0/e/",ss="phc_lyTtbYwvkdSbrcMQNPiKiiRWrrM1seyKIMjycSvItEI",is=/(^|_)(arguments?|args|body|command|headers?|location|message|organization|path|query|response|secret|subject|token|uri|url|user_agent)(_|$)/i,as=new Set("feature action sdk_generation telemetry_schema_version sdk_package sdk_version server_id runtime_id identity_stability distinct_id validation_run_id is_validation".split(" ")),rt=crypto.randomUUID(),En=new Set,nt=new Set,Pn=new Map;function ot(e){return[...e].some(t=>{let n=t.charCodeAt(0);return n<32||n===127})}function st(e){return typeof process>"u"?void 0:process.env?.[e]}function Sn(e){let t=st(e);return t!==void 0&&t.length>0&&t.length<=128&&!ot(t)?t:void 0}function kn(){if(st("MCP_USE_ANONYMIZED_TELEMETRY")==="false")return!0;try{return globalThis.__MCP_USE_ANONYMIZED_TELEMETRY__===!1||typeof localStorage<"u"&&localStorage.getItem("MCP_USE_ANONYMIZED_TELEMETRY")==="false"}catch{return!1}}function _n(){return kn()}function us(e){return Object.fromEntries(Object.entries(e).filter(([t,n])=>t.length>128||ot(t)||t.startsWith("$")||as.has(t)||is.test(t)||n===void 0?!1:typeof n=="string"?n.length<=128&&!ot(n):typeof n=="boolean"||typeof n=="number"&&Number.isFinite(n)))}async function ds(e){let t=Sn("MCP_USE_TELEMETRY_PROJECT_ID");if(t!==void 0)return{id:t,stability:"project"};if(e===void 0||typeof process>"u")return{id:rt,stability:"process"};let n=Pn.get(e);if(n!==void 0)return n;let r=(async()=>{try{let o=await import("fs/promises"),s=`${e}/.mcp-use`,i=`${s}/usage.json`,u=async()=>{try{let c=JSON.parse(await o.readFile(i,"utf8"));if(typeof c=="object"&&c!==null&&"schemaVersion"in c&&c.schemaVersion===1&&"serverId"in c&&typeof c.serverId=="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(c.serverId))return c.serverId}catch{}},a=await u();if(a!==void 0)return{id:a,stability:"server"};await o.mkdir(s,{recursive:!0,mode:448});let d=crypto.randomUUID();try{return await o.writeFile(i,`${JSON.stringify({schemaVersion:1,serverId:d})}
8
- `,{flag:"wx",mode:384}),{id:d,stability:"server"}}catch{let c=await u();if(c!==void 0)return{id:c,stability:"server"}}}catch{}return{id:rt,stability:"process"}})();return Pn.set(e,r),r}function cs(e,t,n,r,o){let s=Sn("MCP_USE_TELEMETRY_VALIDATION_ID");if(kn()||st("NODE_ENV")==="test"&&s===void 0||nt.size>=16)return;if(r.onceKey!==void 0){if(En.has(r.onceKey))return;En.add(r.onceKey)}let i=Math.max(0,Math.min(1,r.sampleRate??1));if(s===void 0&&Math.random()>=i)return;let u=(async()=>{try{let a=await o(),d=JSON.stringify({api_key:ss,event:rs,properties:{...us(n),feature:e,action:t,sdk_generation:"v2",telemetry_schema_version:2,sdk_package:"mcp-use",sdk_version:typeof __MCP_USE_PACKAGE_VERSION__>"u"?"development":__MCP_USE_PACKAGE_VERSION__,server_id:a.id,runtime_id:rt,identity_stability:a.stability,distinct_id:a.id,sample_rate:s===void 0?i:1,$process_person_profile:!1,$geoip_disable:!0,...s!==void 0&&{is_validation:!0,validation_run_id:s}}});await fetch(os,{method:"POST",headers:{"content-type":"application/json"},keepalive:!0,body:d})}catch{return}})();nt.add(u),u.then(()=>nt.delete(u))}function be(e,t,n={},r={}){cs(e,t,n,r,()=>ds(r.serverRoot))}var xe=Symbol("mcp-use/registerViews");function In(e,t){if(!e.startsWith("/"))throw new Error(`View manifest asset path must be origin-absolute (start with "/"); got ${JSON.stringify(e)}`);return`${t}${e}`}function ls(e,t){return`${G(e,`_mcp-use/views/${t}`)}/`}function it(e,t,n,r){return e.startsWith("http://")||e.startsWith("https://")||e.startsWith("data:")?e:e.startsWith("/")?In(e,t):`${t}${ls(n,r)}${e.replace(/^\/+/,"")}`}function ps(e,t){return`${e}${G(t,"_mcp-use/public")}/`}function fs(e){return e.replaceAll(/<\/script/gi,"<\\/script").replaceAll("<!--","\\x3C!--")}function ms(e){return e.replaceAll(/<\/style/gi,"<\\/style")}function at(e){return e.replaceAll("&","&amp;").replaceAll('"',"&quot;").replaceAll("<","&lt;").replaceAll(">","&gt;")}var Un="<style>html,body,#root{background:transparent}</style>";function ut(e,t,n,r){let o={publicBase:ps(t,n)},s=`<script>globalThis.__mcpUseViewConfig=${JSON.stringify(o)};</script>`;if(e.kind==="inline"){let d=e.css.length>0?`<style>${ms(e.css)}</style>`:"",c=`<script type="module">${fs(e.js)}</script>`;return`<!doctype html>
7
+ `)}function Lo(e){return e.trim().replace(/[^a-zA-Z0-9_-]+/g,"_").replace(/_+/g,"_").replace(/^_/,"").replace(/_$/,"").slice(0,64)||"openapi_tool"}function jo(e,t,n){let r={},o=[];for(let{parameter:a,inputName:d}of n.parameters){let c=hn(e,a.schema??{});r[d]={...c,description:a.description??`${a.in} parameter`},(a.required||a.in==="path")&&o.push(d)}let s=yn(t.requestBody);s!==void 0&&n.bodyInputName!==void 0&&(r[n.bodyInputName]=hn(e,s),t.requestBody?.required&&o.push(n.bodyInputName));let i=qo(e),u={type:"object",properties:r,additionalProperties:!1,...o.length>0&&{required:o},...i!==void 0&&{$defs:i}};return Co(u)}function No(e){let t=e.parameters.filter(i=>i.in!=="cookie"),n=yn(e.requestBody)===void 0?void 0:"body",r=new Map;for(let i of t)r.set(i.name,(r.get(i.name)??0)+1);let o=new Set(n===void 0?[]:[n]);return{parameters:t.map(i=>{let a=(r.get(i.name)??0)>1||i.name===n?`${i.name}_${i.in}`:i.name;return{parameter:i,inputName:Ho(a,o)}}),...n!==void 0&&{bodyInputName:n}}}function Ho(e,t){let n=e,r=2;for(;t.has(n);)n=`${e}_${r}`,r+=1;return t.add(n),n}function qo(e){let t=Z(e.components?.schemas);if(t===void 0)return;let n={};for(let[r,o]of Object.entries(t))n[r]=fe(e,o,new Set);return n}function hn(e,t){let n=fe(e,t,new Set);return Z(n)??{}}function fe(e,t,n){if(Array.isArray(t))return t.map(u=>fe(e,u,n));let r=Z(t);if(r===void 0)return t;let o=typeof r.$ref=="string"?r.$ref:void 0,s={};for(let[u,a]of Object.entries(r))u!=="$ref"&&(u==="nullable"&&typeof a=="boolean"||(s[u]=fe(e,a,n)));let i=s;if(o!==void 0){let u=Do(e,o);if(u!==void 0)i={$ref:u,...s};else if(!n.has(o)){let a=X(e,{$ref:o});if(a!==void 0){let d=new Set(n);d.add(o),i={...Z(fe(e,a,d))??{},...s}}}}return r.nullable===!0?{anyOf:[i,{type:"null"}]}:i}function Do(e,t){let n="#/components/schemas/";if(t.startsWith(n))return X(e,{$ref:t})===void 0?void 0:`#/$defs/${t.slice(n.length)}`}function yn(e){let t=e?.content;if(t!==void 0)return t["application/json"]?.schema??t["application/*+json"]?.schema??Object.entries(t).find(([n])=>n.includes("+json"))?.[1].schema}async function $o(e,t,n,r,o){let s=n.fetch??globalThis.fetch,i=Vo(e,t,r.parameters,o),u=Bo(r.parameters,t,n),a=r.bodyInputName,d=a===void 0||t[a]===void 0?void 0:JSON.stringify(t[a]);d!==void 0&&!Jo(u,"content-type")&&(u["content-type"]="application/json");let c=await s(i,{method:e.method.toUpperCase(),headers:u,...d!==void 0&&{body:d}}),l=c.headers.get("content-type")??"";if(!c.ok)return{content:[{type:"text",text:await c.text()}],isError:!0};if(l.includes("application/json")||l.includes("+json")){let p=await c.text();try{let g=JSON.parse(p);return{content:[{type:"text",text:JSON.stringify(g)}],structuredContent:g}}catch{return{content:[{type:"text",text:p}]}}}return{content:[{type:"text",text:await c.text()}]}}function Vo(e,t,n,r){let o=e.path.replace(/{([^}]+)}/g,(i,u)=>{let a=n.find(({parameter:d})=>d.in==="path"&&d.name===u);return encodeURIComponent(String(a===void 0?"":t[a.inputName]??""))}),s=new URL(o.replace(/^\/+/,""),zo(r));for(let{parameter:i,inputName:u}of n){if(i.in!=="query")continue;let a=t[u];a==null||a===""||Wo(s,i.name,a)}return s.toString()}function Bo(e,t,n){let r={...n.headers??{}};for(let{parameter:o,inputName:s}of e){if(o.in!=="header")continue;let i=t[s];i==null||i===""||(r[o.name]=String(i))}return n.auth?.type==="bearer"&&n.auth.token&&(r.authorization=`Bearer ${n.auth.token}`),n.auth?.type==="header"&&n.auth.value&&(r[n.auth.name]=n.auth.value),r}function Fo(e){let t=e.baseUrl??e.spec.servers?.[0]?.url;if(t===void 0||t.trim()==="")throw new Error("MCPServer.fromOpenAPI requires options.baseUrl or spec.servers[0].url");return t}function Wo(e,t,n){if(Array.isArray(n)){for(let r of n)r!=null&&r!==""&&e.searchParams.append(t,String(r));return}e.searchParams.set(t,String(n))}function zo(e){return e.endsWith("/")?e:`${e}/`}function Jo(e,t){return Object.keys(e).some(n=>n.toLowerCase()===t)}function me(e){let t=Z(e);return t!==void 0&&typeof t.$ref=="string"}function X(e,t){if(!me(t))return t;if(!t.$ref.startsWith("#/"))return;let n=t.$ref.slice(2).split("/").map(o=>o.replace(/~1/g,"/").replace(/~0/g,"~")),r=e;for(let o of n){let s=Z(r);if(s===void 0||!(o in s))return;r=s[o]}return r}function Z(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:void 0}import{OAuthError as va,OAuthErrorCode as Ra,bearerAuthChallengeResponse as Ta,getOAuthProtectedResourceMetadataUrl as On,oauthMetadataResponse as ba,requireBearerAuth as An,verifyBearerToken as Ma}from"@modelcontextprotocol/server";import{getOAuthProtectedResourceMetadataUrl as da,oauthMetadataResponse as es,requireBearerAuth as ca}from"@modelcontextprotocol/server";function L(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function W(e){let t=e.hostname.toLowerCase();return t==="localhost"||t.endsWith(".localhost")||t==="[::1]"||/^127(?:\.\d{1,3}){3}$/.test(t)}function z(e,t){let n;try{n=new URL(e)}catch{throw new Error(`${t} must be an absolute URL`)}if(n.origin==="null"||n.username!==""||n.password!=="")throw new Error(`${t} must be an absolute URL without credentials`);return n}function J(e,t){if(e.protocol!=="https:"&&!(e.protocol==="http:"&&W(e)))throw new Error(`${t} must use HTTPS, or HTTP for localhost`)}import{OAuthError as Ko,OAuthErrorCode as Go}from"@modelcontextprotocol/server";function w(e,t){let n=new Ko(Go.InvalidToken,e);return t!==void 0&&(n.cause=t),n}function wn(e){let t=e.provider,n=et(e.basePath);if(t.resource!==void 0)return Xe(t.resource,n);if(e.mcpUrl!==void 0)return Xe(Tn(Rn(e.mcpUrl,"MCP_URL"),n),n)}function vn(e,t){let n=Rn(e,"listen origin");if(!W(n))throw new Error("OAuth listen origin must be localhost or a loopback address");return Xe(Tn(n,et(t)),t)}function Xe(e,t){let n=et(t),r=z(e,"OAuth resource");if(r.search!==""||r.hash!=="")throw new Error("OAuth resource must not include a query string or fragment");if(J(r,"OAuth resource"),bn(r.pathname)!==n)throw new Error(`OAuth resource path must exactly match basePath (${n})`);return r.pathname=n,r}function Ze(e,t){let n=Qe(t),r=e.createTokenVerifier(new URL(n.href));if(r===null||typeof r!="object"||typeof r.verifyAccessToken!="function")throw new TypeError("OAuth provider createTokenVerifier must return an OAuthTokenVerifier");return{async verifyAccessToken(o){let s=await r.verifyAccessToken(o);Zo(s),Yo(s,n);let i;try{i=e.mapAuthInfo(s)}catch(u){throw w("Token identity mapping failed",u)}return Qo(i),{...s,scopes:[...s.scopes],extra:{...s.extra,...i}}}}}function Yo(e,t){if(e.resource===void 0)throw w("Token verifier did not return a validated protected resource");if(Xo(e.resource).href!==Qe(t).href)throw w("Token resource does not match the protected resource")}function Xo(e){if(!(e instanceof URL))throw w("Token resource must be an absolute HTTPS URL, or HTTP URL for localhost");let t=e;if(!/^https?:$/.test(t.protocol)||t.username!==""||t.password!==""||t.search!==""||t.hash!==""||t.protocol==="http:"&&!W(t))throw w("Token resource must be an absolute HTTPS URL, or HTTP URL for localhost");return Qe(t)}function Qe(e){let t=new URL(e);return t.pathname=t.pathname==="/"?"/":t.pathname.replace(/\/+$/,""),t}function be(e){return{oauthMetadata:e.oauthMetadata,...e.requiredScopes!==void 0&&{requiredScopes:[...e.requiredScopes]},...e.scopesSupported!==void 0&&{scopesSupported:[...e.scopesSupported]},...e.resourceName!==void 0&&{resourceName:e.resourceName},...e.serviceDocumentationUrl!==void 0&&{serviceDocumentationUrl:e.serviceDocumentationUrl}}}function Zo(e){if(e===null||typeof e!="object"||typeof e.token!="string"||e.token.length===0||typeof e.clientId!="string"||!Array.isArray(e.scopes)||!e.scopes.every(t=>typeof t=="string")||typeof e.expiresAt!="number"||!Number.isFinite(e.expiresAt)||e.expiresAt<=Date.now()/1e3)throw w("Token verifier returned invalid authentication information")}function Qo(e){if(e===null||typeof e!="object"||!("user"in e)||e.user===void 0||!L(e.payload)||!Array.isArray(e.permissions)||!e.permissions.every(t=>typeof t=="string"))throw w("Token identity mapping must return user, payload, and string permissions")}function Rn(e,t){let n=z(e,t);if(n.pathname!=="/"||n.search!==""||n.hash!==""||n.username!==""||n.password!=="")throw new Error(`${t} must be an absolute origin without a path`);return n}function Tn(e,t){let n=new URL(e.origin);return n.pathname=t,n}function et(e){if(!e.startsWith("/")||e.includes("?")||e.includes("#"))throw new Error("basePath must be an absolute URL pathname");return bn(e)}function bn(e){if(e==="/")return"/";let t=e.length;for(;t>0&&e.charCodeAt(t-1)===47;)t--;return e.slice(0,t)}function tt(e,t){let n=be(e);return async(r,o)=>{let s=es(r,{oauthMetadata:n.oauthMetadata,resourceServerUrl:t,...n.scopesSupported!==void 0&&{scopesSupported:[...n.scopesSupported]},...n.resourceName!==void 0&&{resourceName:n.resourceName},...n.serviceDocumentationUrl!==void 0&&{serviceDocumentationUrl:n.serviceDocumentationUrl}});return s!==void 0?s:o()}}function Mn(e){return T(e).authInfo}function x(e){if(e===null||typeof e!="object"||typeof e.createTokenVerifier!="function"||typeof e.mapAuthInfo!="function")throw new TypeError("oauthCustomProvider requires createTokenVerifier, oauthMetadata, and mapAuthInfo");if(ts(e.oauthMetadata),e.resource!==void 0&&ns(e.resource),xn(e.requiredScopes,"requiredScopes"),xn(e.scopesSupported,"scopesSupported"),e.resourceName!==void 0&&(typeof e.resourceName!="string"||e.resourceName.trim().length===0))throw new TypeError("resourceName must be a non-empty string");if(e.serviceDocumentationUrl!==void 0){if(!(e.serviceDocumentationUrl instanceof URL))throw new TypeError("serviceDocumentationUrl must be a URL");J(e.serviceDocumentationUrl,"serviceDocumentationUrl")}return{createTokenVerifier:e.createTokenVerifier,oauthMetadata:e.oauthMetadata,mapAuthInfo:e.mapAuthInfo,...e.resource!==void 0&&{resource:e.resource},...e.requiredScopes!==void 0&&{requiredScopes:[...e.requiredScopes]},...e.scopesSupported!==void 0&&{scopesSupported:[...e.scopesSupported]},...e.resourceName!==void 0&&{resourceName:e.resourceName},...e.serviceDocumentationUrl!==void 0&&{serviceDocumentationUrl:e.serviceDocumentationUrl}}}function ts(e){if(e===null||typeof e!="object"||!("issuer"in e)||typeof e.issuer!="string")throw new TypeError("oauthMetadata must include a string issuer");J(z(e.issuer,"oauthMetadata.issuer"),"oauthMetadata.issuer")}function ns(e){J(z(e,"resource"),"resource")}function xn(e,t){if(e!==void 0&&(!Array.isArray(e)||!e.every(n=>typeof n=="string")))throw new TypeError(`${t} must be an array of strings`)}function Cn(e){return e.inputSchema??e.schema}var rs="mcp_use_sdk_event",os="https://eu.i.posthog.com/i/v0/e/",ss="phc_lyTtbYwvkdSbrcMQNPiKiiRWrrM1seyKIMjycSvItEI",is=/(^|_)(arguments?|args|body|command|headers?|location|message|organization|path|query|response|secret|subject|token|uri|url|user_agent)(_|$)/i,as=new Set("feature action sdk_generation telemetry_schema_version sdk_package sdk_version server_id runtime_id identity_stability distinct_id validation_run_id is_validation".split(" ")),rt=crypto.randomUUID(),En=new Set,nt=new Set,Pn=new Map;function ot(e){return[...e].some(t=>{let n=t.charCodeAt(0);return n<32||n===127})}function st(e){return typeof process>"u"?void 0:process.env?.[e]}function Sn(e){let t=st(e);return t!==void 0&&t.length>0&&t.length<=128&&!ot(t)?t:void 0}function kn(){if(st("MCP_USE_ANONYMIZED_TELEMETRY")==="false")return!0;try{return globalThis.__MCP_USE_ANONYMIZED_TELEMETRY__===!1||typeof localStorage<"u"&&localStorage.getItem("MCP_USE_ANONYMIZED_TELEMETRY")==="false"}catch{return!1}}function _n(){return kn()}function us(e){return Object.fromEntries(Object.entries(e).filter(([t,n])=>t.length>128||ot(t)||t.startsWith("$")||as.has(t)||is.test(t)||n===void 0?!1:typeof n=="string"?n.length<=128&&!ot(n):typeof n=="boolean"||typeof n=="number"&&Number.isFinite(n)))}async function ds(e){let t=Sn("MCP_USE_TELEMETRY_PROJECT_ID");if(t!==void 0)return{id:t,stability:"project"};if(e===void 0||typeof process>"u")return{id:rt,stability:"process"};let n=Pn.get(e);if(n!==void 0)return n;let r=(async()=>{try{let o=await import("fs/promises"),s=`${e}/.mcp-use`,i=`${s}/usage.json`,u=async()=>{try{let c=JSON.parse(await o.readFile(i,"utf8"));if(typeof c=="object"&&c!==null&&"schemaVersion"in c&&c.schemaVersion===1&&"serverId"in c&&typeof c.serverId=="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(c.serverId))return c.serverId}catch{}},a=await u();if(a!==void 0)return{id:a,stability:"server"};await o.mkdir(s,{recursive:!0,mode:448});let d=crypto.randomUUID();try{return await o.writeFile(i,`${JSON.stringify({schemaVersion:1,serverId:d})}
8
+ `,{flag:"wx",mode:384}),{id:d,stability:"server"}}catch{let c=await u();if(c!==void 0)return{id:c,stability:"server"}}}catch{}return{id:rt,stability:"process"}})();return Pn.set(e,r),r}function cs(e,t,n,r,o){let s=Sn("MCP_USE_TELEMETRY_VALIDATION_ID");if(kn()||st("NODE_ENV")==="test"&&s===void 0||nt.size>=16)return;if(r.onceKey!==void 0){if(En.has(r.onceKey))return;En.add(r.onceKey)}let i=Math.max(0,Math.min(1,r.sampleRate??1));if(s===void 0&&Math.random()>=i)return;let u=(async()=>{try{let a=await o(),d=JSON.stringify({api_key:ss,event:rs,properties:{...us(n),feature:e,action:t,sdk_generation:"v2",telemetry_schema_version:2,sdk_package:"mcp-use",sdk_version:typeof __MCP_USE_PACKAGE_VERSION__>"u"?"development":__MCP_USE_PACKAGE_VERSION__,server_id:a.id,runtime_id:rt,identity_stability:a.stability,distinct_id:a.id,sample_rate:s===void 0?i:1,$process_person_profile:!1,$geoip_disable:!0,...s!==void 0&&{is_validation:!0,validation_run_id:s}}});await fetch(os,{method:"POST",headers:{"content-type":"application/json"},keepalive:!0,body:d})}catch{return}})();nt.add(u),u.then(()=>nt.delete(u))}function Me(e,t,n={},r={}){cs(e,t,n,r,()=>ds(r.serverRoot))}var xe=Symbol("mcp-use/registerViews");function In(e,t){if(!e.startsWith("/"))throw new Error(`View manifest asset path must be origin-absolute (start with "/"); got ${JSON.stringify(e)}`);return`${t}${e}`}function ls(e,t){return`${G(e,`_mcp-use/views/${t}`)}/`}function it(e,t,n,r){return e.startsWith("http://")||e.startsWith("https://")||e.startsWith("data:")?e:e.startsWith("/")?In(e,t):`${t}${ls(n,r)}${e.replace(/^\/+/,"")}`}function ps(e,t){return`${e}${G(t,"_mcp-use/public")}/`}function fs(e){return e.replaceAll(/<\/script/gi,"<\\/script").replaceAll("<!--","\\x3C!--")}function ms(e){return e.replaceAll(/<\/style/gi,"<\\/style")}function at(e){return e.replaceAll("&","&amp;").replaceAll('"',"&quot;").replaceAll("<","&lt;").replaceAll(">","&gt;")}var Un=`<style>
9
+ html,body,#root{background:transparent}
10
+ html,body{margin:0}
11
+ #root[data-mcp-use-loading]{display:flex;min-height:100vh;align-items:center;justify-content:center;flex-direction:column;gap:10px}
12
+ #root[data-mcp-use-loading]::before{width:24px;height:24px;box-sizing:border-box;border:2px solid rgba(127,127,127,.28);border-top-color:rgba(127,127,127,.9);border-radius:50%;content:"";animation:mcp-use-view-spin .7s linear infinite}
13
+ #root[data-mcp-use-loading]::after{color:rgba(127,127,127,.9);content:"Compiling...";font:500 13px/1.2 ui-sans-serif,system-ui,sans-serif}
14
+ @keyframes mcp-use-view-spin{to{transform:rotate(360deg)}}
15
+ @media (prefers-reduced-motion:reduce){#root[data-mcp-use-loading]::before{animation-duration:1.4s}}
16
+ </style>`;function ut(e,t,n,r){let o={publicBase:ps(t,n)},s=`<script>globalThis.__mcpUseViewConfig=${JSON.stringify(o)};</script>`;if(e.kind==="inline"){let d=e.css.length>0?`<style>${ms(e.css)}</style>`:"",c=`<script type="module">${fs(e.js)}</script>`;return`<!doctype html>
9
17
  <html>
10
18
  <head>
11
19
  <meta charset="utf-8">
@@ -14,7 +22,7 @@ ${Un}
14
22
  ${d}
15
23
  </head>
16
24
  <body>
17
- <div id="root"></div>
25
+ <div id="root" data-mcp-use-loading></div>
18
26
  ${c}
19
27
  </body>
20
28
  </html>`}if(r===void 0)throw new Error("viewName is required when synthesizing an external view document.");let i=e.css.map(d=>`<link rel="stylesheet" href="${at(it(d,t,n,r))}">`).join(`
@@ -28,8 +36,8 @@ ${Un}
28
36
  ${i}
29
37
  </head>
30
38
  <body>
31
- <div id="root"></div>
39
+ <div id="root" data-mcp-use-loading></div>
32
40
  ${u}
33
41
  <script type="module" src="${at(a)}"></script>
34
42
  </body>
35
- </html>`}var hs={connectDomains:"CSP_CONNECT_DOMAINS",resourceDomains:"CSP_RESOURCE_DOMAINS",frameDomains:"CSP_FRAME_DOMAINS",baseUriDomains:"CSP_BASE_URI_DOMAINS"};function Ln(e){return e===void 0||e.trim()===""?[]:e.split(",").map(t=>t.trim()).filter(t=>t.length>0)}function jn(e){if(typeof process>"u")return;let t=process.env[e];if(!(t===void 0||t.trim()===""))return Ln(t)}function gs(){return jn("CSP_URLS")??[]}function Oe(e){let t=jn(hs[e]);return t!==void 0?t:gs()}function Ae(...e){let t=new Set,n=[];for(let r of e)for(let o of r)t.has(o)||(t.add(o),n.push(o));return n}function ys(e){return e.startsWith("https://")?`wss://${e.slice(8)}`:e.startsWith("http://")?`ws://${e.slice(7)}`:e}function dt(e,t){let n=e?.csp,r=[];t.serverOrigin!==""&&(r.push(t.serverOrigin),t.hmrWs===!0&&r.push(ys(t.serverOrigin)));let o=[],s=t.explicitAssetsBase?t.assetsOrigin:t.serverOrigin;s!==""&&o.push(s);let i=Ae(n?.connectDomains??[],Oe("connectDomains"),r),u=Ae(n?.resourceDomains??[],Oe("resourceDomains"),o),a=Ae(n?.frameDomains??[],Oe("frameDomains")),d=Ae(n?.baseUriDomains??[],Oe("baseUriDomains"));return{...n,connectDomains:i,resourceDomains:u,frameDomains:a,baseUriDomains:d}}var ws=".mcp-use/build/views/public",vs="public",Rs=".mcp-use/build/views";function ct(e,t,n){if(t.size===0)return;let r=G(e,"_mcp-use/views"),o=n?.projectRoot??process.cwd();return async s=>{if(s.method!=="GET"&&s.method!=="HEAD")return new Response("Method Not Allowed",{status:405});if(!He(s,r))return new Response("Not Found",{status:404});let u=ae(s).slice(r.length+1),a=u.indexOf("/");if(a<=0||a===u.length-1)return new Response("Not Found",{status:404});let d=u.slice(0,a),c=u.slice(a+1),l=t.get(d);if(l===void 0||l.kind!=="external")return new Response("Not Found",{status:404});let[{join:p},{resolvePublicFilePath:g,servePublicFile:f}]=await Promise.all([import("path"),import("./public-route-GWDSKOSN.js")]),h=p(o,Rs,d),R=await g(h,c);return R===null?new Response("Not Found",{status:404}):await f(R,{...n?.deferCors===!0&&{deferCors:!0},...s.method==="HEAD"&&{head:!0}})}}function lt(e,t,n){if(t.size===0&&n?.enabled!==!0)return;let r=G(e,"_mcp-use/public"),o=n?.dev===!0?vs:ws,s=n?.projectRoot??process.cwd();return async i=>{if(i.method!=="GET"&&i.method!=="HEAD")return new Response("Method Not Allowed",{status:405});if(!He(i,r))return new Response("Not Found",{status:404});let a=ae(i).slice(r.length+1),d;try{d=decodeURIComponent(a)}catch{return new Response("Not Found",{status:404})}if(d.length===0)return new Response("Not Found",{status:404});let[{join:c},{resolvePublicFilePath:l,servePublicFile:p}]=await Promise.all([import("path"),import("./public-route-GWDSKOSN.js")]),g=c(s,o),f=await l(g,d);return f===null?new Response("Not Found",{status:404}):await p(f,{...n?.deferCors===!0&&{deferCors:!0},...i.method==="HEAD"&&{head:!0}})}}function pt(e,t,n){if(e===void 0&&t===void 0&&n===void 0)return;let r={...n},o=n?.["ui"],s=typeof o=="object"&&o!==null&&!Array.isArray(o),i=s?{...o}:{};if(e!==void 0){let u=Y(e);i.resourceUri=u,r[de]=u}else delete i.resourceUri,delete r[de];return t!==void 0?i.visibility=[t]:delete i.visibility,(e!==void 0||t!==void 0||s)&&(r["ui"]=i),r}function ft(e){let t=Y(e);return{ui:{resourceUri:t},[de]:t}}function Ts(e){let t=e?.request,n=e?.serverOrigin??(t!==void 0?ke(t):""),r=e?.assetsBase??(t!==void 0?$(t):n);return{serverOrigin:n,assetsOrigin:_e(r),explicitAssetsBase:Ue(),...e?.hmrWs===!0?{hmrWs:!0}:{}}}function Ce(e,t){let r={csp:dt(e,Ts(t))};return e?.permissions!==void 0&&(r.permissions=e.permissions),e?.domain!==void 0&&(r.domain=e.domain),e?.prefersBorder!==void 0&&(r.prefersBorder=e.prefersBorder),{ui:r}}function mt(e,t,n,r){return{mimeType:ue,...n?.description!==void 0&&{description:n.description},_meta:Ce(n,r)}}function Q(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:void 0}function ht(e,t){if(typeof e!="string")return t;let n=e.trim();return n.length>0&&n.length<=64&&![...n].some(r=>{let o=r.charCodeAt(0);return o<32||o===127})?n:t}function Dn(e){if(!Bn(e))return;let t=Q(e.params);if(e.method==="initialize"){let s=Q(t?.clientInfo),i=Q(t?.capabilities)??{};return $n(s,i,t?.protocolVersion,"legacy")}let n=Q(t?._meta),r=Q(n?.[As]),o=Q(n?.[Os]);if(!(r===void 0||o===void 0))return $n(r,o,n?.[Cs],"modern")}function $n(e,t,n,r){let o=t;return{client_name:ht(e?.name,"other"),client_version:ht(e?.version,"unknown"),protocol_era:r,protocol_version:ht(n,"unknown"),connection_mode:r==="modern"?"stateless_request":"legacy_session",sampling_capability:Object.hasOwn(t,"sampling"),elicitation_capability:Object.hasOwn(t,"elicitation"),roots_capability:Object.hasOwn(t,"roots"),extensions_capability:Object.hasOwn(t,"extensions"),views_capability:ce(o),capability_count:Object.keys(t).length}}function Vn(e){if(typeof e!="object"||e===null||Array.isArray(e)||!("$schema"in e))return e;let t={...e};return delete t.$schema,t}function Ps(e){return e.map(t=>({...t,inputSchema:Vn(t.inputSchema),...t.outputSchema===void 0?{}:{outputSchema:Vn(t.outputSchema)}}))}function Ss(e,t){e.use("*",async(n,r)=>{let o=await t(n.req.raw,async()=>(await r(),n.res));return n.res=o,o})}var ge=class e{#e;#t;#n=new Map;#r=new Map;#l=new Map;#i=new Map;#o=new Map;#a=new Map;#g=!1;#p=!1;#u=process.cwd();#E;#_;#f;#M;#y;#b;#x=!1;#U=!1;#I=!1;#w=[];#m=[];#L=crypto.randomUUID();#v=new Set;#h=new Set;#O=new Set;#A=new Set;#j=0;#P=0;#N=0;#H=0;#q=0;#D=0;#$=[];#S=new Set;#V=!1;app;get;post;put;patch;delete;all;fetch;static fromOpenAPI(t){let n=new e({name:t.name??t.spec.info.title,version:t.version??t.spec.info.version??"1.0.0"});gn(n,t);for(let r of n.#n.keys())n.#v.add(r);return n}constructor(t){if(Pt(t),this.#e=t,this.#t=Ot(t),this.app=new qn,this.app.use("*",async(n,r)=>{T(n.req.raw).honoContext=n,await r()}),this.get=this.app.get.bind(this.app),this.post=this.app.post.bind(this.app),this.put=this.app.put.bind(this.app),this.patch=this.app.patch.bind(this.app),this.delete=this.app.delete.bind(this.app),this.all=this.app.all.bind(this.app),this.fetch=async(n,r,o)=>(this.#c("handler"),this.#_.fetch(n,r,o)),t.oauth!==void 0){let n=typeof process>"u"?void 0:process.env.MCP_URL,r=wn({provider:t.oauth,basePath:this.#d(),...n!==void 0&&{mcpUrl:n}});this.#b=r,this.#x=r!==void 0,this.#U=r===void 0}}get basePath(){return this.#d()}get host(){return this.#e.host}get port(){return this.#e.port}get branding(){return this.#t}getHandler(){return this.fetch}tool(t,n){return this.#s("tool",t.name),this.#G(t),this.#v.delete(t.name),this.#h.delete(t.name),this.#n.set(t.name,{definition:t,callback:n}),Object.freeze({name:t.name})}[xe](t,n){if(this.#g)throw new Error("Cannot prime views: the views registry is already primed on this server instance.");this.#s("views","manifest"),this.#p=n?.dev===!0,n?.projectRoot!==void 0&&(this.#u=n.projectRoot);for(let[r,o]of Object.entries(t))this.#o.set(r,o);this.#g=!0}__primeViews(t,n){this[xe](t,n)}resource(t,n){this.#s("resource",t.name);let r=this.#r.get(t.name);return r!==void 0&&this.#O.delete(r.definition.uri),this.#r.set(t.name,{definition:t,callback:n}),this}resourceTemplate(t,n){this.#s("resourceTemplate",t.name);let r=t.complete===void 0?void 0:pn(t.complete);return this.#l.set(t.name,{definition:t,...r!==void 0&&{complete:r},callback:n}),this}prompt(t,n){return this.#s("prompt",t.name),this.#A.delete(t.name),this.#i.set(t.name,{definition:t,callback:n}),this}async proxy(t){this.#k("proxy()");let n=(async()=>{let{isProxyConnection:r,mountProxyConnection:o,mountProxyServers:s}=await import("./mcp-proxy-O6GLK2IL.js");if(r(t)){this.#P+=1,await o(this.#B(),t);return}this.#P+=Object.keys(t).length,await s(this.#B(),t)})();this.#S.add(n);try{await n}finally{this.#S.delete(n)}}use(t,...n){if(typeof t=="string"&&t.startsWith("mcp:")){this.#s("middleware",t);let o=n[0];return this.#w.push(Zt(t,o)),this}return this.app.use.call(this.app,t,...n),this.#j+=typeof t=="function"?1:n.length,this}on(t,n){return this.#s("event listener",t),this.#m.push(Qt(t,n)),this}__setEventBus(t){this.#s("event bus","shared"),this.#M=t}__mount(){this.#c("handler")}async notifyToolsChanged(){await this.#c("handler").handler.notify.toolsChanged()}async notifyPromptsChanged(){await this.#c("handler").handler.notify.promptsChanged()}async notifyResourcesChanged(){await this.#c("handler").handler.notify.resourcesChanged()}async notifyResourceUpdated(t){await this.#c("handler").handler.notify.resourceUpdated(t)}async listen(t=void 0,n={}){this.#k("listen()");let r=St(n.host,this.#e.host),o=kt(t,this.#e.port);return this.#z(r),new Promise((s,i)=>{let u,a,d=new Promise((f,h)=>{u=f,a=h});d.catch(()=>{});let c=!1,l=f=>{c||(c=!0,i(f)),a?.(f),new Promise(h=>g.close(()=>h())).catch(()=>{}).finally(()=>{this.#y===g&&(this.#y=void 0)})},p=Ht({fetch:async f=>(await d)(f)}),g=Es((f,h)=>{p(f,h)});g.once("error",l),g.listen(o,r,()=>{try{let f=g.address(),h=typeof f=="object"&&f!==null?f.port:o,{fetch:R}=this.#c("listen",h,r);u?.(R),c||(c=!0,s({port:h,url:`http://localhost:${h}${this.#d()}`}))}catch(f){l(f)}}),this.#y=g})}async close(){this.#V=!0,await Promise.allSettled([...this.#S]);let t=[],n=this.#$.splice(0),r=await Promise.allSettled(n.map(s=>s.close()));for(let s of r)s.status==="rejected"&&t.push(s.reason);try{await this.#f?.close()}catch(s){t.push(s)}let o=this.#y;if(o!==void 0)try{await new Promise((s,i)=>{o.close(u=>u?i(u):s())}),this.#y=void 0}catch(s){t.push(s)}if(t.length>0)throw new AggregateError(t,"Failed to close MCP server cleanly")}#k(t){if(this.#V)throw t!==void 0?new Error(`Cannot call ${t} after the server has closed.`):new Error("Cannot use the server after it has closed.")}#d(){return this.#e.basePath??"/mcp"}#W(t,n,r){if(this.#e.oauth===void 0)return;if(this.#x)return this.#b;let o=r??this.#e.host??"127.0.0.1",s=t==="listen"&&n!==void 0&&["127.0.0.1","localhost","::1"].includes(o);if(this.#U&&s)return this.#b=vn(`http://localhost:${n}`,this.#d()),this.#x=!0,this.#b;throw new Error("OAuth requires an explicit resource or MCP_URL when using server.fetch or listening on a non-local host")}#z(t){if(this.#e.oauth!==void 0&&!["127.0.0.1","localhost","::1"].includes(t)&&!this.#x)throw new Error("OAuth listen() on a public or wildcard host requires an explicit provider resource or valid MCP_URL.")}#s(t,n){if(this.#f!==void 0)throw new Error(`Cannot register ${t} "${n}" after the server has started: registrations are replayed per request from the registry, so register everything before listen()/server.fetch.`)}#J(){be("server","configured",{tools_total:this.#n.size,tools_local:this.#n.size-this.#v.size-this.#h.size,tools_openapi:this.#v.size,tools_proxied:this.#h.size,resources:this.#r.size,resource_templates:this.#l.size,prompts:this.#i.size,views:this.#o.size,proxy_servers_configured:this.#P,proxy_servers_connected:this.#N,proxy_tools_discovered:this.#H,proxy_resources_discovered:this.#q,proxy_prompts_discovered:this.#D,proxy_tools_mounted:this.#h.size,proxy_resources_mounted:this.#O.size,proxy_prompts_mounted:this.#A.size,http_middleware:this.#j,mcp_middleware:this.#w.length,observers_before:this.#m.filter(({phase:t})=>t==="before").length,observers_complete:this.#m.filter(({phase:t})=>t==="complete").length,oauth_configured:this.#e.oauth!==void 0,cors_configured:this.#e.cors!==void 0,request_state_configured:this.#e.requestState!==void 0,legacy_policy:this.#e.legacy??"stateless"},{onceKey:`${this.#L}:server`,serverRoot:this.#u})}#K(t){let n=Dn(t);n!==void 0&&be("client","observed",{...n},{onceKey:`${this.#L}:client:${JSON.stringify(n)}`,serverRoot:this.#u})}#B(){return{isStarted:()=>this.#f!==void 0,hasTool:t=>this.#n.has(t),hasResource:t=>this.#r.has(t),hasPrompt:t=>this.#i.has(t),registerTool:(t,n)=>{this.#s("tool",t.name),this.#h.add(t.name),this.#n.set(t.name,{definition:t,callback:n})},registerResource:(t,n)=>{this.#s("resource",t.name),this.#O.add(t.uri),this.#r.set(t.name,{definition:t,callback:n})},registerPrompt:(t,n)=>{this.#s("prompt",t.name),this.#A.add(t.name),this.#i.set(t.name,{definition:t,callback:n})},trackOwner:t=>{this.#$.push(t)},trackNamespace:({tools:t,resources:n,prompts:r})=>{this.#N+=1,this.#H+=t,this.#q+=n,this.#D+=r}}}#F(t,n){let{allowedHosts:r,allowedOrigins:o}=this.#e,s=n??this.#e.host??"127.0.0.1",i=["127.0.0.1","localhost","::1"].includes(s),u=r!==void 0?[...new Set([...Nn(),...r])]:t==="listen"&&i?Nn():void 0,a=o!==void 0?[...new Set([...Ms(),...o])]:void 0;return{hosts:u,origins:a}}#c(t,n,r){if(this.#k(),this.#E===void 0||this.#f===void 0){let{hosts:o,origins:s}=this.#F(t,r),i=this.#d(),u=i==="/"?"":i,a=new qn,d=[$t(),dn(this.#e.logging)],c=this.#e.cors;c!==void 0&&d.unshift(Kt(c));let l=Gt(c);o!==void 0&&d.unshift(Vt(o)),s!==void 0&&d.push(Bt(s)),o===void 0&&t==="listen"&&console.warn(`[mcp-use] listen() is serving on ${r} without Host validation. Behind a platform edge that only routes your own domains this is expected; if this process is reachable directly, set allowedHosts to restrict it.`),this.#Y();let p=this.#W(t,n,r);if(p!==void 0){let v=this.#e.oauth;d.push(tt(v,p))}for(let v of d)Ss(a,v);let{handler:g,fetch:f}=cn(v=>this.#X(v),{path:i,...(this.#e.legacy!==void 0||this.#M!==void 0)&&{handler:{...this.#e.legacy!==void 0&&{legacy:this.#e.legacy},...this.#M!==void 0&&{bus:this.#M}}},...p!==void 0&&{authInfo:v=>bn(v)}}),h=async(v,k)=>k();if(p!==void 0){let v=this.#e.oauth,k=Me(v),Se=An({verifier:Ze(v,p),resourceMetadataUrl:On(p),...k.requiredScopes!==void 0&&{requiredScopes:k.requiredScopes}});h=async(D,ie)=>{let K=await Se(D);if(K instanceof Response)return K;let sr=T(D);return sr.authInfo=K,ie()},a.use("*",async(D,ie)=>{if(new URL(D.req.url).pathname!==i){await ie();return}if(this.#e.publicLandingPage===!0&&qe(D.req.raw)){await ie();return}let K=await h(D.req.raw,async()=>(await ie(),D.res));return D.res=K,K})}let R=v=>{let k=T(v).parsedBody;return Bn(k)&&(this.#J(),this.#K(k)),f(v)},H=async v=>qe(v)?(async()=>{let{createLandingPageResponse:Se}=await import("./landing-handler-2IDA43KU.js");return Se(v,i,this.#e,this.#t,this.#n.values(),this.#i.values(),this.#r.values())})():R(v),F=this.#g?this.#p:process.env.NODE_ENV!=="production",O=Et(this.#t,{dev:F,projectRoot:this.#u,deferCors:l});O!==void 0&&this.app.all("/favicon.ico",v=>O(v.req.raw));let q=lt(i,this.#o,{dev:this.#g?this.#p:F,projectRoot:this.#u,enabled:Ct(this.#t),deferCors:l});if(q!==void 0&&this.app.on(["GET","HEAD"],`${u}/_mcp-use/public/*`,v=>q(v.req.raw)),!this.#p){let v=ct(i,this.#o,{projectRoot:this.#u,deferCors:l});v!==void 0&&this.app.on(["GET","HEAD"],`${u}/_mcp-use/views/*`,k=>v(k.req.raw))}this.app.all(i,v=>H(v.req.raw)),a.route("/",this.app),this.#_=a,this.#E=async v=>a.fetch(v),this.#f=g,this.#I=o!==void 0}else if(t==="listen"&&!this.#I&&this.#F("listen",r).hosts!==void 0)throw new Error("Cannot listen() on a localhost bind after server.fetch mounted the app without Host validation (server.fetch expects a platform edge in front). Call listen() first, or set allowedHosts.");return{fetch:this.#E,handler:this.#f}}#G(t){let n=t.view;if(n===void 0)return;if(t.outputSchema===void 0)throw new Error(`Tool "${t.name}" declares view "${n.name}" but has no outputSchema. View-bound tools require an outputSchema \u2014 the view reads structuredContent typed from it. Use outputSchema: z.object({}) for a view that takes no structured output.`);let r=this.#a.get(n.name);if(r!==void 0)throw new Error(`View "${n.name}" is already bound to tool "${r.toolName}"; tool "${t.name}" cannot bind the same view. Each view may be bound to one tool.`);this.#a.set(n.name,{toolName:t.name,config:n})}#Y(){if(this.#a.size>0&&!this.#g){let t=[...this.#n.values()].find(r=>r.definition.view!==void 0),n=t?.definition.view?.name??"unknown";throw new Error(`Tool "${t?.definition.name??"unknown"}" is bound to view "${n}" but no views were primed. Run \`mcp-use build\` and deploy the built entry, or in dev let the CLI prime views automatically.`)}for(let t of this.#n.values()){let n=t.definition.view?.name;if(n!==void 0&&!this.#o.has(n))throw new Error(`Tool "${t.definition.name}" is bound to view "${n}" which is not in the primed views registry. Run \`mcp-use build\` and deploy the built entry, or in dev let the CLI prime views automatically.`)}for(let t of this.#o.keys())this.#a.has(t)||console.warn(`[mcp-use] View "${t}" is registered but no tool binds it.`)}#X(t){let{name:n,version:r,title:o,description:s,instructions:i}=this.#e,u=t.authInfo,a=new bs({name:n,version:r,...o!==void 0&&{title:o},...s!==void 0&&{description:s},...this.#t.websiteUrl!==void 0&&{websiteUrl:this.#t.websiteUrl},...this.#t.icons!==void 0&&{icons:At(this.#t.icons,t.requestInfo,this.#d())}},{capabilities:{logging:{},tools:{listChanged:!0},prompts:{listChanged:!0},resources:{listChanged:!0,subscribe:!0}},...i!==void 0&&{instructions:i},...u!==void 0&&{authInfo:u},...this.#e.requestState!==void 0&&{requestState:this.#e.requestState}}),d=t.requestInfo,c=d!==void 0?{request:d,hmrWs:this.#p}:{hmrWs:this.#p},l=this.#d();for(let p of this.#n.values())this.#ee(a,p);for(let p of this.#r.values())this.#ne(a,p);for(let p of this.#l.values())this.#re(a,p);for(let p of this.#i.values())this.#se(a,p);for(let[p,g]of this.#o.entries())this.#te(a,p,g,c,l);return this.#Q(a),a}#R(t,n,r){let o=we(r);return Object.assign(o,{method:t,params:n,...r.sessionId!==void 0&&{session:{sessionId:r.sessionId}},...r.http?.authInfo!==void 0&&{auth:r.http.authInfo},state:new Map})}#T(t,n,r){let o=t==="tools/call"&&this.#w.length===0&&this.#m.length===0?r:()=>en(this.#w,this.#m,t,n,r);if(_n())return o();let s=performance.now(),i=this.#w.filter(l=>le(l.pattern,t)).length,u=l=>this.#m.filter(p=>p.phase===l&&le(p.pattern,t)).length,a=n.request?.raw,d=a===void 0?void 0:Dn(T(a).parsedBody),c=(l,p)=>{be("operation","completed",{method:t,outcome:l,duration_ms:Math.max(0,Math.round(performance.now()-s)),primitive_origin:this.#Z(t,n.params),matched_middleware:i,observers_before:u("before"),observers_complete:p?u("complete"):0,...d?.protocol_era==="modern"?d:{client_name:"unknown",protocol_era:"legacy"}},{sampleRate:l==="success"?.1:1,serverRoot:this.#u})};return o().then(l=>{let p=Hn(l)?"input_required":t==="tools/call"&&typeof l=="object"&&l!==null&&"isError"in l&&l.isError===!0?"error":"success";return c(p,!0),l},l=>{throw c("error",!1),l})}#Z(t,n){if(t==="tools/call"){let r=String(n.name);return this.#h.has(r)?"proxied":this.#v.has(r)?"openapi":"local"}return t==="resources/read"?this.#O.has(String(n.uri))?"proxied":"local":t==="prompts/get"?this.#A.has(String(n.name))?"proxied":"local":"mixed"}#Q(t){let n=t.server._requestHandlers;if(n===void 0)return;let r=(o,s,i)=>{let u=n.get(o);if(u===void 0||u.__mcpListWrapped)return;let a=async(d,c)=>{let l=c,p=d.params??{},g=this.#R(o,p,l),f,h=async()=>{let F=Xt(d,g.params),O=await u(F,c);if(typeof O!="object"||O===null)throw new TypeError(`[mcp-use] ${o} handler returned a non-object result`);f=O;let q=f[s];if(!Array.isArray(q))throw new TypeError(`[mcp-use] ${o} handler result is missing a ${s} array`);return q},R=await this.#T(o,g,h);if(!Array.isArray(R))throw new TypeError(`[mcp-use] ${o} middleware must return a ${s} array`);let H=i?.(R)??R;return{...f,[s]:H}};a.__mcpListWrapped=!0,n.set(o,a)};r("tools/list","tools",Ps),r("resources/list","resources"),r("prompts/list","prompts")}#ee(t,{definition:n,callback:r}){let o=n.view,s=pt(o?.name,n.visibility,n._meta),i={...n.title!==void 0&&{title:n.title},...n.description!==void 0&&{description:n.description},...n.annotations!==void 0&&{annotations:n.annotations},...n.outputSchema!==void 0&&{outputSchema:n.outputSchema},...s!==void 0&&{_meta:s}},u=o!==void 0?ft(o.name):void 0,a=Cn(n),d=async(c,l)=>{let p=this.#R("tools/call",{name:n.name,arguments:c,...l.mcpReq._meta!==void 0&&{_meta:l.mcpReq._meta}},l),g=async()=>{let f=p.params.arguments??{},h=await r(f,this.#C(l));return Hn(h)||u===void 0||h.isError===!0?h:{...h,_meta:{...h._meta,...u}}};return await this.#T("tools/call",p,g)};a!==void 0?t.registerTool(n.name,{...i,inputSchema:a},async(c,l)=>d(c,l)):t.registerTool(n.name,i,async c=>d({},c))}#te(t,n,r,o,s){let i=Y(n),u=this.#oe(this.#a.get(n)?.config),a=mt(n,r,u,o);t.registerResource(n,i,a,async(d,c)=>{let l=c.http?.req,p=l!==void 0?{request:l,...o.hmrWs===!0?{hmrWs:!0}:{}}:o.hmrWs===!0?{hmrWs:!0}:{},g=l!==void 0?$(l):o.request!==void 0?$(o.request):"",f=ut(r,g,s,n);return{contents:[{uri:d.href,mimeType:a.mimeType,text:f,_meta:Ce(u,p)}]}})}#ne(t,{definition:n,callback:r}){t.registerResource(n.name,n.uri,{...n.title!==void 0&&{title:n.title},...n.description!==void 0&&{description:n.description},...n.mimeType!==void 0&&{mimeType:n.mimeType},...n.annotations!==void 0&&{annotations:n.annotations},...n._meta!==void 0&&{_meta:{...n._meta}}},async(o,s)=>{let i=this.#R("resources/read",{uri:o.href,...s.mcpReq._meta!==void 0&&{_meta:s.mcpReq._meta}},s),u=async()=>Fe(await r(o,this.#C(s)),o.href);return await this.#T("resources/read",i,u)})}#re(t,{definition:n,callback:r,complete:o}){let s=new xs(n.uriTemplate,{list:void 0,...o!==void 0&&{complete:o}});t.registerResource(n.name,s,{...n.title!==void 0&&{title:n.title},...n.description!==void 0&&{description:n.description},...n.mimeType!==void 0&&{mimeType:n.mimeType},...n.annotations!==void 0&&{annotations:n.annotations},...n._meta!==void 0&&{_meta:{...n._meta}}},async(i,u,a)=>{let d=this.#R("resources/read",{uri:i.href,...a.mcpReq._meta!==void 0&&{_meta:a.mcpReq._meta}},a),c=async()=>Fe(await r(i,u,this.#C(a)),i.href);return await this.#T("resources/read",d,c)})}#oe(t){if(t!==void 0)return{...t.description!==void 0&&{description:t.description},...t.csp!==void 0&&{csp:t.csp},...t.permissions!==void 0&&{permissions:t.permissions},...t.domain!==void 0&&{domain:t.domain},...t.prefersBorder!==void 0&&{prefersBorder:t.prefersBorder}}}#se(t,{definition:n,callback:r}){let o={...n.title!==void 0&&{title:n.title},...n.description!==void 0&&{description:n.description}},s=async(i,u)=>{let a=this.#R("prompts/get",{name:n.name,arguments:i,...u.mcpReq._meta!==void 0&&{_meta:u.mcpReq._meta}},u),d=async()=>{let c=a.params.arguments??{};return Jt(await r(c,this.#C(u)))};return await this.#T("prompts/get",a,d)};if(n.schema!==void 0)t.registerPrompt(n.name,{...o,argsSchema:n.schema},async(i,u)=>s(i,u));else{let i=async u=>s({},u);t.registerPrompt(n.name,o,i)}}#C(t){return this.#e.oauth===void 0?we(t):zt(t)}};import{OAuthError as ks}from"@modelcontextprotocol/server";import{createRemoteJWKSet as _s,jwtVerify as Us,errors as j}from"jose";function A(e){let t=e.key??_s(e.jwksUrl),n=Fn(e.resource),r=Ns(e.audience);if(r!==void 0&&e.issuerBoundAccessTokens===!0)throw new TypeError("JWT verifier cannot combine audience and issuer-bound access tokens");return{async verifyAccessToken(o){try{let{payload:s}=await Us(o,t,{issuer:e.issuer,...r!==void 0&&{audience:r},...e.algorithms!==void 0&&{algorithms:[...e.algorithms]},requiredClaims:["exp","sub"]}),i={...s},u=M(i,"client_id")??M(i,"azp"),a=Ls(i,"exp"),d=js(i,n,r!==void 0||e.issuerBoundAccessTokens===!0);return{token:o,clientId:u??"",scopes:b(i.scope),expiresAt:a,extra:{payload:i},resource:d}}catch(s){throw s instanceof ks?s:qs(s)?(process.env.MCP_USE_OAUTH_DEBUG&&$s(o,s),w("JWT verification failed",s)):s}}}}function C(e,t){let n=typeof e=="string"&&!e.includes("://")?`https://${e}`:e,r;try{r=new URL(n)}catch{throw new TypeError(`${t} must be an absolute HTTP(S) URL`)}if(!Wn(r))throw new TypeError(`${t} must use HTTPS, or HTTP for localhost, without credentials, query, or fragment`);return r.pathname=r.pathname.replace(/\/+$/,"")||"/",r}function y(e,t){let n=new URL(e);return n.pathname=`${n.pathname.replace(/\/+$/,"")}/`,new URL(t.replace(/^\/+/,""),n).href}function E(e){let t=e.extra?.payload;if(!L(t))throw w("Verified token payload is missing");return t}function M(e,t){let n=e[t];return typeof n=="string"&&n.trim().length>0?n:void 0}function m(e,t){let n=e[t];return typeof n=="string"?n:void 0}function P(e,t){let n=e[t];return typeof n=="boolean"?n:void 0}function Is(e,t){let n=e[t];return typeof n=="number"&&Number.isFinite(n)?n:void 0}function ye(e,t){let n=e[t];return L(n)?n:void 0}function b(e){return typeof e=="string"?e.split(/\s+/).filter(Boolean):Array.isArray(e)?e.filter(t=>typeof t=="string"&&t.length>0):[]}function Ls(e,t){let n=Is(e,t);if(n===void 0||n<=Date.now()/1e3)throw w(`Missing or expired ${t} claim`);return n}function js(e,t,n){let r=e.resource;if(r!==void 0){if(typeof r!="string")throw w("Token resource claim must be an absolute URL");if(Fn(r).href!==t.href)throw w("Token resource claim does not match protected resource");return t}if(n)return t;let o=e.aud;if(!Hs(o))throw w("Token audience claim must be a string or string array");if(!(typeof o=="string"?[o]:o).includes(t.href))throw w("Token audience does not include the protected resource");return t}function Ns(e){if(e!==void 0){if(typeof e=="string"&&e.trim().length>0)return e;if(Array.isArray(e)&&e.length>0&&e.every(t=>typeof t=="string"&&t.trim().length>0))return[...e];throw new TypeError("JWT verifier audience must be a non-empty string or string array")}}function Hs(e){return typeof e=="string"||Array.isArray(e)&&e.length>0&&e.every(t=>typeof t=="string")}function Fn(e){try{let t=new URL(e);if(!Wn(t))throw new TypeError;return t.pathname=t.pathname==="/"?"/":t.pathname.replace(/\/+$/,""),t}catch{throw w("Token resource claim must be an absolute HTTPS URL, or HTTP URL for localhost")}}function Wn(e){return/^https?:$/.test(e.protocol)&&!e.username&&!e.password&&!e.search&&!e.hash&&(e.protocol!=="http:"||W(e))}function qs(e){return e instanceof j.JWTClaimValidationFailed||e instanceof j.JWTExpired||e instanceof j.JOSEAlgNotAllowed||e instanceof j.JOSENotSupported||e instanceof j.JWSInvalid||e instanceof j.JWTInvalid||e instanceof j.JWSSignatureVerificationFailed||e instanceof j.JWKSNoMatchingKey}var Ds=["iss","aud","azp","sub","exp","iat","nbf","client_id","scope","typ","jti"];function gt(e){return e instanceof Error?e.message:String(e)}function $s(e,t){try{let s=function(a,d){try{return Buffer.from(a,"base64url").toString("utf8")}catch(c){console.error(`[oauth-debug] ${d} decode failed: ${gt(c)}`);return}};var n=s;let r=t instanceof Error?t.constructor.name:typeof t;console.error(`[oauth-debug] JWT verify failed: ${r}: ${gt(t)}`),t instanceof j.JWTClaimValidationFailed&&console.error(`[oauth-debug] claim=${t.claim} reason=${t.reason}`);let o=e.split(".");if(console.error(`[oauth-debug] token segments: ${o.length}`),o.length!==3){let a=e.length>12?`${e.slice(0,12)}\u2026`:e;console.error(`[oauth-debug] non-JWT token preview=${a} length=${e.length}`);return}let i=s(o[0],"header");i!==void 0&&console.error(`[oauth-debug] header=${i}`);let u=s(o[1],"payload");if(u===void 0)return;try{let a=JSON.parse(u),d={};for(let c of Ds)c in a&&(d[c]=a[c]);d.now=Math.floor(Date.now()/1e3),console.error(`[oauth-debug] payload=${JSON.stringify(d)}`)}catch(a){console.error(`[oauth-debug] payload decode failed: ${gt(a)}`)}}catch{}}function zn(e){let t=C(e.domain,"Auth0 domain").href;return x({...e,createTokenVerifier:n=>A({issuer:t,jwksUrl:new URL(y(t,".well-known/jwks.json")),resource:n}),oauthMetadata:{issuer:t,authorization_endpoint:y(t,"authorize"),token_endpoint:y(t,"oauth/token"),registration_endpoint:y(t,"oidc/register"),response_types_supported:["code"],grant_types_supported:["authorization_code","refresh_token"],code_challenge_methods_supported:["S256"]},mapAuthInfo:Vs})}function Vs(e){let t=E(e),n=M(t,"sub");if(n===void 0)throw w("Missing Auth0 subject");return{user:{id:n,...ee("email",m(t,"email")),...ee("name",m(t,"name")),...ee("nickname",m(t,"nickname")),...ee("picture",m(t,"picture")),...ee("emailVerified",P(t,"email_verified")),...ee("updatedAt",m(t,"updated_at")),roles:b(t.roles)},payload:t,permissions:b(t.permissions)}}function ee(e,t){return t===void 0?{}:{[e]:t}}function Jn(e){let t=C(e.authURL,"Better Auth authURL").href.replace(/\/$/,"");return x({...e,createTokenVerifier:n=>A({issuer:t,jwksUrl:new URL(y(t,"jwks")),resource:n}),oauthMetadata:Bs(t,e.scopesSupported),mapAuthInfo:Fs})}function Bs(e,t){return{issuer:e,authorization_endpoint:y(e,"oauth2/authorize"),token_endpoint:y(e,"oauth2/token"),registration_endpoint:y(e,"oauth2/register"),jwks_uri:y(e,"jwks"),response_types_supported:["code"],grant_types_supported:["authorization_code","client_credentials","refresh_token"],code_challenge_methods_supported:["S256"],scopes_supported:t===void 0?["openid","profile","email","offline_access"]:[...t]}}function Fs(e){let t=E(e),n=M(t,"sub");if(n===void 0)throw w("Missing Better Auth subject");return{user:{id:n,...te("email",m(t,"email")),...te("name",m(t,"name")),...te("picture",m(t,"picture")),...te("emailVerified",P(t,"email_verified")),...te("sessionId",m(t,"sid")),...te("isAnonymous",P(t,"is_anonymous")??P(t,"isAnonymous")),roles:b(t.roles)},payload:t,permissions:b(t.permissions)}}function te(e,t){return t===void 0?{}:{[e]:t}}function Kn(e){if(e.audience!==void 0&&(typeof e.audience!="string"||e.audience.trim().length===0))throw new TypeError("Clerk audience must be non-empty");let t=C(e.frontendApiUrl,"Clerk frontendApiUrl").href.replace(/\/$/,"");return x({...e,createTokenVerifier:n=>A({issuer:t,jwksUrl:new URL(y(t,".well-known/jwks.json")),resource:n,...e.audience!==void 0?{audience:e.audience}:{issuerBoundAccessTokens:!0}}),oauthMetadata:zs(t),mapAuthInfo:n=>Ws(n)})}function Ws(e){let t=E(e),n=M(t,"sub");if(n===void 0)throw w("Missing Clerk subject");let r=m(t,"org_role");return{user:{id:n,...V("email",m(t,"email")),...V("name",m(t,"name")),...V("username",m(t,"username")),...V("picture",m(t,"picture")),...V("emailVerified",P(t,"email_verified")),...V("organizationId",m(t,"org_id")),...V("organizationRole",r),...V("organizationSlug",m(t,"org_slug")),roles:r===void 0?[]:[r]},payload:t,permissions:b(t.org_permissions)}}function zs(e){return{issuer:e,authorization_endpoint:y(e,"oauth/authorize"),token_endpoint:y(e,"oauth/token"),registration_endpoint:y(e,"oauth/register"),response_types_supported:["code"],grant_types_supported:["authorization_code","refresh_token"],code_challenge_methods_supported:["S256"]}}function V(e,t){return t===void 0?{}:{[e]:t}}function Gn(e){if(typeof e.realm!="string"||e.realm.trim().length===0||/[/?#]/.test(e.realm))throw new TypeError("Keycloak realm is invalid");let t=C(e.serverUrl,"Keycloak serverUrl"),n=y(t,`realms/${encodeURIComponent(e.realm)}`).replace(/\/$/,"");return x({...e,createTokenVerifier:r=>A({issuer:n,jwksUrl:new URL(y(n,"protocol/openid-connect/certs")),resource:r}),oauthMetadata:{issuer:n,authorization_endpoint:y(n,"protocol/openid-connect/auth"),token_endpoint:y(n,"protocol/openid-connect/token"),registration_endpoint:y(n,"clients-registrations/openid-connect"),response_types_supported:["code"],grant_types_supported:["authorization_code","refresh_token"],code_challenge_methods_supported:["S256"]},mapAuthInfo:Js})}function Js(e){let t=E(e),n=M(t,"sub");if(n===void 0)throw w("Missing Keycloak subject");let r=ye(t,"realm_access"),o=ye(t,"resource_access");return{user:{id:n,...ne("email",m(t,"email")),...ne("name",m(t,"name")),...ne("preferredUsername",m(t,"preferred_username")),...ne("givenName",m(t,"given_name")),...ne("familyName",m(t,"family_name")),...ne("emailVerified",P(t,"email_verified")),roles:r===void 0?[]:b(r.roles),...r!==void 0&&{realmAccess:r},...o!==void 0&&{resourceAccess:o}},payload:t,permissions:Ks(o)}}function ne(e,t){return t===void 0?{}:{[e]:t}}function Ks(e){return e===void 0?[]:Object.entries(e).flatMap(([t,n])=>L(n)?b(n.roles).map(r=>`${t}:${r}`):[])}function Yn(e){let t=Ys(e),n=y(t,"auth/v1").replace(/\/$/,""),r=e.jwtSecret,o=e.audience??"authenticated";if(typeof o!="string"||o.trim().length===0)throw new TypeError("Supabase audience must be non-empty");if(r!==void 0&&new TextEncoder().encode(r).length<32)throw new TypeError("Supabase jwtSecret must be at least 32 bytes");return x({...e,createTokenVerifier:s=>A({issuer:n,jwksUrl:new URL(y(t,"auth/v1/.well-known/jwks.json")),...r!==void 0?{key:new TextEncoder().encode(r),algorithms:["HS256"]}:{algorithms:["ES256"]},resource:s,audience:o}),oauthMetadata:{issuer:n,authorization_endpoint:y(t,"auth/v1/oauth/authorize"),token_endpoint:y(t,"auth/v1/oauth/token"),registration_endpoint:y(t,"auth/v1/oauth/clients/register"),response_types_supported:["code"],grant_types_supported:["authorization_code","refresh_token"],code_challenge_methods_supported:["S256"]},mapAuthInfo:Gs})}function Gs(e){let t=E(e),n=M(t,"sub")??M(t,"user_id");if(n===void 0)throw w("Missing Supabase subject");let r=ye(t,"user_metadata")??{},o=m(t,"aal");return{user:{id:n,...B("email",m(t,"email")),...B("name",m(r,"name")),...B("fullName",m(r,"full_name")),...B("username",m(r,"username")),...B("avatarUrl",m(r,"avatar_url")),...B("role",m(t,"role")),...B("aal",o),amr:Xs(t.amr),...B("sessionId",m(t,"session_id"))},payload:t,permissions:o===void 0?[]:[`aal:${o}`]}}function B(e,t){return t===void 0?{}:{[e]:t}}function Ys(e){if(e.supabaseUrl!==void 0)return C(e.supabaseUrl,"supabaseUrl");if(e.projectId===void 0||!/^[a-z0-9-]+$/i.test(e.projectId))throw new TypeError("Supabase requires projectId or supabaseUrl");return new URL(`https://${e.projectId}.supabase.co`)}function Xs(e){return Array.isArray(e)?e.flatMap(t=>{if(!L(t))return[];let n=t.method,r=t.timestamp;return typeof n!="string"||n.length===0?[]:r!==void 0&&(typeof r!="number"||!Number.isFinite(r))?[]:[r===void 0?{method:n}:{method:n,timestamp:r}]}):[]}function Xn(e){let t=Qs(e.subdomain);return x({...e,createTokenVerifier:n=>A({issuer:t,jwksUrl:new URL(y(t,"oauth2/jwks")),resource:n}),oauthMetadata:{issuer:t,authorization_endpoint:y(t,"oauth2/authorize"),token_endpoint:y(t,"oauth2/token"),registration_endpoint:y(t,"oauth2/register"),response_types_supported:["code"],grant_types_supported:["authorization_code","refresh_token"],code_challenge_methods_supported:["S256"]},mapAuthInfo:Zs})}function Zs(e){let t=E(e),n=M(t,"sub");if(n===void 0)throw w("Missing WorkOS subject");return{user:{id:n,...N("email",m(t,"email")),...N("emailVerified",P(t,"email_verified")),...N("name",m(t,"name")),...N("preferredUsername",m(t,"preferred_username")),...N("firstName",m(t,"first_name")),...N("lastName",m(t,"last_name")),...N("picture",m(t,"picture")),roles:b(t.roles),...N("organizationId",m(t,"org_id")),...N("sessionId",m(t,"sid"))},payload:t,permissions:b(t.permissions)}}function N(e,t){return t===void 0?{}:{[e]:t}}function Qs(e){if(typeof e!="string"||e.trim().length===0)throw new TypeError("WorkOS subdomain is required");let t=C(e,"WorkOS subdomain");if(t.pathname!=="/")throw new TypeError("WorkOS subdomain must be a hostname or HTTPS origin");return t.href.replace(/\/$/,"")}function S(e){let t=process.env[e];return t===void 0||t.trim()===""?void 0:t}function re(e){if(typeof e=="object"&&e!==null&&e.verifyJwt===!1)throw new Error("[MCP_USE_V1_COMPAT] verifyJwt: false is not supported by the temporary v1 compatibility entry; v2 always verifies bearer tokens.")}function oe(e,t){return{...(t??e.resource)!==void 0&&{resource:t??e.resource},...e.requiredScopes!==void 0&&{requiredScopes:e.requiredScopes},...e.scopesSupported!==void 0&&{scopesSupported:e.scopesSupported},...e.resourceName!==void 0&&{resourceName:e.resourceName},...e.serviceDocumentationUrl!==void 0&&{serviceDocumentationUrl:e.serviceDocumentationUrl}}}function ei(e={}){re(e);let t=e.projectId??S("MCP_USE_OAUTH_SUPABASE_PROJECT_ID"),n=e.supabaseUrl??S("MCP_USE_OAUTH_SUPABASE_URL"),r=e.jwtSecret??S("MCP_USE_OAUTH_SUPABASE_JWT_SECRET");return Yn({...oe(e),...t!==void 0&&{projectId:t},...n!==void 0&&{supabaseUrl:n},...r!==void 0&&{jwtSecret:r}})}function ti(e={}){re(e);let t=e.domain??S("MCP_USE_OAUTH_AUTH0_DOMAIN"),n=e.audience??S("MCP_USE_OAUTH_AUTH0_AUDIENCE");if(t===void 0)throw new Error("Auth0 domain is required.");return zn({...oe(e,e.resource??n),domain:t})}function ni(e={}){re(e);let t=e.serverUrl??S("MCP_USE_OAUTH_KEYCLOAK_SERVER_URL"),n=e.realm??S("MCP_USE_OAUTH_KEYCLOAK_REALM"),r=e.audience??S("MCP_USE_OAUTH_KEYCLOAK_AUDIENCE");if(t===void 0||n===void 0)throw new Error("Keycloak serverUrl and realm are required.");return Gn({...oe(e,e.resource??r),serverUrl:t,realm:n})}function ri(e={}){re(e);let t=e.subdomain??S("MCP_USE_OAUTH_WORKOS_SUBDOMAIN");if(t===void 0)throw new Error("WorkOS subdomain is required.");return Xn({...oe(e),subdomain:t})}function oi(e={}){re(e);let t=e.frontendApiUrl??S("MCP_USE_OAUTH_CLERK_FRONTEND_API_URL");if(t===void 0)throw new Error("Clerk frontendApiUrl is required.");return Kn({...oe(e,e.resource??e.audience),frontendApiUrl:t})}function si(e={}){re(e);let t=e.authURL??S("MCP_USE_OAUTH_BETTER_AUTH_URL");if(t===void 0)throw new Error("Better Auth authURL is required.");return Jn({...oe(e),authURL:t})}var Zn='Deprecated temporary v1 compatibility. Use the native v2 API from "mcp-use". This entry will be removed in mcp-use v3.',yt="MCP_USE_V1_COMPAT",Qn="__mcpUseV1CompatServer",er=!1,wt=class{#e;#t=new Map;#n=new Map;#r=new Set;config;app;fetch;get;post;put;patch;delete;all;use;on;serverHost;serverPort;serverBaseUrl;constructor(t){mi(),pi(t),this.config=t,this.serverHost=t.host??"localhost",t.baseUrl!==void 0&&(this.serverBaseUrl=t.baseUrl),this.#e=new ge(ui(t)),this.app=this.#e.app,this.fetch=this.#e.fetch,this.get=this.#e.get,this.post=this.#e.post,this.put=this.#e.put,this.patch=this.#e.patch,this.delete=this.#e.delete,this.all=this.#e.all,this.use=this.#e.use.bind(this.#e),this.on=this.#e.on.bind(this.#e);let n=globalThis;if(process.env.MCP_USE_CLI_IMPORT==="1"&&n[Qn]!==void 0)throw se("multiple compatibility servers in one CLI entry","default-export one native v2 server or construct only one v1 server");n[Qn]=this}static fromOpenAPI(t){return ge.fromOpenAPI(t)}get basePath(){return this.#e.basePath}get host(){return this.#e.host}get port(){return this.#e.port}get branding(){return this.#e.branding}tool(t,n){if(t.inputs!==void 0)throw se("tool inputs[] schemas","use a Zod schema field");let r=t.cb;if(r!==void 0&&n!==void 0)throw new TypeError(`Tool "${t.name}" provides both cb and a separate callback.`);let o=n??r;if(o===void 0)throw new TypeError(`Tool "${t.name}" requires a callback.`);if(t.widget!==void 0){let s=t.widget.name;if(this.#t.has(s)||this.#r.has(s))throw se(`binding legacy widget "${s}" to multiple tools`,"use one tool per view or migrate the bindings to native v2");return this.#r.add(s),this.#t.set(s,{definition:t,callback:o}),this}return this.#l(t,o),this}resource(t,n){let r=n??t.readCallback;if(n!==void 0&&t.readCallback!==void 0)throw new TypeError(`Resource "${t.name}" provides both readCallback and a separate callback.`);if(r===void 0)throw new TypeError(`Resource "${t.name}" requires a callback.`);let{readCallback:o,callbacks:s,...i}=t;return this.#e.resource(i,async(u,a)=>r(Ee(a))),this}resourceTemplate(t,n){let r=n??t.readCallback;if(n!==void 0&&t.readCallback!==void 0)throw new TypeError(`Resource template "${t.name}" provides both readCallback and a separate callback.`);if(r===void 0)throw new TypeError(`Resource template "${t.name}" requires a callback.`);let o=t.resourceTemplate,s=t.uriTemplate??o?.uriTemplate;if(s===void 0)throw new TypeError(`Resource template "${t.name}" requires uriTemplate.`);let i=t.callbacks?.complete??o?.callbacks?.complete,u=t.description??o?.description,a=t.mimeType??o?.mimeType,d={name:t.name,uriTemplate:s,...t.title!==void 0&&{title:t.title},...u!==void 0&&{description:u},...a!==void 0&&{mimeType:a},...t.annotations!==void 0&&{annotations:t.annotations},...t._meta!==void 0&&{_meta:t._meta},...i!==void 0&&{complete:i}};return this.#e.resourceTemplate(d,async(c,l,p)=>r(c,l,Ee(p))),this}prompt(t,n){if(t.args!==void 0)throw se("prompt args[] schemas","use a Zod schema field");let r=t.cb;if(r!==void 0&&n!==void 0)throw new TypeError(`Prompt "${t.name}" provides both cb and a separate callback.`);let o=n??r;if(o===void 0)throw new TypeError(`Prompt "${t.name}" requires a callback.`);let{cb:s,args:i,...u}=t;return this.#e.prompt(u,async(a,d)=>o(a,Ee(d))),this}async listen(t,n){if(process.env.MCP_USE_CLI_IMPORT==="1")return;this.#o();let r=await this.#e.listen(t,n);return this.serverPort=r.port,r}async close(){await this.#e.close()}getHandler(){return this.fetch}async proxy(...t){await this.#e.proxy(...t)}async notifyResourceUpdated(t){await this.#e.notifyResourceUpdated(t)}__registerLegacyViews(t){for(let[n,r]of Object.entries(t)){let o=r.widgetMetadata??{};this.#n.set(n,o),this.#i(n),o.exposeAsTool===!0&&!this.#r.has(n)&&this.#a(n,o)}}__primeViews(t,n){this.#o(),this.#e.__primeViews(t,n)}__mount(){this.#o(),this.#e.__mount()}__setEventBus(t){this.#e.__setEventBus(t)}#l(t,n,r,o){let{cb:s,widget:i,inputs:u,...a}=t,d=r===void 0?void 0:rr(r,o),c=a.outputSchema??(r===void 0?void 0:tr(o)??nr),l=or(i,o),p={...a,...c!==void 0&&{outputSchema:c},...d!==void 0&&{view:d},...(a._meta!==void 0||l!==void 0)&&{_meta:{...a._meta,...l}}};this.#e.tool(p,async(g,f)=>n(g,Ee(f)))}#i(t){let n=this.#t.get(t);n!==void 0&&(this.#t.delete(t),this.#l(n.definition,n.callback,t,this.#n.get(t)))}#o(){for(let t of[...this.#t.keys()])this.#i(t)}#a(t,n){this.#r.add(t);let r=tr(n)??nr,o={name:t,...n.title!==void 0&&{title:n.title},description:n.description??n.metadata?.description??`Display ${t}`,inputSchema:r,outputSchema:r,...n.annotations!==void 0&&{annotations:n.annotations},_meta:{...n._meta,...or(void 0,n)},view:rr(t,n)};this.#e.tool(o,async s=>{let i=typeof n.toolOutput=="function"?await n.toolOutput(s):n.toolOutput;return{content:i?.content??[{type:"text",text:`${n.title??t} ready`}],structuredContent:s,...i?.isError===!0&&{isError:!0},...i?._meta!==void 0&&{_meta:i._meta}}})}};function td(e,t={}){return new wt({name:e,version:t.version??"1.0.0",...t})}function nd(e){return{...Ie(e),structuredContent:{data:e}}}function rd(e){let t=Tt(e);return{...t,structuredContent:t.structuredContent??e.props??e.data??{}}}function Pe(e){let t=e.auth;if(t!==void 0)return t;let n=e.get?.("auth");if(n!==void 0)return n;let r=e.req?.raw,o=r===void 0?void 0:T(r).authInfo;if(o!==void 0)return di(o);throw new Error("Authentication context is missing.")}function ii(e,t){let n=Pe(e);return(Array.isArray(t)?t:[t]).every(o=>n.scopes.includes(o)||n.permissions.includes(o))}function ai(e,t){let n=Pe(e);return t.some(r=>n.scopes.includes(r)||n.permissions.includes(r))}function od(e){return async(t,n)=>{if(ii(t,e))return n();let r=Pe(t),o=Array.isArray(e)?e:[e];return t.json({error:"insufficient_scope",required:o,granted_scopes:r.scopes,granted_permissions:r.permissions},403)}}function sd(e){return async(t,n)=>{if(ai(t,e))return n();let r=Pe(t);return t.json({error:"insufficient_scope",required_any:e,granted_scopes:r.scopes,granted_permissions:r.permissions},403)}}function ui(e){let t=e.baseUrl===void 0?void 0:new URL(e.baseUrl),n=t!==void 0&&t.pathname!=="/"?t.pathname.replace(/\/$/,""):void 0,r=e.oauth===void 0?void 0:{...e.oauth,...e.oauth.resource===void 0&&t!==void 0?{resource:new URL(n??"/mcp",t.origin)}:{}};return{name:e.name,version:e.version,...e.title!==void 0&&{title:e.title},...e.description!==void 0&&{description:e.description},...e.instructions!==void 0&&{instructions:e.instructions},...e.host!==void 0&&{host:e.host},...e.port!==void 0&&{port:e.port},...n!==void 0&&{basePath:n},...e.allowedOrigins!==void 0&&{allowedHosts:e.allowedOrigins.map(li)},cors:ci(e.cors),...r!==void 0&&{oauth:r},...e.publicLandingPage!==void 0&&{publicLandingPage:e.publicLandingPage},...e.favicon!==void 0&&{favicon:e.favicon},...e.icons!==void 0&&{icons:e.icons},...e.websiteUrl!==void 0&&{websiteUrl:e.websiteUrl}}}function di(e){let t=e.extra;if(t===void 0||typeof t!="object"||t===null||!("user"in t)||typeof t.user!="object"||t.user===null||Array.isArray(t.user)||!("payload"in t)||typeof t.payload!="object"||t.payload===null||Array.isArray(t.payload)||!("permissions"in t)||!Array.isArray(t.permissions)||!t.permissions.every(o=>typeof o=="string"))throw new Error("Authentication context is missing mapped OAuth data.");let n=t.user,r=n.userId??n.id;return{user:{...n,...typeof r=="string"&&{userId:r},permissions:[...t.permissions],scopes:[...e.scopes]},payload:t.payload,accessToken:e.token,scopes:[...e.scopes],permissions:[...t.permissions]}}function ci(e){return e===void 0?{origin:"*"}:{...e.origin!==void 0&&{origin:e.origin},...e.allowMethods!==void 0&&{methods:e.allowMethods},...e.allowHeaders!==void 0&&{allowedHeaders:e.allowHeaders},...e.credentials!==void 0&&{credentials:e.credentials}}}function li(e){try{return new URL(e).hostname}catch{return e.split(":")[0]??e}}function pi(e){if(e.stateless===!1)throw se("stateless: false","v2 is stateless");for(let[t,n]of[["sessionIdleTimeoutMs",e.sessionIdleTimeoutMs],["autoCreateSessionOnInvalidId",e.autoCreateSessionOnInvalidId],["sessionStore",e.sessionStore],["streamManager",e.streamManager]])if(n!==void 0)throw se(t,"migrate to stateless v2")}function Ee(e){let t=e,n=e.client;n.supportsApps??=()=>n.supportsViews(),t.log=e.sendLog.bind(e);let r=t.auth;if(r!==void 0&&typeof r=="object"&&r!==null){let o=r,s=o.user,i=s.userId??s.id;o.user={...s,...typeof i=="string"&&{userId:i},...s.organizationId!==void 0&&{organization_id:s.organizationId,org_id:s.organizationId},...s.organizationRole!==void 0&&{org_role:s.organizationRole},...s.organizationSlug!==void 0&&{org_slug:s.organizationSlug},permissions:[...o.permissions],scopes:[...o.scopes]}}return t}function tr(e){let t=e?.props??e?.schema??e?.inputs;return fi(t)?t:void 0}function fi(e){return typeof e=="object"&&e!==null&&"~standard"in e&&typeof e["~standard"]?.validate=="function"}var nr={"~standard":{version:1,vendor:"mcp-use-v1-compat",validate(e){return typeof e!="object"||e===null||Array.isArray(e)?{issues:[{message:"expected an object"}]}:{value:e}},jsonSchema:{input:()=>({type:"object",additionalProperties:!0}),output:()=>({type:"object",additionalProperties:!0})}}};function rr(e,t){let n=t?.metadata,r=t?.appsSdkMetadata,o=r?.["openai/widgetCSP"],s=n?.csp??(o===void 0?void 0:{...o.connect_domains!==void 0&&{connectDomains:o.connect_domains},...o.resource_domains!==void 0&&{resourceDomains:o.resource_domains},...o.frame_domains!==void 0&&{frameDomains:o.frame_domains}}),i=n?.description??t?.description??r?.["openai/widgetDescription"],u=n?.prefersBorder??r?.["openai/widgetPrefersBorder"],a=n?.domain??r?.["openai/widgetDomain"];return{name:e,...i!==void 0&&{description:i},...s!==void 0&&{csp:s},...u!==void 0&&{prefersBorder:u},...a!==void 0&&{domain:a}}}function or(e,t){let n=e?.invoking??t?.metadata?.invoking,r=e?.invoked??t?.metadata?.invoked,o=e?.widgetAccessible,s=e?.resultCanProduceWidget;if(!(n===void 0&&r===void 0&&o===void 0&&s===void 0))return{...n!==void 0&&{"openai/toolInvocation/invoking":n},...r!==void 0&&{"openai/toolInvocation/invoked":r},...o!==void 0&&{"openai/widgetAccessible":o},...s!==void 0&&{"openai/resultCanProduceWidget":s}}}function mi(){er||(er=!0,typeof process.emitWarning=="function"?process.emitWarning(Zn,{type:"DeprecationWarning",code:yt}):console.warn(`[${yt}] ${Zn}`))}function se(e,t){return new Error(`[${yt}] ${e} is not supported by the temporary v1 compatibility entry; ${t}.`)}export{wt as MCPServer,nd as array,fr as audio,mr as binary,Ao as completable,td as createMCPServer,cr as css,gr as error,Pe as getAuth,ai as hasAnyScope,ii as hasScope,ur as html,pr as image,lr as javascript,ar as markdown,wr as mix,ti as oauthAuth0Provider,si as oauthBetterAuthProvider,oi as oauthClerkProvider,ni as oauthKeycloakProvider,ei as oauthSupabaseProvider,ri as oauthWorkOSProvider,yr as object,sd as requireAnyScope,od as requireScope,hr as resource,ir as text,rd as widget,dr as xml};
43
+ </html>`}var hs={connectDomains:"CSP_CONNECT_DOMAINS",resourceDomains:"CSP_RESOURCE_DOMAINS",frameDomains:"CSP_FRAME_DOMAINS",baseUriDomains:"CSP_BASE_URI_DOMAINS"};function Ln(e){return e===void 0||e.trim()===""?[]:e.split(",").map(t=>t.trim()).filter(t=>t.length>0)}function jn(e){if(typeof process>"u")return;let t=process.env[e];if(!(t===void 0||t.trim()===""))return Ln(t)}function gs(){return jn("CSP_URLS")??[]}function Oe(e){let t=jn(hs[e]);return t!==void 0?t:gs()}function Ae(...e){let t=new Set,n=[];for(let r of e)for(let o of r)t.has(o)||(t.add(o),n.push(o));return n}function ys(e){return e.startsWith("https://")?`wss://${e.slice(8)}`:e.startsWith("http://")?`ws://${e.slice(7)}`:e}function dt(e,t){let n=e?.csp,r=[];t.serverOrigin!==""&&(r.push(t.serverOrigin),t.hmrWs===!0&&r.push(ys(t.serverOrigin)));let o=[],s=t.explicitAssetsBase?t.assetsOrigin:t.serverOrigin;s!==""&&o.push(s);let i=Ae(n?.connectDomains??[],Oe("connectDomains"),r),u=Ae(n?.resourceDomains??[],Oe("resourceDomains"),o),a=Ae(n?.frameDomains??[],Oe("frameDomains")),d=Ae(n?.baseUriDomains??[],Oe("baseUriDomains"));return{...n,connectDomains:i,resourceDomains:u,frameDomains:a,baseUriDomains:d}}var ws=".mcp-use/build/views/public",vs="public",Rs=".mcp-use/build/views";function ct(e,t,n){if(t.size===0)return;let r=G(e,"_mcp-use/views"),o=n?.projectRoot??process.cwd();return async s=>{if(s.method!=="GET"&&s.method!=="HEAD")return new Response("Method Not Allowed",{status:405});if(!He(s,r))return new Response("Not Found",{status:404});let u=ae(s).slice(r.length+1),a=u.indexOf("/");if(a<=0||a===u.length-1)return new Response("Not Found",{status:404});let d=u.slice(0,a),c=u.slice(a+1),l=t.get(d);if(l===void 0||l.kind!=="external")return new Response("Not Found",{status:404});let[{join:p},{resolvePublicFilePath:g,servePublicFile:f}]=await Promise.all([import("path"),import("./public-route-GWDSKOSN.js")]),h=p(o,Rs,d),R=await g(h,c);return R===null?new Response("Not Found",{status:404}):await f(R,{...n?.deferCors===!0&&{deferCors:!0},...s.method==="HEAD"&&{head:!0}})}}function lt(e,t,n){if(t.size===0&&n?.enabled!==!0)return;let r=G(e,"_mcp-use/public"),o=n?.dev===!0?vs:ws,s=n?.projectRoot??process.cwd();return async i=>{if(i.method!=="GET"&&i.method!=="HEAD")return new Response("Method Not Allowed",{status:405});if(!He(i,r))return new Response("Not Found",{status:404});let a=ae(i).slice(r.length+1),d;try{d=decodeURIComponent(a)}catch{return new Response("Not Found",{status:404})}if(d.length===0)return new Response("Not Found",{status:404});let[{join:c},{resolvePublicFilePath:l,servePublicFile:p}]=await Promise.all([import("path"),import("./public-route-GWDSKOSN.js")]),g=c(s,o),f=await l(g,d);return f===null?new Response("Not Found",{status:404}):await p(f,{...n?.deferCors===!0&&{deferCors:!0},...i.method==="HEAD"&&{head:!0}})}}function pt(e,t,n){if(e===void 0&&t===void 0&&n===void 0)return;let r={...n},o=n?.["ui"],s=typeof o=="object"&&o!==null&&!Array.isArray(o),i=s?{...o}:{};if(e!==void 0){let u=Y(e);i.resourceUri=u,r[de]=u}else delete i.resourceUri,delete r[de];return t!==void 0?i.visibility=[t]:delete i.visibility,(e!==void 0||t!==void 0||s)&&(r["ui"]=i),r}function ft(e){let t=Y(e);return{ui:{resourceUri:t},[de]:t}}function Ts(e){let t=e?.request,n=e?.serverOrigin??(t!==void 0?ke(t):""),r=e?.assetsBase??(t!==void 0?$(t):n);return{serverOrigin:n,assetsOrigin:_e(r),explicitAssetsBase:Ue(),...e?.hmrWs===!0?{hmrWs:!0}:{}}}function Ce(e,t){let r={csp:dt(e,Ts(t))};return e?.permissions!==void 0&&(r.permissions=e.permissions),e?.domain!==void 0&&(r.domain=e.domain),e?.prefersBorder!==void 0&&(r.prefersBorder=e.prefersBorder),{ui:r}}function mt(e,t,n,r){return{mimeType:ue,...n?.description!==void 0&&{description:n.description},_meta:Ce(n,r)}}function Q(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:void 0}function ht(e,t){if(typeof e!="string")return t;let n=e.trim();return n.length>0&&n.length<=64&&![...n].some(r=>{let o=r.charCodeAt(0);return o<32||o===127})?n:t}function Dn(e){if(!Bn(e))return;let t=Q(e.params);if(e.method==="initialize"){let s=Q(t?.clientInfo),i=Q(t?.capabilities)??{};return $n(s,i,t?.protocolVersion,"legacy")}let n=Q(t?._meta),r=Q(n?.[As]),o=Q(n?.[Os]);if(!(r===void 0||o===void 0))return $n(r,o,n?.[Cs],"modern")}function $n(e,t,n,r){let o=t;return{client_name:ht(e?.name,"other"),client_version:ht(e?.version,"unknown"),protocol_era:r,protocol_version:ht(n,"unknown"),connection_mode:r==="modern"?"stateless_request":"legacy_session",sampling_capability:Object.hasOwn(t,"sampling"),elicitation_capability:Object.hasOwn(t,"elicitation"),roots_capability:Object.hasOwn(t,"roots"),extensions_capability:Object.hasOwn(t,"extensions"),views_capability:ce(o),capability_count:Object.keys(t).length}}function Vn(e){if(typeof e!="object"||e===null||Array.isArray(e)||!("$schema"in e))return e;let t={...e};return delete t.$schema,t}function Ps(e){return e.map(t=>({...t,inputSchema:Vn(t.inputSchema),...t.outputSchema===void 0?{}:{outputSchema:Vn(t.outputSchema)}}))}function Ss(e,t){e.use("*",async(n,r)=>{let o=await t(n.req.raw,async()=>(await r(),n.res));return n.res=o,o})}var ge=class e{#e;#t;#n=new Map;#r=new Map;#l=new Map;#i=new Map;#o=new Map;#a=new Map;#g=!1;#p=!1;#u=process.cwd();#E;#_;#f;#b;#y;#M;#x=!1;#U=!1;#I=!1;#w=[];#m=[];#L=crypto.randomUUID();#v=new Set;#h=new Set;#O=new Set;#A=new Set;#j=0;#P=0;#N=0;#H=0;#q=0;#D=0;#$=[];#S=new Set;#V=!1;app;get;post;put;patch;delete;all;fetch;static fromOpenAPI(t){let n=new e({name:t.name??t.spec.info.title,version:t.version??t.spec.info.version??"1.0.0"});gn(n,t);for(let r of n.#n.keys())n.#v.add(r);return n}constructor(t){if(Pt(t),this.#e=t,this.#t=Ot(t),this.app=new qn,this.app.use("*",async(n,r)=>{T(n.req.raw).honoContext=n,await r()}),this.get=this.app.get.bind(this.app),this.post=this.app.post.bind(this.app),this.put=this.app.put.bind(this.app),this.patch=this.app.patch.bind(this.app),this.delete=this.app.delete.bind(this.app),this.all=this.app.all.bind(this.app),this.fetch=async(n,r,o)=>(this.#c("handler"),this.#_.fetch(n,r,o)),t.oauth!==void 0){let n=typeof process>"u"?void 0:process.env.MCP_URL,r=wn({provider:t.oauth,basePath:this.#d(),...n!==void 0&&{mcpUrl:n}});this.#M=r,this.#x=r!==void 0,this.#U=r===void 0}}get basePath(){return this.#d()}get host(){return this.#e.host}get port(){return this.#e.port}get branding(){return this.#t}getHandler(){return this.fetch}tool(t,n){return this.#s("tool",t.name),this.#G(t),this.#v.delete(t.name),this.#h.delete(t.name),this.#n.set(t.name,{definition:t,callback:n}),Object.freeze({name:t.name})}[xe](t,n){if(this.#g)throw new Error("Cannot prime views: the views registry is already primed on this server instance.");this.#s("views","manifest"),this.#p=n?.dev===!0,n?.projectRoot!==void 0&&(this.#u=n.projectRoot);for(let[r,o]of Object.entries(t))this.#o.set(r,o);this.#g=!0}__primeViews(t,n){this[xe](t,n)}resource(t,n){this.#s("resource",t.name);let r=this.#r.get(t.name);return r!==void 0&&this.#O.delete(r.definition.uri),this.#r.set(t.name,{definition:t,callback:n}),this}resourceTemplate(t,n){this.#s("resourceTemplate",t.name);let r=t.complete===void 0?void 0:pn(t.complete);return this.#l.set(t.name,{definition:t,...r!==void 0&&{complete:r},callback:n}),this}prompt(t,n){return this.#s("prompt",t.name),this.#A.delete(t.name),this.#i.set(t.name,{definition:t,callback:n}),this}async proxy(t){this.#k("proxy()");let n=(async()=>{let{isProxyConnection:r,mountProxyConnection:o,mountProxyServers:s}=await import("./mcp-proxy-O6GLK2IL.js");if(r(t)){this.#P+=1,await o(this.#B(),t);return}this.#P+=Object.keys(t).length,await s(this.#B(),t)})();this.#S.add(n);try{await n}finally{this.#S.delete(n)}}use(t,...n){if(typeof t=="string"&&t.startsWith("mcp:")){this.#s("middleware",t);let o=n[0];return this.#w.push(Zt(t,o)),this}return this.app.use.call(this.app,t,...n),this.#j+=typeof t=="function"?1:n.length,this}on(t,n){return this.#s("event listener",t),this.#m.push(Qt(t,n)),this}__setEventBus(t){this.#s("event bus","shared"),this.#b=t}__mount(){this.#c("handler")}async notifyToolsChanged(){await this.#c("handler").handler.notify.toolsChanged()}async notifyPromptsChanged(){await this.#c("handler").handler.notify.promptsChanged()}async notifyResourcesChanged(){await this.#c("handler").handler.notify.resourcesChanged()}async notifyResourceUpdated(t){await this.#c("handler").handler.notify.resourceUpdated(t)}async listen(t=void 0,n={}){this.#k("listen()");let r=St(n.host,this.#e.host),o=kt(t,this.#e.port);return this.#z(r),new Promise((s,i)=>{let u,a,d=new Promise((f,h)=>{u=f,a=h});d.catch(()=>{});let c=!1,l=f=>{c||(c=!0,i(f)),a?.(f),new Promise(h=>g.close(()=>h())).catch(()=>{}).finally(()=>{this.#y===g&&(this.#y=void 0)})},p=Ht({fetch:async f=>(await d)(f)}),g=Es((f,h)=>{p(f,h)});g.once("error",l),g.listen(o,r,()=>{try{let f=g.address(),h=typeof f=="object"&&f!==null?f.port:o,{fetch:R}=this.#c("listen",h,r);u?.(R),c||(c=!0,s({port:h,url:`http://localhost:${h}${this.#d()}`}))}catch(f){l(f)}}),this.#y=g})}async close(){this.#V=!0,await Promise.allSettled([...this.#S]);let t=[],n=this.#$.splice(0),r=await Promise.allSettled(n.map(s=>s.close()));for(let s of r)s.status==="rejected"&&t.push(s.reason);try{await this.#f?.close()}catch(s){t.push(s)}let o=this.#y;if(o!==void 0)try{await new Promise((s,i)=>{o.close(u=>u?i(u):s())}),this.#y=void 0}catch(s){t.push(s)}if(t.length>0)throw new AggregateError(t,"Failed to close MCP server cleanly")}#k(t){if(this.#V)throw t!==void 0?new Error(`Cannot call ${t} after the server has closed.`):new Error("Cannot use the server after it has closed.")}#d(){return this.#e.basePath??"/mcp"}#W(t,n,r){if(this.#e.oauth===void 0)return;if(this.#x)return this.#M;let o=r??this.#e.host??"127.0.0.1",s=t==="listen"&&n!==void 0&&["127.0.0.1","localhost","::1"].includes(o);if(this.#U&&s)return this.#M=vn(`http://localhost:${n}`,this.#d()),this.#x=!0,this.#M;throw new Error("OAuth requires an explicit resource or MCP_URL when using server.fetch or listening on a non-local host")}#z(t){if(this.#e.oauth!==void 0&&!["127.0.0.1","localhost","::1"].includes(t)&&!this.#x)throw new Error("OAuth listen() on a public or wildcard host requires an explicit provider resource or valid MCP_URL.")}#s(t,n){if(this.#f!==void 0)throw new Error(`Cannot register ${t} "${n}" after the server has started: registrations are replayed per request from the registry, so register everything before listen()/server.fetch.`)}#J(){Me("server","configured",{tools_total:this.#n.size,tools_local:this.#n.size-this.#v.size-this.#h.size,tools_openapi:this.#v.size,tools_proxied:this.#h.size,resources:this.#r.size,resource_templates:this.#l.size,prompts:this.#i.size,views:this.#o.size,proxy_servers_configured:this.#P,proxy_servers_connected:this.#N,proxy_tools_discovered:this.#H,proxy_resources_discovered:this.#q,proxy_prompts_discovered:this.#D,proxy_tools_mounted:this.#h.size,proxy_resources_mounted:this.#O.size,proxy_prompts_mounted:this.#A.size,http_middleware:this.#j,mcp_middleware:this.#w.length,observers_before:this.#m.filter(({phase:t})=>t==="before").length,observers_complete:this.#m.filter(({phase:t})=>t==="complete").length,oauth_configured:this.#e.oauth!==void 0,cors_configured:this.#e.cors!==void 0,request_state_configured:this.#e.requestState!==void 0,legacy_policy:this.#e.legacy??"stateless"},{onceKey:`${this.#L}:server`,serverRoot:this.#u})}#K(t){let n=Dn(t);n!==void 0&&Me("client","observed",{...n},{onceKey:`${this.#L}:client:${JSON.stringify(n)}`,serverRoot:this.#u})}#B(){return{isStarted:()=>this.#f!==void 0,hasTool:t=>this.#n.has(t),hasResource:t=>this.#r.has(t),hasPrompt:t=>this.#i.has(t),registerTool:(t,n)=>{this.#s("tool",t.name),this.#h.add(t.name),this.#n.set(t.name,{definition:t,callback:n})},registerResource:(t,n)=>{this.#s("resource",t.name),this.#O.add(t.uri),this.#r.set(t.name,{definition:t,callback:n})},registerPrompt:(t,n)=>{this.#s("prompt",t.name),this.#A.add(t.name),this.#i.set(t.name,{definition:t,callback:n})},trackOwner:t=>{this.#$.push(t)},trackNamespace:({tools:t,resources:n,prompts:r})=>{this.#N+=1,this.#H+=t,this.#q+=n,this.#D+=r}}}#F(t,n){let{allowedHosts:r,allowedOrigins:o}=this.#e,s=n??this.#e.host??"127.0.0.1",i=["127.0.0.1","localhost","::1"].includes(s),u=r!==void 0?[...new Set([...Nn(),...r])]:t==="listen"&&i?Nn():void 0,a=o!==void 0?[...new Set([...bs(),...o])]:void 0;return{hosts:u,origins:a}}#c(t,n,r){if(this.#k(),this.#E===void 0||this.#f===void 0){let{hosts:o,origins:s}=this.#F(t,r),i=this.#d(),u=i==="/"?"":i,a=new qn,d=[$t(),dn(this.#e.logging)],c=this.#e.cors;c!==void 0&&d.unshift(Kt(c));let l=Gt(c);o!==void 0&&d.unshift(Vt(o)),s!==void 0&&d.push(Bt(s)),o===void 0&&t==="listen"&&console.warn(`[mcp-use] listen() is serving on ${r} without Host validation. Behind a platform edge that only routes your own domains this is expected; if this process is reachable directly, set allowedHosts to restrict it.`),this.#Y();let p=this.#W(t,n,r);if(p!==void 0){let v=this.#e.oauth;d.push(tt(v,p))}for(let v of d)Ss(a,v);let{handler:g,fetch:f}=cn(v=>this.#X(v),{path:i,...(this.#e.legacy!==void 0||this.#b!==void 0)&&{handler:{...this.#e.legacy!==void 0&&{legacy:this.#e.legacy},...this.#b!==void 0&&{bus:this.#b}}},...p!==void 0&&{authInfo:v=>Mn(v)}}),h=async(v,k)=>k();if(p!==void 0){let v=this.#e.oauth,k=be(v),Se=An({verifier:Ze(v,p),resourceMetadataUrl:On(p),...k.requiredScopes!==void 0&&{requiredScopes:k.requiredScopes}});h=async(D,ie)=>{let K=await Se(D);if(K instanceof Response)return K;let sr=T(D);return sr.authInfo=K,ie()},a.use("*",async(D,ie)=>{if(new URL(D.req.url).pathname!==i){await ie();return}if(this.#e.publicLandingPage===!0&&qe(D.req.raw)){await ie();return}let K=await h(D.req.raw,async()=>(await ie(),D.res));return D.res=K,K})}let R=v=>{let k=T(v).parsedBody;return Bn(k)&&(this.#J(),this.#K(k)),f(v)},H=async v=>qe(v)?(async()=>{let{createLandingPageResponse:Se}=await import("./landing-handler-2IDA43KU.js");return Se(v,i,this.#e,this.#t,this.#n.values(),this.#i.values(),this.#r.values())})():R(v),F=this.#g?this.#p:process.env.NODE_ENV!=="production",O=Et(this.#t,{dev:F,projectRoot:this.#u,deferCors:l});O!==void 0&&this.app.all("/favicon.ico",v=>O(v.req.raw));let q=lt(i,this.#o,{dev:this.#g?this.#p:F,projectRoot:this.#u,enabled:Ct(this.#t),deferCors:l});if(q!==void 0&&this.app.on(["GET","HEAD"],`${u}/_mcp-use/public/*`,v=>q(v.req.raw)),!this.#p){let v=ct(i,this.#o,{projectRoot:this.#u,deferCors:l});v!==void 0&&this.app.on(["GET","HEAD"],`${u}/_mcp-use/views/*`,k=>v(k.req.raw))}this.app.all(i,v=>H(v.req.raw)),a.route("/",this.app),this.#_=a,this.#E=async v=>a.fetch(v),this.#f=g,this.#I=o!==void 0}else if(t==="listen"&&!this.#I&&this.#F("listen",r).hosts!==void 0)throw new Error("Cannot listen() on a localhost bind after server.fetch mounted the app without Host validation (server.fetch expects a platform edge in front). Call listen() first, or set allowedHosts.");return{fetch:this.#E,handler:this.#f}}#G(t){let n=t.view;if(n===void 0)return;if(t.outputSchema===void 0)throw new Error(`Tool "${t.name}" declares view "${n.name}" but has no outputSchema. View-bound tools require an outputSchema \u2014 the view reads structuredContent typed from it. Use outputSchema: z.object({}) for a view that takes no structured output.`);let r=this.#a.get(n.name);if(r!==void 0)throw new Error(`View "${n.name}" is already bound to tool "${r.toolName}"; tool "${t.name}" cannot bind the same view. Each view may be bound to one tool.`);this.#a.set(n.name,{toolName:t.name,config:n})}#Y(){if(this.#a.size>0&&!this.#g){let t=[...this.#n.values()].find(r=>r.definition.view!==void 0),n=t?.definition.view?.name??"unknown";throw new Error(`Tool "${t?.definition.name??"unknown"}" is bound to view "${n}" but no views were primed. Run \`mcp-use build\` and deploy the built entry, or in dev let the CLI prime views automatically.`)}for(let t of this.#n.values()){let n=t.definition.view?.name;if(n!==void 0&&!this.#o.has(n))throw new Error(`Tool "${t.definition.name}" is bound to view "${n}" which is not in the primed views registry. Run \`mcp-use build\` and deploy the built entry, or in dev let the CLI prime views automatically.`)}for(let t of this.#o.keys())this.#a.has(t)||console.warn(`[mcp-use] View "${t}" is registered but no tool binds it.`)}#X(t){let{name:n,version:r,title:o,description:s,instructions:i}=this.#e,u=t.authInfo,a=new Ms({name:n,version:r,...o!==void 0&&{title:o},...s!==void 0&&{description:s},...this.#t.websiteUrl!==void 0&&{websiteUrl:this.#t.websiteUrl},...this.#t.icons!==void 0&&{icons:At(this.#t.icons,t.requestInfo,this.#d())}},{capabilities:{logging:{},tools:{listChanged:!0},prompts:{listChanged:!0},resources:{listChanged:!0,subscribe:!0}},...i!==void 0&&{instructions:i},...u!==void 0&&{authInfo:u},...this.#e.requestState!==void 0&&{requestState:this.#e.requestState}}),d=t.requestInfo,c=d!==void 0?{request:d,hmrWs:this.#p}:{hmrWs:this.#p},l=this.#d();for(let p of this.#n.values())this.#ee(a,p);for(let p of this.#r.values())this.#ne(a,p);for(let p of this.#l.values())this.#re(a,p);for(let p of this.#i.values())this.#se(a,p);for(let[p,g]of this.#o.entries())this.#te(a,p,g,c,l);return this.#Q(a),a}#R(t,n,r){let o=we(r);return Object.assign(o,{method:t,params:n,...r.sessionId!==void 0&&{session:{sessionId:r.sessionId}},...r.http?.authInfo!==void 0&&{auth:r.http.authInfo},state:new Map})}#T(t,n,r){let o=t==="tools/call"&&this.#w.length===0&&this.#m.length===0?r:()=>en(this.#w,this.#m,t,n,r);if(_n())return o();let s=performance.now(),i=this.#w.filter(l=>le(l.pattern,t)).length,u=l=>this.#m.filter(p=>p.phase===l&&le(p.pattern,t)).length,a=n.request?.raw,d=a===void 0?void 0:Dn(T(a).parsedBody),c=(l,p)=>{Me("operation","completed",{method:t,outcome:l,duration_ms:Math.max(0,Math.round(performance.now()-s)),primitive_origin:this.#Z(t,n.params),matched_middleware:i,observers_before:u("before"),observers_complete:p?u("complete"):0,...d?.protocol_era==="modern"?d:{client_name:"unknown",protocol_era:"legacy"}},{sampleRate:l==="success"?.1:1,serverRoot:this.#u})};return o().then(l=>{let p=Hn(l)?"input_required":t==="tools/call"&&typeof l=="object"&&l!==null&&"isError"in l&&l.isError===!0?"error":"success";return c(p,!0),l},l=>{throw c("error",!1),l})}#Z(t,n){if(t==="tools/call"){let r=String(n.name);return this.#h.has(r)?"proxied":this.#v.has(r)?"openapi":"local"}return t==="resources/read"?this.#O.has(String(n.uri))?"proxied":"local":t==="prompts/get"?this.#A.has(String(n.name))?"proxied":"local":"mixed"}#Q(t){let n=t.server._requestHandlers;if(n===void 0)return;let r=(o,s,i)=>{let u=n.get(o);if(u===void 0||u.__mcpListWrapped)return;let a=async(d,c)=>{let l=c,p=d.params??{},g=this.#R(o,p,l),f,h=async()=>{let F=Xt(d,g.params),O=await u(F,c);if(typeof O!="object"||O===null)throw new TypeError(`[mcp-use] ${o} handler returned a non-object result`);f=O;let q=f[s];if(!Array.isArray(q))throw new TypeError(`[mcp-use] ${o} handler result is missing a ${s} array`);return q},R=await this.#T(o,g,h);if(!Array.isArray(R))throw new TypeError(`[mcp-use] ${o} middleware must return a ${s} array`);let H=i?.(R)??R;return{...f,[s]:H}};a.__mcpListWrapped=!0,n.set(o,a)};r("tools/list","tools",Ps),r("resources/list","resources"),r("prompts/list","prompts")}#ee(t,{definition:n,callback:r}){let o=n.view,s=pt(o?.name,n.visibility,n._meta),i={...n.title!==void 0&&{title:n.title},...n.description!==void 0&&{description:n.description},...n.annotations!==void 0&&{annotations:n.annotations},...n.outputSchema!==void 0&&{outputSchema:n.outputSchema},...s!==void 0&&{_meta:s}},u=o!==void 0?ft(o.name):void 0,a=Cn(n),d=async(c,l)=>{let p=this.#R("tools/call",{name:n.name,arguments:c,...l.mcpReq._meta!==void 0&&{_meta:l.mcpReq._meta}},l),g=async()=>{let f=p.params.arguments??{},h=await r(f,this.#C(l));return Hn(h)||u===void 0||h.isError===!0?h:{...h,_meta:{...h._meta,...u}}};return await this.#T("tools/call",p,g)};a!==void 0?t.registerTool(n.name,{...i,inputSchema:a},async(c,l)=>d(c,l)):t.registerTool(n.name,i,async c=>d({},c))}#te(t,n,r,o,s){let i=Y(n),u=this.#oe(this.#a.get(n)?.config),a=mt(n,r,u,o);t.registerResource(n,i,a,async(d,c)=>{let l=c.http?.req,p=l!==void 0?{request:l,...o.hmrWs===!0?{hmrWs:!0}:{}}:o.hmrWs===!0?{hmrWs:!0}:{},g=l!==void 0?$(l):o.request!==void 0?$(o.request):"",f=ut(r,g,s,n);return{contents:[{uri:d.href,mimeType:a.mimeType,text:f,_meta:Ce(u,p)}]}})}#ne(t,{definition:n,callback:r}){t.registerResource(n.name,n.uri,{...n.title!==void 0&&{title:n.title},...n.description!==void 0&&{description:n.description},...n.mimeType!==void 0&&{mimeType:n.mimeType},...n.annotations!==void 0&&{annotations:n.annotations},...n._meta!==void 0&&{_meta:{...n._meta}}},async(o,s)=>{let i=this.#R("resources/read",{uri:o.href,...s.mcpReq._meta!==void 0&&{_meta:s.mcpReq._meta}},s),u=async()=>Fe(await r(o,this.#C(s)),o.href);return await this.#T("resources/read",i,u)})}#re(t,{definition:n,callback:r,complete:o}){let s=new xs(n.uriTemplate,{list:void 0,...o!==void 0&&{complete:o}});t.registerResource(n.name,s,{...n.title!==void 0&&{title:n.title},...n.description!==void 0&&{description:n.description},...n.mimeType!==void 0&&{mimeType:n.mimeType},...n.annotations!==void 0&&{annotations:n.annotations},...n._meta!==void 0&&{_meta:{...n._meta}}},async(i,u,a)=>{let d=this.#R("resources/read",{uri:i.href,...a.mcpReq._meta!==void 0&&{_meta:a.mcpReq._meta}},a),c=async()=>Fe(await r(i,u,this.#C(a)),i.href);return await this.#T("resources/read",d,c)})}#oe(t){if(t!==void 0)return{...t.description!==void 0&&{description:t.description},...t.csp!==void 0&&{csp:t.csp},...t.permissions!==void 0&&{permissions:t.permissions},...t.domain!==void 0&&{domain:t.domain},...t.prefersBorder!==void 0&&{prefersBorder:t.prefersBorder}}}#se(t,{definition:n,callback:r}){let o={...n.title!==void 0&&{title:n.title},...n.description!==void 0&&{description:n.description}},s=async(i,u)=>{let a=this.#R("prompts/get",{name:n.name,arguments:i,...u.mcpReq._meta!==void 0&&{_meta:u.mcpReq._meta}},u),d=async()=>{let c=a.params.arguments??{};return Jt(await r(c,this.#C(u)))};return await this.#T("prompts/get",a,d)};if(n.schema!==void 0)t.registerPrompt(n.name,{...o,argsSchema:n.schema},async(i,u)=>s(i,u));else{let i=async u=>s({},u);t.registerPrompt(n.name,o,i)}}#C(t){return this.#e.oauth===void 0?we(t):zt(t)}};import{OAuthError as ks}from"@modelcontextprotocol/server";import{createRemoteJWKSet as _s,jwtVerify as Us,errors as j}from"jose";function A(e){let t=e.key??_s(e.jwksUrl),n=Fn(e.resource),r=Ns(e.audience);if(r!==void 0&&e.issuerBoundAccessTokens===!0)throw new TypeError("JWT verifier cannot combine audience and issuer-bound access tokens");return{async verifyAccessToken(o){try{let{payload:s}=await Us(o,t,{issuer:e.issuer,...r!==void 0&&{audience:r},...e.algorithms!==void 0&&{algorithms:[...e.algorithms]},requiredClaims:["exp","sub"]}),i={...s},u=b(i,"client_id")??b(i,"azp"),a=Ls(i,"exp"),d=js(i,n,r!==void 0||e.issuerBoundAccessTokens===!0);return{token:o,clientId:u??"",scopes:M(i.scope),expiresAt:a,extra:{payload:i},resource:d}}catch(s){throw s instanceof ks?s:qs(s)?(process.env.MCP_USE_OAUTH_DEBUG&&$s(o,s),w("JWT verification failed",s)):s}}}}function C(e,t){let n=typeof e=="string"&&!e.includes("://")?`https://${e}`:e,r;try{r=new URL(n)}catch{throw new TypeError(`${t} must be an absolute HTTP(S) URL`)}if(!Wn(r))throw new TypeError(`${t} must use HTTPS, or HTTP for localhost, without credentials, query, or fragment`);return r.pathname=r.pathname.replace(/\/+$/,"")||"/",r}function y(e,t){let n=new URL(e);return n.pathname=`${n.pathname.replace(/\/+$/,"")}/`,new URL(t.replace(/^\/+/,""),n).href}function E(e){let t=e.extra?.payload;if(!L(t))throw w("Verified token payload is missing");return t}function b(e,t){let n=e[t];return typeof n=="string"&&n.trim().length>0?n:void 0}function m(e,t){let n=e[t];return typeof n=="string"?n:void 0}function P(e,t){let n=e[t];return typeof n=="boolean"?n:void 0}function Is(e,t){let n=e[t];return typeof n=="number"&&Number.isFinite(n)?n:void 0}function ye(e,t){let n=e[t];return L(n)?n:void 0}function M(e){return typeof e=="string"?e.split(/\s+/).filter(Boolean):Array.isArray(e)?e.filter(t=>typeof t=="string"&&t.length>0):[]}function Ls(e,t){let n=Is(e,t);if(n===void 0||n<=Date.now()/1e3)throw w(`Missing or expired ${t} claim`);return n}function js(e,t,n){let r=e.resource;if(r!==void 0){if(typeof r!="string")throw w("Token resource claim must be an absolute URL");if(Fn(r).href!==t.href)throw w("Token resource claim does not match protected resource");return t}if(n)return t;let o=e.aud;if(!Hs(o))throw w("Token audience claim must be a string or string array");if(!(typeof o=="string"?[o]:o).includes(t.href))throw w("Token audience does not include the protected resource");return t}function Ns(e){if(e!==void 0){if(typeof e=="string"&&e.trim().length>0)return e;if(Array.isArray(e)&&e.length>0&&e.every(t=>typeof t=="string"&&t.trim().length>0))return[...e];throw new TypeError("JWT verifier audience must be a non-empty string or string array")}}function Hs(e){return typeof e=="string"||Array.isArray(e)&&e.length>0&&e.every(t=>typeof t=="string")}function Fn(e){try{let t=new URL(e);if(!Wn(t))throw new TypeError;return t.pathname=t.pathname==="/"?"/":t.pathname.replace(/\/+$/,""),t}catch{throw w("Token resource claim must be an absolute HTTPS URL, or HTTP URL for localhost")}}function Wn(e){return/^https?:$/.test(e.protocol)&&!e.username&&!e.password&&!e.search&&!e.hash&&(e.protocol!=="http:"||W(e))}function qs(e){return e instanceof j.JWTClaimValidationFailed||e instanceof j.JWTExpired||e instanceof j.JOSEAlgNotAllowed||e instanceof j.JOSENotSupported||e instanceof j.JWSInvalid||e instanceof j.JWTInvalid||e instanceof j.JWSSignatureVerificationFailed||e instanceof j.JWKSNoMatchingKey}var Ds=["iss","aud","azp","sub","exp","iat","nbf","client_id","scope","typ","jti"];function gt(e){return e instanceof Error?e.message:String(e)}function $s(e,t){try{let s=function(a,d){try{return Buffer.from(a,"base64url").toString("utf8")}catch(c){console.error(`[oauth-debug] ${d} decode failed: ${gt(c)}`);return}};var n=s;let r=t instanceof Error?t.constructor.name:typeof t;console.error(`[oauth-debug] JWT verify failed: ${r}: ${gt(t)}`),t instanceof j.JWTClaimValidationFailed&&console.error(`[oauth-debug] claim=${t.claim} reason=${t.reason}`);let o=e.split(".");if(console.error(`[oauth-debug] token segments: ${o.length}`),o.length!==3){let a=e.length>12?`${e.slice(0,12)}\u2026`:e;console.error(`[oauth-debug] non-JWT token preview=${a} length=${e.length}`);return}let i=s(o[0],"header");i!==void 0&&console.error(`[oauth-debug] header=${i}`);let u=s(o[1],"payload");if(u===void 0)return;try{let a=JSON.parse(u),d={};for(let c of Ds)c in a&&(d[c]=a[c]);d.now=Math.floor(Date.now()/1e3),console.error(`[oauth-debug] payload=${JSON.stringify(d)}`)}catch(a){console.error(`[oauth-debug] payload decode failed: ${gt(a)}`)}}catch{}}function zn(e){let t=C(e.domain,"Auth0 domain").href;return x({...e,createTokenVerifier:n=>A({issuer:t,jwksUrl:new URL(y(t,".well-known/jwks.json")),resource:n}),oauthMetadata:{issuer:t,authorization_endpoint:y(t,"authorize"),token_endpoint:y(t,"oauth/token"),registration_endpoint:y(t,"oidc/register"),response_types_supported:["code"],grant_types_supported:["authorization_code","refresh_token"],code_challenge_methods_supported:["S256"]},mapAuthInfo:Vs})}function Vs(e){let t=E(e),n=b(t,"sub");if(n===void 0)throw w("Missing Auth0 subject");return{user:{id:n,...ee("email",m(t,"email")),...ee("name",m(t,"name")),...ee("nickname",m(t,"nickname")),...ee("picture",m(t,"picture")),...ee("emailVerified",P(t,"email_verified")),...ee("updatedAt",m(t,"updated_at")),roles:M(t.roles)},payload:t,permissions:M(t.permissions)}}function ee(e,t){return t===void 0?{}:{[e]:t}}function Jn(e){let t=C(e.authURL,"Better Auth authURL").href.replace(/\/$/,"");return x({...e,createTokenVerifier:n=>A({issuer:t,jwksUrl:new URL(y(t,"jwks")),resource:n}),oauthMetadata:Bs(t,e.scopesSupported),mapAuthInfo:Fs})}function Bs(e,t){return{issuer:e,authorization_endpoint:y(e,"oauth2/authorize"),token_endpoint:y(e,"oauth2/token"),registration_endpoint:y(e,"oauth2/register"),jwks_uri:y(e,"jwks"),response_types_supported:["code"],grant_types_supported:["authorization_code","client_credentials","refresh_token"],code_challenge_methods_supported:["S256"],scopes_supported:t===void 0?["openid","profile","email","offline_access"]:[...t]}}function Fs(e){let t=E(e),n=b(t,"sub");if(n===void 0)throw w("Missing Better Auth subject");return{user:{id:n,...te("email",m(t,"email")),...te("name",m(t,"name")),...te("picture",m(t,"picture")),...te("emailVerified",P(t,"email_verified")),...te("sessionId",m(t,"sid")),...te("isAnonymous",P(t,"is_anonymous")??P(t,"isAnonymous")),roles:M(t.roles)},payload:t,permissions:M(t.permissions)}}function te(e,t){return t===void 0?{}:{[e]:t}}function Kn(e){if(e.audience!==void 0&&(typeof e.audience!="string"||e.audience.trim().length===0))throw new TypeError("Clerk audience must be non-empty");let t=C(e.frontendApiUrl,"Clerk frontendApiUrl").href.replace(/\/$/,"");return x({...e,createTokenVerifier:n=>A({issuer:t,jwksUrl:new URL(y(t,".well-known/jwks.json")),resource:n,...e.audience!==void 0?{audience:e.audience}:{issuerBoundAccessTokens:!0}}),oauthMetadata:zs(t),mapAuthInfo:n=>Ws(n)})}function Ws(e){let t=E(e),n=b(t,"sub");if(n===void 0)throw w("Missing Clerk subject");let r=m(t,"org_role");return{user:{id:n,...V("email",m(t,"email")),...V("name",m(t,"name")),...V("username",m(t,"username")),...V("picture",m(t,"picture")),...V("emailVerified",P(t,"email_verified")),...V("organizationId",m(t,"org_id")),...V("organizationRole",r),...V("organizationSlug",m(t,"org_slug")),roles:r===void 0?[]:[r]},payload:t,permissions:M(t.org_permissions)}}function zs(e){return{issuer:e,authorization_endpoint:y(e,"oauth/authorize"),token_endpoint:y(e,"oauth/token"),registration_endpoint:y(e,"oauth/register"),response_types_supported:["code"],grant_types_supported:["authorization_code","refresh_token"],code_challenge_methods_supported:["S256"]}}function V(e,t){return t===void 0?{}:{[e]:t}}function Gn(e){if(typeof e.realm!="string"||e.realm.trim().length===0||/[/?#]/.test(e.realm))throw new TypeError("Keycloak realm is invalid");let t=C(e.serverUrl,"Keycloak serverUrl"),n=y(t,`realms/${encodeURIComponent(e.realm)}`).replace(/\/$/,"");return x({...e,createTokenVerifier:r=>A({issuer:n,jwksUrl:new URL(y(n,"protocol/openid-connect/certs")),resource:r}),oauthMetadata:{issuer:n,authorization_endpoint:y(n,"protocol/openid-connect/auth"),token_endpoint:y(n,"protocol/openid-connect/token"),registration_endpoint:y(n,"clients-registrations/openid-connect"),response_types_supported:["code"],grant_types_supported:["authorization_code","refresh_token"],code_challenge_methods_supported:["S256"]},mapAuthInfo:Js})}function Js(e){let t=E(e),n=b(t,"sub");if(n===void 0)throw w("Missing Keycloak subject");let r=ye(t,"realm_access"),o=ye(t,"resource_access");return{user:{id:n,...ne("email",m(t,"email")),...ne("name",m(t,"name")),...ne("preferredUsername",m(t,"preferred_username")),...ne("givenName",m(t,"given_name")),...ne("familyName",m(t,"family_name")),...ne("emailVerified",P(t,"email_verified")),roles:r===void 0?[]:M(r.roles),...r!==void 0&&{realmAccess:r},...o!==void 0&&{resourceAccess:o}},payload:t,permissions:Ks(o)}}function ne(e,t){return t===void 0?{}:{[e]:t}}function Ks(e){return e===void 0?[]:Object.entries(e).flatMap(([t,n])=>L(n)?M(n.roles).map(r=>`${t}:${r}`):[])}function Yn(e){let t=Ys(e),n=y(t,"auth/v1").replace(/\/$/,""),r=e.jwtSecret,o=e.audience??"authenticated";if(typeof o!="string"||o.trim().length===0)throw new TypeError("Supabase audience must be non-empty");if(r!==void 0&&new TextEncoder().encode(r).length<32)throw new TypeError("Supabase jwtSecret must be at least 32 bytes");return x({...e,createTokenVerifier:s=>A({issuer:n,jwksUrl:new URL(y(t,"auth/v1/.well-known/jwks.json")),...r!==void 0?{key:new TextEncoder().encode(r),algorithms:["HS256"]}:{algorithms:["ES256"]},resource:s,audience:o}),oauthMetadata:{issuer:n,authorization_endpoint:y(t,"auth/v1/oauth/authorize"),token_endpoint:y(t,"auth/v1/oauth/token"),registration_endpoint:y(t,"auth/v1/oauth/clients/register"),response_types_supported:["code"],grant_types_supported:["authorization_code","refresh_token"],code_challenge_methods_supported:["S256"]},mapAuthInfo:Gs})}function Gs(e){let t=E(e),n=b(t,"sub")??b(t,"user_id");if(n===void 0)throw w("Missing Supabase subject");let r=ye(t,"user_metadata")??{},o=m(t,"aal");return{user:{id:n,...B("email",m(t,"email")),...B("name",m(r,"name")),...B("fullName",m(r,"full_name")),...B("username",m(r,"username")),...B("avatarUrl",m(r,"avatar_url")),...B("role",m(t,"role")),...B("aal",o),amr:Xs(t.amr),...B("sessionId",m(t,"session_id"))},payload:t,permissions:o===void 0?[]:[`aal:${o}`]}}function B(e,t){return t===void 0?{}:{[e]:t}}function Ys(e){if(e.supabaseUrl!==void 0)return C(e.supabaseUrl,"supabaseUrl");if(e.projectId===void 0||!/^[a-z0-9-]+$/i.test(e.projectId))throw new TypeError("Supabase requires projectId or supabaseUrl");return new URL(`https://${e.projectId}.supabase.co`)}function Xs(e){return Array.isArray(e)?e.flatMap(t=>{if(!L(t))return[];let n=t.method,r=t.timestamp;return typeof n!="string"||n.length===0?[]:r!==void 0&&(typeof r!="number"||!Number.isFinite(r))?[]:[r===void 0?{method:n}:{method:n,timestamp:r}]}):[]}function Xn(e){let t=Qs(e.subdomain);return x({...e,createTokenVerifier:n=>A({issuer:t,jwksUrl:new URL(y(t,"oauth2/jwks")),resource:n}),oauthMetadata:{issuer:t,authorization_endpoint:y(t,"oauth2/authorize"),token_endpoint:y(t,"oauth2/token"),registration_endpoint:y(t,"oauth2/register"),response_types_supported:["code"],grant_types_supported:["authorization_code","refresh_token"],code_challenge_methods_supported:["S256"]},mapAuthInfo:Zs})}function Zs(e){let t=E(e),n=b(t,"sub");if(n===void 0)throw w("Missing WorkOS subject");return{user:{id:n,...N("email",m(t,"email")),...N("emailVerified",P(t,"email_verified")),...N("name",m(t,"name")),...N("preferredUsername",m(t,"preferred_username")),...N("firstName",m(t,"first_name")),...N("lastName",m(t,"last_name")),...N("picture",m(t,"picture")),roles:M(t.roles),...N("organizationId",m(t,"org_id")),...N("sessionId",m(t,"sid"))},payload:t,permissions:M(t.permissions)}}function N(e,t){return t===void 0?{}:{[e]:t}}function Qs(e){if(typeof e!="string"||e.trim().length===0)throw new TypeError("WorkOS subdomain is required");let t=C(e,"WorkOS subdomain");if(t.pathname!=="/")throw new TypeError("WorkOS subdomain must be a hostname or HTTPS origin");return t.href.replace(/\/$/,"")}function S(e){let t=process.env[e];return t===void 0||t.trim()===""?void 0:t}function re(e){if(typeof e=="object"&&e!==null&&e.verifyJwt===!1)throw new Error("[MCP_USE_V1_COMPAT] verifyJwt: false is not supported by the temporary v1 compatibility entry; v2 always verifies bearer tokens.")}function oe(e,t){return{...(t??e.resource)!==void 0&&{resource:t??e.resource},...e.requiredScopes!==void 0&&{requiredScopes:e.requiredScopes},...e.scopesSupported!==void 0&&{scopesSupported:e.scopesSupported},...e.resourceName!==void 0&&{resourceName:e.resourceName},...e.serviceDocumentationUrl!==void 0&&{serviceDocumentationUrl:e.serviceDocumentationUrl}}}function ei(e={}){re(e);let t=e.projectId??S("MCP_USE_OAUTH_SUPABASE_PROJECT_ID"),n=e.supabaseUrl??S("MCP_USE_OAUTH_SUPABASE_URL"),r=e.jwtSecret??S("MCP_USE_OAUTH_SUPABASE_JWT_SECRET");return Yn({...oe(e),...t!==void 0&&{projectId:t},...n!==void 0&&{supabaseUrl:n},...r!==void 0&&{jwtSecret:r}})}function ti(e={}){re(e);let t=e.domain??S("MCP_USE_OAUTH_AUTH0_DOMAIN"),n=e.audience??S("MCP_USE_OAUTH_AUTH0_AUDIENCE");if(t===void 0)throw new Error("Auth0 domain is required.");return zn({...oe(e,e.resource??n),domain:t})}function ni(e={}){re(e);let t=e.serverUrl??S("MCP_USE_OAUTH_KEYCLOAK_SERVER_URL"),n=e.realm??S("MCP_USE_OAUTH_KEYCLOAK_REALM"),r=e.audience??S("MCP_USE_OAUTH_KEYCLOAK_AUDIENCE");if(t===void 0||n===void 0)throw new Error("Keycloak serverUrl and realm are required.");return Gn({...oe(e,e.resource??r),serverUrl:t,realm:n})}function ri(e={}){re(e);let t=e.subdomain??S("MCP_USE_OAUTH_WORKOS_SUBDOMAIN");if(t===void 0)throw new Error("WorkOS subdomain is required.");return Xn({...oe(e),subdomain:t})}function oi(e={}){re(e);let t=e.frontendApiUrl??S("MCP_USE_OAUTH_CLERK_FRONTEND_API_URL");if(t===void 0)throw new Error("Clerk frontendApiUrl is required.");return Kn({...oe(e,e.resource??e.audience),frontendApiUrl:t})}function si(e={}){re(e);let t=e.authURL??S("MCP_USE_OAUTH_BETTER_AUTH_URL");if(t===void 0)throw new Error("Better Auth authURL is required.");return Jn({...oe(e),authURL:t})}var Zn='Deprecated temporary v1 compatibility. Use the native v2 API from "mcp-use". This entry will be removed in mcp-use v3.',yt="MCP_USE_V1_COMPAT",Qn="__mcpUseV1CompatServer",er=!1,wt=class{#e;#t=new Map;#n=new Map;#r=new Set;config;app;fetch;get;post;put;patch;delete;all;use;on;serverHost;serverPort;serverBaseUrl;constructor(t){mi(),pi(t),this.config=t,this.serverHost=t.host??"localhost",t.baseUrl!==void 0&&(this.serverBaseUrl=t.baseUrl),this.#e=new ge(ui(t)),this.app=this.#e.app,this.fetch=this.#e.fetch,this.get=this.#e.get,this.post=this.#e.post,this.put=this.#e.put,this.patch=this.#e.patch,this.delete=this.#e.delete,this.all=this.#e.all,this.use=this.#e.use.bind(this.#e),this.on=this.#e.on.bind(this.#e);let n=globalThis;if(process.env.MCP_USE_CLI_IMPORT==="1"&&n[Qn]!==void 0)throw se("multiple compatibility servers in one CLI entry","default-export one native v2 server or construct only one v1 server");n[Qn]=this}static fromOpenAPI(t){return ge.fromOpenAPI(t)}get basePath(){return this.#e.basePath}get host(){return this.#e.host}get port(){return this.#e.port}get branding(){return this.#e.branding}tool(t,n){if(t.inputs!==void 0)throw se("tool inputs[] schemas","use a Zod schema field");let r=t.cb;if(r!==void 0&&n!==void 0)throw new TypeError(`Tool "${t.name}" provides both cb and a separate callback.`);let o=n??r;if(o===void 0)throw new TypeError(`Tool "${t.name}" requires a callback.`);if(t.widget!==void 0){let s=t.widget.name;if(this.#t.has(s)||this.#r.has(s))throw se(`binding legacy widget "${s}" to multiple tools`,"use one tool per view or migrate the bindings to native v2");return this.#r.add(s),this.#t.set(s,{definition:t,callback:o}),this}return this.#l(t,o),this}resource(t,n){let r=n??t.readCallback;if(n!==void 0&&t.readCallback!==void 0)throw new TypeError(`Resource "${t.name}" provides both readCallback and a separate callback.`);if(r===void 0)throw new TypeError(`Resource "${t.name}" requires a callback.`);let{readCallback:o,callbacks:s,...i}=t;return this.#e.resource(i,async(u,a)=>r(Ee(a))),this}resourceTemplate(t,n){let r=n??t.readCallback;if(n!==void 0&&t.readCallback!==void 0)throw new TypeError(`Resource template "${t.name}" provides both readCallback and a separate callback.`);if(r===void 0)throw new TypeError(`Resource template "${t.name}" requires a callback.`);let o=t.resourceTemplate,s=t.uriTemplate??o?.uriTemplate;if(s===void 0)throw new TypeError(`Resource template "${t.name}" requires uriTemplate.`);let i=t.callbacks?.complete??o?.callbacks?.complete,u=t.description??o?.description,a=t.mimeType??o?.mimeType,d={name:t.name,uriTemplate:s,...t.title!==void 0&&{title:t.title},...u!==void 0&&{description:u},...a!==void 0&&{mimeType:a},...t.annotations!==void 0&&{annotations:t.annotations},...t._meta!==void 0&&{_meta:t._meta},...i!==void 0&&{complete:i}};return this.#e.resourceTemplate(d,async(c,l,p)=>r(c,l,Ee(p))),this}prompt(t,n){if(t.args!==void 0)throw se("prompt args[] schemas","use a Zod schema field");let r=t.cb;if(r!==void 0&&n!==void 0)throw new TypeError(`Prompt "${t.name}" provides both cb and a separate callback.`);let o=n??r;if(o===void 0)throw new TypeError(`Prompt "${t.name}" requires a callback.`);let{cb:s,args:i,...u}=t;return this.#e.prompt(u,async(a,d)=>o(a,Ee(d))),this}async listen(t,n){if(process.env.MCP_USE_CLI_IMPORT==="1")return;this.#o();let r=await this.#e.listen(t,n);return this.serverPort=r.port,r}async close(){await this.#e.close()}getHandler(){return this.fetch}async proxy(...t){await this.#e.proxy(...t)}async notifyResourceUpdated(t){await this.#e.notifyResourceUpdated(t)}__registerLegacyViews(t){for(let[n,r]of Object.entries(t)){let o=r.widgetMetadata??{};this.#n.set(n,o),this.#i(n),o.exposeAsTool===!0&&!this.#r.has(n)&&this.#a(n,o)}}__primeViews(t,n){this.#o(),this.#e.__primeViews(t,n)}__mount(){this.#o(),this.#e.__mount()}__setEventBus(t){this.#e.__setEventBus(t)}#l(t,n,r,o){let{cb:s,widget:i,inputs:u,...a}=t,d=r===void 0?void 0:rr(r,o),c=a.outputSchema??(r===void 0?void 0:tr(o)??nr),l=or(i,o),p={...a,...c!==void 0&&{outputSchema:c},...d!==void 0&&{view:d},...(a._meta!==void 0||l!==void 0)&&{_meta:{...a._meta,...l}}};this.#e.tool(p,async(g,f)=>n(g,Ee(f)))}#i(t){let n=this.#t.get(t);n!==void 0&&(this.#t.delete(t),this.#l(n.definition,n.callback,t,this.#n.get(t)))}#o(){for(let t of[...this.#t.keys()])this.#i(t)}#a(t,n){this.#r.add(t);let r=tr(n)??nr,o={name:t,...n.title!==void 0&&{title:n.title},description:n.description??n.metadata?.description??`Display ${t}`,inputSchema:r,outputSchema:r,...n.annotations!==void 0&&{annotations:n.annotations},_meta:{...n._meta,...or(void 0,n)},view:rr(t,n)};this.#e.tool(o,async s=>{let i=typeof n.toolOutput=="function"?await n.toolOutput(s):n.toolOutput;return{content:i?.content??[{type:"text",text:`${n.title??t} ready`}],structuredContent:s,...i?.isError===!0&&{isError:!0},...i?._meta!==void 0&&{_meta:i._meta}}})}};function td(e,t={}){return new wt({name:e,version:t.version??"1.0.0",...t})}function nd(e){return{...Ie(e),structuredContent:{data:e}}}function rd(e){let t=Tt(e);return{...t,structuredContent:t.structuredContent??e.props??e.data??{}}}function Pe(e){let t=e.auth;if(t!==void 0)return t;let n=e.get?.("auth");if(n!==void 0)return n;let r=e.req?.raw,o=r===void 0?void 0:T(r).authInfo;if(o!==void 0)return di(o);throw new Error("Authentication context is missing.")}function ii(e,t){let n=Pe(e);return(Array.isArray(t)?t:[t]).every(o=>n.scopes.includes(o)||n.permissions.includes(o))}function ai(e,t){let n=Pe(e);return t.some(r=>n.scopes.includes(r)||n.permissions.includes(r))}function od(e){return async(t,n)=>{if(ii(t,e))return n();let r=Pe(t),o=Array.isArray(e)?e:[e];return t.json({error:"insufficient_scope",required:o,granted_scopes:r.scopes,granted_permissions:r.permissions},403)}}function sd(e){return async(t,n)=>{if(ai(t,e))return n();let r=Pe(t);return t.json({error:"insufficient_scope",required_any:e,granted_scopes:r.scopes,granted_permissions:r.permissions},403)}}function ui(e){let t=e.baseUrl===void 0?void 0:new URL(e.baseUrl),n=t!==void 0&&t.pathname!=="/"?t.pathname.replace(/\/$/,""):void 0,r=e.oauth===void 0?void 0:{...e.oauth,...e.oauth.resource===void 0&&t!==void 0?{resource:new URL(n??"/mcp",t.origin)}:{}};return{name:e.name,version:e.version,...e.title!==void 0&&{title:e.title},...e.description!==void 0&&{description:e.description},...e.instructions!==void 0&&{instructions:e.instructions},...e.host!==void 0&&{host:e.host},...e.port!==void 0&&{port:e.port},...n!==void 0&&{basePath:n},...e.allowedOrigins!==void 0&&{allowedHosts:e.allowedOrigins.map(li)},cors:ci(e.cors),...r!==void 0&&{oauth:r},...e.publicLandingPage!==void 0&&{publicLandingPage:e.publicLandingPage},...e.favicon!==void 0&&{favicon:e.favicon},...e.icons!==void 0&&{icons:e.icons},...e.websiteUrl!==void 0&&{websiteUrl:e.websiteUrl}}}function di(e){let t=e.extra;if(t===void 0||typeof t!="object"||t===null||!("user"in t)||typeof t.user!="object"||t.user===null||Array.isArray(t.user)||!("payload"in t)||typeof t.payload!="object"||t.payload===null||Array.isArray(t.payload)||!("permissions"in t)||!Array.isArray(t.permissions)||!t.permissions.every(o=>typeof o=="string"))throw new Error("Authentication context is missing mapped OAuth data.");let n=t.user,r=n.userId??n.id;return{user:{...n,...typeof r=="string"&&{userId:r},permissions:[...t.permissions],scopes:[...e.scopes]},payload:t.payload,accessToken:e.token,scopes:[...e.scopes],permissions:[...t.permissions]}}function ci(e){return e===void 0?{origin:"*"}:{...e.origin!==void 0&&{origin:e.origin},...e.allowMethods!==void 0&&{methods:e.allowMethods},...e.allowHeaders!==void 0&&{allowedHeaders:e.allowHeaders},...e.credentials!==void 0&&{credentials:e.credentials}}}function li(e){try{return new URL(e).hostname}catch{return e.split(":")[0]??e}}function pi(e){if(e.stateless===!1)throw se("stateless: false","v2 is stateless");for(let[t,n]of[["sessionIdleTimeoutMs",e.sessionIdleTimeoutMs],["autoCreateSessionOnInvalidId",e.autoCreateSessionOnInvalidId],["sessionStore",e.sessionStore],["streamManager",e.streamManager]])if(n!==void 0)throw se(t,"migrate to stateless v2")}function Ee(e){let t=e,n=e.client;n.supportsApps??=()=>n.supportsViews(),t.log=e.sendLog.bind(e);let r=t.auth;if(r!==void 0&&typeof r=="object"&&r!==null){let o=r,s=o.user,i=s.userId??s.id;o.user={...s,...typeof i=="string"&&{userId:i},...s.organizationId!==void 0&&{organization_id:s.organizationId,org_id:s.organizationId},...s.organizationRole!==void 0&&{org_role:s.organizationRole},...s.organizationSlug!==void 0&&{org_slug:s.organizationSlug},permissions:[...o.permissions],scopes:[...o.scopes]}}return t}function tr(e){let t=e?.props??e?.schema??e?.inputs;return fi(t)?t:void 0}function fi(e){return typeof e=="object"&&e!==null&&"~standard"in e&&typeof e["~standard"]?.validate=="function"}var nr={"~standard":{version:1,vendor:"mcp-use-v1-compat",validate(e){return typeof e!="object"||e===null||Array.isArray(e)?{issues:[{message:"expected an object"}]}:{value:e}},jsonSchema:{input:()=>({type:"object",additionalProperties:!0}),output:()=>({type:"object",additionalProperties:!0})}}};function rr(e,t){let n=t?.metadata,r=t?.appsSdkMetadata,o=r?.["openai/widgetCSP"],s=n?.csp??(o===void 0?void 0:{...o.connect_domains!==void 0&&{connectDomains:o.connect_domains},...o.resource_domains!==void 0&&{resourceDomains:o.resource_domains},...o.frame_domains!==void 0&&{frameDomains:o.frame_domains}}),i=n?.description??t?.description??r?.["openai/widgetDescription"],u=n?.prefersBorder??r?.["openai/widgetPrefersBorder"],a=n?.domain??r?.["openai/widgetDomain"];return{name:e,...i!==void 0&&{description:i},...s!==void 0&&{csp:s},...u!==void 0&&{prefersBorder:u},...a!==void 0&&{domain:a}}}function or(e,t){let n=e?.invoking??t?.metadata?.invoking,r=e?.invoked??t?.metadata?.invoked,o=e?.widgetAccessible,s=e?.resultCanProduceWidget;if(!(n===void 0&&r===void 0&&o===void 0&&s===void 0))return{...n!==void 0&&{"openai/toolInvocation/invoking":n},...r!==void 0&&{"openai/toolInvocation/invoked":r},...o!==void 0&&{"openai/widgetAccessible":o},...s!==void 0&&{"openai/resultCanProduceWidget":s}}}function mi(){er||(er=!0,typeof process.emitWarning=="function"?process.emitWarning(Zn,{type:"DeprecationWarning",code:yt}):console.warn(`[${yt}] ${Zn}`))}function se(e,t){return new Error(`[${yt}] ${e} is not supported by the temporary v1 compatibility entry; ${t}.`)}export{wt as MCPServer,nd as array,fr as audio,mr as binary,Ao as completable,td as createMCPServer,cr as css,gr as error,Pe as getAuth,ai as hasAnyScope,ii as hasScope,ur as html,pr as image,lr as javascript,ar as markdown,wr as mix,ti as oauthAuth0Provider,si as oauthBetterAuthProvider,oi as oauthClerkProvider,ni as oauthKeycloakProvider,ei as oauthSupabaseProvider,ri as oauthWorkOSProvider,yr as object,sd as requireAnyScope,od as requireScope,hr as resource,ir as text,rd as widget,dr as xml};
@@ -731,16 +731,24 @@ ${cyan("=".repeat(80))}`),console.log(bold(cyan("[TRACE] Request Details"))),con
731
731
  `)),level==="trace"&&await printTraceDump(response,requestHeaders,requestBody,!isStreamingMethod),response}}function createMcpMount(factory,options={}){let{path="/mcp",handler:handlerOptions,authInfo:getAuthInfo}=options,legacyMode=handlerOptions?.legacy??"stateless",handler=createMcpHandler(factory,{legacy:"stateless",...handlerOptions});return{handler,fetch:async request=>{if(!matchesPath(request,path))return new Response("Not Found",{status:404});if(legacyMode==="stateless"){let method=request.method.toUpperCase();if(method==="GET"||method==="DELETE"||method==="HEAD")return new Response(null,{status:204})}let bag=getRequestBag(request),parsedBody=bag.parsedBody;if(parsedBody===void 0)try{parsedBody=await request.clone().json()}catch{}let capabilities=extractClientCapabilitiesFromBody(parsedBody);capabilities!==void 0&&stashClientCapabilities(request,capabilities);let authInfo=getAuthInfo?.(request)??bag.authInfo,response=await handler.fetch(request,{...parsedBody!==void 0&&{parsedBody},...authInfo!==void 0&&{authInfo}});return response.headers.get("content-type")?.toLowerCase().includes("application/json")?trackBufferedResponse(request,response):response}}}function createPrefixCompletion(values){let strings=values.map(String);return value=>{let prefix=String(value??"").toLowerCase();return strings.filter(candidate=>candidate.toLowerCase().startsWith(prefix))}}function completable2(schema,complete){return typeof complete=="function"?completable(schema,(value,context)=>complete(String(value??""),context)):completable(schema,createPrefixCompletion(complete))}function normalizeCompletions(completions){let normalized=Object.create(null);for(let[variable,completer]of Object.entries(completions))completer!==void 0&&(normalized[variable]=Array.isArray(completer)?createPrefixCompletion(completer):completer);return normalized}var HTTP_METHODS=["get","put","post","delete","options","head","patch","trace"];function registerOpenAPITools(server,options){let operations=collectOperations(options.spec,options),names=createToolNames(operations),baseUrl=operations.length>0?resolveBaseUrl(options):void 0;for(let[index,operation]of operations.entries()){let name=names[index];if(name===void 0||baseUrl===void 0)continue;let inputBindings=createInputBindings(operation);server.tool({name,description:createToolDescription(operation),inputSchema:createToolInputSchema(options.spec,operation,inputBindings)},async params=>callOpenAPIOperation(operation,params,options,inputBindings,baseUrl))}}function collectOperations(spec,options){let collected=[];for(let[path,pathItemOrRef]of Object.entries(spec.paths??{})){let pathItem=resolveRef(spec,pathItemOrRef);if(pathItem===void 0||isReferenceObject(pathItem))continue;let pathParameters=resolveParameters(spec,pathItem.parameters);for(let method of HTTP_METHODS){let operationOrRef=pathItem[method];if(operationOrRef===void 0)continue;let operation=resolveRef(spec,operationOrRef);if(operation===void 0||isReferenceObject(operation))continue;let operationParameters=resolveParameters(spec,operation.parameters),requestBody=operation.requestBody===void 0?void 0:resolveRef(spec,operation.requestBody),item={method,path,operation,parameters:mergeParameters(pathParameters,operationParameters),...requestBody!==void 0&&!isReferenceObject(requestBody)&&{requestBody}};isIncluded(item,options)&&collected.push(item)}}return collected}function resolveParameters(spec,parameters){let resolved=[];for(let parameter of parameters??[]){let value=resolveRef(spec,parameter);value!==void 0&&!isReferenceObject(value)&&resolved.push(value)}return resolved}function mergeParameters(pathParameters,operationParameters){let merged=new Map;for(let parameter of[...pathParameters,...operationParameters])merged.set(`${parameter.in}:${parameter.name}`,parameter);return[...merged.values()]}function isIncluded(operation,options){if(options.tags?.length){let tags=new Set(operation.operation.tags??[]);if(!options.tags.some(tag=>tags.has(tag)))return!1}return!(options.exclude??[]).some(rule=>matchesExcludeRule(operation,rule))}function matchesExcludeRule(operation,rule){if(rule.method&&rule.method.toLowerCase()!==operation.method||rule.operationId&&!matchesPattern2(rule.operationId,operation.operation.operationId??"")||rule.path&&!matchesPattern2(rule.path,operation.path))return!1;if(rule.tags?.length){let tags=new Set(operation.operation.tags??[]);if(!rule.tags.some(tag=>tags.has(tag)))return!1}return!0}function matchesPattern2(pattern,value){return typeof pattern=="string"?pattern===value:(pattern.lastIndex=0,pattern.test(value))}function createToolNames(operations){let seen=new Map;return operations.map(operation=>{let baseName=slugifyToolName(operation.operation.operationId??`${operation.method}_${operation.path.replace(/[{}]/g,"").replace(/\//g,"_")}`),count=seen.get(baseName)??0;if(seen.set(baseName,count+1),count===0)return baseName;let suffix=`_${count+1}`;return`${baseName.slice(0,64-suffix.length)}${suffix}`})}function createToolDescription(operation){return[operation.operation.summary,operation.operation.description,`HTTP: ${operation.method.toUpperCase()} ${operation.path}`].filter(part=>!!part).join(`
732
732
 
733
733
  `)}function slugifyToolName(value){return value.trim().replace(/[^a-zA-Z0-9_-]+/g,"_").replace(/_+/g,"_").replace(/^_/,"").replace(/_$/,"").slice(0,64)||"openapi_tool"}function createToolInputSchema(spec,operation,inputBindings){let properties={},required2=[];for(let{parameter,inputName}of inputBindings.parameters){let parameterSchema=transformSchema(spec,parameter.schema??{});properties[inputName]={...parameterSchema,description:parameter.description??`${parameter.in} parameter`},(parameter.required||parameter.in==="path")&&required2.push(inputName)}let bodySchema=getJsonRequestBodySchema(operation.requestBody);bodySchema!==void 0&&inputBindings.bodyInputName!==void 0&&(properties[inputBindings.bodyInputName]=transformSchema(spec,bodySchema),operation.requestBody?.required&&required2.push(inputBindings.bodyInputName));let definitions=createSchemaDefinitions(spec),schema={type:"object",properties,additionalProperties:!1,...required2.length>0&&{required:required2},...definitions!==void 0&&{$defs:definitions}};return fromJsonSchema2(schema)}function createInputBindings(operation){let parameters=operation.parameters.filter(parameter=>parameter.in!=="cookie"),bodyInputName=getJsonRequestBodySchema(operation.requestBody)===void 0?void 0:"body",nameCounts=new Map;for(let parameter of parameters)nameCounts.set(parameter.name,(nameCounts.get(parameter.name)??0)+1);let usedNames=new Set(bodyInputName===void 0?[]:[bodyInputName]);return{parameters:parameters.map(parameter=>{let preferredName=(nameCounts.get(parameter.name)??0)>1||parameter.name===bodyInputName?`${parameter.name}_${parameter.in}`:parameter.name;return{parameter,inputName:claimInputName(preferredName,usedNames)}}),...bodyInputName!==void 0&&{bodyInputName}}}function claimInputName(preferredName,usedNames){let inputName=preferredName,suffix=2;for(;usedNames.has(inputName);)inputName=`${preferredName}_${suffix}`,suffix+=1;return usedNames.add(inputName),inputName}function createSchemaDefinitions(spec){let schemas=readRecord(spec.components?.schemas);if(schemas===void 0)return;let definitions={};for(let[name,schema]of Object.entries(schemas))definitions[name]=transformSchemaNode(spec,schema,new Set);return definitions}function transformSchema(spec,schema){let transformed=transformSchemaNode(spec,schema,new Set);return readRecord(transformed)??{}}function transformSchemaNode(spec,value,resolvingRefs){if(Array.isArray(value))return value.map(item=>transformSchemaNode(spec,item,resolvingRefs));let object3=readRecord(value);if(object3===void 0)return value;let ref=typeof object3.$ref=="string"?object3.$ref:void 0,siblings={};for(let[key,child]of Object.entries(object3))key!=="$ref"&&(key==="nullable"&&typeof child=="boolean"||(siblings[key]=transformSchemaNode(spec,child,resolvingRefs)));let transformed=siblings;if(ref!==void 0){let schemaRef=rewriteSchemaRef(spec,ref);if(schemaRef!==void 0)transformed={$ref:schemaRef,...siblings};else if(!resolvingRefs.has(ref)){let resolved=resolveRef(spec,{$ref:ref});if(resolved!==void 0){let nextRefs=new Set(resolvingRefs);nextRefs.add(ref),transformed={...readRecord(transformSchemaNode(spec,resolved,nextRefs))??{},...siblings}}}}return object3.nullable===!0?{anyOf:[transformed,{type:"null"}]}:transformed}function rewriteSchemaRef(spec,ref){let prefix="#/components/schemas/";if(ref.startsWith(prefix))return resolveRef(spec,{$ref:ref})===void 0?void 0:`#/$defs/${ref.slice(prefix.length)}`}function getJsonRequestBodySchema(requestBody){let content=requestBody?.content;if(content!==void 0)return content["application/json"]?.schema??content["application/*+json"]?.schema??Object.entries(content).find(([mediaType])=>mediaType.includes("+json"))?.[1].schema}async function callOpenAPIOperation(operation,params,options,inputBindings,baseUrl){let fetchImpl=options.fetch??globalThis.fetch,url2=buildUrl(operation,params,inputBindings.parameters,baseUrl),headers=buildHeaders(inputBindings.parameters,params,options),bodyInputName=inputBindings.bodyInputName,body=bodyInputName===void 0||params[bodyInputName]===void 0?void 0:JSON.stringify(params[bodyInputName]);body!==void 0&&!hasHeader(headers,"content-type")&&(headers["content-type"]="application/json");let response=await fetchImpl(url2,{method:operation.method.toUpperCase(),headers,...body!==void 0&&{body}}),contentType=response.headers.get("content-type")??"";if(!response.ok)return{content:[{type:"text",text:await response.text()}],isError:!0};if(contentType.includes("application/json")||contentType.includes("+json")){let text2=await response.text();try{let data=JSON.parse(text2);return{content:[{type:"text",text:JSON.stringify(data)}],structuredContent:data}}catch{return{content:[{type:"text",text:text2}]}}}return{content:[{type:"text",text:await response.text()}]}}function buildUrl(operation,params,parameterBindings,baseUrl){let interpolatedPath=operation.path.replace(/{([^}]+)}/g,(_match,name)=>{let binding=parameterBindings.find(({parameter})=>parameter.in==="path"&&parameter.name===name);return encodeURIComponent(String(binding===void 0?"":params[binding.inputName]??""))}),url2=new URL(interpolatedPath.replace(/^\/+/,""),ensureTrailingSlash(baseUrl));for(let{parameter,inputName}of parameterBindings){if(parameter.in!=="query")continue;let value=params[inputName];value==null||value===""||appendQueryParam(url2,parameter.name,value)}return url2.toString()}function buildHeaders(parameterBindings,params,options){let headers={...options.headers??{}};for(let{parameter,inputName}of parameterBindings){if(parameter.in!=="header")continue;let value=params[inputName];value==null||value===""||(headers[parameter.name]=String(value))}return options.auth?.type==="bearer"&&options.auth.token&&(headers.authorization=`Bearer ${options.auth.token}`),options.auth?.type==="header"&&options.auth.value&&(headers[options.auth.name]=options.auth.value),headers}function resolveBaseUrl(options){let baseUrl=options.baseUrl??options.spec.servers?.[0]?.url;if(baseUrl===void 0||baseUrl.trim()==="")throw new Error("MCPServer.fromOpenAPI requires options.baseUrl or spec.servers[0].url");return baseUrl}function appendQueryParam(url2,name,value){if(Array.isArray(value)){for(let item of value)item!=null&&item!==""&&url2.searchParams.append(name,String(item));return}url2.searchParams.set(name,String(value))}function ensureTrailingSlash(url2){return url2.endsWith("/")?url2:`${url2}/`}function hasHeader(headers,name){return Object.keys(headers).some(headerName=>headerName.toLowerCase()===name)}function isReferenceObject(value){let object3=readRecord(value);return object3!==void 0&&typeof object3.$ref=="string"}function resolveRef(spec,value){if(!isReferenceObject(value))return value;if(!value.$ref.startsWith("#/"))return;let segments=value.$ref.slice(2).split("/").map(segment=>segment.replace(/~1/g,"/").replace(/~0/g,"~")),current=spec;for(let segment of segments){let object3=readRecord(current);if(object3===void 0||!(segment in object3))return;current=object3[segment]}return current}function readRecord(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)?value:void 0}function isRecord(value){return value!==null&&typeof value=="object"&&!Array.isArray(value)}function isLocalhost(url2){let hostname=url2.hostname.toLowerCase();return hostname==="localhost"||hostname.endsWith(".localhost")||hostname==="[::1]"||/^127(?:\.\d{1,3}){3}$/.test(hostname)}function parseAbsoluteUrl(value,name){let url2;try{url2=new URL(value)}catch{throw new Error(`${name} must be an absolute URL`)}if(url2.origin==="null"||url2.username!==""||url2.password!=="")throw new Error(`${name} must be an absolute URL without credentials`);return url2}function assertSecureHttpUrl(url2,name){if(url2.protocol!=="https:"&&!(url2.protocol==="http:"&&isLocalhost(url2)))throw new Error(`${name} must use HTTPS, or HTTP for localhost`)}function invalidToken(message,cause){let error3=new OAuthError(OAuthErrorCode.InvalidToken,message);return cause!==void 0&&(error3.cause=cause),error3}function resolveConfiguredOAuthResource(options){let provider=options.provider,basePath=normalizeBasePath(options.basePath);if(provider.resource!==void 0)return validateOAuthResource(provider.resource,basePath);if(options.mcpUrl!==void 0)return validateOAuthResource(appendBasePath(requireAbsoluteOrigin(options.mcpUrl,"MCP_URL"),basePath),basePath)}function resolveLocalOAuthResource(listenOrigin,basePath){let listenOriginUrl=requireAbsoluteOrigin(listenOrigin,"listen origin");if(!isLocalhost(listenOriginUrl))throw new Error("OAuth listen origin must be localhost or a loopback address");return validateOAuthResource(appendBasePath(listenOriginUrl,normalizeBasePath(basePath)),basePath)}function validateOAuthResource(resource2,basePath){let normalizedBasePath=normalizeBasePath(basePath),url2=parseAbsoluteUrl(resource2,"OAuth resource");if(url2.search!==""||url2.hash!=="")throw new Error("OAuth resource must not include a query string or fragment");if(assertSecureHttpUrl(url2,"OAuth resource"),normalizePathname(url2.pathname)!==normalizedBasePath)throw new Error(`OAuth resource path must exactly match basePath (${normalizedBasePath})`);return url2.pathname=normalizedBasePath,url2}function wrapOAuthTokenVerifier(provider,expectedResource){let canonicalResource=normalizeResourceUrl(expectedResource),tokenVerifier=provider.createTokenVerifier(new URL(canonicalResource.href));if(tokenVerifier===null||typeof tokenVerifier!="object"||typeof tokenVerifier.verifyAccessToken!="function")throw new TypeError("OAuth provider createTokenVerifier must return an OAuthTokenVerifier");return{async verifyAccessToken(token){let authInfo=await tokenVerifier.verifyAccessToken(token);assertVerifiedAuthInfo(authInfo),assertResourceBinding(authInfo,canonicalResource);let mapped;try{mapped=provider.mapAuthInfo(authInfo)}catch(error3){throw invalidToken("Token identity mapping failed",error3)}return assertMappedExtra(mapped),{...authInfo,scopes:[...authInfo.scopes],extra:{...authInfo.extra,...mapped}}}}}function assertResourceBinding(authInfo,expectedResource){if(authInfo.resource===void 0)throw invalidToken("Token verifier did not return a validated protected resource");if(parseTokenResource(authInfo.resource).href!==normalizeResourceUrl(expectedResource).href)throw invalidToken("Token resource does not match the protected resource")}function parseTokenResource(value){if(!(value instanceof URL))throw invalidToken("Token resource must be an absolute HTTPS URL, or HTTP URL for localhost");let resource2=value;if(!/^https?:$/.test(resource2.protocol)||resource2.username!==""||resource2.password!==""||resource2.search!==""||resource2.hash!==""||resource2.protocol==="http:"&&!isLocalhost(resource2))throw invalidToken("Token resource must be an absolute HTTPS URL, or HTTP URL for localhost");return normalizeResourceUrl(resource2)}function normalizeResourceUrl(resource2){let normalized=new URL(resource2);return normalized.pathname=normalized.pathname==="/"?"/":normalized.pathname.replace(/\/+$/,""),normalized}function getOAuthProviderOptions(provider){return{oauthMetadata:provider.oauthMetadata,...provider.requiredScopes!==void 0&&{requiredScopes:[...provider.requiredScopes]},...provider.scopesSupported!==void 0&&{scopesSupported:[...provider.scopesSupported]},...provider.resourceName!==void 0&&{resourceName:provider.resourceName},...provider.serviceDocumentationUrl!==void 0&&{serviceDocumentationUrl:provider.serviceDocumentationUrl}}}function assertVerifiedAuthInfo(authInfo){if(authInfo===null||typeof authInfo!="object"||typeof authInfo.token!="string"||authInfo.token.length===0||typeof authInfo.clientId!="string"||!Array.isArray(authInfo.scopes)||!authInfo.scopes.every(scope=>typeof scope=="string")||typeof authInfo.expiresAt!="number"||!Number.isFinite(authInfo.expiresAt)||authInfo.expiresAt<=Date.now()/1e3)throw invalidToken("Token verifier returned invalid authentication information")}function assertMappedExtra(mapped){if(mapped===null||typeof mapped!="object"||!("user"in mapped)||mapped.user===void 0||!isRecord(mapped.payload)||!Array.isArray(mapped.permissions)||!mapped.permissions.every(permission=>typeof permission=="string"))throw invalidToken("Token identity mapping must return user, payload, and string permissions")}function requireAbsoluteOrigin(value,name){let url2=parseAbsoluteUrl(value,name);if(url2.pathname!=="/"||url2.search!==""||url2.hash!==""||url2.username!==""||url2.password!=="")throw new Error(`${name} must be an absolute origin without a path`);return url2}function appendBasePath(origin,basePath){let resource2=new URL(origin.origin);return resource2.pathname=basePath,resource2}function normalizeBasePath(basePath){if(!basePath.startsWith("/")||basePath.includes("?")||basePath.includes("#"))throw new Error("basePath must be an absolute URL pathname");return normalizePathname(basePath)}function normalizePathname(pathname){if(pathname==="/")return"/";let end=pathname.length;for(;end>0&&pathname.charCodeAt(end-1)===47;)end--;return pathname.slice(0,end)}function oauthMetadata(provider,resource2){let options=getOAuthProviderOptions(provider);return async(request,next)=>{let response=oauthMetadataResponse(request,{oauthMetadata:options.oauthMetadata,resourceServerUrl:resource2,...options.scopesSupported!==void 0&&{scopesSupported:[...options.scopesSupported]},...options.resourceName!==void 0&&{resourceName:options.resourceName},...options.serviceDocumentationUrl!==void 0&&{serviceDocumentationUrl:options.serviceDocumentationUrl}});return response!==void 0?response:next()}}function authInfoFromRequest(request){return getRequestBag(request).authInfo}function resolveToolInputSchema(definition){return definition.inputSchema??definition.schema}var EVENT="mcp_use_sdk_event",ENDPOINT="https://eu.i.posthog.com/i/v0/e/",TOKEN="phc_lyTtbYwvkdSbrcMQNPiKiiRWrrM1seyKIMjycSvItEI",CONTENT=/(^|_)(arguments?|args|body|command|headers?|location|message|organization|path|query|response|secret|subject|token|uri|url|user_agent)(_|$)/i,RESERVED=new Set("feature action sdk_generation telemetry_schema_version sdk_package sdk_version server_id runtime_id identity_stability distinct_id validation_run_id is_validation".split(" ")),runtimeId=crypto.randomUUID(),once=new Set,pending=new Set,identities=new Map;function hasControl(value){return[...value].some(character=>{let code=character.charCodeAt(0);return code<32||code===127})}function env(name){return typeof process>"u"?void 0:process.env?.[name]}function safeEnv(name){let value=env(name);return value!==void 0&&value.length>0&&value.length<=128&&!hasControl(value)?value:void 0}function disabled(){if(env("MCP_USE_ANONYMIZED_TELEMETRY")==="false")return!0;try{return globalThis.__MCP_USE_ANONYMIZED_TELEMETRY__===!1||typeof localStorage<"u"&&localStorage.getItem("MCP_USE_ANONYMIZED_TELEMETRY")==="false"}catch{return!1}}function isUsageDisabled(){return disabled()}function clean(properties){return Object.fromEntries(Object.entries(properties).filter(([key,value])=>key.length>128||hasControl(key)||key.startsWith("$")||RESERVED.has(key)||CONTENT.test(key)||value===void 0?!1:typeof value=="string"?value.length<=128&&!hasControl(value):typeof value=="boolean"||typeof value=="number"&&Number.isFinite(value)))}async function identity(serverRoot){let projectId=safeEnv("MCP_USE_TELEMETRY_PROJECT_ID");if(projectId!==void 0)return{id:projectId,stability:"project"};if(serverRoot===void 0||typeof process>"u")return{id:runtimeId,stability:"process"};let existing=identities.get(serverRoot);if(existing!==void 0)return existing;let resolving=(async()=>{try{let fs=await import("fs/promises"),directory=`${serverRoot}/.mcp-use`,file=`${directory}/usage.json`,read=async()=>{try{let value=JSON.parse(await fs.readFile(file,"utf8"));if(typeof value=="object"&&value!==null&&"schemaVersion"in value&&value.schemaVersion===1&&"serverId"in value&&typeof value.serverId=="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(value.serverId))return value.serverId}catch{}},stored=await read();if(stored!==void 0)return{id:stored,stability:"server"};await fs.mkdir(directory,{recursive:!0,mode:448});let created=crypto.randomUUID();try{return await fs.writeFile(file,`${JSON.stringify({schemaVersion:1,serverId:created})}
734
- `,{flag:"wx",mode:384}),{id:created,stability:"server"}}catch{let raced=await read();if(raced!==void 0)return{id:raced,stability:"server"}}}catch{}return{id:runtimeId,stability:"process"}})();return identities.set(serverRoot,resolving),resolving}function capture(feature,action,properties,options,resolveIdentity){let validationId=safeEnv("MCP_USE_TELEMETRY_VALIDATION_ID");if(disabled()||env("NODE_ENV")==="test"&&validationId===void 0||pending.size>=16)return;if(options.onceKey!==void 0){if(once.has(options.onceKey))return;once.add(options.onceKey)}let rate=Math.max(0,Math.min(1,options.sampleRate??1));if(validationId===void 0&&Math.random()>=rate)return;let request=(async()=>{try{let resolvedIdentity=await resolveIdentity(),body=JSON.stringify({api_key:TOKEN,event:EVENT,properties:{...clean(properties),feature,action,sdk_generation:"v2",telemetry_schema_version:2,sdk_package:"mcp-use",sdk_version:"2.0.0-beta.57",server_id:resolvedIdentity.id,runtime_id:runtimeId,identity_stability:resolvedIdentity.stability,distinct_id:resolvedIdentity.id,sample_rate:validationId===void 0?rate:1,$process_person_profile:!1,$geoip_disable:!0,...validationId!==void 0&&{is_validation:!0,validation_run_id:validationId}}});await fetch(ENDPOINT,{method:"POST",headers:{"content-type":"application/json"},keepalive:!0,body})}catch{return}})();pending.add(request),request.then(()=>pending.delete(request))}function recordUsage(feature,action,properties={},options={}){capture(feature,action,properties,options,()=>identity(options.serverRoot))}var registerViews=Symbol("mcp-use/registerViews");function resolveAssetUrl(assetPath,origin){if(!assetPath.startsWith("/"))throw new Error(`View manifest asset path must be origin-absolute (start with "/"); got ${JSON.stringify(assetPath)}`);return`${origin}${assetPath}`}function viewAssetsBasePath(basePath,viewName){return`${pathUnderBase(basePath,`_mcp-use/views/${viewName}`)}/`}function resolveExternalAssetUrl(assetPath,assetsBase,basePath,viewName){return assetPath.startsWith("http://")||assetPath.startsWith("https://")||assetPath.startsWith("data:")?assetPath:assetPath.startsWith("/")?resolveAssetUrl(assetPath,assetsBase):`${assetsBase}${viewAssetsBasePath(basePath,viewName)}${assetPath.replace(/^\/+/,"")}`}function resolvePublicBase(assetsBase,basePath){return`${assetsBase}${pathUnderBase(basePath,"_mcp-use/public")}/`}function escapeInlineScript(code){return code.replaceAll(/<\/script/gi,"<\\/script").replaceAll("<!--","\\x3C!--")}function escapeInlineStyle(css2){return css2.replaceAll(/<\/style/gi,"<\\/style")}function escapeHtml(value){return value.replaceAll("&","&amp;").replaceAll('"',"&quot;").replaceAll("<","&lt;").replaceAll(">","&gt;")}var TRANSPARENT_IFRAME_STYLE="<style>html,body,#root{background:transparent}</style>";function synthesizeViewDocument(entry,assetsBase,basePath,viewName){let viewConfig={publicBase:resolvePublicBase(assetsBase,basePath)},configScript=`<script>globalThis.__mcpUseViewConfig=${JSON.stringify(viewConfig)};</script>`;if(entry.kind==="inline"){let styleTag=entry.css.length>0?`<style>${escapeInlineStyle(entry.css)}</style>`:"",moduleScript=`<script type="module">${escapeInlineScript(entry.js)}</script>`;return`<!doctype html>
734
+ `,{flag:"wx",mode:384}),{id:created,stability:"server"}}catch{let raced=await read();if(raced!==void 0)return{id:raced,stability:"server"}}}catch{}return{id:runtimeId,stability:"process"}})();return identities.set(serverRoot,resolving),resolving}function capture(feature,action,properties,options,resolveIdentity){let validationId=safeEnv("MCP_USE_TELEMETRY_VALIDATION_ID");if(disabled()||env("NODE_ENV")==="test"&&validationId===void 0||pending.size>=16)return;if(options.onceKey!==void 0){if(once.has(options.onceKey))return;once.add(options.onceKey)}let rate=Math.max(0,Math.min(1,options.sampleRate??1));if(validationId===void 0&&Math.random()>=rate)return;let request=(async()=>{try{let resolvedIdentity=await resolveIdentity(),body=JSON.stringify({api_key:TOKEN,event:EVENT,properties:{...clean(properties),feature,action,sdk_generation:"v2",telemetry_schema_version:2,sdk_package:"mcp-use",sdk_version:"2.0.0-beta.59",server_id:resolvedIdentity.id,runtime_id:runtimeId,identity_stability:resolvedIdentity.stability,distinct_id:resolvedIdentity.id,sample_rate:validationId===void 0?rate:1,$process_person_profile:!1,$geoip_disable:!0,...validationId!==void 0&&{is_validation:!0,validation_run_id:validationId}}});await fetch(ENDPOINT,{method:"POST",headers:{"content-type":"application/json"},keepalive:!0,body})}catch{return}})();pending.add(request),request.then(()=>pending.delete(request))}function recordUsage(feature,action,properties={},options={}){capture(feature,action,properties,options,()=>identity(options.serverRoot))}var registerViews=Symbol("mcp-use/registerViews");function resolveAssetUrl(assetPath,origin){if(!assetPath.startsWith("/"))throw new Error(`View manifest asset path must be origin-absolute (start with "/"); got ${JSON.stringify(assetPath)}`);return`${origin}${assetPath}`}function viewAssetsBasePath(basePath,viewName){return`${pathUnderBase(basePath,`_mcp-use/views/${viewName}`)}/`}function resolveExternalAssetUrl(assetPath,assetsBase,basePath,viewName){return assetPath.startsWith("http://")||assetPath.startsWith("https://")||assetPath.startsWith("data:")?assetPath:assetPath.startsWith("/")?resolveAssetUrl(assetPath,assetsBase):`${assetsBase}${viewAssetsBasePath(basePath,viewName)}${assetPath.replace(/^\/+/,"")}`}function resolvePublicBase(assetsBase,basePath){return`${assetsBase}${pathUnderBase(basePath,"_mcp-use/public")}/`}function escapeInlineScript(code){return code.replaceAll(/<\/script/gi,"<\\/script").replaceAll("<!--","\\x3C!--")}function escapeInlineStyle(css2){return css2.replaceAll(/<\/style/gi,"<\\/style")}function escapeHtml(value){return value.replaceAll("&","&amp;").replaceAll('"',"&quot;").replaceAll("<","&lt;").replaceAll(">","&gt;")}var VIEW_BOOTSTRAP_STYLE=`<style>
735
+ html,body,#root{background:transparent}
736
+ html,body{margin:0}
737
+ #root[data-mcp-use-loading]{display:flex;min-height:100vh;align-items:center;justify-content:center;flex-direction:column;gap:10px}
738
+ #root[data-mcp-use-loading]::before{width:24px;height:24px;box-sizing:border-box;border:2px solid rgba(127,127,127,.28);border-top-color:rgba(127,127,127,.9);border-radius:50%;content:"";animation:mcp-use-view-spin .7s linear infinite}
739
+ #root[data-mcp-use-loading]::after{color:rgba(127,127,127,.9);content:"Compiling...";font:500 13px/1.2 ui-sans-serif,system-ui,sans-serif}
740
+ @keyframes mcp-use-view-spin{to{transform:rotate(360deg)}}
741
+ @media (prefers-reduced-motion:reduce){#root[data-mcp-use-loading]::before{animation-duration:1.4s}}
742
+ </style>`;function synthesizeViewDocument(entry,assetsBase,basePath,viewName){let viewConfig={publicBase:resolvePublicBase(assetsBase,basePath)},configScript=`<script>globalThis.__mcpUseViewConfig=${JSON.stringify(viewConfig)};</script>`;if(entry.kind==="inline"){let styleTag=entry.css.length>0?`<style>${escapeInlineStyle(entry.css)}</style>`:"",moduleScript=`<script type="module">${escapeInlineScript(entry.js)}</script>`;return`<!doctype html>
735
743
  <html>
736
744
  <head>
737
745
  <meta charset="utf-8">
738
746
  ${configScript}
739
- ${TRANSPARENT_IFRAME_STYLE}
747
+ ${VIEW_BOOTSTRAP_STYLE}
740
748
  ${styleTag}
741
749
  </head>
742
750
  <body>
743
- <div id="root"></div>
751
+ <div id="root" data-mcp-use-loading></div>
744
752
  ${moduleScript}
745
753
  </body>
746
754
  </html>`}if(viewName===void 0)throw new Error("viewName is required when synthesizing an external view document.");let cssLinks=entry.css.map(path=>`<link rel="stylesheet" href="${escapeHtml(resolveExternalAssetUrl(path,assetsBase,basePath,viewName))}">`).join(`
@@ -750,11 +758,11 @@ ${moduleScript}
750
758
  <head>
751
759
  <meta charset="utf-8">
752
760
  ${configScript}
753
- ${TRANSPARENT_IFRAME_STYLE}
761
+ ${VIEW_BOOTSTRAP_STYLE}
754
762
  ${cssLinks}
755
763
  </head>
756
764
  <body>
757
- <div id="root"></div>
765
+ <div id="root" data-mcp-use-loading></div>
758
766
  ${scriptTags}
759
767
  <script type="module" src="${escapeHtml(entryUrl)}"></script>
760
768
  </body>
package/dist/index.js CHANGED
@@ -1,17 +1,25 @@
1
- import{resolvePublicFilePath,servePublicFile}from"./chunk-ZMU5USAZ.js";import{hasExplicitAssetsBase,originFromAssetsBase,resolveAssetsBase,resolveServerOrigin}from"./chunk-PSKSL567.js";import{registerOpenAPITools}from"./chunk-Y26DNVWA.js";import{completable,normalizeCompletions}from"./chunk-OJF6B5EU.js";import{isUsageDisabled,recordUsage}from"./chunk-P5GGJGEQ.js";import{inheritBufferedResponse,toNodeHandler,trackBufferedResponse}from"./chunk-XYHHP43G.js";import{authInfoFromRequest,composeFetch,getOAuthProtectedResourceMetadataUrl,getRequestBag,hostValidationMiddleware,isHtmlNavigationRequest,jsonBodyMiddleware,matchesPath,matchesPathPrefix,oauthMetadata,originValidationMiddleware,pathUnderBase,pathnameOf,requireBearerAuth}from"./chunk-MIZQEWZS.js";import{getOAuthProviderOptions,resolveConfiguredOAuthResource,resolveLocalOAuthResource,wrapOAuthTokenVerifier}from"./chunk-IS7FKXFR.js";import{localhostAllowedHostnames,localhostAllowedOrigins,McpServer as SdkMcpServer,ResourceTemplate,CLIENT_CAPABILITIES_META_KEY as CLIENT_CAPABILITIES_META_KEY3,CLIENT_INFO_META_KEY as CLIENT_INFO_META_KEY3,PROTOCOL_VERSION_META_KEY,isJSONRPCRequest as isJSONRPCRequest2,isInputRequiredResult as isInputRequiredResult2}from"@modelcontextprotocol/server";import{createServer as createNodeHttpServer}from"#mcp-use-node-http";import{Hono}from"hono";var FAVICON_CACHE_CONTROL="public, max-age=31536000, immutable",FAVICON_REDIRECT_CACHE_CONTROL="public, max-age=300";function protocolOf(value){return/^([a-z][a-z\d+.-]*):/i.exec(value)?.[1]?.toLowerCase()}function publicAssetPath(basePath,source){return`${basePath==="/"?"":basePath}/_mcp-use/public/${source.split("/").map(segment=>encodeURIComponent(segment)).join("/")}`}function isLocalPublicSource(source){return protocolOf(source)===void 0}function selectFaviconFromIcons(icons){return icons[0]}function assertLocalPublicSource(source,field){if(source.startsWith("/")||source.includes("\\")||source.includes("?")||source.includes("#")||source.split("/").some(segment=>segment===""||segment===".."))throw new TypeError(`${field} must be an http(s) URL, image data URL, or safe path relative to public/`)}function parseDataImage(source,field){let comma=source.indexOf(",");if(comma<0)throw new TypeError(`${field} must be a valid image data URL`);let metadata=source.slice(5,comma),payload=source.slice(comma+1),parts=metadata.split(";"),mimeType=parts[0]?.toLowerCase()??"";if(!mimeType.startsWith("image/"))throw new TypeError(`${field} data URL must use an image MIME type`);try{if(parts.includes("base64")){let binary2=atob(payload);return{mimeType,bytes:Uint8Array.from(binary2,character=>character.charCodeAt(0))}}return{mimeType,bytes:new TextEncoder().encode(decodeURIComponent(payload))}}catch{throw new TypeError(`${field} must be a valid image data URL`)}}function assertBrandingSource(source,field){if(typeof source!="string"||source.length===0)throw new TypeError(`${field} must be a non-empty string`);let protocol=protocolOf(source);if(protocol===void 0)return assertLocalPublicSource(source,field),source;if(protocol==="data")return parseDataImage(source,field),source;if(protocol!=="http"&&protocol!=="https")throw new TypeError(`${field} must be an http(s) URL, image data URL, or safe path relative to public/`);try{new URL(source)}catch{throw new TypeError(`${field} must be a valid absolute http(s) URL`)}return source}function normalizeServerBranding(config){let websiteUrl;if(config.websiteUrl!==void 0){if(typeof config.websiteUrl!="string"||config.websiteUrl.length===0)throw new TypeError("websiteUrl must be a non-empty absolute http(s) URL");let parsed;try{parsed=new URL(config.websiteUrl)}catch{throw new TypeError("websiteUrl must be a non-empty absolute http(s) URL")}if(parsed.protocol!=="http:"&&parsed.protocol!=="https:")throw new TypeError("websiteUrl must be a non-empty absolute http(s) URL");websiteUrl=config.websiteUrl}let icons;if(config.icons!==void 0){if(!Array.isArray(config.icons))throw new TypeError("icons must be an array of MCP Icon objects");icons=Object.freeze(config.icons.map((value,index)=>{if(typeof value!="object"||value===null)throw new TypeError(`icons[${index}] must be an MCP Icon object`);let icon=value,src=assertBrandingSource(icon.src,`icons[${index}].src`),mimeType=icon.mimeType;if(mimeType!==void 0&&(typeof mimeType!="string"||!mimeType.toLowerCase().startsWith("image/")))throw new TypeError(`icons[${index}].mimeType must be an image MIME type when provided`);let sizes=icon.sizes;if(sizes!==void 0&&(!Array.isArray(sizes)||sizes.some(size=>typeof size!="string"||size.length===0)))throw new TypeError(`icons[${index}].sizes must be an array of non-empty strings when provided`);let normalizedSizes=sizes===void 0?void 0:sizes.map(size=>size),theme=icon.theme;if(theme!==void 0&&theme!=="light"&&theme!=="dark")throw new TypeError(`icons[${index}].theme must be "light" or "dark" when provided`);return Object.freeze({src,...mimeType!==void 0&&{mimeType},...normalizedSizes!==void 0&&{sizes:Object.freeze(normalizedSizes)},...theme!==void 0&&{theme}})}))}let explicitFavicon=config.favicon===void 0?void 0:assertBrandingSource(config.favicon,"favicon"),inferred=explicitFavicon===void 0?selectFaviconFromIcons(icons??[]):void 0,favicon=explicitFavicon??inferred?.src,faviconMimeType=inferred?.mimeType??icons?.find(icon=>icon.src===explicitFavicon)?.mimeType;return Object.freeze({...favicon!==void 0&&{favicon},...faviconMimeType!==void 0&&{faviconMimeType},...icons!==void 0&&{icons},...websiteUrl!==void 0&&{websiteUrl}})}function resolveImplementationIcons(icons,request,basePath){if(icons!==void 0)return icons.map(icon=>({...icon,src:request!==void 0&&isLocalPublicSource(icon.src)?`${resolveAssetsBase(request)}${publicAssetPath(basePath,icon.src)}`:icon.src,...icon.sizes!==void 0&&{sizes:[...icon.sizes]}}))}function hasLocalBrandingAsset(branding){return branding.favicon!==void 0&&isLocalPublicSource(branding.favicon)||branding.icons?.some(icon=>isLocalPublicSource(icon.src))===!0}function createFaviconHandler(branding,options){let source=branding.favicon;if(source!==void 0)return async request=>{if(request.method!=="GET"&&request.method!=="HEAD")return new Response("Method Not Allowed",{status:405,headers:{Allow:"GET, HEAD"}});if(new URL(request.url).pathname!=="/favicon.ico")return new Response("Not Found",{status:404});let protocol=protocolOf(source);if(protocol==="http"||protocol==="https")return new Response(null,{status:307,headers:{Location:source,"Cache-Control":FAVICON_REDIRECT_CACHE_CONTROL}});if(protocol==="data"){let data=parseDataImage(source,"favicon");return new Response(request.method==="HEAD"?null:data.bytes.buffer,{status:200,headers:{"Content-Type":branding.faviconMimeType??data.mimeType,"Cache-Control":FAVICON_CACHE_CONTROL,"X-Content-Type-Options":"nosniff"}})}let{join}=await import("path"),publicRoot=options.dev?join(options.projectRoot,"public"):join(options.projectRoot,".mcp-use/build/views/public"),diskPath=await resolvePublicFilePath(publicRoot,source);if(diskPath===null)return new Response("Not Found",{status:404,headers:{"Cache-Control":"no-store"}});let response=await servePublicFile(diskPath,{...options.deferCors===!0&&{deferCors:!0},...request.method==="HEAD"&&{head:!0}});return response.headers.set("Cache-Control",FAVICON_CACHE_CONTROL),response.headers.set("X-Content-Type-Options","nosniff"),branding.faviconMimeType!==void 0&&response.headers.set("Content-Type",branding.faviconMimeType),response}}function assertServerConfig(config){if(config.basePath!==void 0){if(typeof config.basePath!="string")throw new TypeError("basePath must be an absolute URL pathname without empty segments, trailing slash, query, fragment, or whitespace");let{basePath}=config;if(!basePath.startsWith("/")||basePath.includes("?")||basePath.includes("#")||/\s/.test(basePath)||basePath.includes("//")||basePath.length>1&&basePath.endsWith("/"))throw new TypeError("basePath must be an absolute URL pathname without empty segments, trailing slash, query, fragment, or whitespace")}if(config.port!==void 0&&(typeof config.port!="number"||!Number.isInteger(config.port)||config.port<0||config.port>65535))throw new TypeError("port must be an integer between 0 and 65535")}var DEFAULT_LISTEN_HOST="127.0.0.1";function resolveListenHost(explicitHost,configuredHost,env=process.env){if(explicitHost!==void 0)return explicitHost;let envHost=env.HOST?.trim();return envHost!==void 0&&envHost!==""?envHost:configuredHost??DEFAULT_LISTEN_HOST}function resolveListenPort(explicitPort,configuredPort,env=process.env){if(explicitPort!==void 0)return explicitPort;let envPort=parsePort(env.PORT);return envPort!==void 0?envPort:configuredPort??3e3}function parsePort(value){if(value===void 0||value.trim()==="")return;let port=Number(value);return Number.isInteger(port)&&port>=0&&port<=65535?port:void 0}import{CLIENT_CAPABILITIES_META_KEY as CLIENT_CAPABILITIES_META_KEY2,CLIENT_INFO_META_KEY,inputRequired,inputResponse}from"@modelcontextprotocol/server";import{HonoRequest}from"hono/request";import{CLIENT_CAPABILITIES_META_KEY}from"@modelcontextprotocol/server";var UI_EXTENSION_ID="io.modelcontextprotocol/ui",UI_MIME_TYPE="text/html;profile=mcp-app",UI_RESOURCE_URI_PREFIX="ui://views/";var UI_RESOURCE_URI_META_KEY="ui/resourceUri";function viewResourceUri(viewName){return`${UI_RESOURCE_URI_PREFIX}${viewName}.html`}var clientCapabilitiesByRequest=new WeakMap;function stashClientCapabilities(request,capabilities){clientCapabilitiesByRequest.set(request,capabilities)}function extractClientCapabilitiesFromBody(body){if(typeof body!="object"||body===null)return;let params=body.params;if(typeof params!="object"||params===null)return;let meta=params._meta;if(typeof meta!="object"||meta===null)return;let capabilities=meta[CLIENT_CAPABILITIES_META_KEY];if(!(typeof capabilities!="object"||capabilities===null))return capabilities}function supportsViews(capabilities){let extensions=capabilities?.extensions;if(extensions===void 0)return!1;let uiExtension=extensions[UI_EXTENSION_ID];if(typeof uiExtension!="object"||uiExtension===null)return!1;let mimeTypes=uiExtension.mimeTypes;return Array.isArray(mimeTypes)?mimeTypes.includes(UI_MIME_TYPE):!1}function requireOAuthAuthInfo(authInfo){if(authInfo===void 0||authInfo.extra===void 0||authInfo.expiresAt===void 0)throw new Error("OAuth callback did not receive mapped AuthInfo.extra")}function stringValue(value){return typeof value=="string"?value:void 0}function coordinateValue(value){return typeof value=="string"||typeof value=="number"&&Number.isFinite(value)?value:void 0}function normalizeUserContext(meta){if(meta===void 0)return;let locale=stringValue(meta["openai/locale"])??stringValue(meta["webplus/i18n"]),userAgent=stringValue(meta["openai/userAgent"]),subject=stringValue(meta["openai/subject"]),conversationId=stringValue(meta["openai/session"]),organizationId=stringValue(meta["openai/organization"]),rawLocation=meta["openai/userLocation"],location;if(typeof rawLocation=="object"&&rawLocation!==null&&!Array.isArray(rawLocation)){let values=rawLocation,normalized={city:stringValue(values.city),region:stringValue(values.region),country:stringValue(values.country),timezone:stringValue(values.timezone),latitude:coordinateValue(values.latitude),longitude:coordinateValue(values.longitude)},entries=Object.entries(normalized).filter(entry=>entry[1]!==void 0);entries.length>0&&(location=Object.fromEntries(entries))}if(!(locale===void 0&&userAgent===void 0&&location===void 0&&subject===void 0&&conversationId===void 0&&organizationId===void 0))return{...locale!==void 0&&{locale},...userAgent!==void 0&&{userAgent},...location!==void 0&&{location},...subject!==void 0&&{subject},...conversationId!==void 0&&{conversationId},...organizationId!==void 0&&{organizationId}}}function toClientContext(ctx){let envelope=ctx.mcpReq.envelope,capabilities={...envelope?.[CLIENT_CAPABILITIES_META_KEY2]??{}},info={...envelope?.[CLIENT_INFO_META_KEY]??{}},user=normalizeUserContext(ctx.mcpReq._meta);return{can(capability){return Object.hasOwn(capabilities,capability)},capabilities(){return{...capabilities}},extension(id){let settings=capabilities.extensions?.[id];return settings===void 0?void 0:{...settings}},info(){return{...info}},user(){return user===void 0?void 0:{...user,...user.location!==void 0&&{location:{...user.location}}}},supportsViews(){return supportsViews(capabilities)}}}function createElicit(inputResponses){return async function(key,message,schemaOrUrl){let request,formSchema;if(typeof schemaOrUrl=="string")request=inputRequired.elicitUrl({message,url:schemaOrUrl});else if(schemaOrUrl!==void 0)formSchema=schemaOrUrl,request=inputRequired.elicit({message,requestedSchema:schemaOrUrl});else throw new TypeError("ctx.elicit(key, message, value) requires a form schema or URL string");let response=inputResponse(inputResponses,key);if(response.kind==="elicit"){if(response.action!=="accept")return{status:response.action};if(formSchema===void 0)return{status:"accept"};if(response.content!==void 0){let outcome=await formSchema["~standard"].validate(response.content);if(outcome.issues===void 0)return{status:"accept",data:outcome.value}}}return{status:"required",result:inputRequired({inputRequests:{[key]:request}})}}}function toRequestContext(ctx){let rawRequest=ctx.http?.req,http=rawRequest===void 0?void 0:getRequestBag(rawRequest).honoContext,request=http?.req??(rawRequest===void 0?void 0:new HonoRequest(rawRequest)),additions={signal:ctx.mcpReq.signal,...request!==void 0&&{request},...ctx.mcpReq.inputResponses!==void 0&&{inputResponses:ctx.mcpReq.inputResponses},client:toClientContext(ctx),elicit:createElicit(ctx.mcpReq.inputResponses),requestState:()=>ctx.mcpReq.requestState(),async sendNotification(method,params){await ctx.mcpReq.notify({method,...params!==void 0&&{params}})},async reportProgress(progress,total,message){let progressToken=ctx.mcpReq._meta?.progressToken;return progressToken===void 0?!1:(await ctx.mcpReq.notify({method:"notifications/progress",params:{progressToken,progress,...total!==void 0&&{total},...message!==void 0&&{message}}}),!0)},async sendLog(level,data,logger){await ctx.mcpReq.notify({method:"notifications/message",params:{level,data,...logger!==void 0&&{logger}}})}};return http!==void 0?Object.assign(http,additions):{...additions,...request!==void 0&&{req:request}}}function toAuthenticatedRequestContext(ctx){let authInfo=ctx.http?.authInfo;return requireOAuthAuthInfo(authInfo),Object.assign(toRequestContext(ctx),{auth:{user:authInfo.extra.user,payload:authInfo.extra.payload,accessToken:authInfo.token,scopes:[...authInfo.scopes],permissions:[...authInfo.extra.permissions],...authInfo.clientId.length>0&&{clientId:authInfo.clientId},expiresAt:authInfo.expiresAt,...authInfo.resource!==void 0&&{resource:authInfo.resource}}})}function isReadResourceResult(result){return"contents"in result&&Array.isArray(result.contents)}function isGetPromptResult(result){return"messages"in result&&Array.isArray(result.messages)}function toResourceResult(result,uri){if(isReadResourceResult(result))return result;let mime=result._meta&&typeof result._meta=="object"&&typeof result._meta.mimeType=="string"?result._meta.mimeType:void 0,contents=[];for(let block of result.content??[]){let mapped=contentBlockToResourceContents(block,uri,mime);mapped!==void 0&&contents.push(mapped)}return contents.length===0&&result.structuredContent!==void 0&&contents.push({uri,mimeType:"application/json",text:JSON.stringify(result.structuredContent)}),contents.length===0&&contents.push({uri,mimeType:"text/plain",text:""}),{contents}}function contentBlockToResourceContents(block,uri,mimeHint){if(block.type==="text")return{uri,mimeType:mimeHint??"text/plain",text:block.text};if(block.type==="image"||block.type==="audio")return{uri,mimeType:block.mimeType,blob:block.data};if(block.type==="resource")return{...block.resource}}function toPromptResult(result){if(isGetPromptResult(result))return result;let messages=(result.content??[]).map(content=>({role:"user",content}));return messages.length===0&&result.structuredContent!==void 0&&messages.push({role:"user",content:{type:"text",text:JSON.stringify(result.structuredContent)}}),messages.length===0&&messages.push({role:"user",content:{type:"text",text:""}}),{messages}}var DEFAULT_METHODS=["GET","HEAD","POST","OPTIONS"],DEFAULT_ALLOWED_HEADERS=["Content-Type","Authorization","mcp-protocol-version","mcp-method","mcp-name"];function resolveAllowedOrigin(origin,requestOrigin){return origin===void 0?requestOrigin:typeof origin=="function"?origin(requestOrigin):origin==="*"?"*":Array.isArray(origin)?requestOrigin!==null&&origin.includes(requestOrigin)?requestOrigin:null:origin}function corsHeaders(options,request){if(request.headers.has("Access-Control-Allow-Origin"))return;let requestOrigin=request.headers.get("Origin"),allowedOrigin=resolveAllowedOrigin(options.origin,requestOrigin);if(allowedOrigin===null)return;let headers={"Access-Control-Allow-Origin":allowedOrigin,"Access-Control-Allow-Methods":options.methods.join(", "),"Access-Control-Allow-Headers":options.allowedHeaders.join(", ")};return options.credentials&&(headers["Access-Control-Allow-Credentials"]="true"),allowedOrigin!=="*"&&(headers.Vary="Origin"),headers}function mergeCorsHeaders(response,headers){if(response.headers.has("Access-Control-Allow-Origin"))return response;let merged=new Headers(response.headers);return new Headers(headers).forEach((value,key)=>{merged.set(key,value)}),inheritBufferedResponse(response,new Response(response.body,{status:response.status,statusText:response.statusText,headers:merged}))}function corsFetchMiddleware(options){if(!(options.enabled!==!1))return async(_request,next)=>next();let resolved={...options.origin!==void 0&&{origin:options.origin},methods:options.methods??DEFAULT_METHODS,allowedHeaders:options.allowedHeaders??DEFAULT_ALLOWED_HEADERS,credentials:options.credentials??!1};return async(request,next)=>{let headers=corsHeaders(resolved,request);if(headers===void 0)return next();if(request.method==="OPTIONS")return new Response(null,{status:204,headers});let response=await next();return mergeCorsHeaders(response,headers)}}function isGlobalCorsEnabled(cors){return cors!==void 0&&cors.enabled!==!1}import{CallToolResultSchema,GetPromptResultSchema,ListPromptsResultSchema,ListResourcesResultSchema,ListToolsResultSchema,ReadResourceResultSchema}from"@modelcontextprotocol/core";import{isInputRequiredResult}from"@modelcontextprotocol/server";var MCP_MIDDLEWARE_METHODS=["tools/call","tools/list","resources/read","resources/list","prompts/get","prompts/list"];function withMcpMiddlewareParams(request,params){if(typeof request!="object"||request===null||Array.isArray(request))throw new TypeError("[mcp-use] MCP middleware received an invalid downstream request");return{...request,params}}function createMcpMiddlewareEntry(pattern,handler){let normalizedPattern=normalizeMcpMiddlewarePattern(pattern),invoke=handler;if(normalizedPattern!=="*"&&!isMcpMiddlewareMethod(normalizedPattern))throw new TypeError(`Unsupported MCP middleware pattern "${pattern}". Use an exact MCP method or "mcp:*".`);return normalizedPattern==="*"?{pattern:normalizedPattern,handler:async(ctx,next)=>{let downstreamCalled=!1,downstreamResult;if(await invoke(ctx,async()=>{downstreamResult=await next(),downstreamCalled=!0}),!downstreamCalled)throw new Error(`Wildcard MCP middleware "${normalizedPattern}" must call next()`);return downstreamResult}}:{pattern:normalizedPattern,handler:(ctx,next)=>invoke(ctx,next)}}function createMcpEventListenerEntry(pattern,handler){let{pattern:normalizedPattern,phase}=parseMcpPattern(pattern),invoke=handler;return{pattern:normalizedPattern,phase,handler:(ctx,result)=>invoke(ctx,result)}}function matchesPattern(pattern,method){if(pattern==="*")return!0;if(pattern.endsWith("/*")){let prefix=pattern.slice(0,-1);return method.startsWith(prefix)}return pattern===method}function isMcpMiddlewareMethod(value){return MCP_MIDDLEWARE_METHODS.some(method=>method===value)}function composeMiddleware(entries,method,innerFn){let matching=entries.filter(entry=>matchesPattern(entry.pattern,method));return matching.length===0?_ctx=>innerFn():ctx=>{let index=-1,dispatch=i=>i<=index?Promise.reject(new Error("next() called multiple times")):(index=i,i===matching.length?innerFn():matching[i].handler(ctx,()=>dispatch(i+1)));return dispatch(0)}}function freezeMiddlewareContext(ctx){return Object.freeze({method:ctx.method,params:Object.freeze({...ctx.params}),...ctx.request!==void 0&&{request:ctx.request},...ctx.req!==void 0&&{req:ctx.req},...ctx.session!==void 0&&{session:Object.freeze({...ctx.session})},...ctx.auth!==void 0&&{auth:ctx.auth},state:new Map(ctx.state)})}async function runMcpOperation(middlewares,events,method,ctx,innerFn){dispatchMcpEvents(events,method,"before",ctx);let result=await composeMiddleware(middlewares,method,innerFn)(ctx);return assertValidMiddlewareResult(method,result),dispatchMcpEvents(events,method,"complete",ctx,result),result}function assertValidMiddlewareResult(method,result){if((method==="tools/call"||method==="resources/read"||method==="prompts/get")&&isInputRequiredResult(result))return;let validation=(()=>{switch(method){case"tools/call":return assertArrayProperty(method,result,"content"),CallToolResultSchema.safeParse(result);case"tools/list":return assertArrayResult(method,result),ListToolsResultSchema.safeParse({tools:result});case"resources/read":return assertArrayProperty(method,result,"contents"),ReadResourceResultSchema.safeParse(result);case"resources/list":return assertArrayResult(method,result),ListResourcesResultSchema.safeParse({resources:result});case"prompts/get":return assertArrayProperty(method,result,"messages"),GetPromptResultSchema.safeParse(result);case"prompts/list":return assertArrayResult(method,result),ListPromptsResultSchema.safeParse({prompts:result});default:throw new TypeError(`Unsupported MCP middleware method "${method}"`)}})();if(!validation.success)throw new TypeError(`[mcp-use] ${method} middleware returned an invalid result: ${validation.error.message}`)}function assertArrayResult(method,result){if(!Array.isArray(result))throw new TypeError(`[mcp-use] ${method} middleware returned an invalid result: expected an array`)}function assertArrayProperty(method,result,property){if(typeof result!="object"||result===null||!Array.isArray(result[property]))throw new TypeError(`[mcp-use] ${method} middleware returned an invalid result: expected a ${property} array`)}function dispatchMcpEvents(events,method,phase,ctx,result){let frozen=freezeMiddlewareContext(ctx);for(let entry of events)if(!(entry.phase!==phase||!matchesPattern(entry.pattern,method)))try{entry.handler(frozen,result)}catch(error2){console.error(`[mcp-use] MCP event listener for "${entry.pattern}" (${phase}) threw:`,error2)}}function parseMcpPattern(raw){let pattern=raw.startsWith("mcp:")?raw.slice(4):raw;return pattern.endsWith(":complete")?{pattern:pattern.slice(0,-9),phase:"complete"}:{pattern,phase:"before"}}function normalizeMcpMiddlewarePattern(raw){return raw.startsWith("mcp:")?raw.slice(4):raw}import{CLIENT_INFO_META_KEY as CLIENT_INFO_META_KEY2,isJSONRPCRequest}from"@modelcontextprotocol/server";function colorsEnabled(){return typeof process>"u"||process.env?.NO_COLOR!==void 0?!1:process.stdout?.isTTY===!0}function ansi(open,close){return text2=>colorsEnabled()?`\x1B[${open}m${text2}\x1B[${close}m`:text2}var bold=ansi(1,22),dim=ansi(2,22),red=ansi(31,39),green=ansi(32,39),yellow=ansi(33,39),blue=ansi(34,39),magenta=ansi(35,39),cyan=ansi(36,39),gray=ansi(90,39);function resolveLogLevel(configured){let raw=typeof process>"u"?void 0:process.env?.MCP_USE_LOG_LEVEL?.toLowerCase();return raw==="info"||raw==="debug"||raw==="trace"?raw:configured??"info"}function formatClientInfo(info){if(info!==void 0)return typeof info.version=="string"&&info.version!==""?`${info.name}/${info.version}`:info.name}var detailFormatters={initialize:p=>({subject:formatClientInfo(p.clientInfo)}),ping:()=>({}),"server/discover":()=>({}),"completion/complete":p=>({subject:p.ref.type==="ref/prompt"?p.ref.name:p.ref.uri,input:p.argument}),"logging/setLevel":p=>({subject:p.level}),"prompts/get":p=>({subject:p.name,input:p.arguments}),"prompts/list":()=>({}),"resources/list":()=>({}),"resources/templates/list":()=>({}),"resources/read":p=>({subject:p.uri}),"resources/subscribe":p=>({subject:p.uri}),"resources/unsubscribe":p=>({subject:p.uri}),"subscriptions/listen":()=>({}),"tools/call":p=>({subject:p.name,input:p.arguments}),"tools/list":()=>({}),"sampling/createMessage":()=>({}),"elicitation/create":()=>({}),"roots/list":()=>({})};function isKnownMethod(method){return Object.prototype.hasOwnProperty.call(detailFormatters,method)}function formatDetail(message){if(!isKnownMethod(message.method))return{};try{let formatter=detailFormatters[message.method],detail=formatter(message.params);return typeof detail.subject=="string"||detail.subject===void 0?detail:{}}catch{return{}}}var INLINE_JSON_MAX_LENGTH=80;function inlineJson(value){let text2;try{text2=JSON.stringify(value)??String(value)}catch{text2=String(value)}return text2.length>INLINE_JSON_MAX_LENGTH?`${text2.slice(0,INLINE_JSON_MAX_LENGTH)}...`:text2}function formatClientIdentity(message){let meta=message.params?._meta;if(meta===void 0)return;let info=meta[CLIENT_INFO_META_KEY2];if(!(typeof info!="object"||info===null||typeof info.name!="string"))return formatClientInfo(info)}function sanitize(text2){return text2.replace(/[\u0000-\u001F\u007F-\u009F]+/g," ")}function methodStyle(method){return method.startsWith("tools/")?cyan:method.startsWith("resources/")?green:method.startsWith("prompts/")?magenta:method==="initialize"||method==="ping"?gray:blue}var REDACTED_HEADERS=new Set(["authorization","proxy-authorization","cookie","set-cookie","x-api-key"]);function redactHeaders(headers){return Object.fromEntries(Object.entries(headers).map(([name,value])=>[name,REDACTED_HEADERS.has(name.toLowerCase())?"[REDACTED]":value]))}async function extractResponseOutcome(res){if(!res.body)return{errorMessage:null};let text2;try{text2=await res.clone().text()}catch{return{errorMessage:null}}if(!text2)return{errorMessage:null};let isSse=(res.headers.get("content-type")??"").includes("text/event-stream"),payloads=[],tryParse=raw=>{try{payloads.push(JSON.parse(raw))}catch{}};if(isSse){for(let line of text2.split(/\r?\n/))if(line.startsWith("data:")){let data=line.slice(5).trim();data&&tryParse(data)}}else tryParse(text2);let result;for(let payload of payloads){if(payload===null||typeof payload!="object")continue;let message=payload;if(typeof message.error?.message=="string")return{errorMessage:message.error.message};if(message.result?.isError===!0){let textBlock=(Array.isArray(message.result.content)?message.result.content:[]).find(b=>b?.type==="text"&&typeof b.text=="string");return{errorMessage:textBlock?String(textBlock.text):"tool error"}}"result"in message&&(result=message.result)}return{errorMessage:null,result}}function compactToolResult(result){if(result===null||typeof result!="object")return result;let{structuredContent,content}=result;if(structuredContent!==void 0)return structuredContent;if(Array.isArray(content)){let[block]=content;if(content.length===1&&block?.type==="text")return block.text}return content}function formatForDump(value){function truncate(val){return typeof val=="string"&&val.length>100?`${val.slice(0,100)}...`:Array.isArray(val)?val.map(truncate):val!==null&&typeof val=="object"?Object.fromEntries(Object.entries(val).map(([k,v])=>[k,truncate(v)])):val}try{return JSON.stringify(truncate(value),null,2)}catch{return String(value)}}var DUMP_BODY_MAX_LENGTH=1e4;async function printTraceDump(response,requestHeaders,requestBody,readResponseBody){console.log(`
1
+ import{resolvePublicFilePath,servePublicFile}from"./chunk-ZMU5USAZ.js";import{hasExplicitAssetsBase,originFromAssetsBase,resolveAssetsBase,resolveServerOrigin}from"./chunk-PSKSL567.js";import{registerOpenAPITools}from"./chunk-Y26DNVWA.js";import{completable,normalizeCompletions}from"./chunk-OJF6B5EU.js";import{isUsageDisabled,recordUsage}from"./chunk-5FRWUAFA.js";import{inheritBufferedResponse,toNodeHandler,trackBufferedResponse}from"./chunk-XYHHP43G.js";import{authInfoFromRequest,composeFetch,getOAuthProtectedResourceMetadataUrl,getRequestBag,hostValidationMiddleware,isHtmlNavigationRequest,jsonBodyMiddleware,matchesPath,matchesPathPrefix,oauthMetadata,originValidationMiddleware,pathUnderBase,pathnameOf,requireBearerAuth}from"./chunk-MIZQEWZS.js";import{getOAuthProviderOptions,resolveConfiguredOAuthResource,resolveLocalOAuthResource,wrapOAuthTokenVerifier}from"./chunk-IS7FKXFR.js";import{localhostAllowedHostnames,localhostAllowedOrigins,McpServer as SdkMcpServer,ResourceTemplate,CLIENT_CAPABILITIES_META_KEY as CLIENT_CAPABILITIES_META_KEY3,CLIENT_INFO_META_KEY as CLIENT_INFO_META_KEY3,PROTOCOL_VERSION_META_KEY,isJSONRPCRequest as isJSONRPCRequest2,isInputRequiredResult as isInputRequiredResult2}from"@modelcontextprotocol/server";import{createServer as createNodeHttpServer}from"#mcp-use-node-http";import{Hono}from"hono";var FAVICON_CACHE_CONTROL="public, max-age=31536000, immutable",FAVICON_REDIRECT_CACHE_CONTROL="public, max-age=300";function protocolOf(value){return/^([a-z][a-z\d+.-]*):/i.exec(value)?.[1]?.toLowerCase()}function publicAssetPath(basePath,source){return`${basePath==="/"?"":basePath}/_mcp-use/public/${source.split("/").map(segment=>encodeURIComponent(segment)).join("/")}`}function isLocalPublicSource(source){return protocolOf(source)===void 0}function selectFaviconFromIcons(icons){return icons[0]}function assertLocalPublicSource(source,field){if(source.startsWith("/")||source.includes("\\")||source.includes("?")||source.includes("#")||source.split("/").some(segment=>segment===""||segment===".."))throw new TypeError(`${field} must be an http(s) URL, image data URL, or safe path relative to public/`)}function parseDataImage(source,field){let comma=source.indexOf(",");if(comma<0)throw new TypeError(`${field} must be a valid image data URL`);let metadata=source.slice(5,comma),payload=source.slice(comma+1),parts=metadata.split(";"),mimeType=parts[0]?.toLowerCase()??"";if(!mimeType.startsWith("image/"))throw new TypeError(`${field} data URL must use an image MIME type`);try{if(parts.includes("base64")){let binary2=atob(payload);return{mimeType,bytes:Uint8Array.from(binary2,character=>character.charCodeAt(0))}}return{mimeType,bytes:new TextEncoder().encode(decodeURIComponent(payload))}}catch{throw new TypeError(`${field} must be a valid image data URL`)}}function assertBrandingSource(source,field){if(typeof source!="string"||source.length===0)throw new TypeError(`${field} must be a non-empty string`);let protocol=protocolOf(source);if(protocol===void 0)return assertLocalPublicSource(source,field),source;if(protocol==="data")return parseDataImage(source,field),source;if(protocol!=="http"&&protocol!=="https")throw new TypeError(`${field} must be an http(s) URL, image data URL, or safe path relative to public/`);try{new URL(source)}catch{throw new TypeError(`${field} must be a valid absolute http(s) URL`)}return source}function normalizeServerBranding(config){let websiteUrl;if(config.websiteUrl!==void 0){if(typeof config.websiteUrl!="string"||config.websiteUrl.length===0)throw new TypeError("websiteUrl must be a non-empty absolute http(s) URL");let parsed;try{parsed=new URL(config.websiteUrl)}catch{throw new TypeError("websiteUrl must be a non-empty absolute http(s) URL")}if(parsed.protocol!=="http:"&&parsed.protocol!=="https:")throw new TypeError("websiteUrl must be a non-empty absolute http(s) URL");websiteUrl=config.websiteUrl}let icons;if(config.icons!==void 0){if(!Array.isArray(config.icons))throw new TypeError("icons must be an array of MCP Icon objects");icons=Object.freeze(config.icons.map((value,index)=>{if(typeof value!="object"||value===null)throw new TypeError(`icons[${index}] must be an MCP Icon object`);let icon=value,src=assertBrandingSource(icon.src,`icons[${index}].src`),mimeType=icon.mimeType;if(mimeType!==void 0&&(typeof mimeType!="string"||!mimeType.toLowerCase().startsWith("image/")))throw new TypeError(`icons[${index}].mimeType must be an image MIME type when provided`);let sizes=icon.sizes;if(sizes!==void 0&&(!Array.isArray(sizes)||sizes.some(size=>typeof size!="string"||size.length===0)))throw new TypeError(`icons[${index}].sizes must be an array of non-empty strings when provided`);let normalizedSizes=sizes===void 0?void 0:sizes.map(size=>size),theme=icon.theme;if(theme!==void 0&&theme!=="light"&&theme!=="dark")throw new TypeError(`icons[${index}].theme must be "light" or "dark" when provided`);return Object.freeze({src,...mimeType!==void 0&&{mimeType},...normalizedSizes!==void 0&&{sizes:Object.freeze(normalizedSizes)},...theme!==void 0&&{theme}})}))}let explicitFavicon=config.favicon===void 0?void 0:assertBrandingSource(config.favicon,"favicon"),inferred=explicitFavicon===void 0?selectFaviconFromIcons(icons??[]):void 0,favicon=explicitFavicon??inferred?.src,faviconMimeType=inferred?.mimeType??icons?.find(icon=>icon.src===explicitFavicon)?.mimeType;return Object.freeze({...favicon!==void 0&&{favicon},...faviconMimeType!==void 0&&{faviconMimeType},...icons!==void 0&&{icons},...websiteUrl!==void 0&&{websiteUrl}})}function resolveImplementationIcons(icons,request,basePath){if(icons!==void 0)return icons.map(icon=>({...icon,src:request!==void 0&&isLocalPublicSource(icon.src)?`${resolveAssetsBase(request)}${publicAssetPath(basePath,icon.src)}`:icon.src,...icon.sizes!==void 0&&{sizes:[...icon.sizes]}}))}function hasLocalBrandingAsset(branding){return branding.favicon!==void 0&&isLocalPublicSource(branding.favicon)||branding.icons?.some(icon=>isLocalPublicSource(icon.src))===!0}function createFaviconHandler(branding,options){let source=branding.favicon;if(source!==void 0)return async request=>{if(request.method!=="GET"&&request.method!=="HEAD")return new Response("Method Not Allowed",{status:405,headers:{Allow:"GET, HEAD"}});if(new URL(request.url).pathname!=="/favicon.ico")return new Response("Not Found",{status:404});let protocol=protocolOf(source);if(protocol==="http"||protocol==="https")return new Response(null,{status:307,headers:{Location:source,"Cache-Control":FAVICON_REDIRECT_CACHE_CONTROL}});if(protocol==="data"){let data=parseDataImage(source,"favicon");return new Response(request.method==="HEAD"?null:data.bytes.buffer,{status:200,headers:{"Content-Type":branding.faviconMimeType??data.mimeType,"Cache-Control":FAVICON_CACHE_CONTROL,"X-Content-Type-Options":"nosniff"}})}let{join}=await import("path"),publicRoot=options.dev?join(options.projectRoot,"public"):join(options.projectRoot,".mcp-use/build/views/public"),diskPath=await resolvePublicFilePath(publicRoot,source);if(diskPath===null)return new Response("Not Found",{status:404,headers:{"Cache-Control":"no-store"}});let response=await servePublicFile(diskPath,{...options.deferCors===!0&&{deferCors:!0},...request.method==="HEAD"&&{head:!0}});return response.headers.set("Cache-Control",FAVICON_CACHE_CONTROL),response.headers.set("X-Content-Type-Options","nosniff"),branding.faviconMimeType!==void 0&&response.headers.set("Content-Type",branding.faviconMimeType),response}}function assertServerConfig(config){if(config.basePath!==void 0){if(typeof config.basePath!="string")throw new TypeError("basePath must be an absolute URL pathname without empty segments, trailing slash, query, fragment, or whitespace");let{basePath}=config;if(!basePath.startsWith("/")||basePath.includes("?")||basePath.includes("#")||/\s/.test(basePath)||basePath.includes("//")||basePath.length>1&&basePath.endsWith("/"))throw new TypeError("basePath must be an absolute URL pathname without empty segments, trailing slash, query, fragment, or whitespace")}if(config.port!==void 0&&(typeof config.port!="number"||!Number.isInteger(config.port)||config.port<0||config.port>65535))throw new TypeError("port must be an integer between 0 and 65535")}var DEFAULT_LISTEN_HOST="127.0.0.1";function resolveListenHost(explicitHost,configuredHost,env=process.env){if(explicitHost!==void 0)return explicitHost;let envHost=env.HOST?.trim();return envHost!==void 0&&envHost!==""?envHost:configuredHost??DEFAULT_LISTEN_HOST}function resolveListenPort(explicitPort,configuredPort,env=process.env){if(explicitPort!==void 0)return explicitPort;let envPort=parsePort(env.PORT);return envPort!==void 0?envPort:configuredPort??3e3}function parsePort(value){if(value===void 0||value.trim()==="")return;let port=Number(value);return Number.isInteger(port)&&port>=0&&port<=65535?port:void 0}import{CLIENT_CAPABILITIES_META_KEY as CLIENT_CAPABILITIES_META_KEY2,CLIENT_INFO_META_KEY,inputRequired,inputResponse}from"@modelcontextprotocol/server";import{HonoRequest}from"hono/request";import{CLIENT_CAPABILITIES_META_KEY}from"@modelcontextprotocol/server";var UI_EXTENSION_ID="io.modelcontextprotocol/ui",UI_MIME_TYPE="text/html;profile=mcp-app",UI_RESOURCE_URI_PREFIX="ui://views/";var UI_RESOURCE_URI_META_KEY="ui/resourceUri";function viewResourceUri(viewName){return`${UI_RESOURCE_URI_PREFIX}${viewName}.html`}var clientCapabilitiesByRequest=new WeakMap;function stashClientCapabilities(request,capabilities){clientCapabilitiesByRequest.set(request,capabilities)}function extractClientCapabilitiesFromBody(body){if(typeof body!="object"||body===null)return;let params=body.params;if(typeof params!="object"||params===null)return;let meta=params._meta;if(typeof meta!="object"||meta===null)return;let capabilities=meta[CLIENT_CAPABILITIES_META_KEY];if(!(typeof capabilities!="object"||capabilities===null))return capabilities}function supportsViews(capabilities){let extensions=capabilities?.extensions;if(extensions===void 0)return!1;let uiExtension=extensions[UI_EXTENSION_ID];if(typeof uiExtension!="object"||uiExtension===null)return!1;let mimeTypes=uiExtension.mimeTypes;return Array.isArray(mimeTypes)?mimeTypes.includes(UI_MIME_TYPE):!1}function requireOAuthAuthInfo(authInfo){if(authInfo===void 0||authInfo.extra===void 0||authInfo.expiresAt===void 0)throw new Error("OAuth callback did not receive mapped AuthInfo.extra")}function stringValue(value){return typeof value=="string"?value:void 0}function coordinateValue(value){return typeof value=="string"||typeof value=="number"&&Number.isFinite(value)?value:void 0}function normalizeUserContext(meta){if(meta===void 0)return;let locale=stringValue(meta["openai/locale"])??stringValue(meta["webplus/i18n"]),userAgent=stringValue(meta["openai/userAgent"]),subject=stringValue(meta["openai/subject"]),conversationId=stringValue(meta["openai/session"]),organizationId=stringValue(meta["openai/organization"]),rawLocation=meta["openai/userLocation"],location;if(typeof rawLocation=="object"&&rawLocation!==null&&!Array.isArray(rawLocation)){let values=rawLocation,normalized={city:stringValue(values.city),region:stringValue(values.region),country:stringValue(values.country),timezone:stringValue(values.timezone),latitude:coordinateValue(values.latitude),longitude:coordinateValue(values.longitude)},entries=Object.entries(normalized).filter(entry=>entry[1]!==void 0);entries.length>0&&(location=Object.fromEntries(entries))}if(!(locale===void 0&&userAgent===void 0&&location===void 0&&subject===void 0&&conversationId===void 0&&organizationId===void 0))return{...locale!==void 0&&{locale},...userAgent!==void 0&&{userAgent},...location!==void 0&&{location},...subject!==void 0&&{subject},...conversationId!==void 0&&{conversationId},...organizationId!==void 0&&{organizationId}}}function toClientContext(ctx){let envelope=ctx.mcpReq.envelope,capabilities={...envelope?.[CLIENT_CAPABILITIES_META_KEY2]??{}},info={...envelope?.[CLIENT_INFO_META_KEY]??{}},user=normalizeUserContext(ctx.mcpReq._meta);return{can(capability){return Object.hasOwn(capabilities,capability)},capabilities(){return{...capabilities}},extension(id){let settings=capabilities.extensions?.[id];return settings===void 0?void 0:{...settings}},info(){return{...info}},user(){return user===void 0?void 0:{...user,...user.location!==void 0&&{location:{...user.location}}}},supportsViews(){return supportsViews(capabilities)}}}function createElicit(inputResponses){return async function(key,message,schemaOrUrl){let request,formSchema;if(typeof schemaOrUrl=="string")request=inputRequired.elicitUrl({message,url:schemaOrUrl});else if(schemaOrUrl!==void 0)formSchema=schemaOrUrl,request=inputRequired.elicit({message,requestedSchema:schemaOrUrl});else throw new TypeError("ctx.elicit(key, message, value) requires a form schema or URL string");let response=inputResponse(inputResponses,key);if(response.kind==="elicit"){if(response.action!=="accept")return{status:response.action};if(formSchema===void 0)return{status:"accept"};if(response.content!==void 0){let outcome=await formSchema["~standard"].validate(response.content);if(outcome.issues===void 0)return{status:"accept",data:outcome.value}}}return{status:"required",result:inputRequired({inputRequests:{[key]:request}})}}}function toRequestContext(ctx){let rawRequest=ctx.http?.req,http=rawRequest===void 0?void 0:getRequestBag(rawRequest).honoContext,request=http?.req??(rawRequest===void 0?void 0:new HonoRequest(rawRequest)),additions={signal:ctx.mcpReq.signal,...request!==void 0&&{request},...ctx.mcpReq.inputResponses!==void 0&&{inputResponses:ctx.mcpReq.inputResponses},client:toClientContext(ctx),elicit:createElicit(ctx.mcpReq.inputResponses),requestState:()=>ctx.mcpReq.requestState(),async sendNotification(method,params){await ctx.mcpReq.notify({method,...params!==void 0&&{params}})},async reportProgress(progress,total,message){let progressToken=ctx.mcpReq._meta?.progressToken;return progressToken===void 0?!1:(await ctx.mcpReq.notify({method:"notifications/progress",params:{progressToken,progress,...total!==void 0&&{total},...message!==void 0&&{message}}}),!0)},async sendLog(level,data,logger){await ctx.mcpReq.notify({method:"notifications/message",params:{level,data,...logger!==void 0&&{logger}}})}};return http!==void 0?Object.assign(http,additions):{...additions,...request!==void 0&&{req:request}}}function toAuthenticatedRequestContext(ctx){let authInfo=ctx.http?.authInfo;return requireOAuthAuthInfo(authInfo),Object.assign(toRequestContext(ctx),{auth:{user:authInfo.extra.user,payload:authInfo.extra.payload,accessToken:authInfo.token,scopes:[...authInfo.scopes],permissions:[...authInfo.extra.permissions],...authInfo.clientId.length>0&&{clientId:authInfo.clientId},expiresAt:authInfo.expiresAt,...authInfo.resource!==void 0&&{resource:authInfo.resource}}})}function isReadResourceResult(result){return"contents"in result&&Array.isArray(result.contents)}function isGetPromptResult(result){return"messages"in result&&Array.isArray(result.messages)}function toResourceResult(result,uri){if(isReadResourceResult(result))return result;let mime=result._meta&&typeof result._meta=="object"&&typeof result._meta.mimeType=="string"?result._meta.mimeType:void 0,contents=[];for(let block of result.content??[]){let mapped=contentBlockToResourceContents(block,uri,mime);mapped!==void 0&&contents.push(mapped)}return contents.length===0&&result.structuredContent!==void 0&&contents.push({uri,mimeType:"application/json",text:JSON.stringify(result.structuredContent)}),contents.length===0&&contents.push({uri,mimeType:"text/plain",text:""}),{contents}}function contentBlockToResourceContents(block,uri,mimeHint){if(block.type==="text")return{uri,mimeType:mimeHint??"text/plain",text:block.text};if(block.type==="image"||block.type==="audio")return{uri,mimeType:block.mimeType,blob:block.data};if(block.type==="resource")return{...block.resource}}function toPromptResult(result){if(isGetPromptResult(result))return result;let messages=(result.content??[]).map(content=>({role:"user",content}));return messages.length===0&&result.structuredContent!==void 0&&messages.push({role:"user",content:{type:"text",text:JSON.stringify(result.structuredContent)}}),messages.length===0&&messages.push({role:"user",content:{type:"text",text:""}}),{messages}}var DEFAULT_METHODS=["GET","HEAD","POST","OPTIONS"],DEFAULT_ALLOWED_HEADERS=["Content-Type","Authorization","mcp-protocol-version","mcp-method","mcp-name"];function resolveAllowedOrigin(origin,requestOrigin){return origin===void 0?requestOrigin:typeof origin=="function"?origin(requestOrigin):origin==="*"?"*":Array.isArray(origin)?requestOrigin!==null&&origin.includes(requestOrigin)?requestOrigin:null:origin}function corsHeaders(options,request){if(request.headers.has("Access-Control-Allow-Origin"))return;let requestOrigin=request.headers.get("Origin"),allowedOrigin=resolveAllowedOrigin(options.origin,requestOrigin);if(allowedOrigin===null)return;let headers={"Access-Control-Allow-Origin":allowedOrigin,"Access-Control-Allow-Methods":options.methods.join(", "),"Access-Control-Allow-Headers":options.allowedHeaders.join(", ")};return options.credentials&&(headers["Access-Control-Allow-Credentials"]="true"),allowedOrigin!=="*"&&(headers.Vary="Origin"),headers}function mergeCorsHeaders(response,headers){if(response.headers.has("Access-Control-Allow-Origin"))return response;let merged=new Headers(response.headers);return new Headers(headers).forEach((value,key)=>{merged.set(key,value)}),inheritBufferedResponse(response,new Response(response.body,{status:response.status,statusText:response.statusText,headers:merged}))}function corsFetchMiddleware(options){if(!(options.enabled!==!1))return async(_request,next)=>next();let resolved={...options.origin!==void 0&&{origin:options.origin},methods:options.methods??DEFAULT_METHODS,allowedHeaders:options.allowedHeaders??DEFAULT_ALLOWED_HEADERS,credentials:options.credentials??!1};return async(request,next)=>{let headers=corsHeaders(resolved,request);if(headers===void 0)return next();if(request.method==="OPTIONS")return new Response(null,{status:204,headers});let response=await next();return mergeCorsHeaders(response,headers)}}function isGlobalCorsEnabled(cors){return cors!==void 0&&cors.enabled!==!1}import{CallToolResultSchema,GetPromptResultSchema,ListPromptsResultSchema,ListResourcesResultSchema,ListToolsResultSchema,ReadResourceResultSchema}from"@modelcontextprotocol/core";import{isInputRequiredResult}from"@modelcontextprotocol/server";var MCP_MIDDLEWARE_METHODS=["tools/call","tools/list","resources/read","resources/list","prompts/get","prompts/list"];function withMcpMiddlewareParams(request,params){if(typeof request!="object"||request===null||Array.isArray(request))throw new TypeError("[mcp-use] MCP middleware received an invalid downstream request");return{...request,params}}function createMcpMiddlewareEntry(pattern,handler){let normalizedPattern=normalizeMcpMiddlewarePattern(pattern),invoke=handler;if(normalizedPattern!=="*"&&!isMcpMiddlewareMethod(normalizedPattern))throw new TypeError(`Unsupported MCP middleware pattern "${pattern}". Use an exact MCP method or "mcp:*".`);return normalizedPattern==="*"?{pattern:normalizedPattern,handler:async(ctx,next)=>{let downstreamCalled=!1,downstreamResult;if(await invoke(ctx,async()=>{downstreamResult=await next(),downstreamCalled=!0}),!downstreamCalled)throw new Error(`Wildcard MCP middleware "${normalizedPattern}" must call next()`);return downstreamResult}}:{pattern:normalizedPattern,handler:(ctx,next)=>invoke(ctx,next)}}function createMcpEventListenerEntry(pattern,handler){let{pattern:normalizedPattern,phase}=parseMcpPattern(pattern),invoke=handler;return{pattern:normalizedPattern,phase,handler:(ctx,result)=>invoke(ctx,result)}}function matchesPattern(pattern,method){if(pattern==="*")return!0;if(pattern.endsWith("/*")){let prefix=pattern.slice(0,-1);return method.startsWith(prefix)}return pattern===method}function isMcpMiddlewareMethod(value){return MCP_MIDDLEWARE_METHODS.some(method=>method===value)}function composeMiddleware(entries,method,innerFn){let matching=entries.filter(entry=>matchesPattern(entry.pattern,method));return matching.length===0?_ctx=>innerFn():ctx=>{let index=-1,dispatch=i=>i<=index?Promise.reject(new Error("next() called multiple times")):(index=i,i===matching.length?innerFn():matching[i].handler(ctx,()=>dispatch(i+1)));return dispatch(0)}}function freezeMiddlewareContext(ctx){return Object.freeze({method:ctx.method,params:Object.freeze({...ctx.params}),...ctx.request!==void 0&&{request:ctx.request},...ctx.req!==void 0&&{req:ctx.req},...ctx.session!==void 0&&{session:Object.freeze({...ctx.session})},...ctx.auth!==void 0&&{auth:ctx.auth},state:new Map(ctx.state)})}async function runMcpOperation(middlewares,events,method,ctx,innerFn){dispatchMcpEvents(events,method,"before",ctx);let result=await composeMiddleware(middlewares,method,innerFn)(ctx);return assertValidMiddlewareResult(method,result),dispatchMcpEvents(events,method,"complete",ctx,result),result}function assertValidMiddlewareResult(method,result){if((method==="tools/call"||method==="resources/read"||method==="prompts/get")&&isInputRequiredResult(result))return;let validation=(()=>{switch(method){case"tools/call":return assertArrayProperty(method,result,"content"),CallToolResultSchema.safeParse(result);case"tools/list":return assertArrayResult(method,result),ListToolsResultSchema.safeParse({tools:result});case"resources/read":return assertArrayProperty(method,result,"contents"),ReadResourceResultSchema.safeParse(result);case"resources/list":return assertArrayResult(method,result),ListResourcesResultSchema.safeParse({resources:result});case"prompts/get":return assertArrayProperty(method,result,"messages"),GetPromptResultSchema.safeParse(result);case"prompts/list":return assertArrayResult(method,result),ListPromptsResultSchema.safeParse({prompts:result});default:throw new TypeError(`Unsupported MCP middleware method "${method}"`)}})();if(!validation.success)throw new TypeError(`[mcp-use] ${method} middleware returned an invalid result: ${validation.error.message}`)}function assertArrayResult(method,result){if(!Array.isArray(result))throw new TypeError(`[mcp-use] ${method} middleware returned an invalid result: expected an array`)}function assertArrayProperty(method,result,property){if(typeof result!="object"||result===null||!Array.isArray(result[property]))throw new TypeError(`[mcp-use] ${method} middleware returned an invalid result: expected a ${property} array`)}function dispatchMcpEvents(events,method,phase,ctx,result){let frozen=freezeMiddlewareContext(ctx);for(let entry of events)if(!(entry.phase!==phase||!matchesPattern(entry.pattern,method)))try{entry.handler(frozen,result)}catch(error2){console.error(`[mcp-use] MCP event listener for "${entry.pattern}" (${phase}) threw:`,error2)}}function parseMcpPattern(raw){let pattern=raw.startsWith("mcp:")?raw.slice(4):raw;return pattern.endsWith(":complete")?{pattern:pattern.slice(0,-9),phase:"complete"}:{pattern,phase:"before"}}function normalizeMcpMiddlewarePattern(raw){return raw.startsWith("mcp:")?raw.slice(4):raw}import{CLIENT_INFO_META_KEY as CLIENT_INFO_META_KEY2,isJSONRPCRequest}from"@modelcontextprotocol/server";function colorsEnabled(){return typeof process>"u"||process.env?.NO_COLOR!==void 0?!1:process.stdout?.isTTY===!0}function ansi(open,close){return text2=>colorsEnabled()?`\x1B[${open}m${text2}\x1B[${close}m`:text2}var bold=ansi(1,22),dim=ansi(2,22),red=ansi(31,39),green=ansi(32,39),yellow=ansi(33,39),blue=ansi(34,39),magenta=ansi(35,39),cyan=ansi(36,39),gray=ansi(90,39);function resolveLogLevel(configured){let raw=typeof process>"u"?void 0:process.env?.MCP_USE_LOG_LEVEL?.toLowerCase();return raw==="info"||raw==="debug"||raw==="trace"?raw:configured??"info"}function formatClientInfo(info){if(info!==void 0)return typeof info.version=="string"&&info.version!==""?`${info.name}/${info.version}`:info.name}var detailFormatters={initialize:p=>({subject:formatClientInfo(p.clientInfo)}),ping:()=>({}),"server/discover":()=>({}),"completion/complete":p=>({subject:p.ref.type==="ref/prompt"?p.ref.name:p.ref.uri,input:p.argument}),"logging/setLevel":p=>({subject:p.level}),"prompts/get":p=>({subject:p.name,input:p.arguments}),"prompts/list":()=>({}),"resources/list":()=>({}),"resources/templates/list":()=>({}),"resources/read":p=>({subject:p.uri}),"resources/subscribe":p=>({subject:p.uri}),"resources/unsubscribe":p=>({subject:p.uri}),"subscriptions/listen":()=>({}),"tools/call":p=>({subject:p.name,input:p.arguments}),"tools/list":()=>({}),"sampling/createMessage":()=>({}),"elicitation/create":()=>({}),"roots/list":()=>({})};function isKnownMethod(method){return Object.prototype.hasOwnProperty.call(detailFormatters,method)}function formatDetail(message){if(!isKnownMethod(message.method))return{};try{let formatter=detailFormatters[message.method],detail=formatter(message.params);return typeof detail.subject=="string"||detail.subject===void 0?detail:{}}catch{return{}}}var INLINE_JSON_MAX_LENGTH=80;function inlineJson(value){let text2;try{text2=JSON.stringify(value)??String(value)}catch{text2=String(value)}return text2.length>INLINE_JSON_MAX_LENGTH?`${text2.slice(0,INLINE_JSON_MAX_LENGTH)}...`:text2}function formatClientIdentity(message){let meta=message.params?._meta;if(meta===void 0)return;let info=meta[CLIENT_INFO_META_KEY2];if(!(typeof info!="object"||info===null||typeof info.name!="string"))return formatClientInfo(info)}function sanitize(text2){return text2.replace(/[\u0000-\u001F\u007F-\u009F]+/g," ")}function methodStyle(method){return method.startsWith("tools/")?cyan:method.startsWith("resources/")?green:method.startsWith("prompts/")?magenta:method==="initialize"||method==="ping"?gray:blue}var REDACTED_HEADERS=new Set(["authorization","proxy-authorization","cookie","set-cookie","x-api-key"]);function redactHeaders(headers){return Object.fromEntries(Object.entries(headers).map(([name,value])=>[name,REDACTED_HEADERS.has(name.toLowerCase())?"[REDACTED]":value]))}async function extractResponseOutcome(res){if(!res.body)return{errorMessage:null};let text2;try{text2=await res.clone().text()}catch{return{errorMessage:null}}if(!text2)return{errorMessage:null};let isSse=(res.headers.get("content-type")??"").includes("text/event-stream"),payloads=[],tryParse=raw=>{try{payloads.push(JSON.parse(raw))}catch{}};if(isSse){for(let line of text2.split(/\r?\n/))if(line.startsWith("data:")){let data=line.slice(5).trim();data&&tryParse(data)}}else tryParse(text2);let result;for(let payload of payloads){if(payload===null||typeof payload!="object")continue;let message=payload;if(typeof message.error?.message=="string")return{errorMessage:message.error.message};if(message.result?.isError===!0){let textBlock=(Array.isArray(message.result.content)?message.result.content:[]).find(b=>b?.type==="text"&&typeof b.text=="string");return{errorMessage:textBlock?String(textBlock.text):"tool error"}}"result"in message&&(result=message.result)}return{errorMessage:null,result}}function compactToolResult(result){if(result===null||typeof result!="object")return result;let{structuredContent,content}=result;if(structuredContent!==void 0)return structuredContent;if(Array.isArray(content)){let[block]=content;if(content.length===1&&block?.type==="text")return block.text}return content}function formatForDump(value){function truncate(val){return typeof val=="string"&&val.length>100?`${val.slice(0,100)}...`:Array.isArray(val)?val.map(truncate):val!==null&&typeof val=="object"?Object.fromEntries(Object.entries(val).map(([k,v])=>[k,truncate(v)])):val}try{return JSON.stringify(truncate(value),null,2)}catch{return String(value)}}var DUMP_BODY_MAX_LENGTH=1e4;async function printTraceDump(response,requestHeaders,requestBody,readResponseBody){console.log(`
2
2
  ${cyan("=".repeat(80))}`),console.log(bold(cyan("[TRACE] Request Details"))),console.log(cyan("-".repeat(80))),Object.keys(requestHeaders).length>0&&(console.log(yellow("Request Headers:")),console.log(formatForDump(redactHeaders(requestHeaders)))),requestBody!==void 0&&(console.log(yellow("Request Body:")),console.log(typeof requestBody=="string"?requestBody:formatForDump(requestBody)));let responseHeaders={};if(response.headers.forEach((value,key)=>{responseHeaders[key]=value}),Object.keys(responseHeaders).length>0&&(console.log(yellow("Response Headers:")),console.log(formatForDump(redactHeaders(responseHeaders)))),!readResponseBody)console.log(`${yellow("Response Body:")} (streaming \u2014 not dumped)`);else if(response.body===null)console.log(`${yellow("Response Body:")} (no body)`);else try{let text2=await response.clone().text();if(text2.length===0)console.log(`${yellow("Response Body:")} (empty)`);else{console.log(yellow("Response Body:"));try{console.log(formatForDump(JSON.parse(text2)))}catch{console.log(text2.length>DUMP_BODY_MAX_LENGTH?`${text2.slice(0,DUMP_BODY_MAX_LENGTH)}
3
3
  ... (truncated, ${text2.length-DUMP_BODY_MAX_LENGTH} more characters)`:text2)}}}catch{console.log(`${yellow("Response Body:")} (unable to read)`)}console.log(`${cyan("=".repeat(80))}
4
4
  `)}function styleStatus(status){let text2=String(status);return status>=500?magenta(text2):status>=400?red(text2):status>=300?yellow(text2):green(text2)}function isNoisyRequest(httpMethod,pathname){return httpMethod!=="GET"&&httpMethod!=="HEAD"?!1:pathname.endsWith("/favicon.ico")}function requestLogger(options={}){return options.enabled===!1?(_request,next)=>next():async(request,next)=>{let level=resolveLogLevel(options.level),startedAt=Date.now(),httpMethod=request.method,pathname=new URL(request.url).pathname;if(isNoisyRequest(httpMethod,pathname))return next();let requestHeaders={};level==="trace"&&request.headers.forEach((value,key)=>{requestHeaders[key]=value});let requestBody;if(httpMethod!=="GET"&&httpMethod!=="HEAD"){let parsedBody=getRequestBag(request).parsedBody;if(parsedBody!==void 0)requestBody=parsedBody;else try{requestBody=await request.clone().json()}catch{}}let response=await next(),durationMs=Date.now()-startedAt,timestamp=new Date().toISOString().substring(11,19),mcpRequest=isJSONRPCRequest(requestBody)?requestBody:void 0,isStreamingMethod=mcpRequest?.method==="subscriptions/listen",lines=[[dim(timestamp),bold(httpMethod),pathname,styleStatus(response.status),dim(`in ${durationMs}ms`)].join(" ")];if(mcpRequest!==void 0){let method=sanitize(mcpRequest.method),parts=[` ${methodStyle(method)(method)}`],detail=formatDetail(mcpRequest);detail.subject!==void 0&&parts.push(bold(sanitize(detail.subject)));let echoPayloads=level!=="info";echoPayloads&&detail.input!==void 0&&parts.push(inlineJson(detail.input));let outcome=isStreamingMethod?{errorMessage:null}:await extractResponseOutcome(response);if(echoPayloads&&mcpRequest.method==="tools/call"&&outcome.errorMessage===null&&outcome.result!==void 0&&parts.push(dim("->"),inlineJson(compactToolResult(outcome.result))),mcpRequest.method!=="initialize"){let client=formatClientIdentity(mcpRequest);client!==void 0&&parts.push(dim(sanitize(client)))}outcome.errorMessage!==null?parts.push(red(`ERROR ${sanitize(outcome.errorMessage)}`)):response.status>=400&&parts.push(red(`ERROR (HTTP ${response.status})`)),lines.push(parts.join(" "))}return console.log(lines.join(`
5
- `)),level==="trace"&&await printTraceDump(response,requestHeaders,requestBody,!isStreamingMethod),response}}import{createMcpHandler}from"@modelcontextprotocol/server";function createMcpMount(factory,options={}){let{path="/mcp",handler:handlerOptions,authInfo:getAuthInfo}=options,legacyMode=handlerOptions?.legacy??"stateless",handler=createMcpHandler(factory,{legacy:"stateless",...handlerOptions});return{handler,fetch:async request=>{if(!matchesPath(request,path))return new Response("Not Found",{status:404});if(legacyMode==="stateless"){let method=request.method.toUpperCase();if(method==="GET"||method==="DELETE"||method==="HEAD")return new Response(null,{status:204})}let bag=getRequestBag(request),parsedBody=bag.parsedBody;if(parsedBody===void 0)try{parsedBody=await request.clone().json()}catch{}let capabilities=extractClientCapabilitiesFromBody(parsedBody);capabilities!==void 0&&stashClientCapabilities(request,capabilities);let authInfo=getAuthInfo?.(request)??bag.authInfo,response=await handler.fetch(request,{...parsedBody!==void 0&&{parsedBody},...authInfo!==void 0&&{authInfo}});return response.headers.get("content-type")?.toLowerCase().includes("application/json")?trackBufferedResponse(request,response):response}}}function resolveToolInputSchema(definition){return definition.inputSchema??definition.schema}var registerViews=Symbol("mcp-use/registerViews");function resolveAssetUrl(assetPath,origin){if(!assetPath.startsWith("/"))throw new Error(`View manifest asset path must be origin-absolute (start with "/"); got ${JSON.stringify(assetPath)}`);return`${origin}${assetPath}`}function viewAssetsBasePath(basePath,viewName){return`${pathUnderBase(basePath,`_mcp-use/views/${viewName}`)}/`}function resolveExternalAssetUrl(assetPath,assetsBase,basePath,viewName){return assetPath.startsWith("http://")||assetPath.startsWith("https://")||assetPath.startsWith("data:")?assetPath:assetPath.startsWith("/")?resolveAssetUrl(assetPath,assetsBase):`${assetsBase}${viewAssetsBasePath(basePath,viewName)}${assetPath.replace(/^\/+/,"")}`}function resolvePublicBase(assetsBase,basePath){return`${assetsBase}${pathUnderBase(basePath,"_mcp-use/public")}/`}function escapeInlineScript(code){return code.replaceAll(/<\/script/gi,"<\\/script").replaceAll("<!--","\\x3C!--")}function escapeInlineStyle(css2){return css2.replaceAll(/<\/style/gi,"<\\/style")}function escapeHtml(value){return value.replaceAll("&","&amp;").replaceAll('"',"&quot;").replaceAll("<","&lt;").replaceAll(">","&gt;")}var TRANSPARENT_IFRAME_STYLE="<style>html,body,#root{background:transparent}</style>";function synthesizeViewDocument(entry,assetsBase,basePath,viewName){let viewConfig={publicBase:resolvePublicBase(assetsBase,basePath)},configScript=`<script>globalThis.__mcpUseViewConfig=${JSON.stringify(viewConfig)};</script>`;if(entry.kind==="inline"){let styleTag=entry.css.length>0?`<style>${escapeInlineStyle(entry.css)}</style>`:"",moduleScript=`<script type="module">${escapeInlineScript(entry.js)}</script>`;return`<!doctype html>
5
+ `)),level==="trace"&&await printTraceDump(response,requestHeaders,requestBody,!isStreamingMethod),response}}import{createMcpHandler}from"@modelcontextprotocol/server";function createMcpMount(factory,options={}){let{path="/mcp",handler:handlerOptions,authInfo:getAuthInfo}=options,legacyMode=handlerOptions?.legacy??"stateless",handler=createMcpHandler(factory,{legacy:"stateless",...handlerOptions});return{handler,fetch:async request=>{if(!matchesPath(request,path))return new Response("Not Found",{status:404});if(legacyMode==="stateless"){let method=request.method.toUpperCase();if(method==="GET"||method==="DELETE"||method==="HEAD")return new Response(null,{status:204})}let bag=getRequestBag(request),parsedBody=bag.parsedBody;if(parsedBody===void 0)try{parsedBody=await request.clone().json()}catch{}let capabilities=extractClientCapabilitiesFromBody(parsedBody);capabilities!==void 0&&stashClientCapabilities(request,capabilities);let authInfo=getAuthInfo?.(request)??bag.authInfo,response=await handler.fetch(request,{...parsedBody!==void 0&&{parsedBody},...authInfo!==void 0&&{authInfo}});return response.headers.get("content-type")?.toLowerCase().includes("application/json")?trackBufferedResponse(request,response):response}}}function resolveToolInputSchema(definition){return definition.inputSchema??definition.schema}var registerViews=Symbol("mcp-use/registerViews");function resolveAssetUrl(assetPath,origin){if(!assetPath.startsWith("/"))throw new Error(`View manifest asset path must be origin-absolute (start with "/"); got ${JSON.stringify(assetPath)}`);return`${origin}${assetPath}`}function viewAssetsBasePath(basePath,viewName){return`${pathUnderBase(basePath,`_mcp-use/views/${viewName}`)}/`}function resolveExternalAssetUrl(assetPath,assetsBase,basePath,viewName){return assetPath.startsWith("http://")||assetPath.startsWith("https://")||assetPath.startsWith("data:")?assetPath:assetPath.startsWith("/")?resolveAssetUrl(assetPath,assetsBase):`${assetsBase}${viewAssetsBasePath(basePath,viewName)}${assetPath.replace(/^\/+/,"")}`}function resolvePublicBase(assetsBase,basePath){return`${assetsBase}${pathUnderBase(basePath,"_mcp-use/public")}/`}function escapeInlineScript(code){return code.replaceAll(/<\/script/gi,"<\\/script").replaceAll("<!--","\\x3C!--")}function escapeInlineStyle(css2){return css2.replaceAll(/<\/style/gi,"<\\/style")}function escapeHtml(value){return value.replaceAll("&","&amp;").replaceAll('"',"&quot;").replaceAll("<","&lt;").replaceAll(">","&gt;")}var VIEW_BOOTSTRAP_STYLE=`<style>
6
+ html,body,#root{background:transparent}
7
+ html,body{margin:0}
8
+ #root[data-mcp-use-loading]{display:flex;min-height:100vh;align-items:center;justify-content:center;flex-direction:column;gap:10px}
9
+ #root[data-mcp-use-loading]::before{width:24px;height:24px;box-sizing:border-box;border:2px solid rgba(127,127,127,.28);border-top-color:rgba(127,127,127,.9);border-radius:50%;content:"";animation:mcp-use-view-spin .7s linear infinite}
10
+ #root[data-mcp-use-loading]::after{color:rgba(127,127,127,.9);content:"Compiling...";font:500 13px/1.2 ui-sans-serif,system-ui,sans-serif}
11
+ @keyframes mcp-use-view-spin{to{transform:rotate(360deg)}}
12
+ @media (prefers-reduced-motion:reduce){#root[data-mcp-use-loading]::before{animation-duration:1.4s}}
13
+ </style>`;function synthesizeViewDocument(entry,assetsBase,basePath,viewName){let viewConfig={publicBase:resolvePublicBase(assetsBase,basePath)},configScript=`<script>globalThis.__mcpUseViewConfig=${JSON.stringify(viewConfig)};</script>`;if(entry.kind==="inline"){let styleTag=entry.css.length>0?`<style>${escapeInlineStyle(entry.css)}</style>`:"",moduleScript=`<script type="module">${escapeInlineScript(entry.js)}</script>`;return`<!doctype html>
6
14
  <html>
7
15
  <head>
8
16
  <meta charset="utf-8">
9
17
  ${configScript}
10
- ${TRANSPARENT_IFRAME_STYLE}
18
+ ${VIEW_BOOTSTRAP_STYLE}
11
19
  ${styleTag}
12
20
  </head>
13
21
  <body>
14
- <div id="root"></div>
22
+ <div id="root" data-mcp-use-loading></div>
15
23
  ${moduleScript}
16
24
  </body>
17
25
  </html>`}if(viewName===void 0)throw new Error("viewName is required when synthesizing an external view document.");let cssLinks=entry.css.map(path=>`<link rel="stylesheet" href="${escapeHtml(resolveExternalAssetUrl(path,assetsBase,basePath,viewName))}">`).join(`
@@ -21,11 +29,11 @@ ${moduleScript}
21
29
  <head>
22
30
  <meta charset="utf-8">
23
31
  ${configScript}
24
- ${TRANSPARENT_IFRAME_STYLE}
32
+ ${VIEW_BOOTSTRAP_STYLE}
25
33
  ${cssLinks}
26
34
  </head>
27
35
  <body>
28
- <div id="root"></div>
36
+ <div id="root" data-mcp-use-loading></div>
29
37
  ${scriptTags}
30
38
  <script type="module" src="${escapeHtml(entryUrl)}"></script>
31
39
  </body>
@@ -1 +1 @@
1
- import{flushUsage,isUsageDisabled,recordUsage}from"../chunk-P5GGJGEQ.js";export{flushUsage,isUsageDisabled,recordUsage};
1
+ import{flushUsage,isUsageDisabled,recordUsage}from"../chunk-5FRWUAFA.js";export{flushUsage,isUsageDisabled,recordUsage};
@@ -882,6 +882,7 @@ function configsEqual(a, b) {
882
882
  return a.displayModes.every((mode, index) => mode === b.displayModes[index]);
883
883
  }
884
884
  function renderView(mounted, View) {
885
+ document.getElementById(mounted.rootId)?.removeAttribute("data-mcp-use-loading");
885
886
  mounted.root.render(
886
887
  /* @__PURE__ */ jsx3(ErrorBoundary, { children: /* @__PURE__ */ jsx3(ViewRuntimeProvider, { runtime: mounted.runtime, children: /* @__PURE__ */ jsx3(View, {}) }) })
887
888
  );
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "mcp-use",
3
3
  "type": "module",
4
- "version": "2.0.0-beta.57",
4
+ "version": "2.0.0-beta.59",
5
5
  "description": "MCP framework and CLI built on the official v2 SDK",
6
6
  "author": "mcp-use, Inc.",
7
7
  "license": "MIT",
@@ -107,8 +107,8 @@
107
107
  "@modelcontextprotocol/server": "2.0.0-beta.5",
108
108
  "hono": "^4.12.27",
109
109
  "jose": "^6.1.3",
110
- "@mcp-use/cli": "4.0.0-beta.13",
111
- "@mcp-use/inspector": "20.0.0-beta.49"
110
+ "@mcp-use/cli": "4.0.0-beta.14",
111
+ "@mcp-use/inspector": "20.0.0-beta.51"
112
112
  },
113
113
  "peerDependencies": {
114
114
  "@mcp-use/client": "^2.0.0-alpha.0",
@@ -142,7 +142,7 @@
142
142
  "vite": "^8.0.16",
143
143
  "vitest": "^4.1.9",
144
144
  "zod": "^4.4.3",
145
- "mcp-use": "2.0.0-beta.57",
145
+ "mcp-use": "2.0.0-beta.59",
146
146
  "@mcp-use/client": "2.0.0-beta.16"
147
147
  },
148
148
  "publishConfig": {