mcp-use 2.0.0-beta.52 → 2.0.0-beta.55

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/compat-v1.js CHANGED
@@ -1,16 +1,16 @@
1
- import{a as wt,b as vt}from"./chunk-ZBN5QPYD.js";import{a as ke,b as _e,c as V,d as Ue}from"./chunk-4TTKTNKI.js";function Xn(e){return{content:[{type:"text",text:e}],_meta:{mimeType:"text/plain"}}}function Zn(e){return{content:[{type:"text",text:e}],_meta:{mimeType:"text/markdown"}}}function Qn(e){return{content:[{type:"text",text:e}],_meta:{mimeType:"text/html"}}}function er(e){return{content:[{type:"text",text:e}],_meta:{mimeType:"text/xml"}}}function tr(e){return{content:[{type:"text",text:e}],_meta:{mimeType:"text/css"}}}function nr(e){return{content:[{type:"text",text:e}],_meta:{mimeType:"text/javascript"}}}function rr(e,t="image/png"){return{content:[{type:"image",data:e,mimeType:t}],_meta:{mimeType:t,isImage:!0}}}function or(e,t="audio/wav"){return{content:[{type:"audio",data:e,mimeType:t}],_meta:{mimeType:t,isAudio:!0}}}function sr(e,t){return{content:[{type:"text",text:e}],_meta:{mimeType:t,isBinary:!0}}}function ir(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 u=o._meta;typeof u.mimeType=="string"&&(i=u.mimeType)}let a=o.content?.[0];return a?.type==="text"&&"text"in a&&(s=a.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 ar(e){return{isError:!0,content:[{type:"text",text:e}]}}function ur(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 dr(...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 Sn,localhostAllowedOrigins as vs,McpServer as Ts,ResourceTemplate as Rs,CLIENT_CAPABILITIES_META_KEY as Ms,CLIENT_INFO_META_KEY as bs,PROTOCOL_VERSION_META_KEY as xs,isJSONRPCRequest as jn,isInputRequiredResult as kn}from"@modelcontextprotocol/server";import{Hono as _n}from"hono";var Rt="public, max-age=31536000, immutable",cr="public, max-age=300";function je(e){return/^([a-z][a-z\d+.-]*):/i.exec(e)?.[1]?.toLowerCase()}function lr(e,t){return`${e==="/"?"":e}/_mcp-use/public/${t.split("/").map(r=>encodeURIComponent(r)).join("/")}`}function Le(e){return je(e)===void 0}function pr(e){return e[0]}function fr(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 bt(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 a=atob(o);return{mimeType:i,bytes:Uint8Array.from(a,u=>u.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 fr(e,t),e;if(n==="data")return bt(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 xt(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 a;try{a=new URL(e.websiteUrl)}catch{throw new TypeError("websiteUrl must be a non-empty absolute http(s) URL")}if(a.protocol!=="http:"&&a.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((a,u)=>{if(typeof a!="object"||a===null)throw new TypeError(`icons[${u}] must be an MCP Icon object`);let d=a,c=Mt(d.src,`icons[${u}].src`),l=d.mimeType;if(l!==void 0&&(typeof l!="string"||!l.toLowerCase().startsWith("image/")))throw new TypeError(`icons[${u}].mimeType must be an image MIME type when provided`);let p=d.sizes;if(p!==void 0&&(!Array.isArray(p)||p.some(y=>typeof y!="string"||y.length===0)))throw new TypeError(`icons[${u}].sizes must be an array of non-empty strings when provided`);let g=p===void 0?void 0:p.map(y=>y),T=d.theme;if(T!==void 0&&T!=="light"&&T!=="dark")throw new TypeError(`icons[${u}].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)},...T!==void 0&&{theme:T}})}))}let r=e.favicon===void 0?void 0:Mt(e.favicon,"favicon"),o=r===void 0?pr(n??[]):void 0,s=r??o?.src,i=o?.mimeType??n?.find(a=>a.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 Ot(e,t,n){if(e!==void 0)return e.map(r=>({...r,src:t!==void 0&&Le(r.src)?`${V(t)}${lr(n,r.src)}`:r.src,...r.sizes!==void 0&&{sizes:[...r.sizes]}}))}function At(e){return e.favicon!==void 0&&Le(e.favicon)||e.icons?.some(t=>Le(t.src))===!0}function Ct(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":cr}});if(o==="data"){let d=bt(n,"favicon");return new Response(r.method==="HEAD"?null:d.bytes.buffer,{status:200,headers:{"Content-Type":e.faviconMimeType??d.mimeType,"Cache-Control":Rt,"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"),a=await wt(i,n);if(a===null)return new Response("Not Found",{status:404,headers:{"Cache-Control":"no-store"}});let u=await vt(a,{...t.deferCors===!0&&{deferCors:!0},...r.method==="HEAD"&&{head:!0}});return u.headers.set("Cache-Control",Rt),u.headers.set("X-Content-Type-Options","nosniff"),e.faviconMimeType!==void 0&&u.headers.set("Content-Type",e.faviconMimeType),u}}function Et(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 Pt(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 St(e,t,n=process.env){if(e!==void 0)return e;let r=hr(n.PORT);return r!==void 0?r:t??3e3}function hr(e){if(e===void 0||e.trim()==="")return;let t=Number(e);return Number.isInteger(t)&&t>=0&&t<=65535?t:void 0}import{CLIENT_CAPABILITIES_META_KEY as Tr,CLIENT_INFO_META_KEY as Rr,inputRequired as Ve,inputResponse as Mr}from"@modelcontextprotocol/server";import{HonoRequest as br}from"hono/request";import{hostHeaderValidationResponse as gr,originValidationResponse as yr}from"@modelcontextprotocol/server";var kt=new WeakMap;function M(e){let t=kt.get(e);return t===void 0&&(t={},kt.set(e,t)),t}function ae(e){return new URL(e.url).pathname}function _t(e,t){return ae(e)===t}function Ne(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 He(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,a]=s.trim().toLowerCase().split("=");return i==="q"&&Number(a)===0})})}function Ut(){return async(e,t)=>{let n=M(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 It(e){return async(t,n)=>gr(t,e)??n()}function Lt(e,t=!0){return async(n,r)=>t&&(n.method==="GET"||n.method==="HEAD")?r():yr(n,e)??r()}import{CLIENT_CAPABILITIES_META_KEY as wr}from"@modelcontextprotocol/server";var qe="io.modelcontextprotocol/ui",ue="text/html;profile=mcp-app",jt="ui://views/";var de="ui/resourceUri";function Y(e){return`${jt}${e}.html`}var vr=new WeakMap;function De(e,t){vr.set(e,t)}function $e(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[wr];if(!(typeof r!="object"||r===null))return r}function ce(e){let t=e?.extensions;if(t===void 0)return!1;let n=t[qe];if(typeof n!="object"||n===null)return!1;let r=n.mimeTypes;return Array.isArray(r)?r.includes(ue):!1}function xr(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 U(e){return typeof e=="string"?e:void 0}function Nt(e){return typeof e=="string"||typeof e=="number"&&Number.isFinite(e)?e:void 0}function Or(e){if(e===void 0)return;let t=U(e["openai/locale"])??U(e["webplus/i18n"]),n=U(e["openai/userAgent"]),r=U(e["openai/subject"]),o=U(e["openai/session"]),s=U(e["openai/organization"]),i=e["openai/userLocation"],a;if(typeof i=="object"&&i!==null&&!Array.isArray(i)){let u=i,d={city:U(u.city),region:U(u.region),country:U(u.country),timezone:U(u.timezone),latitude:Nt(u.latitude),longitude:Nt(u.longitude)},c=Object.entries(d).filter(l=>l[1]!==void 0);c.length>0&&(a=Object.fromEntries(c))}if(!(t===void 0&&n===void 0&&a===void 0&&r===void 0&&o===void 0&&s===void 0))return{...t!==void 0&&{locale:t},...n!==void 0&&{userAgent:n},...a!==void 0&&{location:a},...r!==void 0&&{subject:r},...o!==void 0&&{conversationId:o},...s!==void 0&&{organizationId:s}}}function Ar(e){let t=e.mcpReq.envelope,n={...t?.[Tr]??{}},r={...t?.[Rr]??{}},o=Or(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 Cr(e){return async function(n,r,o){let s,i;if(typeof o=="string")s=Ve.elicitUrl({message:r,url:o});else if(o!==void 0)i=o,s=Ve.elicit({message:r,requestedSchema:o});else throw new TypeError("ctx.elicit(key, message, value) requires a form schema or URL string");let a=Mr(e,n);if(a.kind==="elicit"){if(a.action!=="accept")return{status:a.action};if(i===void 0)return{status:"accept"};if(a.content!==void 0){let u=await i["~standard"].validate(a.content);if(u.issues===void 0)return{status:"accept",data:u.value}}}return{status:"required",result:Ve({inputRequests:{[n]:s}})}}}function we(e){let t=e.http?.req,n=t===void 0?void 0:M(t).honoContext,r=n?.req??(t===void 0?void 0:new br(t)),o={signal:e.mcpReq.signal,...r!==void 0&&{request:r},...e.mcpReq.inputResponses!==void 0&&{inputResponses:e.mcpReq.inputResponses},client:Ar(e),elicit:Cr(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,a){let u=e.mcpReq._meta?.progressToken;return u===void 0?!1:(await e.mcpReq.notify({method:"notifications/progress",params:{progressToken:u,progress:s,...i!==void 0&&{total:i},...a!==void 0&&{message:a}}}),!0)},async sendLog(s,i,a){await e.mcpReq.notify({method:"notifications/message",params:{level:s,data:i,...a!==void 0&&{logger:a}}})}};return n!==void 0?Object.assign(n,o):{...o,...r!==void 0&&{req:r}}}function Ht(e){let t=e.http?.authInfo;return xr(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 Er(e){return"contents"in e&&Array.isArray(e.contents)}function Pr(e){return"messages"in e&&Array.isArray(e.messages)}function Be(e,t){if(Er(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=Sr(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 Sr(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 qt(e){if(Pr(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 kr=["GET","HEAD","POST","OPTIONS"],_r=["Content-Type","Authorization","mcp-protocol-version","mcp-method","mcp-name"];function Ur(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 Ir(e,t){if(t.headers.has("Access-Control-Allow-Origin"))return;let n=t.headers.get("Origin"),r=Ur(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 Lr(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)}),new Response(e.body,{status:e.status,statusText:e.statusText,headers:n})}function Dt(e){if(!(e.enabled!==!1))return async(r,o)=>o();let n={...e.origin!==void 0&&{origin:e.origin},methods:e.methods??kr,allowedHeaders:e.allowedHeaders??_r,credentials:e.credentials??!1};return async(r,o)=>{let s=Ir(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 Lr(i,s)}}function $t(e){return e!==void 0&&e.enabled!==!1}import{CallToolResultSchema as jr,GetPromptResultSchema as Nr,ListPromptsResultSchema as Hr,ListResourcesResultSchema as qr,ListToolsResultSchema as Dr,ReadResourceResultSchema as $r}from"@modelcontextprotocol/core";import{isInputRequiredResult as Vr}from"@modelcontextprotocol/server";var Br=["tools/call","tools/list","resources/read","resources/list","prompts/get","prompts/list"];function Bt(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 Ft(e,t){let n=Gr(e),r=t;if(n!=="*"&&!Fr(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,a;if(await r(o,async()=>{a=await s(),i=!0}),!i)throw new Error(`Wildcard MCP middleware "${n}" must call next()`);return a}}:{pattern:n,handler:(o,s)=>r(o,s)}}function Wt(e,t){let{pattern:n,phase:r}=Kr(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 Fr(e){return Br.some(t=>t===e)}function Wr(e,t,n){let r=e.filter(o=>le(o.pattern,t));return r.length===0?o=>n():o=>{let s=-1,i=a=>a<=s?Promise.reject(new Error("next() called multiple times")):(s=a,a===r.length?n():r[a].handler(o,()=>i(a+1)));return i(0)}}function zr(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 zt(e,t,n,r,o){Vt(t,n,"before",r);let i=await Wr(e,n,o)(r);return Jr(n,i),Vt(t,n,"complete",r,i),i}function Jr(e,t){if((e==="tools/call"||e==="resources/read"||e==="prompts/get")&&Vr(t))return;let n=(()=>{switch(e){case"tools/call":return We(e,t,"content"),jr.safeParse(t);case"tools/list":return Fe(e,t),Dr.safeParse({tools:t});case"resources/read":return We(e,t,"contents"),$r.safeParse(t);case"resources/list":return Fe(e,t),qr.safeParse({resources:t});case"prompts/get":return We(e,t,"messages"),Nr.safeParse(t);case"prompts/list":return Fe(e,t),Hr.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 Fe(e,t){if(!Array.isArray(t))throw new TypeError(`[mcp-use] ${e} middleware returned an invalid result: expected an array`)}function We(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 Vt(e,t,n,r,o){let s=zr(r);for(let i of e)if(!(i.phase!==n||!le(i.pattern,t)))try{i.handler(s,o)}catch(a){console.error(`[mcp-use] MCP event listener for "${i.pattern}" (${n}) threw:`,a)}}function Kr(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 Gr(e){return e.startsWith("mcp:")?e.slice(4):e}import{CLIENT_INFO_META_KEY as Yr,isJSONRPCRequest as Xr}from"@modelcontextprotocol/server";function Zr(){return typeof process>"u"||process.env?.NO_COLOR!==void 0?!1:process.stdout?.isTTY===!0}function j(e,t){return n=>Zr()?`\x1B[${e}m${n}\x1B[${t}m`:n}var Je=j(1,22),ve=j(2,22),Ke=j(31,39),Yt=j(32,39),L=j(33,39),Qr=j(34,39),Xt=j(35,39),pe=j(36,39),eo=j(90,39);function to(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 Zt(e){if(e!==void 0)return typeof e.version=="string"&&e.version!==""?`${e.name}/${e.version}`:e.name}var Qt={initialize:e=>({subject:Zt(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 no(e){return Object.prototype.hasOwnProperty.call(Qt,e)}function ro(e){if(!no(e.method))return{};try{let t=Qt[e.method],n=t(e.params);return typeof n.subject=="string"||n.subject===void 0?n:{}}catch{return{}}}var Jt=80;function Kt(e){let t;try{t=JSON.stringify(e)??String(e)}catch{t=String(e)}return t.length>Jt?`${t.slice(0,Jt)}...`:t}function oo(e){let t=e.params?._meta;if(t===void 0)return;let n=t[Yr];if(!(typeof n!="object"||n===null||typeof n.name!="string"))return Zt(n)}function Te(e){return e.replace(/[\u0000-\u001F\u007F-\u009F]+/g," ")}function so(e){return e.startsWith("tools/")?pe:e.startsWith("resources/")?Yt:e.startsWith("prompts/")?Xt:e==="initialize"||e==="ping"?eo:Qr}var io=new Set(["authorization","proxy-authorization","cookie","set-cookie","x-api-key"]);function Gt(e){return Object.fromEntries(Object.entries(e).map(([t,n])=>[t,io.has(t.toLowerCase())?"[REDACTED]":n]))}async function ao(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 a=i.slice(5).trim();a&&o(a)}}else o(t);let s;for(let i of r){if(i===null||typeof i!="object")continue;let a=i;if(typeof a.error?.message=="string")return{errorMessage:a.error.message};if(a.result?.isError===!0){let d=(Array.isArray(a.result.content)?a.result.content:[]).find(c=>c?.type==="text"&&typeof c.text=="string");return{errorMessage:d?String(d.text):"tool error"}}"result"in a&&(s=a.result)}return{errorMessage:null,result:s}}function uo(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 Re(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 ze=1e4;async function co(e,t,n,r){console.log(`
2
- ${pe("=".repeat(80))}`),console.log(Je(pe("[TRACE] Request Details"))),console.log(pe("-".repeat(80))),Object.keys(t).length>0&&(console.log(L("Request Headers:")),console.log(Re(Gt(t)))),n!==void 0&&(console.log(L("Request Body:")),console.log(typeof n=="string"?n:Re(n)));let o={};if(e.headers.forEach((s,i)=>{o[i]=s}),Object.keys(o).length>0&&(console.log(L("Response Headers:")),console.log(Re(Gt(o)))),!r)console.log(`${L("Response Body:")} (streaming \u2014 not dumped)`);else if(e.body===null)console.log(`${L("Response Body:")} (no body)`);else try{let s=await e.clone().text();if(s.length===0)console.log(`${L("Response Body:")} (empty)`);else{console.log(L("Response Body:"));try{console.log(Re(JSON.parse(s)))}catch{console.log(s.length>ze?`${s.slice(0,ze)}
3
- ... (truncated, ${s.length-ze} more characters)`:s)}}}catch{console.log(`${L("Response Body:")} (unable to read)`)}console.log(`${pe("=".repeat(80))}
4
- `)}function lo(e){let t=String(e);return e>=500?Xt(t):e>=400?Ke(t):e>=300?L(t):Yt(t)}function po(e,t){return e!=="GET"&&e!=="HEAD"?!1:t.endsWith("/favicon.ico")}function en(e={}){return e.enabled===!1?(t,n)=>n():async(t,n)=>{let r=to(e.level),o=Date.now(),s=t.method,i=new URL(t.url).pathname;if(po(s,i))return n();let a={};r==="trace"&&t.headers.forEach((y,m)=>{a[m]=y});let u;if(s!=="GET"&&s!=="HEAD"){let y=M(t).parsedBody;if(y!==void 0)u=y;else try{u=await t.clone().json()}catch{}}let d=await n(),c=Date.now()-o,l=new Date().toISOString().substring(11,19),p=Xr(u)?u:void 0,g=p?.method==="subscriptions/listen",T=[[ve(l),Je(s),i,lo(d.status),ve(`in ${c}ms`)].join(" ")];if(p!==void 0){let y=Te(p.method),m=[` ${so(y)(y)}`],R=ro(p);R.subject!==void 0&&m.push(Je(Te(R.subject)));let I=r!=="info";I&&R.input!==void 0&&m.push(Kt(R.input));let A=g?{errorMessage:null}:await ao(d);if(I&&p.method==="tools/call"&&A.errorMessage===null&&A.result!==void 0&&m.push(ve("->"),Kt(uo(A.result))),p.method!=="initialize"){let D=oo(p);D!==void 0&&m.push(ve(Te(D)))}A.errorMessage!==null?m.push(Ke(`ERROR ${Te(A.errorMessage)}`)):d.status>=400&&m.push(Ke(`ERROR (HTTP ${d.status})`)),T.push(m.join(" "))}return console.log(T.join(`
5
- `)),r==="trace"&&await co(d,a,u,!g),d}}import{createMcpHandler as fo}from"@modelcontextprotocol/server";function tn(e,t={}){let{path:n="/mcp",handler:r,authInfo:o}=t,s=r?.legacy??"stateless",i=fo(e,{legacy:"stateless",...r});return{handler:i,fetch:async u=>{if(!_t(u,n))return new Response("Not Found",{status:404});if(s==="stateless"){let g=u.method.toUpperCase();if(g==="GET"||g==="DELETE"||g==="HEAD")return new Response(null,{status:204})}let d=M(u),c=d.parsedBody;if(c===void 0)try{c=await u.clone().json()}catch{}let l=$e(c);l!==void 0&&De(u,l);let p=o?.(u)??d.authInfo;return i.fetch(u,{...c!==void 0&&{parsedBody:c},...p!==void 0&&{authInfo:p}})}}}import{completable as nn}from"@modelcontextprotocol/server";function Ge(e){let t=e.map(String);return n=>{let r=String(n??"").toLowerCase();return t.filter(o=>o.toLowerCase().startsWith(r))}}function mo(e,t){return typeof t=="function"?nn(e,(n,r)=>t(String(n??""),r)):nn(e,Ge(t))}function rn(e){let t=Object.create(null);for(let[n,r]of Object.entries(e))r!==void 0&&(t[n]=Array.isArray(r)?Ge(r):r);return t}import{fromJsonSchema as ho}from"@modelcontextprotocol/server";var go=["get","put","post","delete","options","head","patch","trace"];function un(e,t){let n=yo(t.spec,t),r=Ro(n),o=n.length>0?_o(t):void 0;for(let[s,i]of n.entries()){let a=r[s];if(a===void 0||o===void 0)continue;let u=Oo(i);e.tool({name:a,description:Mo(i),inputSchema:xo(t.spec,i,u)},async d=>Po(i,d,t,u,o))}}function yo(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=on(e,s.parameters);for(let a of go){let u=s[a];if(u===void 0)continue;let d=X(e,u);if(d===void 0||me(d))continue;let c=on(e,d.parameters),l=d.requestBody===void 0?void 0:X(e,d.requestBody),p={method:a,path:r,operation:d,parameters:wo(i,c),...l!==void 0&&!me(l)&&{requestBody:l}};vo(p,t)&&n.push(p)}}return n}function on(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 wo(e,t){let n=new Map;for(let r of[...e,...t])n.set(`${r.in}:${r.name}`,r);return[...n.values()]}function vo(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=>To(e,n))}function To(e,t){if(t.method&&t.method.toLowerCase()!==e.method||t.operationId&&!sn(t.operationId,e.operation.operationId??"")||t.path&&!sn(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 sn(e,t){return typeof e=="string"?e===t:(e.lastIndex=0,e.test(t))}function Ro(e){let t=new Map;return e.map(n=>{let r=bo(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 Mo(e){return[e.operation.summary,e.operation.description,`HTTP: ${e.method.toUpperCase()} ${e.path}`].filter(t=>!!t).join(`
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(`
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
+ ... (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(`
6
6
 
7
- `)}function bo(e){return e.trim().replace(/[^a-zA-Z0-9_-]+/g,"_").replace(/_+/g,"_").replace(/^_/,"").replace(/_$/,"").slice(0,64)||"openapi_tool"}function xo(e,t,n){let r={},o=[];for(let{parameter:u,inputName:d}of n.parameters){let c=an(e,u.schema??{});r[d]={...c,description:u.description??`${u.in} parameter`},(u.required||u.in==="path")&&o.push(d)}let s=dn(t.requestBody);s!==void 0&&n.bodyInputName!==void 0&&(r[n.bodyInputName]=an(e,s),t.requestBody?.required&&o.push(n.bodyInputName));let i=Co(e),a={type:"object",properties:r,additionalProperties:!1,...o.length>0&&{required:o},...i!==void 0&&{$defs:i}};return ho(a)}function Oo(e){let t=e.parameters.filter(i=>i.in!=="cookie"),n=dn(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 u=(r.get(i.name)??0)>1||i.name===n?`${i.name}_${i.in}`:i.name;return{parameter:i,inputName:Ao(u,o)}}),...n!==void 0&&{bodyInputName:n}}}function Ao(e,t){let n=e,r=2;for(;t.has(n);)n=`${e}_${r}`,r+=1;return t.add(n),n}function Co(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 an(e,t){let n=fe(e,t,new Set);return Z(n)??{}}function fe(e,t,n){if(Array.isArray(t))return t.map(a=>fe(e,a,n));let r=Z(t);if(r===void 0)return t;let o=typeof r.$ref=="string"?r.$ref:void 0,s={};for(let[a,u]of Object.entries(r))a!=="$ref"&&(a==="nullable"&&typeof u=="boolean"||(s[a]=fe(e,u,n)));let i=s;if(o!==void 0){let a=Eo(e,o);if(a!==void 0)i={$ref:a,...s};else if(!n.has(o)){let u=X(e,{$ref:o});if(u!==void 0){let d=new Set(n);d.add(o),i={...Z(fe(e,u,d))??{},...s}}}}return r.nullable===!0?{anyOf:[i,{type:"null"}]}:i}function Eo(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 dn(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 Po(e,t,n,r,o){let s=n.fetch??globalThis.fetch,i=So(e,t,r.parameters,o),a=ko(r.parameters,t,n),u=r.bodyInputName,d=u===void 0||t[u]===void 0?void 0:JSON.stringify(t[u]);d!==void 0&&!Lo(a,"content-type")&&(a["content-type"]="application/json");let c=await s(i,{method:e.method.toUpperCase(),headers:a,...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 So(e,t,n,r){let o=e.path.replace(/{([^}]+)}/g,(i,a)=>{let u=n.find(({parameter:d})=>d.in==="path"&&d.name===a);return encodeURIComponent(String(u===void 0?"":t[u.inputName]??""))}),s=new URL(o.replace(/^\/+/,""),Io(r));for(let{parameter:i,inputName:a}of n){if(i.in!=="query")continue;let u=t[a];u==null||u===""||Uo(s,i.name,u)}return s.toString()}function ko(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 _o(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 Uo(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 Io(e){return e.endsWith("/")?e:`${e}/`}function Lo(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 ta,OAuthErrorCode as na,bearerAuthChallengeResponse as ra,getOAuthProtectedResourceMetadataUrl as Tn,oauthMetadataResponse as oa,requireBearerAuth as Rn,verifyBearerToken as sa}from"@modelcontextprotocol/server";import{getOAuthProtectedResourceMetadataUrl as Wi,oauthMetadataResponse as Yo,requireBearerAuth as zi}from"@modelcontextprotocol/server";function N(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 cn,OAuthErrorCode as jo}from"@modelcontextprotocol/server";import{createRemoteJWKSet as No,jwtVerify as Ho,errors as H}from"jose";function C(e){let t=e.key??No(e.jwksUrl),n=ln(e.resource);return{async verifyAccessToken(r){try{let{payload:o}=await Ho(r,t,{issuer:e.issuer,...e.algorithms!==void 0&&{algorithms:[...e.algorithms]},requiredClaims:["exp","sub"]}),s={...o},i=b(s,"client_id")??b(s,"azp"),a=Do(s,"exp"),u=$o(s,n);return{token:r,clientId:i??"",scopes:x(s.scope),expiresAt:a,extra:{payload:s},resource:u}}catch(o){throw o instanceof cn?o:Bo(o)?(process.env.MCP_USE_OAUTH_DEBUG&&Wo(r,o),v("JWT verification failed",o)):o}}}}function E(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(!pn(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 h(e,t){let n=new URL(e);return n.pathname=`${n.pathname.replace(/\/+$/,"")}/`,new URL(t.replace(/^\/+/,""),n).href}function P(e){let t=e.extra?.payload;if(!N(t))throw v("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 f(e,t){let n=e[t];return typeof n=="string"?n:void 0}function S(e,t){let n=e[t];return typeof n=="boolean"?n:void 0}function qo(e,t){let n=e[t];return typeof n=="number"&&Number.isFinite(n)?n:void 0}function he(e,t){let n=e[t];return N(n)?n:void 0}function x(e){return typeof e=="string"?e.split(/\s+/).filter(Boolean):Array.isArray(e)?e.filter(t=>typeof t=="string"&&t.length>0):[]}function Do(e,t){let n=qo(e,t);if(n===void 0||n<=Date.now()/1e3)throw v(`Missing or expired ${t} claim`);return n}function v(e,t){let n=new cn(jo.InvalidToken,e);return t!==void 0&&(n.cause=t),n}function $o(e,t){let n=e.resource;if(n!==void 0){if(typeof n!="string")throw v("Token resource claim must be an absolute URL");if(ln(n).href!==t.href)throw v("Token resource claim does not match protected resource");return t}let r=e.aud;if(!Vo(r))throw v("Token audience claim must be a string or string array");if(!(typeof r=="string"?[r]:r).includes(t.href))throw v("Token audience does not include the protected resource");return t}function Vo(e){return typeof e=="string"||Array.isArray(e)&&e.length>0&&e.every(t=>typeof t=="string")}function ln(e){try{let t=new URL(e);if(!pn(t))throw new TypeError;return t.pathname=t.pathname==="/"?"/":t.pathname.replace(/\/+$/,""),t}catch{throw v("Token resource claim must be an absolute HTTPS URL, or HTTP URL for localhost")}}function pn(e){return/^https?:$/.test(e.protocol)&&!e.username&&!e.password&&!e.search&&!e.hash&&(e.protocol!=="http:"||W(e))}function Bo(e){return e instanceof H.JWTClaimValidationFailed||e instanceof H.JWTExpired||e instanceof H.JOSEAlgNotAllowed||e instanceof H.JOSENotSupported||e instanceof H.JWSInvalid||e instanceof H.JWTInvalid||e instanceof H.JWSSignatureVerificationFailed||e instanceof H.JWKSNoMatchingKey}var Fo=["iss","aud","azp","sub","exp","iat","nbf","client_id","scope","typ","jti"];function Ye(e){return e instanceof Error?e.message:String(e)}function Wo(e,t){try{let s=function(u,d){try{return Buffer.from(u,"base64url").toString("utf8")}catch(c){console.error(`[oauth-debug] ${d} decode failed: ${Ye(c)}`);return}};var n=s;let r=t instanceof Error?t.constructor.name:typeof t;console.error(`[oauth-debug] JWT verify failed: ${r}: ${Ye(t)}`),t instanceof H.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 u=e.length>12?`${e.slice(0,12)}\u2026`:e;console.error(`[oauth-debug] non-JWT token preview=${u} length=${e.length}`);return}let i=s(o[0],"header");i!==void 0&&console.error(`[oauth-debug] header=${i}`);let a=s(o[1],"payload");if(a===void 0)return;try{let u=JSON.parse(a),d={};for(let c of Fo)c in u&&(d[c]=u[c]);d.now=Math.floor(Date.now()/1e3),console.error(`[oauth-debug] payload=${JSON.stringify(d)}`)}catch(u){console.error(`[oauth-debug] payload decode failed: ${Ye(u)}`)}}catch{}}function fn(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(gn(hn(e.mcpUrl,"MCP_URL"),n),n)}function mn(e,t){let n=hn(e,"listen origin");if(!W(n))throw new Error("OAuth listen origin must be localhost or a loopback address");return Xe(gn(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"),yn(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);Ko(s),zo(s,n);let i;try{i=e.mapAuthInfo(s)}catch(a){throw v("Token identity mapping failed",a)}return Go(i),{...s,scopes:[...s.scopes],extra:{...s.extra,...i}}}}}function zo(e,t){if(e.resource===void 0)throw v("Token verifier did not return a validated protected resource");if(Jo(e.resource).href!==Qe(t).href)throw v("Token resource does not match the protected resource")}function Jo(e){if(!(e instanceof URL))throw v("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 v("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 Ko(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 v("Token verifier returned invalid authentication information")}function Go(e){if(e===null||typeof e!="object"||!("user"in e)||e.user===void 0||!N(e.payload)||!Array.isArray(e.permissions)||!e.permissions.every(t=>typeof t=="string"))throw v("Token identity mapping must return user, payload, and string permissions")}function hn(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 gn(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 yn(e)}function yn(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=Yo(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 wn(e){return M(e).authInfo}function O(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(Xo(e.oauthMetadata),e.resource!==void 0&&Zo(e.resource),vn(e.requiredScopes,"requiredScopes"),vn(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 Xo(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 Zo(e){J(z(e,"resource"),"resource")}function vn(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 Mn(e){return e.inputSchema??e.schema}var Qo="mcp_use_sdk_event",es="https://eu.i.posthog.com/i/v0/e/",ts="phc_lyTtbYwvkdSbrcMQNPiKiiRWrrM1seyKIMjycSvItEI",ns=/(^|_)(arguments?|args|body|command|headers?|location|message|organization|path|query|response|secret|subject|token|uri|url|user_agent)(_|$)/i,rs=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(),bn=new Set,nt=new Set,xn=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 On(e){let t=st(e);return t!==void 0&&t.length>0&&t.length<=128&&!ot(t)?t:void 0}function os(){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 ss(e){return Object.fromEntries(Object.entries(e).filter(([t,n])=>t.length>128||ot(t)||t.startsWith("$")||rs.has(t)||ns.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 is(e){let t=On("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=xn.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`,a=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{}},u=await a();if(u!==void 0)return{id:u,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 a();if(c!==void 0)return{id:c,stability:"server"}}}catch{}return{id:rt,stability:"process"}})();return xn.set(e,r),r}function as(e,t,n,r,o){let s=On("MCP_USE_TELEMETRY_VALIDATION_ID");if(os()||st("NODE_ENV")==="test"&&s===void 0||nt.size>=16)return;if(r.onceKey!==void 0){if(bn.has(r.onceKey))return;bn.add(r.onceKey)}let i=Math.max(0,Math.min(1,r.sampleRate??1));if(s===void 0&&Math.random()>=i)return;let a=(async()=>{try{let u=await o(),d=JSON.stringify({api_key:ts,event:Qo,properties:{...ss(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:u.id,runtime_id:rt,identity_stability:u.stability,distinct_id:u.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(es,{method:"POST",headers:{"content-type":"application/json"},keepalive:!0,body:d})}catch{return}})();nt.add(a),a.then(()=>nt.delete(a))}function be(e,t,n={},r={}){as(e,t,n,r,()=>is(r.serverRoot))}var xe=Symbol("mcp-use/registerViews");function Cn(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 us(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("/")?Cn(e,t):`${t}${us(n,r)}${e.replace(/^\/+/,"")}`}function ds(e,t){return`${e}${G(t,"_mcp-use/public")}/`}function cs(e){return e.replaceAll(/<\/script/gi,"<\\/script").replaceAll("<!--","\\x3C!--")}function ls(e){return e.replaceAll(/<\/style/gi,"<\\/style")}function at(e){return e.replaceAll("&","&amp;").replaceAll('"',"&quot;").replaceAll("<","&lt;").replaceAll(">","&gt;")}var An="<style>html,body,#root{background:transparent}</style>";function ut(e,t,n,r){let o={publicBase:ds(t,n)},s=`<script>globalThis.__mcpUseViewConfig=${JSON.stringify(o)};</script>`;if(e.kind==="inline"){let d=e.css.length>0?`<style>${ls(e.css)}</style>`:"",c=`<script type="module">${cs(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 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>
9
9
  <html>
10
10
  <head>
11
11
  <meta charset="utf-8">
12
12
  ${s}
13
- ${An}
13
+ ${Un}
14
14
  ${d}
15
15
  </head>
16
16
  <body>
@@ -18,18 +18,18 @@ ${d}
18
18
  ${c}
19
19
  </body>
20
20
  </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(`
21
- `),a=(e.scripts??[]).map(d=>`<script type="module" src="${at(it(d,t,n,r))}"></script>`).join(`
22
- `),u=it(e.entry,t,n,r);return`<!doctype html>
21
+ `),u=(e.scripts??[]).map(d=>`<script type="module" src="${at(it(d,t,n,r))}"></script>`).join(`
22
+ `),a=it(e.entry,t,n,r);return`<!doctype html>
23
23
  <html>
24
24
  <head>
25
25
  <meta charset="utf-8">
26
26
  ${s}
27
- ${An}
27
+ ${Un}
28
28
  ${i}
29
29
  </head>
30
30
  <body>
31
31
  <div id="root"></div>
32
- ${a}
33
- <script type="module" src="${at(u)}"></script>
32
+ ${u}
33
+ <script type="module" src="${at(a)}"></script>
34
34
  </body>
35
- </html>`}var ps={connectDomains:"CSP_CONNECT_DOMAINS",resourceDomains:"CSP_RESOURCE_DOMAINS",frameDomains:"CSP_FRAME_DOMAINS",baseUriDomains:"CSP_BASE_URI_DOMAINS"};function En(e){return e===void 0||e.trim()===""?[]:e.split(",").map(t=>t.trim()).filter(t=>t.length>0)}function Pn(e){if(typeof process>"u")return;let t=process.env[e];if(!(t===void 0||t.trim()===""))return En(t)}function fs(){return Pn("CSP_URLS")??[]}function Oe(e){let t=Pn(ps[e]);return t!==void 0?t:fs()}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 ms(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(ms(t.serverOrigin)));let o=[],s=t.explicitAssetsBase?t.assetsOrigin:t.serverOrigin;s!==""&&o.push(s);let i=Ae(n?.connectDomains??[],Oe("connectDomains"),r),a=Ae(n?.resourceDomains??[],Oe("resourceDomains"),o),u=Ae(n?.frameDomains??[],Oe("frameDomains")),d=Ae(n?.baseUriDomains??[],Oe("baseUriDomains"));return{...n,connectDomains:i,resourceDomains:a,frameDomains:u,baseUriDomains:d}}var hs=".mcp-use/build/views/public",gs="public",ys=".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(!Ne(s,r))return new Response("Not Found",{status:404});let a=ae(s).slice(r.length+1),u=a.indexOf("/");if(u<=0||u===a.length-1)return new Response("Not Found",{status:404});let d=a.slice(0,u),c=a.slice(u+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:T}]=await Promise.all([import("path"),import("./public-route-GWDSKOSN.js")]),y=p(o,ys,d),m=await g(y,c);return m===null?new Response("Not Found",{status:404}):await T(m,{...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?gs:hs,s=n?.projectRoot??process.cwd();return async i=>{if(i.method!=="GET"&&i.method!=="HEAD")return new Response("Method Not Allowed",{status:405});if(!Ne(i,r))return new Response("Not Found",{status:404});let u=ae(i).slice(r.length+1),d;try{d=decodeURIComponent(u)}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),T=await l(g,d);return T===null?new Response("Not Found",{status:404}):await p(T,{...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 a=Y(e);i.resourceUri=a,r[de]=a}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 ws(e){let t=e?.request,n=e?.serverOrigin??(t!==void 0?ke(t):""),r=e?.assetsBase??(t!==void 0?V(t):n);return{serverOrigin:n,assetsOrigin:_e(r),explicitAssetsBase:Ue(),...e?.hmrWs===!0?{hmrWs:!0}:{}}}function Ce(e,t){let r={csp:dt(e,ws(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 Un(e){if(!jn(e))return;let t=Q(e.params);if(e.method==="initialize"){let s=Q(t?.clientInfo),i=Q(t?.capabilities)??{};return In(s,i,t?.protocolVersion,"legacy")}let n=Q(t?._meta),r=Q(n?.[bs]),o=Q(n?.[Ms]);if(!(r===void 0||o===void 0))return In(r,o,n?.[xs],"modern")}function In(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 Ln(e){if(typeof e!="object"||e===null||Array.isArray(e)||!("$schema"in e))return e;let t={...e};return delete t.$schema,t}function Os(e){return e.map(t=>({...t,inputSchema:Ln(t.inputSchema),...t.outputSchema===void 0?{}:{outputSchema:Ln(t.outputSchema)}}))}function As(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 ye=class e{#e;#t;#n=new Map;#r=new Map;#l=new Map;#i=new Map;#o=new Map;#a=new Map;#h=!1;#p=!1;#u=process.cwd();#E;#_;#f;#R;#g;#M;#b=!1;#U=!1;#I=!1;#x=[];#y=[];#L=crypto.randomUUID();#w=new Set;#m=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"});un(n,t);for(let r of n.#n.keys())n.#w.add(r);return n}constructor(t){if(Et(t),this.#e=t,this.#t=xt(t),this.app=new _n,this.app.use("*",async(n,r)=>{M(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=fn({provider:t.oauth,basePath:this.#d(),...n!==void 0&&{mcpUrl:n}});this.#M=r,this.#b=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.#w.delete(t.name),this.#m.delete(t.name),this.#n.set(t.name,{definition:t,callback:n}),Object.freeze({name:t.name})}[xe](t,n){if(this.#h)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.#h=!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:rn(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.#x.push(Ft(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.#y.push(Wt(t,n)),this}__setEventBus(t){this.#s("event bus","shared"),this.#R=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{createServer:r}=await import("http"),{toNodeHandler:o}=await import("./node-bridge-KQ3STLK5.js"),s=Pt(n.host,this.#e.host),i=St(t,this.#e.port);return this.#z(s),new Promise((a,u)=>{let d,c,l=new Promise((m,R)=>{d=m,c=R});l.catch(()=>{});let p=!1,g=m=>{p||(p=!0,u(m)),c?.(m),new Promise(R=>y.close(()=>R())).catch(()=>{}).finally(()=>{this.#g===y&&(this.#g=void 0)})},T=o({fetch:async m=>(await l)(m)}),y=r((m,R)=>{T(m,R)});y.once("error",g),y.listen(i,s,()=>{try{let m=y.address(),R=typeof m=="object"&&m!==null?m.port:i,{fetch:I}=this.#c("listen",R,s);d?.(I),p||(p=!0,a({port:R,url:`http://localhost:${R}${this.#d()}`}))}catch(m){g(m)}}),this.#g=y})}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.#g;if(o!==void 0)try{await new Promise((s,i)=>{o.close(a=>a?i(a):s())}),this.#g=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.#b)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=mn(`http://localhost:${n}`,this.#d()),this.#b=!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.#b)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.#w.size-this.#m.size,tools_openapi:this.#w.size,tools_proxied:this.#m.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.#m.size,proxy_resources_mounted:this.#O.size,proxy_prompts_mounted:this.#A.size,http_middleware:this.#j,mcp_middleware:this.#x.length,observers_before:this.#y.filter(({phase:t})=>t==="before").length,observers_complete:this.#y.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=Un(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.#m.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),a=r!==void 0?[...new Set([...Sn(),...r])]:t==="listen"&&i?Sn():void 0,u=o!==void 0?[...new Set([...vs(),...o])]:void 0;return{hosts:a,origins:u}}#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(),a=i==="/"?"":i,u=new _n,d=[Ut(),en(this.#e.logging)],c=this.#e.cors;c!==void 0&&d.unshift(Dt(c));let l=$t(c);o!==void 0&&d.unshift(It(o)),s!==void 0&&d.push(Lt(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 w=this.#e.oauth;d.push(tt(w,p))}for(let w of d)As(u,w);let{handler:g,fetch:T}=tn(w=>this.#X(w),{path:i,...(this.#e.legacy!==void 0||this.#R!==void 0)&&{handler:{...this.#e.legacy!==void 0&&{legacy:this.#e.legacy},...this.#R!==void 0&&{bus:this.#R}}},...p!==void 0&&{authInfo:w=>wn(w)}}),y=async(w,_)=>_();if(p!==void 0){let w=this.#e.oauth,_=Me(w),Se=Rn({verifier:Ze(w,p),resourceMetadataUrl:Tn(p),..._.requiredScopes!==void 0&&{requiredScopes:_.requiredScopes}});y=async($,ie)=>{let K=await Se($);if(K instanceof Response)return K;let Yn=M($);return Yn.authInfo=K,ie()},u.use("*",async($,ie)=>{if(new URL($.req.url).pathname!==i){await ie();return}if(this.#e.publicLandingPage===!0&&He($.req.raw)){await ie();return}let K=await y($.req.raw,async()=>(await ie(),$.res));return $.res=K,K})}let m=w=>{let _=M(w).parsedBody;return jn(_)&&(this.#J(),this.#K(_)),T(w)},R=async w=>He(w)?(async()=>{let{createLandingPageResponse:Se}=await import("./landing-handler-2IDA43KU.js");return Se(w,i,this.#e,this.#t,this.#n.values(),this.#i.values(),this.#r.values())})():m(w),I=this.#h?this.#p:process.env.NODE_ENV!=="production",A=Ct(this.#t,{dev:I,projectRoot:this.#u,deferCors:l});A!==void 0&&this.app.all("/favicon.ico",w=>A(w.req.raw));let D=lt(i,this.#o,{dev:this.#h?this.#p:I,projectRoot:this.#u,enabled:At(this.#t),deferCors:l});if(D!==void 0&&this.app.on(["GET","HEAD"],`${a}/_mcp-use/public/*`,w=>D(w.req.raw)),!this.#p){let w=ct(i,this.#o,{projectRoot:this.#u,deferCors:l});w!==void 0&&this.app.on(["GET","HEAD"],`${a}/_mcp-use/views/*`,_=>w(_.req.raw))}this.app.all(i,w=>R(w.req.raw)),u.route("/",this.app),this.#_=u,this.#E=async w=>u.fetch(w),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.#h){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,a=t.authInfo,u=new Ts({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:Ot(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},...a!==void 0&&{authInfo:a},...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(u,p);for(let p of this.#r.values())this.#ne(u,p);for(let p of this.#l.values())this.#re(u,p);for(let p of this.#i.values())this.#se(u,p);for(let[p,g]of this.#o.entries())this.#te(u,p,g,c,l);return this.#Q(u),u}#v(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=performance.now(),s=this.#x.filter(c=>le(c.pattern,t)).length,i=c=>this.#y.filter(l=>l.phase===c&&le(l.pattern,t)).length,a=n.request?.raw,u=a===void 0?void 0:Un(M(a).parsedBody),d=(c,l)=>{be("operation","completed",{method:t,outcome:c,duration_ms:Math.max(0,Math.round(performance.now()-o)),primitive_origin:this.#Z(t,n.params),matched_middleware:s,observers_before:i("before"),observers_complete:l?i("complete"):0,...u?.protocol_era==="modern"?u:{client_name:"unknown",protocol_era:"legacy"}},{sampleRate:c==="success"?.1:1,serverRoot:this.#u})};return zt(this.#x,this.#y,t,n,r).then(c=>{let l=kn(c)?"input_required":t==="tools/call"&&typeof c=="object"&&c!==null&&"isError"in c&&c.isError===!0?"error":"success";return d(l,!0),c},c=>{throw d("error",!1),c})}#Z(t,n){if(t==="tools/call"){let r=String(n.name);return this.#m.has(r)?"proxied":this.#w.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 a=n.get(o);if(a===void 0||a.__mcpListWrapped)return;let u=async(d,c)=>{let l=c,p=d.params??{},g=this.#v(o,p,l),T,y=async()=>{let I=Bt(d,g.params),A=await a(I,c);if(typeof A!="object"||A===null)throw new TypeError(`[mcp-use] ${o} handler returned a non-object result`);T=A;let D=T[s];if(!Array.isArray(D))throw new TypeError(`[mcp-use] ${o} handler result is missing a ${s} array`);return D},m=await this.#T(o,g,y);if(!Array.isArray(m))throw new TypeError(`[mcp-use] ${o} middleware must return a ${s} array`);let R=i?.(m)??m;return{...T,[s]:R}};u.__mcpListWrapped=!0,n.set(o,u)};r("tools/list","tools",Os),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}},a=o!==void 0?ft(o.name):void 0,u=Mn(n),d=async(c,l)=>{let p=this.#v("tools/call",{name:n.name,arguments:c,...l.mcpReq._meta!==void 0&&{_meta:l.mcpReq._meta}},l),g=async()=>{let T=p.params.arguments??{},y=await r(T,this.#C(l));return kn(y)||a===void 0||y.isError===!0?y:{...y,_meta:{...y._meta,...a}}};return await this.#T("tools/call",p,g)};u!==void 0?t.registerTool(n.name,{...i,inputSchema:u},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),a=this.#oe(this.#a.get(n)?.config),u=mt(n,r,a,o);t.registerResource(n,i,u,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?V(l):o.request!==void 0?V(o.request):"",T=ut(r,g,s,n);return{contents:[{uri:d.href,mimeType:u.mimeType,text:T,_meta:Ce(a,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.#v("resources/read",{uri:o.href,...s.mcpReq._meta!==void 0&&{_meta:s.mcpReq._meta}},s),a=async()=>Be(await r(o,this.#C(s)),o.href);return await this.#T("resources/read",i,a)})}#re(t,{definition:n,callback:r,complete:o}){let s=new Rs(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,a,u)=>{let d=this.#v("resources/read",{uri:i.href,...u.mcpReq._meta!==void 0&&{_meta:u.mcpReq._meta}},u),c=async()=>Be(await r(i,a,this.#C(u)),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,a)=>{let u=this.#v("prompts/get",{name:n.name,arguments:i,...a.mcpReq._meta!==void 0&&{_meta:a.mcpReq._meta}},a),d=async()=>{let c=u.params.arguments??{};return qt(await r(c,this.#C(a)))};return await this.#T("prompts/get",u,d)};if(n.schema!==void 0)t.registerPrompt(n.name,{...o,argsSchema:n.schema},async(i,a)=>s(i,a));else{let i=async a=>s({},a);t.registerPrompt(n.name,o,i)}}#C(t){return this.#e.oauth===void 0?we(t):Ht(t)}};function Nn(e){let t=E(e.domain,"Auth0 domain").href;return O({...e,createTokenVerifier:n=>C({issuer:t,jwksUrl:new URL(h(t,".well-known/jwks.json")),resource:n}),oauthMetadata:{issuer:t,authorization_endpoint:h(t,"authorize"),token_endpoint:h(t,"oauth/token"),registration_endpoint:h(t,"oidc/register"),response_types_supported:["code"],grant_types_supported:["authorization_code","refresh_token"],code_challenge_methods_supported:["S256"]},mapAuthInfo:Cs})}function Cs(e){let t=P(e),n=b(t,"sub");if(n===void 0)throw v("Missing Auth0 subject");return{user:{id:n,...ee("email",f(t,"email")),...ee("name",f(t,"name")),...ee("nickname",f(t,"nickname")),...ee("picture",f(t,"picture")),...ee("emailVerified",S(t,"email_verified")),...ee("updatedAt",f(t,"updated_at")),roles:x(t.roles)},payload:t,permissions:x(t.permissions)}}function ee(e,t){return t===void 0?{}:{[e]:t}}function Hn(e){let t=E(e.authURL,"Better Auth authURL").href.replace(/\/$/,"");return O({...e,createTokenVerifier:n=>C({issuer:t,jwksUrl:new URL(h(t,"jwks")),resource:n}),oauthMetadata:Es(t,e.scopesSupported),mapAuthInfo:Ps})}function Es(e,t){return{issuer:e,authorization_endpoint:h(e,"oauth2/authorize"),token_endpoint:h(e,"oauth2/token"),registration_endpoint:h(e,"oauth2/register"),jwks_uri:h(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 Ps(e){let t=P(e),n=b(t,"sub");if(n===void 0)throw v("Missing Better Auth subject");return{user:{id:n,...te("email",f(t,"email")),...te("name",f(t,"name")),...te("picture",f(t,"picture")),...te("emailVerified",S(t,"email_verified")),...te("sessionId",f(t,"sid")),...te("isAnonymous",S(t,"is_anonymous")??S(t,"isAnonymous")),roles:x(t.roles)},payload:t,permissions:x(t.permissions)}}function te(e,t){return t===void 0?{}:{[e]:t}}function qn(e){let t=E(e.frontendApiUrl,"Clerk frontendApiUrl").href.replace(/\/$/,"");return O({...e,createTokenVerifier:n=>C({issuer:t,jwksUrl:new URL(h(t,".well-known/jwks.json")),resource:n}),oauthMetadata:ks(t),mapAuthInfo:n=>Ss(n)})}function Ss(e){let t=P(e),n=b(t,"sub");if(n===void 0)throw v("Missing Clerk subject");let r=f(t,"org_role");return{user:{id:n,...B("email",f(t,"email")),...B("name",f(t,"name")),...B("username",f(t,"username")),...B("picture",f(t,"picture")),...B("emailVerified",S(t,"email_verified")),...B("organizationId",f(t,"org_id")),...B("organizationRole",r),...B("organizationSlug",f(t,"org_slug")),roles:r===void 0?[]:[r]},payload:t,permissions:x(t.org_permissions)}}function ks(e){return{issuer:e,authorization_endpoint:h(e,"oauth/authorize"),token_endpoint:h(e,"oauth/token"),registration_endpoint:h(e,"oauth/register"),response_types_supported:["code"],grant_types_supported:["authorization_code","refresh_token"],code_challenge_methods_supported:["S256"]}}function B(e,t){return t===void 0?{}:{[e]:t}}function Dn(e){if(typeof e.realm!="string"||e.realm.trim().length===0||/[/?#]/.test(e.realm))throw new TypeError("Keycloak realm is invalid");let t=E(e.serverUrl,"Keycloak serverUrl"),n=h(t,`realms/${encodeURIComponent(e.realm)}`).replace(/\/$/,"");return O({...e,createTokenVerifier:r=>C({issuer:n,jwksUrl:new URL(h(n,"protocol/openid-connect/certs")),resource:r}),oauthMetadata:{issuer:n,authorization_endpoint:h(n,"protocol/openid-connect/auth"),token_endpoint:h(n,"protocol/openid-connect/token"),registration_endpoint:h(n,"clients-registrations/openid-connect"),response_types_supported:["code"],grant_types_supported:["authorization_code","refresh_token"],code_challenge_methods_supported:["S256"]},mapAuthInfo:_s})}function _s(e){let t=P(e),n=b(t,"sub");if(n===void 0)throw v("Missing Keycloak subject");let r=he(t,"realm_access"),o=he(t,"resource_access");return{user:{id:n,...ne("email",f(t,"email")),...ne("name",f(t,"name")),...ne("preferredUsername",f(t,"preferred_username")),...ne("givenName",f(t,"given_name")),...ne("familyName",f(t,"family_name")),...ne("emailVerified",S(t,"email_verified")),roles:r===void 0?[]:x(r.roles),...r!==void 0&&{realmAccess:r},...o!==void 0&&{resourceAccess:o}},payload:t,permissions:Us(o)}}function ne(e,t){return t===void 0?{}:{[e]:t}}function Us(e){return e===void 0?[]:Object.entries(e).flatMap(([t,n])=>N(n)?x(n.roles).map(r=>`${t}:${r}`):[])}function $n(e){let t=Ls(e),n=h(t,"auth/v1").replace(/\/$/,""),r=e.jwtSecret;if(r!==void 0&&new TextEncoder().encode(r).length<32)throw new TypeError("Supabase jwtSecret must be at least 32 bytes");return O({...e,createTokenVerifier:o=>C({issuer:n,jwksUrl:new URL(h(t,"auth/v1/.well-known/jwks.json")),...r!==void 0?{key:new TextEncoder().encode(r),algorithms:["HS256"]}:{algorithms:["ES256"]},resource:o}),oauthMetadata:{issuer:n,authorization_endpoint:h(t,"auth/v1/oauth/authorize"),token_endpoint:h(t,"auth/v1/oauth/token"),registration_endpoint:h(t,"auth/v1/oauth/clients/register"),response_types_supported:["code"],grant_types_supported:["authorization_code","refresh_token"],code_challenge_methods_supported:["S256"]},mapAuthInfo:Is})}function Is(e){let t=P(e),n=b(t,"sub")??b(t,"user_id");if(n===void 0)throw v("Missing Supabase subject");let r=he(t,"user_metadata")??{},o=f(t,"aal");return{user:{id:n,...F("email",f(t,"email")),...F("name",f(r,"name")),...F("fullName",f(r,"full_name")),...F("username",f(r,"username")),...F("avatarUrl",f(r,"avatar_url")),...F("role",f(t,"role")),...F("aal",o),amr:js(t.amr),...F("sessionId",f(t,"session_id"))},payload:t,permissions:o===void 0?[]:[`aal:${o}`]}}function F(e,t){return t===void 0?{}:{[e]:t}}function Ls(e){if(e.supabaseUrl!==void 0)return E(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 js(e){return Array.isArray(e)?e.flatMap(t=>{if(!N(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 Vn(e){let t=Hs(e.subdomain);return O({...e,createTokenVerifier:n=>C({issuer:t,jwksUrl:new URL(h(t,"oauth2/jwks")),resource:n}),oauthMetadata:{issuer:t,authorization_endpoint:h(t,"oauth2/authorize"),token_endpoint:h(t,"oauth2/token"),registration_endpoint:h(t,"oauth2/register"),response_types_supported:["code"],grant_types_supported:["authorization_code","refresh_token"],code_challenge_methods_supported:["S256"]},mapAuthInfo:Ns})}function Ns(e){let t=P(e),n=b(t,"sub");if(n===void 0)throw v("Missing WorkOS subject");return{user:{id:n,...q("email",f(t,"email")),...q("emailVerified",S(t,"email_verified")),...q("name",f(t,"name")),...q("preferredUsername",f(t,"preferred_username")),...q("firstName",f(t,"first_name")),...q("lastName",f(t,"last_name")),...q("picture",f(t,"picture")),roles:x(t.roles),...q("organizationId",f(t,"org_id")),...q("sessionId",f(t,"sid"))},payload:t,permissions:x(t.permissions)}}function q(e,t){return t===void 0?{}:{[e]:t}}function Hs(e){if(typeof e!="string"||e.trim().length===0)throw new TypeError("WorkOS subdomain is required");let t=E(e,"WorkOS subdomain");if(t.pathname!=="/")throw new TypeError("WorkOS subdomain must be a hostname or HTTPS origin");return t.href.replace(/\/$/,"")}function k(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 qs(e={}){re(e);let t=e.projectId??k("MCP_USE_OAUTH_SUPABASE_PROJECT_ID"),n=e.supabaseUrl??k("MCP_USE_OAUTH_SUPABASE_URL"),r=e.jwtSecret??k("MCP_USE_OAUTH_SUPABASE_JWT_SECRET");return $n({...oe(e),...t!==void 0&&{projectId:t},...n!==void 0&&{supabaseUrl:n},...r!==void 0&&{jwtSecret:r}})}function Ds(e={}){re(e);let t=e.domain??k("MCP_USE_OAUTH_AUTH0_DOMAIN"),n=e.audience??k("MCP_USE_OAUTH_AUTH0_AUDIENCE");if(t===void 0)throw new Error("Auth0 domain is required.");return Nn({...oe(e,e.resource??n),domain:t})}function $s(e={}){re(e);let t=e.serverUrl??k("MCP_USE_OAUTH_KEYCLOAK_SERVER_URL"),n=e.realm??k("MCP_USE_OAUTH_KEYCLOAK_REALM"),r=e.audience??k("MCP_USE_OAUTH_KEYCLOAK_AUDIENCE");if(t===void 0||n===void 0)throw new Error("Keycloak serverUrl and realm are required.");return Dn({...oe(e,e.resource??r),serverUrl:t,realm:n})}function Vs(e={}){re(e);let t=e.subdomain??k("MCP_USE_OAUTH_WORKOS_SUBDOMAIN");if(t===void 0)throw new Error("WorkOS subdomain is required.");return Vn({...oe(e),subdomain:t})}function Bs(e={}){re(e);let t=e.frontendApiUrl??k("MCP_USE_OAUTH_CLERK_FRONTEND_API_URL");if(t===void 0)throw new Error("Clerk frontendApiUrl is required.");return qn({...oe(e,e.resource??e.audience),frontendApiUrl:t})}function Fs(e={}){re(e);let t=e.authURL??k("MCP_USE_OAUTH_BETTER_AUTH_URL");if(t===void 0)throw new Error("Better Auth authURL is required.");return Hn({...oe(e),authURL:t})}var Bn='Deprecated temporary v1 compatibility. Use the native v2 API from "mcp-use". This entry will be removed in mcp-use v3.',gt="MCP_USE_V1_COMPAT",Fn="__mcpUseV1CompatServer",Wn=!1,yt=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){Qs(),Xs(t),this.config=t,this.serverHost=t.host??"localhost",t.baseUrl!==void 0&&(this.serverBaseUrl=t.baseUrl),this.#e=new ye(Js(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[Fn]!==void 0)throw se("multiple compatibility servers in one CLI entry","default-export one native v2 server or construct only one v1 server");n[Fn]=this}static fromOpenAPI(t){return ye.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(a,u)=>r(Ee(u))),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,a=t.description??o?.description,u=t.mimeType??o?.mimeType,d={name:t.name,uriTemplate:s,...t.title!==void 0&&{title:t.title},...a!==void 0&&{description:a},...u!==void 0&&{mimeType:u},...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,...a}=t;return this.#e.prompt(a,async(u,d)=>o(u,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:a,...u}=t,d=r===void 0?void 0:Kn(r,o),c=u.outputSchema??(r===void 0?void 0:zn(o)??Jn),l=Gn(i,o),p={...u,...c!==void 0&&{outputSchema:c},...d!==void 0&&{view:d},...(u._meta!==void 0||l!==void 0)&&{_meta:{...u._meta,...l}}};this.#e.tool(p,async(g,T)=>n(g,Ee(T)))}#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=zn(n)??Jn,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,...Gn(void 0,n)},view:Kn(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 Pu(e,t={}){return new yt({name:e,version:t.version??"1.0.0",...t})}function Su(e){return{...Ie(e),structuredContent:{data:e}}}function ku(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:M(r).authInfo;if(o!==void 0)return Ks(o);throw new Error("Authentication context is missing.")}function Ws(e,t){let n=Pe(e);return(Array.isArray(t)?t:[t]).every(o=>n.scopes.includes(o)||n.permissions.includes(o))}function zs(e,t){let n=Pe(e);return t.some(r=>n.scopes.includes(r)||n.permissions.includes(r))}function _u(e){return async(t,n)=>{if(Ws(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 Uu(e){return async(t,n)=>{if(zs(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 Js(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(Ys)},cors:Gs(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 Ks(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 Gs(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 Ys(e){try{return new URL(e).hostname}catch{return e.split(":")[0]??e}}function Xs(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 zn(e){let t=e?.props??e?.schema??e?.inputs;return Zs(t)?t:void 0}function Zs(e){return typeof e=="object"&&e!==null&&"~standard"in e&&typeof e["~standard"]?.validate=="function"}var Jn={"~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 Kn(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"],a=n?.prefersBorder??r?.["openai/widgetPrefersBorder"],u=n?.domain??r?.["openai/widgetDomain"];return{name:e,...i!==void 0&&{description:i},...s!==void 0&&{csp:s},...a!==void 0&&{prefersBorder:a},...u!==void 0&&{domain:u}}}function Gn(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 Qs(){Wn||(Wn=!0,typeof process.emitWarning=="function"?process.emitWarning(Bn,{type:"DeprecationWarning",code:gt}):console.warn(`[${gt}] ${Bn}`))}function se(e,t){return new Error(`[${gt}] ${e} is not supported by the temporary v1 compatibility entry; ${t}.`)}export{yt as MCPServer,Su as array,or as audio,sr as binary,mo as completable,Pu as createMCPServer,tr as css,ar as error,Pe as getAuth,zs as hasAnyScope,Ws as hasScope,Qn as html,rr as image,nr as javascript,Zn as markdown,dr as mix,Ds as oauthAuth0Provider,Fs as oauthBetterAuthProvider,Bs as oauthClerkProvider,$s as oauthKeycloakProvider,qs as oauthSupabaseProvider,Vs as oauthWorkOSProvider,ur as object,Uu as requireAnyScope,_u as requireScope,ir as resource,Xn as text,ku as widget,er as xml};
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};