mcp-use 2.0.0-beta.63 → 2.0.0-beta.65

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.
Files changed (42) hide show
  1. package/dist/bin.js +1 -1
  2. package/dist/{chunk-VJ4S2BU7.js → chunk-ZG2PVYTM.js} +1 -1
  3. package/dist/context.d.ts +7 -0
  4. package/dist/index-node.js +14 -12
  5. package/dist/index.d.ts +10 -7
  6. package/dist/index.js +1 -1
  7. package/dist/internal/usage.js +1 -1
  8. package/dist/landing.d.ts +17 -4
  9. package/dist/middleware/mcp-middleware.d.ts +18 -0
  10. package/dist/next/config.d.ts +33 -4
  11. package/dist/next/handler.d.ts +16 -0
  12. package/dist/next/index.d.ts +5 -0
  13. package/dist/node-bridge.d.ts +33 -4
  14. package/dist/oauth/auth0.d.ts +24 -0
  15. package/dist/oauth/better-auth.d.ts +23 -0
  16. package/dist/oauth/clerk.d.ts +26 -0
  17. package/dist/oauth/keycloak.d.ts +28 -0
  18. package/dist/oauth/provider.d.ts +17 -1
  19. package/dist/oauth/supabase.d.ts +36 -1
  20. package/dist/oauth/workos.d.ts +27 -0
  21. package/dist/react/components/error-boundary.d.ts +3 -0
  22. package/dist/react/components/theme-provider.d.ts +4 -3
  23. package/dist/react/hooks/use-view-tool.d.ts +3 -3
  24. package/dist/react/index.d.ts +5 -13
  25. package/dist/react/index.js +7 -177
  26. package/dist/react/runtime/bootstrap-view.d.ts +3 -3
  27. package/dist/react/runtime/view-runtime.d.ts +0 -2
  28. package/dist/react/types/file-types.d.ts +2 -0
  29. package/dist/react/types/host-types.d.ts +2 -0
  30. package/dist/response-helpers.d.ts +8 -0
  31. package/dist/server.d.ts +2 -0
  32. package/dist/views/types.d.ts +3 -3
  33. package/package.json +8 -12
  34. package/dist/chunk-4TTKTNKI.js +0 -1
  35. package/dist/chunk-ZBN5QPYD.js +0 -1
  36. package/dist/compat-v1/oauth.d.ts +0 -37
  37. package/dist/compat-v1.d.ts +0 -528
  38. package/dist/compat-v1.js +0 -43
  39. package/dist/landing-handler-2IDA43KU.js +0 -630
  40. package/dist/mcp-proxy-O6GLK2IL.js +0 -2
  41. package/dist/public-route-GWDSKOSN.js +0 -1
  42. package/dist/react/compat-v1.d.ts +0 -221
package/dist/compat-v1.js DELETED
@@ -1,43 +0,0 @@
1
- import{a as vt,b as Tt}from"./chunk-ZBN5QPYD.js";import{a as ke,b as _e,c as $,d as Ue}from"./chunk-4TTKTNKI.js";function ar(e){return{content:[{type:"text",text:e}],_meta:{mimeType:"text/plain"}}}function ur(e){return{content:[{type:"text",text:e}],_meta:{mimeType:"text/markdown"}}}function dr(e){return{content:[{type:"text",text:e}],_meta:{mimeType:"text/html"}}}function cr(e){return{content:[{type:"text",text:e}],_meta:{mimeType:"text/xml"}}}function lr(e){return{content:[{type:"text",text:e}],_meta:{mimeType:"text/css"}}}function pr(e){return{content:[{type:"text",text:e}],_meta:{mimeType:"text/javascript"}}}function fr(e,t="image/png"){return{content:[{type:"image",data:e,mimeType:t}],_meta:{mimeType:t,isImage:!0}}}function mr(e,t="audio/wav"){return{content:[{type:"audio",data:e,mimeType:t}],_meta:{mimeType:t,isAudio:!0}}}function hr(e,t){return{content:[{type:"text",text:e}],_meta:{mimeType:t,isBinary:!0}}}function gr(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 yr(e){return{isError:!0,content:[{type:"text",text:e}]}}function wr(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 Rt(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 vr(...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 Hn,localhostAllowedOrigins as xs,McpServer as Os,ResourceTemplate as As,CLIENT_CAPABILITIES_META_KEY as Cs,CLIENT_INFO_META_KEY as Es,PROTOCOL_VERSION_META_KEY as Ps,isJSONRPCRequest as Fn,isInputRequiredResult as qn}from"@modelcontextprotocol/server";import{createServer as Ss}from"#mcp-use-node-http";import{Hono as Dn}from"hono";var bt="public, max-age=31536000, immutable",Tr="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 br(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 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 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=Mt(d.src,`icons[${a}].src`),l=d.mimeType;if(l!==void 0&&(typeof l!="string"||!l.toLowerCase().startsWith("image/")))throw new TypeError(`icons[${a}].mimeType must be an image MIME type when provided`);let p=d.sizes;if(p!==void 0&&(!Array.isArray(p)||p.some(h=>typeof h!="string"||h.length===0)))throw new TypeError(`icons[${a}].sizes must be an array of non-empty strings when provided`);let m=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},...m!==void 0&&{sizes:Object.freeze(m)},...f!==void 0&&{theme:f}})}))}let r=e.favicon===void 0?void 0:Mt(e.favicon,"favicon"),o=r===void 0?br(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":Tr}});if(o==="data"){let d=xt(n,"favicon");return new Response(r.method==="HEAD"?null:d.bytes.buffer,{status:200,headers:{"Content-Type":e.faviconMimeType??d.mimeType,"Cache-Control":bt,"X-Content-Type-Options":"nosniff"}})}let{join:s}=await import("path"),i=t.dev?s(t.projectRoot,"public"):s(t.projectRoot,".mcp-use/build/views/public"),u=await vt(i,n);if(u===null)return new Response("Not Found",{status:404,headers:{"Cache-Control":"no-store"}});let a=await Tt(u,{...t.deferCors===!0&&{deferCors:!0},...r.method==="HEAD"&&{head:!0}});return a.headers.set("Cache-Control",bt),a.headers.set("X-Content-Type-Options","nosniff"),e.faviconMimeType!==void 0&&a.headers.set("Content-Type",e.faviconMimeType),a}}function Pt(e){if(e.basePath!==void 0){if(typeof e.basePath!="string")throw new TypeError("basePath must be an absolute URL pathname without empty segments, trailing slash, query, fragment, or whitespace");let{basePath:t}=e;if(!t.startsWith("/")||t.includes("?")||t.includes("#")||/\s/.test(t)||t.includes("//")||t.length>1&&t.endsWith("/"))throw new TypeError("basePath must be an absolute URL pathname without empty segments, trailing slash, query, fragment, or whitespace")}if(e.port!==void 0&&(typeof e.port!="number"||!Number.isInteger(e.port)||e.port<0||e.port>65535))throw new TypeError("port must be an integer between 0 and 65535")}var xr="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??xr}function kt(e,t,n=process.env){if(e!==void 0)return e;let r=Or(n.PORT);return r!==void 0?r:t??3e3}function Or(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 Ar(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=Er(Cr(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 m=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(),m])}}catch{}s=!0,r.end()}}async function Ar(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 Cr(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 Er(e){return Response.json({jsonrpc:"2.0",error:{code:-32603,message:"Internal server error"},id:e},{status:500})}import{CLIENT_CAPABILITIES_META_KEY as Ur,CLIENT_INFO_META_KEY as Ir,inputRequired as Ve,inputResponse as Lr}from"@modelcontextprotocol/server";import{HonoRequest as jr}from"hono/request";import{hostHeaderValidationResponse as Pr,originValidationResponse as Sr}from"@modelcontextprotocol/server";var qt=new WeakMap;function R(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=R(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 Bt(e){return async(t,n)=>Pr(t,e)??n()}function Vt(e,t=!0){return async(n,r)=>t&&(n.method==="GET"||n.method==="HEAD")?r():Sr(n,e)??r()}import{CLIENT_CAPABILITIES_META_KEY as kr}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 _r=new WeakMap;function $e(e,t){_r.set(e,t)}function Be(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[kr];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 Nr(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 Hr(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 qr(e){let t=e.mcpReq.envelope,n={...t?.[Ur]??{}},r={...t?.[Ir]??{}},o=Hr(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 Dr(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 u=Lr(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:Ve({inputRequests:{[n]:s}})}}}function we(e){let t=e.http?.req,n=t===void 0?void 0:R(t).honoContext,r=n?.req??(t===void 0?void 0:new jr(t)),o={signal:e.mcpReq.signal,...r!==void 0&&{request:r},...e.mcpReq.inputResponses!==void 0&&{inputResponses:e.mcpReq.inputResponses},client:qr(e),elicit:Dr(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 Nr(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 $r(e){return"contents"in e&&Array.isArray(e.contents)}function Br(e){return"messages"in e&&Array.isArray(e.messages)}function Fe(e,t){if($r(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(Br(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 Fr=["GET","HEAD","POST","OPTIONS"],Wr=["Content-Type","Authorization","mcp-protocol-version","mcp-method","mcp-name"];function zr(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 Jr(e,t){if(t.headers.has("Access-Control-Allow-Origin"))return;let n=t.headers.get("Origin"),r=zr(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 Kr(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??Fr,allowedHeaders:e.allowedHeaders??Wr,credentials:e.credentials??!1};return async(r,o)=>{let s=Jr(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 Kr(i,s)}}function Gt(e){return e!==void 0&&e.enabled!==!1}import{CallToolResultSchema as Gr,GetPromptResultSchema as Yr,ListPromptsResultSchema as Xr,ListResourcesResultSchema as Zr,ListToolsResultSchema as Qr,ReadResourceResultSchema as eo}from"@modelcontextprotocol/core";import{isInputRequiredResult as to}from"@modelcontextprotocol/server";var no=["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=uo(e),r=t;if(n!=="*"&&!ro(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}=ao(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 ro(e){return no.some(t=>t===e)}function oo(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 so(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 oo(e,n,o)(r);return io(n,i),Yt(t,n,"complete",r,i),i}function io(e,t){if((e==="tools/call"||e==="resources/read"||e==="prompts/get")&&to(t))return;let n=(()=>{switch(e){case"tools/call":return ze(e,t,"content"),Gr.safeParse(t);case"tools/list":return We(e,t),Qr.safeParse({tools:t});case"resources/read":return ze(e,t,"contents"),eo.safeParse(t);case"resources/list":return We(e,t),Zr.safeParse({resources:t});case"prompts/get":return ze(e,t,"messages"),Yr.safeParse(t);case"prompts/list":return We(e,t),Xr.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=so(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 ao(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 uo(e){return e.startsWith("mcp:")?e.slice(4):e}import{CLIENT_INFO_META_KEY as co,isJSONRPCRequest as lo}from"@modelcontextprotocol/server";function po(){return typeof process>"u"||process.env?.NO_COLOR!==void 0?!1:process.stdout?.isTTY===!0}function I(e,t){return n=>po()?`\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),fo=I(34,39),sn=I(35,39),pe=I(36,39),mo=I(90,39);function ho(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 go(e){return Object.prototype.hasOwnProperty.call(un,e)}function yo(e){if(!go(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 wo(e){let t=e.params?._meta;if(t===void 0)return;let n=t[co];if(!(typeof n!="object"||n===null||typeof n.name!="string"))return an(n)}function Te(e){return e.replace(/[\u0000-\u001F\u007F-\u009F]+/g," ")}function vo(e){return e.startsWith("tools/")?pe:e.startsWith("resources/")?on:e.startsWith("prompts/")?sn:e==="initialize"||e==="ping"?mo:fo}var To=new Set(["authorization","proxy-authorization","cookie","set-cookie","x-api-key"]);function rn(e){return Object.fromEntries(Object.entries(e).map(([t,n])=>[t,To.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 bo(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 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(Re(rn(t)))),n!==void 0&&(console.log(U("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(U("Response Headers:")),console.log(Re(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(Re(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 xo(e){let t=String(e);return e>=500?sn(t):e>=400?Ge(t):e>=300?U(t):on(t)}function Oo(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=ho(e.level),o=Date.now(),s=t.method,i=new URL(t.url).pathname;if(Oo(s,i))return n();let u={};r==="trace"&&t.headers.forEach((h,T)=>{u[T]=h});let a;if(s!=="GET"&&s!=="HEAD"){let h=R(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=lo(a)?a:void 0,m=p?.method==="subscriptions/listen",f=[[ve(l),Ke(s),i,xo(d.status),ve(`in ${c}ms`)].join(" ")];if(p!==void 0){let h=Te(p.method),T=[` ${vo(h)(h)}`],H=yo(p);H.subject!==void 0&&T.push(Ke(Te(H.subject)));let F=r!=="info";F&&H.input!==void 0&&T.push(nn(H.input));let O=m?{errorMessage:null}:await Ro(d);if(F&&p.method==="tools/call"&&O.errorMessage===null&&O.result!==void 0&&T.push(ve("->"),nn(bo(O.result))),p.method!=="initialize"){let q=wo(p);q!==void 0&&T.push(ve(Te(q)))}O.errorMessage!==null?T.push(Ge(`ERROR ${Te(O.errorMessage)}`)):d.status>=400&&T.push(Ge(`ERROR (HTTP ${d.status})`)),f.push(T.join(" "))}return console.log(f.join(`
5
- `)),r==="trace"&&await Mo(d,u,a,!m),d}}import{createMcpHandler as Ao}from"@modelcontextprotocol/server";function cn(e,t={}){let{path:n="/mcp",handler:r,authInfo:o}=t,s=r?.legacy??"stateless",i=Ao(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 h=a.method.toUpperCase();if(h==="GET"||h==="DELETE"||h==="HEAD")return new Response(null,{status:204})}let d=R(a),c=d.parsedBody;if(c===void 0)try{c=await a.clone().json()}catch{}let l=Be(c);l!==void 0&&$e(a,l);let p=o?.(a)??d.authInfo,m=await i.fetch(a,{...c!==void 0&&{parsedBody:c},...p!==void 0&&{authInfo:p}});return m.headers.get("content-type")?.toLowerCase().includes("application/json")?"Bun"in globalThis&&m.body!==null?new Response(await m.arrayBuffer(),{status:m.status,statusText:m.statusText,headers:m.headers}):Lt(a,m):m}}}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 Co(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 Eo}from"@modelcontextprotocol/server";var Po=["get","put","post","delete","options","head","patch","trace"];function gn(e,t){let n=So(t.spec,t),r=Io(n),o=n.length>0?Wo(t):void 0;for(let[s,i]of n.entries()){let u=r[s];if(u===void 0||o===void 0)continue;let a=Ho(i);e.tool({name:u,description:Lo(i),inputSchema:No(t.spec,i,a)},async d=>Bo(i,d,t,a,o))}}function So(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 Po){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:ko(i,c),...l!==void 0&&!me(l)&&{requestBody:l}};_o(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 ko(e,t){let n=new Map;for(let r of[...e,...t])n.set(`${r.in}:${r.name}`,r);return[...n.values()]}function _o(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=>Uo(e,n))}function Uo(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 Io(e){let t=new Map;return e.map(n=>{let r=jo(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 Lo(e){return[e.operation.summary,e.operation.description,`HTTP: ${e.method.toUpperCase()} ${e.path}`].filter(t=>!!t).join(`
6
-
7
- `)}function jo(e){return e.trim().replace(/[^a-zA-Z0-9_-]+/g,"_").replace(/_+/g,"_").replace(/^_/,"").replace(/_$/,"").slice(0,64)||"openapi_tool"}function No(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=Do(e),u={type:"object",properties:r,additionalProperties:!1,...o.length>0&&{required:o},...i!==void 0&&{$defs:i}};return Eo(u)}function Ho(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:qo(a,o)}}),...n!==void 0&&{bodyInputName:n}}}function qo(e,t){let n=e,r=2;for(;t.has(n);)n=`${e}_${r}`,r+=1;return t.add(n),n}function Do(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=$o(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 $o(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 Bo(e,t,n,r,o){let s=n.fetch??globalThis.fetch,i=Vo(e,t,r.parameters,o),u=Fo(r.parameters,t,n),a=r.bodyInputName,d=a===void 0||t[a]===void 0?void 0:JSON.stringify(t[a]);d!==void 0&&!Ko(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 m=JSON.parse(p);return{content:[{type:"text",text:JSON.stringify(m)}],structuredContent:m}}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(/^\/+/,""),Jo(r));for(let{parameter:i,inputName:u}of n){if(i.in!=="query")continue;let a=t[u];a==null||a===""||zo(s,i.name,a)}return s.toString()}function Fo(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 Wo(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 zo(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 Jo(e){return e.endsWith("/")?e:`${e}/`}function Ko(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 Ra,OAuthErrorCode as ba,bearerAuthChallengeResponse as Ma,getOAuthProtectedResourceMetadataUrl as On,oauthMetadataResponse as xa,requireBearerAuth as An,verifyBearerToken as Oa}from"@modelcontextprotocol/server";import{getOAuthProtectedResourceMetadataUrl as la,oauthMetadataResponse as ts,requireBearerAuth as pa}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 Go,OAuthErrorCode as Yo}from"@modelcontextprotocol/server";function w(e,t){let n=new Go(Yo.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(Rn(Tn(e.mcpUrl,"MCP_URL"),n),n)}function vn(e,t){let n=Tn(e,"listen origin");if(!W(n))throw new Error("OAuth listen origin must be localhost or a loopback address");return Xe(Rn(n,et(t)),t)}function Xe(e,t){let n=et(t),r=z(e,"OAuth resource");if(r.search!==""||r.hash!=="")throw new Error("OAuth resource must not include a query string or fragment");if(J(r,"OAuth resource"),bn(r.pathname)!==n)throw new Error(`OAuth resource path must exactly match basePath (${n})`);return r.pathname=n,r}function Ze(e,t){let n=Qe(t),r=e.createTokenVerifier(new URL(n.href));if(r===null||typeof r!="object"||typeof r.verifyAccessToken!="function")throw new TypeError("OAuth provider createTokenVerifier must return an OAuthTokenVerifier");return{async verifyAccessToken(o){let s=await r.verifyAccessToken(o);Qo(s),Xo(s,n);let i;try{i=e.mapAuthInfo(s)}catch(u){throw w("Token identity mapping failed",u)}return es(i),{...s,scopes:[...s.scopes],extra:{...s.extra,...i}}}}}function Xo(e,t){if(e.resource===void 0)throw w("Token verifier did not return a validated protected resource");if(Zo(e.resource).href!==Qe(t).href)throw w("Token resource does not match the protected resource")}function Zo(e){if(!(e instanceof URL))throw w("Token resource must be an absolute HTTPS URL, or HTTP URL for localhost");let t=e;if(!/^https?:$/.test(t.protocol)||t.username!==""||t.password!==""||t.search!==""||t.hash!==""||t.protocol==="http:"&&!W(t))throw w("Token resource must be an absolute HTTPS URL, or HTTP URL for localhost");return Qe(t)}function Qe(e){let t=new URL(e);return t.pathname=t.pathname==="/"?"/":t.pathname.replace(/\/+$/,""),t}function be(e){return{oauthMetadata:e.oauthMetadata,...e.requiredScopes!==void 0&&{requiredScopes:[...e.requiredScopes]},...e.scopesSupported!==void 0&&{scopesSupported:[...e.scopesSupported]},...e.resourceName!==void 0&&{resourceName:e.resourceName},...e.serviceDocumentationUrl!==void 0&&{serviceDocumentationUrl:e.serviceDocumentationUrl}}}function Qo(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 es(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 Tn(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 Rn(e,t){let n=new URL(e.origin);return n.pathname=t,n}function et(e){if(!e.startsWith("/")||e.includes("?")||e.includes("#"))throw new Error("basePath must be an absolute URL pathname");return bn(e)}function bn(e){if(e==="/")return"/";let t=e.length;for(;t>0&&e.charCodeAt(t-1)===47;)t--;return e.slice(0,t)}function tt(e,t){let n=be(e);return async(r,o)=>{let s=ts(r,{oauthMetadata:n.oauthMetadata,resourceServerUrl:t,...n.scopesSupported!==void 0&&{scopesSupported:[...n.scopesSupported]},...n.resourceName!==void 0&&{resourceName:n.resourceName},...n.serviceDocumentationUrl!==void 0&&{serviceDocumentationUrl:n.serviceDocumentationUrl}});return s!==void 0?s:o()}}function Mn(e){return R(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(ns(e.oauthMetadata),e.resource!==void 0&&rs(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 ns(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 rs(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 os="mcp_use_sdk_event",ss="https://eu.i.posthog.com/i/v0/e/",is="phc_lyTtbYwvkdSbrcMQNPiKiiRWrrM1seyKIMjycSvItEI",as=/(^|_)(arguments?|args|body|command|headers?|location|message|organization|path|query|response|secret|subject|token|uri|url|user_agent)(_|$)/i,us=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(" ")),En;function rt(){return En??=crypto.randomUUID(),En}var Pn=new Set,nt=new Set,Sn=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 kn(e){let t=st(e);return t!==void 0&&t.length>0&&t.length<=128&&!ot(t)?t:void 0}function ds(){return typeof process>"u"||process.versions?.node===void 0?!1:!("Deno"in globalThis)}function _n(){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 Un(){return _n()}function cs(e){return Object.fromEntries(Object.entries(e).filter(([t,n])=>t.length>128||ot(t)||t.startsWith("$")||us.has(t)||as.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 ls(e){let t=kn("MCP_USE_TELEMETRY_PROJECT_ID");if(t!==void 0)return{id:t,stability:"project"};if(e===void 0||!ds())return{id:rt(),stability:"process"};let n=Sn.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 Sn.set(e,r),r}function ps(e,t,n,r,o){let s=kn("MCP_USE_TELEMETRY_VALIDATION_ID");if(_n()||st("NODE_ENV")==="test"&&s===void 0||nt.size>=16)return;if(r.onceKey!==void 0){if(Pn.has(r.onceKey))return;Pn.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:is,event:os,properties:{...cs(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(ss,{method:"POST",headers:{"content-type":"application/json"},keepalive:!0,body:d})}catch{return}})();nt.add(u),u.then(()=>nt.delete(u))}function Me(e,t,n={},r={}){ps(e,t,n,r,()=>ls(r.serverRoot))}var xe=Symbol("mcp-use/registerViews");function Ln(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 fs(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("/")?Ln(e,t):`${t}${fs(n,r)}${e.replace(/^\/+/,"")}`}function ms(e,t){return`${e}${G(t,"_mcp-use/public")}/`}function hs(e){return e.replaceAll(/<\/script/gi,"<\\/script").replaceAll("<!--","\\x3C!--")}function gs(e){return e.replaceAll(/<\/style/gi,"<\\/style")}function at(e){return e.replaceAll("&","&amp;").replaceAll('"',"&quot;").replaceAll("<","&lt;").replaceAll(">","&gt;")}var In=`<style>
9
- html,body,#root{background:transparent}
10
- html,body{margin:0}
11
- #root[data-mcp-use-loading]{display:flex;min-height:100vh;align-items:center;justify-content:center;flex-direction:column;gap:10px}
12
- #root[data-mcp-use-loading]::before{width:24px;height:24px;box-sizing:border-box;border:2px solid rgba(127,127,127,.28);border-top-color:rgba(127,127,127,.9);border-radius:50%;content:"";animation:mcp-use-view-spin .7s linear infinite}
13
- #root[data-mcp-use-loading]::after{color:rgba(127,127,127,.9);content:"Compiling...";font:500 13px/1.2 ui-sans-serif,system-ui,sans-serif}
14
- @keyframes mcp-use-view-spin{to{transform:rotate(360deg)}}
15
- @media (prefers-reduced-motion:reduce){#root[data-mcp-use-loading]::before{animation-duration:1.4s}}
16
- </style>`;function ut(e,t,n,r){let o={publicBase:ms(t,n)},s=`<script>globalThis.__mcpUseViewConfig=${JSON.stringify(o)};</script>`;if(e.kind==="inline"){let d=e.css.length>0?`<style>${gs(e.css)}</style>`:"",c=`<script type="module">${hs(e.js)}</script>`;return`<!doctype html>
17
- <html>
18
- <head>
19
- <meta charset="utf-8">
20
- ${s}
21
- ${In}
22
- ${d}
23
- </head>
24
- <body>
25
- <div id="root" data-mcp-use-loading></div>
26
- ${c}
27
- </body>
28
- </html>`}if(r===void 0)throw new Error("viewName is required when synthesizing an external view document.");let i=e.css.map(d=>`<link rel="stylesheet" href="${at(it(d,t,n,r))}">`).join(`
29
- `),u=(e.scripts??[]).map(d=>`<script type="module" src="${at(it(d,t,n,r))}"></script>`).join(`
30
- `),a=it(e.entry,t,n,r);return`<!doctype html>
31
- <html>
32
- <head>
33
- <meta charset="utf-8">
34
- ${s}
35
- ${In}
36
- ${i}
37
- </head>
38
- <body>
39
- <div id="root" data-mcp-use-loading></div>
40
- ${u}
41
- <script type="module" src="${at(a)}"></script>
42
- </body>
43
- </html>`}var ys={connectDomains:"CSP_CONNECT_DOMAINS",resourceDomains:"CSP_RESOURCE_DOMAINS",frameDomains:"CSP_FRAME_DOMAINS",baseUriDomains:"CSP_BASE_URI_DOMAINS"};function jn(e){return e===void 0||e.trim()===""?[]:e.split(",").map(t=>t.trim()).filter(t=>t.length>0)}function Nn(e){if(typeof process>"u")return;let t=process.env[e];if(!(t===void 0||t.trim()===""))return jn(t)}function ws(){return Nn("CSP_URLS")??[]}function Oe(e){let t=Nn(ys[e]);return t!==void 0?t:ws()}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 vs(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(vs(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 Ts=".mcp-use/build/views/public",Rs="public",bs=".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:m,servePublicFile:f}]=await Promise.all([import("path"),import("./public-route-GWDSKOSN.js")]),h=p(o,bs,d),T=await m(h,c);return T===null?new Response("Not Found",{status:404}):await f(T,{...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?Rs:Ts,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")]),m=c(s,o),f=await l(m,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 Ms(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,Ms(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 $n(e){if(!Fn(e))return;let t=Q(e.params);if(e.method==="initialize"){let s=Q(t?.clientInfo),i=Q(t?.capabilities)??{};return Bn(s,i,t?.protocolVersion,"legacy")}let n=Q(t?._meta),r=Q(n?.[Es]),o=Q(n?.[Cs]);if(!(r===void 0||o===void 0))return Bn(r,o,n?.[Ps],"modern")}function Bn(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 ks(e){return e.map(t=>({...t,inputSchema:Vn(t.inputSchema),...t.outputSchema===void 0?{}:{outputSchema:Vn(t.outputSchema)}}))}function _s(e,t){e.use("*",async(n,r)=>{let o=await t(n.req.raw,async()=>(await r(),n.res));return n.res=o,o})}var ge=class e{#e;#t;#n=new Map;#r=new Map;#l=new Map;#i=new Map;#o=new Map;#a=new Map;#g=!1;#p=!1;#u=process.cwd();#E;#_;#f;#b;#y;#M;#x=!1;#U=!1;#I=!1;#w=[];#m=[];#L;#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;#B=!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 Dn,this.app.use("*",async(n,r)=>{R(n.req.raw).honoContext=n,await r()}),this.get=this.app.get.bind(this.app),this.post=this.app.post.bind(this.app),this.put=this.app.put.bind(this.app),this.patch=this.app.patch.bind(this.app),this.delete=this.app.delete.bind(this.app),this.all=this.app.all.bind(this.app),this.fetch=async(n,r,o)=>(this.#c("handler"),this.#_.fetch(n,r,o)),t.oauth!==void 0){let n=typeof process>"u"?void 0:process.env.MCP_URL,r=wn({provider:t.oauth,basePath:this.#d(),...n!==void 0&&{mcpUrl:n}});this.#M=r,this.#x=r!==void 0,this.#U=r===void 0}}get basePath(){return this.#d()}get host(){return this.#e.host}get port(){return this.#e.port}get branding(){return this.#t}getHandler(){return this.fetch}tool(t,n){return this.#s("tool",t.name),this.#Y(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.#F(),t);return}this.#P+=Object.keys(t).length,await s(this.#F(),t)})();this.#S.add(n);try{await n}finally{this.#S.delete(n)}}use(t,...n){if(typeof t=="string"&&t.startsWith("mcp:")){this.#s("middleware",t);let o=n[0];return this.#w.push(Zt(t,o)),this}return this.app.use.call(this.app,t,...n),this.#j+=typeof t=="function"?1:n.length,this}on(t,n){return this.#s("event listener",t),this.#m.push(Qt(t,n)),this}__setEventBus(t){this.#s("event bus","shared"),this.#b=t}__mount(){this.#c("handler")}async notifyToolsChanged(){await this.#c("handler").handler.notify.toolsChanged()}async notifyPromptsChanged(){await this.#c("handler").handler.notify.promptsChanged()}async notifyResourcesChanged(){await this.#c("handler").handler.notify.resourcesChanged()}async notifyResourceUpdated(t){await this.#c("handler").handler.notify.resourceUpdated(t)}async listen(t=void 0,n={}){this.#k("listen()");let r=St(n.host,this.#e.host),o=kt(t,this.#e.port);return this.#J(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=>m.close(()=>h())).catch(()=>{}).finally(()=>{this.#y===m&&(this.#y=void 0)})},p=Ht({fetch:async f=>(await d)(f)}),m=Ss((f,h)=>{p(f,h)});m.once("error",l),m.listen(o,r,()=>{try{let f=m.address(),h=typeof f=="object"&&f!==null?f.port:o,{fetch:T}=this.#c("listen",h,r);u?.(T),c||(c=!0,s({port:h,url:`http://localhost:${h}${this.#d()}`}))}catch(f){l(f)}}),this.#y=m})}async close(){this.#B=!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.#B)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"}#z(t,n,r){if(this.#e.oauth===void 0)return;if(this.#x)return this.#M;let o=r??this.#e.host??"127.0.0.1",s=t==="listen"&&n!==void 0&&["127.0.0.1","localhost","::1"].includes(o);if(this.#U&&s)return this.#M=vn(`http://localhost:${n}`,this.#d()),this.#x=!0,this.#M;throw new Error("OAuth requires an explicit resource or MCP_URL when using server.fetch or listening on a non-local host")}#J(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.`)}#K(){Me("server","configured",{tools_total:this.#n.size,tools_local:this.#n.size-this.#v.size-this.#h.size,tools_openapi:this.#v.size,tools_proxied:this.#h.size,resources:this.#r.size,resource_templates:this.#l.size,prompts:this.#i.size,views:this.#o.size,proxy_servers_configured:this.#P,proxy_servers_connected:this.#N,proxy_tools_discovered:this.#H,proxy_resources_discovered:this.#q,proxy_prompts_discovered:this.#D,proxy_tools_mounted:this.#h.size,proxy_resources_mounted:this.#O.size,proxy_prompts_mounted:this.#A.size,http_middleware:this.#j,mcp_middleware:this.#w.length,observers_before:this.#m.filter(({phase:t})=>t==="before").length,observers_complete:this.#m.filter(({phase:t})=>t==="complete").length,oauth_configured:this.#e.oauth!==void 0,cors_configured:this.#e.cors!==void 0,request_state_configured:this.#e.requestState!==void 0,legacy_policy:this.#e.legacy??"stateless"},{onceKey:`${this.#V()}:server`,serverRoot:this.#u})}#G(t){let n=$n(t);n!==void 0&&Me("client","observed",{...n},{onceKey:`${this.#V()}:client:${JSON.stringify(n)}`,serverRoot:this.#u})}#V(){return this.#L??=crypto.randomUUID(),this.#L}#F(){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}}}#W(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([...Hn(),...r])]:t==="listen"&&i?Hn():void 0,a=o!==void 0?[...new Set([...xs(),...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.#W(t,r),i=this.#d(),u=i==="/"?"":i,a=new Dn,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(Bt(o)),s!==void 0&&d.push(Vt(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.#X();let p=this.#z(t,n,r);if(p!==void 0){let v=this.#e.oauth;d.push(tt(v,p))}for(let v of d)_s(a,v);let{handler:m,fetch:f}=cn(v=>this.#Z(v),{path:i,...(this.#e.legacy!==void 0||this.#b!==void 0)&&{handler:{...this.#e.legacy!==void 0&&{legacy:this.#e.legacy},...this.#b!==void 0&&{bus:this.#b}}},...p!==void 0&&{authInfo:v=>Mn(v)}}),h=async(v,k)=>k();if(p!==void 0){let v=this.#e.oauth,k=be(v),Se=An({verifier:Ze(v,p),resourceMetadataUrl:On(p),...k.requiredScopes!==void 0&&{requiredScopes:k.requiredScopes}});h=async(D,ie)=>{let K=await Se(D);if(K instanceof Response)return K;let ir=R(D);return ir.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 T=v=>{let k=R(v).parsedBody;return Fn(k)&&(this.#K(),this.#G(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())})():T(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=m,this.#I=o!==void 0}else if(t==="listen"&&!this.#I&&this.#W("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}}#Y(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})}#X(){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.`)}#Z(t){let{name:n,version:r,title:o,description:s,instructions:i}=this.#e,u=t.authInfo,a=new Os({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.#te(a,p);for(let p of this.#r.values())this.#re(a,p);for(let p of this.#l.values())this.#oe(a,p);for(let p of this.#i.values())this.#ie(a,p);for(let[p,m]of this.#o.entries())this.#ne(a,p,m,c,l);return this.#ee(a),a}#T(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})}#R(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(Un())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:$n(R(a).parsedBody),c=(l,p)=>{Me("operation","completed",{method:t,outcome:l,duration_ms:Math.max(0,Math.round(performance.now()-s)),primitive_origin:this.#Q(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=qn(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})}#Q(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"}#ee(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??{},m=this.#T(o,p,l),f,h=async()=>{let F=Xt(d,m.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},T=await this.#R(o,m,h);if(!Array.isArray(T))throw new TypeError(`[mcp-use] ${o} middleware must return a ${s} array`);let H=i?.(T)??T;return{...f,[s]:H}};a.__mcpListWrapped=!0,n.set(o,a)};r("tools/list","tools",ks),r("resources/list","resources"),r("prompts/list","prompts")}#te(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.#T("tools/call",{name:n.name,arguments:c,...l.mcpReq._meta!==void 0&&{_meta:l.mcpReq._meta}},l),m=async()=>{let f=p.params.arguments??{},h=await r(f,this.#C(l));return qn(h)||u===void 0||h.isError===!0?h:{...h,_meta:{...h._meta,...u}}};return await this.#R("tools/call",p,m)};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))}#ne(t,n,r,o,s){let i=Y(n),u=this.#se(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}:{},m=l!==void 0?$(l):o.request!==void 0?$(o.request):"",f=ut(r,m,s,n);return{contents:[{uri:d.href,mimeType:a.mimeType,text:f,_meta:Ce(u,p)}]}})}#re(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.#T("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.#R("resources/read",i,u)})}#oe(t,{definition:n,callback:r,complete:o}){let s=new As(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.#T("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.#R("resources/read",d,c)})}#se(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}}}#ie(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.#T("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.#R("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 Us}from"@modelcontextprotocol/server";import{createRemoteJWKSet as Is,jwtVerify as Ls,errors as j}from"jose";function A(e){let t=e.key??Is(e.jwksUrl),n=Wn(e.resource),r=qs(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 Ls(o,t,{issuer:e.issuer,...r!==void 0&&{audience:r},...e.algorithms!==void 0&&{algorithms:[...e.algorithms]},requiredClaims:["exp","sub"]}),i={...s},u=b(i,"client_id")??b(i,"azp"),a=Ns(i,"exp"),d=Hs(i,n,r!==void 0||e.issuerBoundAccessTokens===!0);return{token:o,clientId:u??"",scopes:M(i.scope),expiresAt:a,extra:{payload:i},resource:d}}catch(s){throw s instanceof Us?s:$s(s)?(process.env.MCP_USE_OAUTH_DEBUG&&Vs(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(!zn(r))throw new TypeError(`${t} must use HTTPS, or HTTP for localhost, without credentials, query, or fragment`);return r.pathname=r.pathname.replace(/\/+$/,"")||"/",r}function y(e,t){let n=new URL(e);return n.pathname=`${n.pathname.replace(/\/+$/,"")}/`,new URL(t.replace(/^\/+/,""),n).href}function E(e){let t=e.extra?.payload;if(!L(t))throw w("Verified token payload is missing");return t}function b(e,t){let n=e[t];return typeof n=="string"&&n.trim().length>0?n:void 0}function g(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 js(e,t){let n=e[t];return typeof n=="number"&&Number.isFinite(n)?n:void 0}function ye(e,t){let n=e[t];return L(n)?n:void 0}function M(e){return typeof e=="string"?e.split(/\s+/).filter(Boolean):Array.isArray(e)?e.filter(t=>typeof t=="string"&&t.length>0):[]}function Ns(e,t){let n=js(e,t);if(n===void 0||n<=Date.now()/1e3)throw w(`Missing or expired ${t} claim`);return n}function Hs(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(Wn(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(!Ds(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 qs(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 Ds(e){return typeof e=="string"||Array.isArray(e)&&e.length>0&&e.every(t=>typeof t=="string")}function Wn(e){try{let t=new URL(e);if(!zn(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 zn(e){return/^https?:$/.test(e.protocol)&&!e.username&&!e.password&&!e.search&&!e.hash&&(e.protocol!=="http:"||W(e))}function $s(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 Bs=["iss","aud","azp","sub","exp","iat","nbf","client_id","scope","typ","jti"];function gt(e){return e instanceof Error?e.message:String(e)}function Vs(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 Bs)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 Jn(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:Fs})}function Fs(e){let t=E(e),n=b(t,"sub");if(n===void 0)throw w("Missing Auth0 subject");return{user:{id:n,...ee("email",g(t,"email")),...ee("name",g(t,"name")),...ee("nickname",g(t,"nickname")),...ee("picture",g(t,"picture")),...ee("emailVerified",P(t,"email_verified")),...ee("updatedAt",g(t,"updated_at")),roles:M(t.roles)},payload:t,permissions:M(t.permissions)}}function ee(e,t){return t===void 0?{}:{[e]:t}}function Kn(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:Ws(t,e.scopesSupported),mapAuthInfo:zs})}function Ws(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 zs(e){let t=E(e),n=b(t,"sub");if(n===void 0)throw w("Missing Better Auth subject");return{user:{id:n,...te("email",g(t,"email")),...te("name",g(t,"name")),...te("picture",g(t,"picture")),...te("emailVerified",P(t,"email_verified")),...te("sessionId",g(t,"sid")),...te("isAnonymous",P(t,"is_anonymous")??P(t,"isAnonymous")),roles:M(t.roles)},payload:t,permissions:M(t.permissions)}}function te(e,t){return t===void 0?{}:{[e]:t}}function Gn(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:Ks(t),mapAuthInfo:n=>Js(n)})}function Js(e){let t=E(e),n=b(t,"sub");if(n===void 0)throw w("Missing Clerk subject");let r=g(t,"org_role");return{user:{id:n,...B("email",g(t,"email")),...B("name",g(t,"name")),...B("username",g(t,"username")),...B("picture",g(t,"picture")),...B("emailVerified",P(t,"email_verified")),...B("organizationId",g(t,"org_id")),...B("organizationRole",r),...B("organizationSlug",g(t,"org_slug")),roles:r===void 0?[]:[r]},payload:t,permissions:M(t.org_permissions)}}function Ks(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 B(e,t){return t===void 0?{}:{[e]:t}}function Yn(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:Gs})}function Gs(e){let t=E(e),n=b(t,"sub");if(n===void 0)throw w("Missing Keycloak subject");let r=ye(t,"realm_access"),o=ye(t,"resource_access");return{user:{id:n,...ne("email",g(t,"email")),...ne("name",g(t,"name")),...ne("preferredUsername",g(t,"preferred_username")),...ne("givenName",g(t,"given_name")),...ne("familyName",g(t,"family_name")),...ne("emailVerified",P(t,"email_verified")),roles:r===void 0?[]:M(r.roles),...r!==void 0&&{realmAccess:r},...o!==void 0&&{resourceAccess:o}},payload:t,permissions:Ys(o)}}function ne(e,t){return t===void 0?{}:{[e]:t}}function Ys(e){return e===void 0?[]:Object.entries(e).flatMap(([t,n])=>L(n)?M(n.roles).map(r=>`${t}:${r}`):[])}function Xn(e){let t=Zs(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:Xs})}function Xs(e){let t=E(e),n=b(t,"sub")??b(t,"user_id");if(n===void 0)throw w("Missing Supabase subject");let r=ye(t,"user_metadata")??{},o=g(t,"aal");return{user:{id:n,...V("email",g(t,"email")),...V("name",g(r,"name")),...V("fullName",g(r,"full_name")),...V("username",g(r,"username")),...V("avatarUrl",g(r,"avatar_url")),...V("role",g(t,"role")),...V("aal",o),amr:Qs(t.amr),...V("sessionId",g(t,"session_id"))},payload:t,permissions:o===void 0?[]:[`aal:${o}`]}}function V(e,t){return t===void 0?{}:{[e]:t}}function Zs(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 Qs(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 Zn(e){let t=ti(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:ei})}function ei(e){let t=E(e),n=b(t,"sub");if(n===void 0)throw w("Missing WorkOS subject");return{user:{id:n,...N("email",g(t,"email")),...N("emailVerified",P(t,"email_verified")),...N("name",g(t,"name")),...N("preferredUsername",g(t,"preferred_username")),...N("firstName",g(t,"first_name")),...N("lastName",g(t,"last_name")),...N("picture",g(t,"picture")),roles:M(t.roles),...N("organizationId",g(t,"org_id")),...N("sessionId",g(t,"sid"))},payload:t,permissions:M(t.permissions)}}function N(e,t){return t===void 0?{}:{[e]:t}}function ti(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 ni(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 Xn({...oe(e),...t!==void 0&&{projectId:t},...n!==void 0&&{supabaseUrl:n},...r!==void 0&&{jwtSecret:r}})}function ri(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 Jn({...oe(e,e.resource??n),domain:t})}function oi(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 Yn({...oe(e,e.resource??r),serverUrl:t,realm:n})}function si(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 Zn({...oe(e),subdomain:t})}function ii(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 Gn({...oe(e,e.resource??e.audience),frontendApiUrl:t})}function ai(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 Kn({...oe(e),authURL:t})}var Qn='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",er="__mcpUseV1CompatServer",tr=!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){gi(),mi(t),this.config=t,this.serverHost=t.host??"localhost",t.baseUrl!==void 0&&(this.serverBaseUrl=t.baseUrl),this.#e=new ge(ci(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[er]!==void 0)throw se("multiple compatibility servers in one CLI entry","default-export one native v2 server or construct only one v1 server");n[er]=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:or(r,o),c=a.outputSchema??(r===void 0?void 0:nr(o)??rr),l=sr(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(m,f)=>n(m,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=nr(n)??rr,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,...sr(void 0,n)},view:or(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 rd(e,t={}){return new wt({name:e,version:t.version??"1.0.0",...t})}function od(e){return{...Ie(e),structuredContent:{data:e}}}function sd(e){let t=Rt(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:R(r).authInfo;if(o!==void 0)return li(o);throw new Error("Authentication context is missing.")}function ui(e,t){let n=Pe(e);return(Array.isArray(t)?t:[t]).every(o=>n.scopes.includes(o)||n.permissions.includes(o))}function di(e,t){let n=Pe(e);return t.some(r=>n.scopes.includes(r)||n.permissions.includes(r))}function id(e){return async(t,n)=>{if(ui(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 ad(e){return async(t,n)=>{if(di(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 ci(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(fi)},cors:pi(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 li(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 pi(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 fi(e){try{return new URL(e).hostname}catch{return e.split(":")[0]??e}}function mi(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 nr(e){let t=e?.props??e?.schema??e?.inputs;return hi(t)?t:void 0}function hi(e){return typeof e=="object"&&e!==null&&"~standard"in e&&typeof e["~standard"]?.validate=="function"}var rr={"~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 or(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 sr(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 gi(){tr||(tr=!0,typeof process.emitWarning=="function"?process.emitWarning(Qn,{type:"DeprecationWarning",code:yt}):console.warn(`[${yt}] ${Qn}`))}function se(e,t){return new Error(`[${yt}] ${e} is not supported by the temporary v1 compatibility entry; ${t}.`)}export{wt as MCPServer,od as array,mr as audio,hr as binary,Co as completable,rd as createMCPServer,lr as css,yr as error,Pe as getAuth,di as hasAnyScope,ui as hasScope,dr as html,fr as image,pr as javascript,ur as markdown,vr as mix,ri as oauthAuth0Provider,ai as oauthBetterAuthProvider,ii as oauthClerkProvider,oi as oauthKeycloakProvider,ni as oauthSupabaseProvider,si as oauthWorkOSProvider,wr as object,ad as requireAnyScope,id as requireScope,gr as resource,ar as text,sd as widget,cr as xml};