mcp-use 2.0.0-beta.45 → 2.0.0-beta.47
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/bin.js +1 -1
- package/dist/chunk-4TTKTNKI.js +1 -0
- package/dist/{chunk-PNCTRGFS.js → chunk-MNSSFPOL.js} +1 -1
- package/dist/chunk-ZBN5QPYD.js +1 -0
- package/dist/compat-v1/oauth.d.ts +37 -0
- package/dist/compat-v1.d.ts +528 -0
- package/dist/compat-v1.js +35 -0
- package/dist/index.js +2 -2
- package/dist/internal/usage.js +1 -1
- package/dist/landing-handler-2IDA43KU.js +630 -0
- package/dist/mcp-proxy-O6GLK2IL.js +2 -0
- package/dist/node-bridge-KQ3STLK5.js +1 -0
- package/dist/public-route-GWDSKOSN.js +1 -0
- package/dist/react/compat-v1.d.ts +221 -0
- package/dist/react/index.d.ts +7 -0
- package/dist/react/index.js +192 -20
- package/dist/react/runtime/view-runtime-context.d.ts +1 -3
- package/dist/react/runtime/view-runtime.d.ts +2 -0
- package/package.json +8 -4
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import{a as wt,b as vt}from"./chunk-ZBN5QPYD.js";import{a as ke,b as _e,c as V,d as Ue}from"./chunk-4TTKTNKI.js";function Xn(e){return{content:[{type:"text",text:e}],_meta:{mimeType:"text/plain"}}}function Zn(e){return{content:[{type:"text",text:e}],_meta:{mimeType:"text/markdown"}}}function Qn(e){return{content:[{type:"text",text:e}],_meta:{mimeType:"text/html"}}}function er(e){return{content:[{type:"text",text:e}],_meta:{mimeType:"text/xml"}}}function tr(e){return{content:[{type:"text",text:e}],_meta:{mimeType:"text/css"}}}function nr(e){return{content:[{type:"text",text:e}],_meta:{mimeType:"text/javascript"}}}function rr(e,t="image/png"){return{content:[{type:"image",data:e,mimeType:t}],_meta:{mimeType:t,isImage:!0}}}function or(e,t="audio/wav"){return{content:[{type:"audio",data:e,mimeType:t}],_meta:{mimeType:t,isAudio:!0}}}function sr(e,t){return{content:[{type:"text",text:e}],_meta:{mimeType:t,isBinary:!0}}}function ir(e,t,n){if(typeof t=="object"&&t!==null&&"content"in t){let o=t,s,i;if(o._meta&&typeof o._meta=="object"){let u=o._meta;typeof u.mimeType=="string"&&(i=u.mimeType)}let a=o.content?.[0];return a?.type==="text"&&"text"in a&&(s=a.text),{content:[{type:"resource",resource:{uri:e,...i!==void 0&&{mimeType:i},text:s??""}}]}}let r=t;return{content:[{type:"resource",resource:{uri:e,...r!==void 0&&r!==""&&{mimeType:r},text:n??""}}]}}function ar(e){return{isError:!0,content:[{type:"text",text:e}]}}function ur(e){return Array.isArray(e)?Ie(e):{content:[{type:"text",text:JSON.stringify(e,null,2)}],structuredContent:e,_meta:{mimeType:"application/json"}}}function Ie(e){return{content:[{type:"text",text:JSON.stringify(e,null,2)}],structuredContent:e}}function Tt(e){let t=e.props??e.data??{},{output:n,message:r,metadata:o}=e,i={content:r?[{type:"text",text:r}]:Array.isArray(n?.content)&&n.content.length>0?n.content:[{type:"text",text:""}]};return o!==void 0&&Object.keys(o).length>0&&(i._meta=o),n?.structuredContent!==void 0?i.structuredContent=n.structuredContent:Object.keys(t).length>0&&(i.structuredContent=t),i}function dr(...e){let t=e.filter(s=>s.structuredContent!==void 0),n=t.length>0?t.map(s=>s.structuredContent).reduce((s,i)=>({...s,...typeof i=="object"&&i!==null?i:{}}),{}):void 0,r=e.filter(s=>s._meta!==void 0),o=r.length>0?r.map(s=>s._meta).reduce((s,i)=>({...s,...i!==void 0?i:{}}),{}):void 0;return{content:e.flatMap(s=>s.content),...n!==void 0&&Object.keys(n).length>0&&{structuredContent:n},...o!==void 0&&Object.keys(o).length>0&&{_meta:o}}}import{localhostAllowedHostnames as Sn,localhostAllowedOrigins as vs,McpServer as Ts,ResourceTemplate as Rs,CLIENT_CAPABILITIES_META_KEY as Ms,CLIENT_INFO_META_KEY as bs,PROTOCOL_VERSION_META_KEY as xs,isJSONRPCRequest as jn,isInputRequiredResult as kn}from"@modelcontextprotocol/server";import{Hono as _n}from"hono";var Rt="public, max-age=31536000, immutable",cr="public, max-age=300";function je(e){return/^([a-z][a-z\d+.-]*):/i.exec(e)?.[1]?.toLowerCase()}function lr(e,t){return`${e==="/"?"":e}/_mcp-use/public/${t.split("/").map(r=>encodeURIComponent(r)).join("/")}`}function Le(e){return je(e)===void 0}function pr(e){return e[0]}function fr(e,t){if(e.startsWith("/")||e.includes("\\")||e.includes("?")||e.includes("#")||e.split("/").some(n=>n===""||n===".."))throw new TypeError(`${t} must be an http(s) URL, image data URL, or safe path relative to public/`)}function bt(e,t){let n=e.indexOf(",");if(n<0)throw new TypeError(`${t} must be a valid image data URL`);let r=e.slice(5,n),o=e.slice(n+1),s=r.split(";"),i=s[0]?.toLowerCase()??"";if(!i.startsWith("image/"))throw new TypeError(`${t} data URL must use an image MIME type`);try{if(s.includes("base64")){let a=atob(o);return{mimeType:i,bytes:Uint8Array.from(a,u=>u.charCodeAt(0))}}return{mimeType:i,bytes:new TextEncoder().encode(decodeURIComponent(o))}}catch{throw new TypeError(`${t} must be a valid image data URL`)}}function Mt(e,t){if(typeof e!="string"||e.length===0)throw new TypeError(`${t} must be a non-empty string`);let n=je(e);if(n===void 0)return fr(e,t),e;if(n==="data")return bt(e,t),e;if(n!=="http"&&n!=="https")throw new TypeError(`${t} must be an http(s) URL, image data URL, or safe path relative to public/`);try{new URL(e)}catch{throw new TypeError(`${t} must be a valid absolute http(s) URL`)}return e}function xt(e){let t;if(e.websiteUrl!==void 0){if(typeof e.websiteUrl!="string"||e.websiteUrl.length===0)throw new TypeError("websiteUrl must be a non-empty absolute http(s) URL");let a;try{a=new URL(e.websiteUrl)}catch{throw new TypeError("websiteUrl must be a non-empty absolute http(s) URL")}if(a.protocol!=="http:"&&a.protocol!=="https:")throw new TypeError("websiteUrl must be a non-empty absolute http(s) URL");t=e.websiteUrl}let n;if(e.icons!==void 0){if(!Array.isArray(e.icons))throw new TypeError("icons must be an array of MCP Icon objects");n=Object.freeze(e.icons.map((a,u)=>{if(typeof a!="object"||a===null)throw new TypeError(`icons[${u}] must be an MCP Icon object`);let d=a,c=Mt(d.src,`icons[${u}].src`),l=d.mimeType;if(l!==void 0&&(typeof l!="string"||!l.toLowerCase().startsWith("image/")))throw new TypeError(`icons[${u}].mimeType must be an image MIME type when provided`);let p=d.sizes;if(p!==void 0&&(!Array.isArray(p)||p.some(y=>typeof y!="string"||y.length===0)))throw new TypeError(`icons[${u}].sizes must be an array of non-empty strings when provided`);let g=p===void 0?void 0:p.map(y=>y),T=d.theme;if(T!==void 0&&T!=="light"&&T!=="dark")throw new TypeError(`icons[${u}].theme must be "light" or "dark" when provided`);return Object.freeze({src:c,...l!==void 0&&{mimeType:l},...g!==void 0&&{sizes:Object.freeze(g)},...T!==void 0&&{theme:T}})}))}let r=e.favicon===void 0?void 0:Mt(e.favicon,"favicon"),o=r===void 0?pr(n??[]):void 0,s=r??o?.src,i=o?.mimeType??n?.find(a=>a.src===r)?.mimeType;return Object.freeze({...s!==void 0&&{favicon:s},...i!==void 0&&{faviconMimeType:i},...n!==void 0&&{icons:n},...t!==void 0&&{websiteUrl:t}})}function Ot(e,t,n){if(e!==void 0)return e.map(r=>({...r,src:t!==void 0&&Le(r.src)?`${V(t)}${lr(n,r.src)}`:r.src,...r.sizes!==void 0&&{sizes:[...r.sizes]}}))}function At(e){return e.favicon!==void 0&&Le(e.favicon)||e.icons?.some(t=>Le(t.src))===!0}function Ct(e,t){let n=e.favicon;if(n!==void 0)return async r=>{if(r.method!=="GET"&&r.method!=="HEAD")return new Response("Method Not Allowed",{status:405,headers:{Allow:"GET, HEAD"}});if(new URL(r.url).pathname!=="/favicon.ico")return new Response("Not Found",{status:404});let o=je(n);if(o==="http"||o==="https")return new Response(null,{status:307,headers:{Location:n,"Cache-Control":cr}});if(o==="data"){let d=bt(n,"favicon");return new Response(r.method==="HEAD"?null:d.bytes.buffer,{status:200,headers:{"Content-Type":e.faviconMimeType??d.mimeType,"Cache-Control":Rt,"X-Content-Type-Options":"nosniff"}})}let{join:s}=await import("path"),i=t.dev?s(t.projectRoot,"public"):s(t.projectRoot,".mcp-use/build/views/public"),a=await wt(i,n);if(a===null)return new Response("Not Found",{status:404,headers:{"Cache-Control":"no-store"}});let u=await vt(a,{...t.deferCors===!0&&{deferCors:!0},...r.method==="HEAD"&&{head:!0}});return u.headers.set("Cache-Control",Rt),u.headers.set("X-Content-Type-Options","nosniff"),e.faviconMimeType!==void 0&&u.headers.set("Content-Type",e.faviconMimeType),u}}function Et(e){if(e.basePath!==void 0){if(typeof e.basePath!="string")throw new TypeError("basePath must be an absolute URL pathname without empty segments, trailing slash, query, fragment, or whitespace");let{basePath:t}=e;if(!t.startsWith("/")||t.includes("?")||t.includes("#")||/\s/.test(t)||t.includes("//")||t.length>1&&t.endsWith("/"))throw new TypeError("basePath must be an absolute URL pathname without empty segments, trailing slash, query, fragment, or whitespace")}if(e.port!==void 0&&(typeof e.port!="number"||!Number.isInteger(e.port)||e.port<0||e.port>65535))throw new TypeError("port must be an integer between 0 and 65535")}var mr="127.0.0.1";function Pt(e,t,n=process.env){if(e!==void 0)return e;let r=n.HOST?.trim();return r!==void 0&&r!==""?r:t??mr}function St(e,t,n=process.env){if(e!==void 0)return e;let r=hr(n.PORT);return r!==void 0?r:t??3e3}function hr(e){if(e===void 0||e.trim()==="")return;let t=Number(e);return Number.isInteger(t)&&t>=0&&t<=65535?t:void 0}import{CLIENT_CAPABILITIES_META_KEY as Tr,CLIENT_INFO_META_KEY as Rr,inputRequired as Ve,inputResponse as Mr}from"@modelcontextprotocol/server";import{HonoRequest as br}from"hono/request";import{hostHeaderValidationResponse as gr,originValidationResponse as yr}from"@modelcontextprotocol/server";var kt=new WeakMap;function M(e){let t=kt.get(e);return t===void 0&&(t={},kt.set(e,t)),t}function ae(e){return new URL(e.url).pathname}function _t(e,t){return ae(e)===t}function Ne(e,t){let n=ae(e);return n===t||n.startsWith(`${t}/`)}function G(e,t){let n=t.replace(/^\/+/,"");return e==="/"?`/${n}`:`${e}/${n}`}function He(e){if(e.method!=="GET"&&e.method!=="HEAD")return!1;let t=e.headers.get("accept");return t===null?!1:t.split(",").some(n=>{let[r,...o]=n.split(";");return r?.trim().toLowerCase()!=="text/html"?!1:!o.some(s=>{let[i,a]=s.trim().toLowerCase().split("=");return i==="q"&&Number(a)===0})})}function Ut(){return async(e,t)=>{let n=M(e);if(n.parsedBody!==void 0||!(e.headers.get("content-type")??"").includes("application/json"))return t();try{n.parsedBody=await e.clone().json()}catch{return new Response("Invalid JSON",{status:400})}return t()}}function It(e){return async(t,n)=>gr(t,e)??n()}function Lt(e,t=!0){return async(n,r)=>t&&(n.method==="GET"||n.method==="HEAD")?r():yr(n,e)??r()}import{CLIENT_CAPABILITIES_META_KEY as wr}from"@modelcontextprotocol/server";var qe="io.modelcontextprotocol/ui",ue="text/html;profile=mcp-app",jt="ui://views/";var de="ui/resourceUri";function Y(e){return`${jt}${e}.html`}var vr=new WeakMap;function De(e,t){vr.set(e,t)}function $e(e){if(typeof e!="object"||e===null)return;let t=e.params;if(typeof t!="object"||t===null)return;let n=t._meta;if(typeof n!="object"||n===null)return;let r=n[wr];if(!(typeof r!="object"||r===null))return r}function ce(e){let t=e?.extensions;if(t===void 0)return!1;let n=t[qe];if(typeof n!="object"||n===null)return!1;let r=n.mimeTypes;return Array.isArray(r)?r.includes(ue):!1}function xr(e){if(e===void 0||e.extra===void 0||e.expiresAt===void 0)throw new Error("OAuth callback did not receive mapped AuthInfo.extra")}function U(e){return typeof e=="string"?e:void 0}function Nt(e){return typeof e=="string"||typeof e=="number"&&Number.isFinite(e)?e:void 0}function Or(e){if(e===void 0)return;let t=U(e["openai/locale"])??U(e["webplus/i18n"]),n=U(e["openai/userAgent"]),r=U(e["openai/subject"]),o=U(e["openai/session"]),s=U(e["openai/organization"]),i=e["openai/userLocation"],a;if(typeof i=="object"&&i!==null&&!Array.isArray(i)){let u=i,d={city:U(u.city),region:U(u.region),country:U(u.country),timezone:U(u.timezone),latitude:Nt(u.latitude),longitude:Nt(u.longitude)},c=Object.entries(d).filter(l=>l[1]!==void 0);c.length>0&&(a=Object.fromEntries(c))}if(!(t===void 0&&n===void 0&&a===void 0&&r===void 0&&o===void 0&&s===void 0))return{...t!==void 0&&{locale:t},...n!==void 0&&{userAgent:n},...a!==void 0&&{location:a},...r!==void 0&&{subject:r},...o!==void 0&&{conversationId:o},...s!==void 0&&{organizationId:s}}}function Ar(e){let t=e.mcpReq.envelope,n={...t?.[Tr]??{}},r={...t?.[Rr]??{}},o=Or(e.mcpReq._meta);return{can(s){return Object.hasOwn(n,s)},capabilities(){return{...n}},extension(s){let i=n.extensions?.[s];return i===void 0?void 0:{...i}},info(){return{...r}},user(){return o===void 0?void 0:{...o,...o.location!==void 0&&{location:{...o.location}}}},supportsViews(){return ce(n)}}}function Cr(e){return async function(n,r,o){let s,i;if(typeof o=="string")s=Ve.elicitUrl({message:r,url:o});else if(o!==void 0)i=o,s=Ve.elicit({message:r,requestedSchema:o});else throw new TypeError("ctx.elicit(key, message, value) requires a form schema or URL string");let a=Mr(e,n);if(a.kind==="elicit"){if(a.action!=="accept")return{status:a.action};if(i===void 0)return{status:"accept"};if(a.content!==void 0){let u=await i["~standard"].validate(a.content);if(u.issues===void 0)return{status:"accept",data:u.value}}}return{status:"required",result:Ve({inputRequests:{[n]:s}})}}}function we(e){let t=e.http?.req,n=t===void 0?void 0:M(t).honoContext,r=n?.req??(t===void 0?void 0:new br(t)),o={signal:e.mcpReq.signal,...r!==void 0&&{request:r},...e.mcpReq.inputResponses!==void 0&&{inputResponses:e.mcpReq.inputResponses},client:Ar(e),elicit:Cr(e.mcpReq.inputResponses),requestState:()=>e.mcpReq.requestState(),async sendNotification(s,i){await e.mcpReq.notify({method:s,...i!==void 0&&{params:i}})},async reportProgress(s,i,a){let u=e.mcpReq._meta?.progressToken;return u===void 0?!1:(await e.mcpReq.notify({method:"notifications/progress",params:{progressToken:u,progress:s,...i!==void 0&&{total:i},...a!==void 0&&{message:a}}}),!0)},async sendLog(s,i,a){await e.mcpReq.notify({method:"notifications/message",params:{level:s,data:i,...a!==void 0&&{logger:a}}})}};return n!==void 0?Object.assign(n,o):{...o,...r!==void 0&&{req:r}}}function Ht(e){let t=e.http?.authInfo;return xr(t),Object.assign(we(e),{auth:{user:t.extra.user,payload:t.extra.payload,accessToken:t.token,scopes:[...t.scopes],permissions:[...t.extra.permissions],...t.clientId.length>0&&{clientId:t.clientId},expiresAt:t.expiresAt,...t.resource!==void 0&&{resource:t.resource}}})}function Er(e){return"contents"in e&&Array.isArray(e.contents)}function Pr(e){return"messages"in e&&Array.isArray(e.messages)}function Be(e,t){if(Er(e))return e;let n=e._meta&&typeof e._meta=="object"&&typeof e._meta.mimeType=="string"?e._meta.mimeType:void 0,r=[];for(let o of e.content??[]){let s=Sr(o,t,n);s!==void 0&&r.push(s)}return r.length===0&&e.structuredContent!==void 0&&r.push({uri:t,mimeType:"application/json",text:JSON.stringify(e.structuredContent)}),r.length===0&&r.push({uri:t,mimeType:"text/plain",text:""}),{contents:r}}function Sr(e,t,n){if(e.type==="text")return{uri:t,mimeType:n??"text/plain",text:e.text};if(e.type==="image"||e.type==="audio")return{uri:t,mimeType:e.mimeType,blob:e.data};if(e.type==="resource")return{...e.resource}}function qt(e){if(Pr(e))return e;let t=(e.content??[]).map(n=>({role:"user",content:n}));return t.length===0&&e.structuredContent!==void 0&&t.push({role:"user",content:{type:"text",text:JSON.stringify(e.structuredContent)}}),t.length===0&&t.push({role:"user",content:{type:"text",text:""}}),{messages:t}}var kr=["GET","HEAD","POST","OPTIONS"],_r=["Content-Type","Authorization","mcp-protocol-version","mcp-method","mcp-name"];function Ur(e,t){return e===void 0?t:typeof e=="function"?e(t):e==="*"?"*":Array.isArray(e)?t!==null&&e.includes(t)?t:null:e}function Ir(e,t){if(t.headers.has("Access-Control-Allow-Origin"))return;let n=t.headers.get("Origin"),r=Ur(e.origin,n);if(r===null)return;let o={"Access-Control-Allow-Origin":r,"Access-Control-Allow-Methods":e.methods.join(", "),"Access-Control-Allow-Headers":e.allowedHeaders.join(", ")};return e.credentials&&(o["Access-Control-Allow-Credentials"]="true"),r!=="*"&&(o.Vary="Origin"),o}function Lr(e,t){if(e.headers.has("Access-Control-Allow-Origin"))return e;let n=new Headers(e.headers);return new Headers(t).forEach((o,s)=>{n.set(s,o)}),new Response(e.body,{status:e.status,statusText:e.statusText,headers:n})}function Dt(e){if(!(e.enabled!==!1))return async(r,o)=>o();let n={...e.origin!==void 0&&{origin:e.origin},methods:e.methods??kr,allowedHeaders:e.allowedHeaders??_r,credentials:e.credentials??!1};return async(r,o)=>{let s=Ir(n,r);if(s===void 0)return o();if(r.method==="OPTIONS")return new Response(null,{status:204,headers:s});let i=await o();return Lr(i,s)}}function $t(e){return e!==void 0&&e.enabled!==!1}import{CallToolResultSchema as jr,GetPromptResultSchema as Nr,ListPromptsResultSchema as Hr,ListResourcesResultSchema as qr,ListToolsResultSchema as Dr,ReadResourceResultSchema as $r}from"@modelcontextprotocol/core";import{isInputRequiredResult as Vr}from"@modelcontextprotocol/server";var Br=["tools/call","tools/list","resources/read","resources/list","prompts/get","prompts/list"];function Bt(e,t){if(typeof e!="object"||e===null||Array.isArray(e))throw new TypeError("[mcp-use] MCP middleware received an invalid downstream request");return{...e,params:t}}function Ft(e,t){let n=Gr(e),r=t;if(n!=="*"&&!Fr(n))throw new TypeError(`Unsupported MCP middleware pattern "${e}". Use an exact MCP method or "mcp:*".`);return n==="*"?{pattern:n,handler:async(o,s)=>{let i=!1,a;if(await r(o,async()=>{a=await s(),i=!0}),!i)throw new Error(`Wildcard MCP middleware "${n}" must call next()`);return a}}:{pattern:n,handler:(o,s)=>r(o,s)}}function Wt(e,t){let{pattern:n,phase:r}=Kr(e),o=t;return{pattern:n,phase:r,handler:(s,i)=>o(s,i)}}function le(e,t){if(e==="*")return!0;if(e.endsWith("/*")){let n=e.slice(0,-1);return t.startsWith(n)}return e===t}function Fr(e){return Br.some(t=>t===e)}function Wr(e,t,n){let r=e.filter(o=>le(o.pattern,t));return r.length===0?o=>n():o=>{let s=-1,i=a=>a<=s?Promise.reject(new Error("next() called multiple times")):(s=a,a===r.length?n():r[a].handler(o,()=>i(a+1)));return i(0)}}function zr(e){return Object.freeze({method:e.method,params:Object.freeze({...e.params}),...e.request!==void 0&&{request:e.request},...e.req!==void 0&&{req:e.req},...e.session!==void 0&&{session:Object.freeze({...e.session})},...e.auth!==void 0&&{auth:e.auth},state:new Map(e.state)})}async function zt(e,t,n,r,o){Vt(t,n,"before",r);let i=await Wr(e,n,o)(r);return Jr(n,i),Vt(t,n,"complete",r,i),i}function Jr(e,t){if((e==="tools/call"||e==="resources/read"||e==="prompts/get")&&Vr(t))return;let n=(()=>{switch(e){case"tools/call":return We(e,t,"content"),jr.safeParse(t);case"tools/list":return Fe(e,t),Dr.safeParse({tools:t});case"resources/read":return We(e,t,"contents"),$r.safeParse(t);case"resources/list":return Fe(e,t),qr.safeParse({resources:t});case"prompts/get":return We(e,t,"messages"),Nr.safeParse(t);case"prompts/list":return Fe(e,t),Hr.safeParse({prompts:t});default:throw new TypeError(`Unsupported MCP middleware method "${e}"`)}})();if(!n.success)throw new TypeError(`[mcp-use] ${e} middleware returned an invalid result: ${n.error.message}`)}function Fe(e,t){if(!Array.isArray(t))throw new TypeError(`[mcp-use] ${e} middleware returned an invalid result: expected an array`)}function We(e,t,n){if(typeof t!="object"||t===null||!Array.isArray(t[n]))throw new TypeError(`[mcp-use] ${e} middleware returned an invalid result: expected a ${n} array`)}function Vt(e,t,n,r,o){let s=zr(r);for(let i of e)if(!(i.phase!==n||!le(i.pattern,t)))try{i.handler(s,o)}catch(a){console.error(`[mcp-use] MCP event listener for "${i.pattern}" (${n}) threw:`,a)}}function Kr(e){let t=e.startsWith("mcp:")?e.slice(4):e;return t.endsWith(":complete")?{pattern:t.slice(0,-9),phase:"complete"}:{pattern:t,phase:"before"}}function Gr(e){return e.startsWith("mcp:")?e.slice(4):e}import{CLIENT_INFO_META_KEY as Yr,isJSONRPCRequest as Xr}from"@modelcontextprotocol/server";function Zr(){return typeof process>"u"||process.env?.NO_COLOR!==void 0?!1:process.stdout?.isTTY===!0}function j(e,t){return n=>Zr()?`\x1B[${e}m${n}\x1B[${t}m`:n}var Je=j(1,22),ve=j(2,22),Ke=j(31,39),Yt=j(32,39),L=j(33,39),Qr=j(34,39),Xt=j(35,39),pe=j(36,39),eo=j(90,39);function to(e){let t=typeof process>"u"?void 0:process.env?.MCP_USE_LOG_LEVEL?.toLowerCase();return t==="info"||t==="debug"||t==="trace"?t:e??"info"}function Zt(e){if(e!==void 0)return typeof e.version=="string"&&e.version!==""?`${e.name}/${e.version}`:e.name}var Qt={initialize:e=>({subject:Zt(e.clientInfo)}),ping:()=>({}),"server/discover":()=>({}),"completion/complete":e=>({subject:e.ref.type==="ref/prompt"?e.ref.name:e.ref.uri,input:e.argument}),"logging/setLevel":e=>({subject:e.level}),"prompts/get":e=>({subject:e.name,input:e.arguments}),"prompts/list":()=>({}),"resources/list":()=>({}),"resources/templates/list":()=>({}),"resources/read":e=>({subject:e.uri}),"resources/subscribe":e=>({subject:e.uri}),"resources/unsubscribe":e=>({subject:e.uri}),"subscriptions/listen":()=>({}),"tools/call":e=>({subject:e.name,input:e.arguments}),"tools/list":()=>({}),"sampling/createMessage":()=>({}),"elicitation/create":()=>({}),"roots/list":()=>({})};function no(e){return Object.prototype.hasOwnProperty.call(Qt,e)}function ro(e){if(!no(e.method))return{};try{let t=Qt[e.method],n=t(e.params);return typeof n.subject=="string"||n.subject===void 0?n:{}}catch{return{}}}var Jt=80;function Kt(e){let t;try{t=JSON.stringify(e)??String(e)}catch{t=String(e)}return t.length>Jt?`${t.slice(0,Jt)}...`:t}function oo(e){let t=e.params?._meta;if(t===void 0)return;let n=t[Yr];if(!(typeof n!="object"||n===null||typeof n.name!="string"))return Zt(n)}function Te(e){return e.replace(/[\u0000-\u001F\u007F-\u009F]+/g," ")}function so(e){return e.startsWith("tools/")?pe:e.startsWith("resources/")?Yt:e.startsWith("prompts/")?Xt:e==="initialize"||e==="ping"?eo:Qr}var io=new Set(["authorization","proxy-authorization","cookie","set-cookie","x-api-key"]);function Gt(e){return Object.fromEntries(Object.entries(e).map(([t,n])=>[t,io.has(t.toLowerCase())?"[REDACTED]":n]))}async function ao(e){if(!e.body)return{errorMessage:null};let t;try{t=await e.clone().text()}catch{return{errorMessage:null}}if(!t)return{errorMessage:null};let n=(e.headers.get("content-type")??"").includes("text/event-stream"),r=[],o=i=>{try{r.push(JSON.parse(i))}catch{}};if(n){for(let i of t.split(/\r?\n/))if(i.startsWith("data:")){let a=i.slice(5).trim();a&&o(a)}}else o(t);let s;for(let i of r){if(i===null||typeof i!="object")continue;let a=i;if(typeof a.error?.message=="string")return{errorMessage:a.error.message};if(a.result?.isError===!0){let d=(Array.isArray(a.result.content)?a.result.content:[]).find(c=>c?.type==="text"&&typeof c.text=="string");return{errorMessage:d?String(d.text):"tool error"}}"result"in a&&(s=a.result)}return{errorMessage:null,result:s}}function uo(e){if(e===null||typeof e!="object")return e;let{structuredContent:t,content:n}=e;if(t!==void 0)return t;if(Array.isArray(n)){let[r]=n;if(n.length===1&&r?.type==="text")return r.text}return n}function Re(e){function t(n){return typeof n=="string"&&n.length>100?`${n.slice(0,100)}...`:Array.isArray(n)?n.map(t):n!==null&&typeof n=="object"?Object.fromEntries(Object.entries(n).map(([r,o])=>[r,t(o)])):n}try{return JSON.stringify(t(e),null,2)}catch{return String(e)}}var ze=1e4;async function co(e,t,n,r){console.log(`
|
|
2
|
+
${pe("=".repeat(80))}`),console.log(Je(pe("[TRACE] Request Details"))),console.log(pe("-".repeat(80))),Object.keys(t).length>0&&(console.log(L("Request Headers:")),console.log(Re(Gt(t)))),n!==void 0&&(console.log(L("Request Body:")),console.log(typeof n=="string"?n:Re(n)));let o={};if(e.headers.forEach((s,i)=>{o[i]=s}),Object.keys(o).length>0&&(console.log(L("Response Headers:")),console.log(Re(Gt(o)))),!r)console.log(`${L("Response Body:")} (streaming \u2014 not dumped)`);else if(e.body===null)console.log(`${L("Response Body:")} (no body)`);else try{let s=await e.clone().text();if(s.length===0)console.log(`${L("Response Body:")} (empty)`);else{console.log(L("Response Body:"));try{console.log(Re(JSON.parse(s)))}catch{console.log(s.length>ze?`${s.slice(0,ze)}
|
|
3
|
+
... (truncated, ${s.length-ze} more characters)`:s)}}}catch{console.log(`${L("Response Body:")} (unable to read)`)}console.log(`${pe("=".repeat(80))}
|
|
4
|
+
`)}function lo(e){let t=String(e);return e>=500?Xt(t):e>=400?Ke(t):e>=300?L(t):Yt(t)}function po(e,t){return e!=="GET"&&e!=="HEAD"?!1:t.endsWith("/favicon.ico")}function en(e={}){return e.enabled===!1?(t,n)=>n():async(t,n)=>{let r=to(e.level),o=Date.now(),s=t.method,i=new URL(t.url).pathname;if(po(s,i))return n();let a={};r==="trace"&&t.headers.forEach((y,m)=>{a[m]=y});let u;if(s!=="GET"&&s!=="HEAD"){let y=M(t).parsedBody;if(y!==void 0)u=y;else try{u=await t.clone().json()}catch{}}let d=await n(),c=Date.now()-o,l=new Date().toISOString().substring(11,19),p=Xr(u)?u:void 0,g=p?.method==="subscriptions/listen",T=[[ve(l),Je(s),i,lo(d.status),ve(`in ${c}ms`)].join(" ")];if(p!==void 0){let y=Te(p.method),m=[` ${so(y)(y)}`],R=ro(p);R.subject!==void 0&&m.push(Je(Te(R.subject)));let I=r!=="info";I&&R.input!==void 0&&m.push(Kt(R.input));let A=g?{errorMessage:null}:await ao(d);if(I&&p.method==="tools/call"&&A.errorMessage===null&&A.result!==void 0&&m.push(ve("->"),Kt(uo(A.result))),p.method!=="initialize"){let D=oo(p);D!==void 0&&m.push(ve(Te(D)))}A.errorMessage!==null?m.push(Ke(`ERROR ${Te(A.errorMessage)}`)):d.status>=400&&m.push(Ke(`ERROR (HTTP ${d.status})`)),T.push(m.join(" "))}return console.log(T.join(`
|
|
5
|
+
`)),r==="trace"&&await co(d,a,u,!g),d}}import{createMcpHandler as fo}from"@modelcontextprotocol/server";function tn(e,t={}){let{path:n="/mcp",handler:r,authInfo:o}=t,s=r?.legacy??"stateless",i=fo(e,{legacy:"stateless",...r});return{handler:i,fetch:async u=>{if(!_t(u,n))return new Response("Not Found",{status:404});if(s==="stateless"){let g=u.method.toUpperCase();if(g==="GET"||g==="DELETE"||g==="HEAD")return new Response(null,{status:204})}let d=M(u),c=d.parsedBody;if(c===void 0)try{c=await u.clone().json()}catch{}let l=$e(c);l!==void 0&&De(u,l);let p=o?.(u)??d.authInfo;return i.fetch(u,{...c!==void 0&&{parsedBody:c},...p!==void 0&&{authInfo:p}})}}}import{completable as nn}from"@modelcontextprotocol/server";function Ge(e){let t=e.map(String);return n=>{let r=String(n??"").toLowerCase();return t.filter(o=>o.toLowerCase().startsWith(r))}}function mo(e,t){return typeof t=="function"?nn(e,(n,r)=>t(String(n??""),r)):nn(e,Ge(t))}function rn(e){let t=Object.create(null);for(let[n,r]of Object.entries(e))r!==void 0&&(t[n]=Array.isArray(r)?Ge(r):r);return t}import{fromJsonSchema as ho}from"@modelcontextprotocol/server";var go=["get","put","post","delete","options","head","patch","trace"];function un(e,t){let n=yo(t.spec,t),r=Ro(n),o=n.length>0?_o(t):void 0;for(let[s,i]of n.entries()){let a=r[s];if(a===void 0||o===void 0)continue;let u=Oo(i);e.tool({name:a,description:Mo(i),inputSchema:xo(t.spec,i,u)},async d=>Po(i,d,t,u,o))}}function yo(e,t){let n=[];for(let[r,o]of Object.entries(e.paths??{})){let s=X(e,o);if(s===void 0||me(s))continue;let i=on(e,s.parameters);for(let a of go){let u=s[a];if(u===void 0)continue;let d=X(e,u);if(d===void 0||me(d))continue;let c=on(e,d.parameters),l=d.requestBody===void 0?void 0:X(e,d.requestBody),p={method:a,path:r,operation:d,parameters:wo(i,c),...l!==void 0&&!me(l)&&{requestBody:l}};vo(p,t)&&n.push(p)}}return n}function on(e,t){let n=[];for(let r of t??[]){let o=X(e,r);o!==void 0&&!me(o)&&n.push(o)}return n}function wo(e,t){let n=new Map;for(let r of[...e,...t])n.set(`${r.in}:${r.name}`,r);return[...n.values()]}function vo(e,t){if(t.tags?.length){let n=new Set(e.operation.tags??[]);if(!t.tags.some(r=>n.has(r)))return!1}return!(t.exclude??[]).some(n=>To(e,n))}function To(e,t){if(t.method&&t.method.toLowerCase()!==e.method||t.operationId&&!sn(t.operationId,e.operation.operationId??"")||t.path&&!sn(t.path,e.path))return!1;if(t.tags?.length){let n=new Set(e.operation.tags??[]);if(!t.tags.some(r=>n.has(r)))return!1}return!0}function sn(e,t){return typeof e=="string"?e===t:(e.lastIndex=0,e.test(t))}function Ro(e){let t=new Map;return e.map(n=>{let r=bo(n.operation.operationId??`${n.method}_${n.path.replace(/[{}]/g,"").replace(/\//g,"_")}`),o=t.get(r)??0;if(t.set(r,o+1),o===0)return r;let s=`_${o+1}`;return`${r.slice(0,64-s.length)}${s}`})}function Mo(e){return[e.operation.summary,e.operation.description,`HTTP: ${e.method.toUpperCase()} ${e.path}`].filter(t=>!!t).join(`
|
|
6
|
+
|
|
7
|
+
`)}function bo(e){return e.trim().replace(/[^a-zA-Z0-9_-]+/g,"_").replace(/_+/g,"_").replace(/^_/,"").replace(/_$/,"").slice(0,64)||"openapi_tool"}function xo(e,t,n){let r={},o=[];for(let{parameter:u,inputName:d}of n.parameters){let c=an(e,u.schema??{});r[d]={...c,description:u.description??`${u.in} parameter`},(u.required||u.in==="path")&&o.push(d)}let s=dn(t.requestBody);s!==void 0&&n.bodyInputName!==void 0&&(r[n.bodyInputName]=an(e,s),t.requestBody?.required&&o.push(n.bodyInputName));let i=Co(e),a={type:"object",properties:r,additionalProperties:!1,...o.length>0&&{required:o},...i!==void 0&&{$defs:i}};return ho(a)}function Oo(e){let t=e.parameters.filter(i=>i.in!=="cookie"),n=dn(e.requestBody)===void 0?void 0:"body",r=new Map;for(let i of t)r.set(i.name,(r.get(i.name)??0)+1);let o=new Set(n===void 0?[]:[n]);return{parameters:t.map(i=>{let u=(r.get(i.name)??0)>1||i.name===n?`${i.name}_${i.in}`:i.name;return{parameter:i,inputName:Ao(u,o)}}),...n!==void 0&&{bodyInputName:n}}}function Ao(e,t){let n=e,r=2;for(;t.has(n);)n=`${e}_${r}`,r+=1;return t.add(n),n}function Co(e){let t=Z(e.components?.schemas);if(t===void 0)return;let n={};for(let[r,o]of Object.entries(t))n[r]=fe(e,o,new Set);return n}function an(e,t){let n=fe(e,t,new Set);return Z(n)??{}}function fe(e,t,n){if(Array.isArray(t))return t.map(a=>fe(e,a,n));let r=Z(t);if(r===void 0)return t;let o=typeof r.$ref=="string"?r.$ref:void 0,s={};for(let[a,u]of Object.entries(r))a!=="$ref"&&(a==="nullable"&&typeof u=="boolean"||(s[a]=fe(e,u,n)));let i=s;if(o!==void 0){let a=Eo(e,o);if(a!==void 0)i={$ref:a,...s};else if(!n.has(o)){let u=X(e,{$ref:o});if(u!==void 0){let d=new Set(n);d.add(o),i={...Z(fe(e,u,d))??{},...s}}}}return r.nullable===!0?{anyOf:[i,{type:"null"}]}:i}function Eo(e,t){let n="#/components/schemas/";if(t.startsWith(n))return X(e,{$ref:t})===void 0?void 0:`#/$defs/${t.slice(n.length)}`}function dn(e){let t=e?.content;if(t!==void 0)return t["application/json"]?.schema??t["application/*+json"]?.schema??Object.entries(t).find(([n])=>n.includes("+json"))?.[1].schema}async function Po(e,t,n,r,o){let s=n.fetch??globalThis.fetch,i=So(e,t,r.parameters,o),a=ko(r.parameters,t,n),u=r.bodyInputName,d=u===void 0||t[u]===void 0?void 0:JSON.stringify(t[u]);d!==void 0&&!Lo(a,"content-type")&&(a["content-type"]="application/json");let c=await s(i,{method:e.method.toUpperCase(),headers:a,...d!==void 0&&{body:d}}),l=c.headers.get("content-type")??"";if(!c.ok)return{content:[{type:"text",text:await c.text()}],isError:!0};if(l.includes("application/json")||l.includes("+json")){let p=await c.text();try{let g=JSON.parse(p);return{content:[{type:"text",text:JSON.stringify(g)}],structuredContent:g}}catch{return{content:[{type:"text",text:p}]}}}return{content:[{type:"text",text:await c.text()}]}}function So(e,t,n,r){let o=e.path.replace(/{([^}]+)}/g,(i,a)=>{let u=n.find(({parameter:d})=>d.in==="path"&&d.name===a);return encodeURIComponent(String(u===void 0?"":t[u.inputName]??""))}),s=new URL(o.replace(/^\/+/,""),Io(r));for(let{parameter:i,inputName:a}of n){if(i.in!=="query")continue;let u=t[a];u==null||u===""||Uo(s,i.name,u)}return s.toString()}function ko(e,t,n){let r={...n.headers??{}};for(let{parameter:o,inputName:s}of e){if(o.in!=="header")continue;let i=t[s];i==null||i===""||(r[o.name]=String(i))}return n.auth?.type==="bearer"&&n.auth.token&&(r.authorization=`Bearer ${n.auth.token}`),n.auth?.type==="header"&&n.auth.value&&(r[n.auth.name]=n.auth.value),r}function _o(e){let t=e.baseUrl??e.spec.servers?.[0]?.url;if(t===void 0||t.trim()==="")throw new Error("MCPServer.fromOpenAPI requires options.baseUrl or spec.servers[0].url");return t}function Uo(e,t,n){if(Array.isArray(n)){for(let r of n)r!=null&&r!==""&&e.searchParams.append(t,String(r));return}e.searchParams.set(t,String(n))}function Io(e){return e.endsWith("/")?e:`${e}/`}function Lo(e,t){return Object.keys(e).some(n=>n.toLowerCase()===t)}function me(e){let t=Z(e);return t!==void 0&&typeof t.$ref=="string"}function X(e,t){if(!me(t))return t;if(!t.$ref.startsWith("#/"))return;let n=t.$ref.slice(2).split("/").map(o=>o.replace(/~1/g,"/").replace(/~0/g,"~")),r=e;for(let o of n){let s=Z(r);if(s===void 0||!(o in s))return;r=s[o]}return r}function Z(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:void 0}import{OAuthError as ta,OAuthErrorCode as na,bearerAuthChallengeResponse as ra,getOAuthProtectedResourceMetadataUrl as Tn,oauthMetadataResponse as oa,requireBearerAuth as Rn,verifyBearerToken as sa}from"@modelcontextprotocol/server";import{getOAuthProtectedResourceMetadataUrl as Wi,oauthMetadataResponse as Yo,requireBearerAuth as zi}from"@modelcontextprotocol/server";function N(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function W(e){let t=e.hostname.toLowerCase();return t==="localhost"||t.endsWith(".localhost")||t==="[::1]"||/^127(?:\.\d{1,3}){3}$/.test(t)}function z(e,t){let n;try{n=new URL(e)}catch{throw new Error(`${t} must be an absolute URL`)}if(n.origin==="null"||n.username!==""||n.password!=="")throw new Error(`${t} must be an absolute URL without credentials`);return n}function J(e,t){if(e.protocol!=="https:"&&!(e.protocol==="http:"&&W(e)))throw new Error(`${t} must use HTTPS, or HTTP for localhost`)}import{OAuthError as cn,OAuthErrorCode as jo}from"@modelcontextprotocol/server";import{createRemoteJWKSet as No,jwtVerify as Ho,errors as H}from"jose";function C(e){let t=e.key??No(e.jwksUrl),n=ln(e.resource);return{async verifyAccessToken(r){try{let{payload:o}=await Ho(r,t,{issuer:e.issuer,...e.algorithms!==void 0&&{algorithms:[...e.algorithms]},requiredClaims:["exp","sub"]}),s={...o},i=b(s,"client_id")??b(s,"azp"),a=Do(s,"exp"),u=$o(s,n);return{token:r,clientId:i??"",scopes:x(s.scope),expiresAt:a,extra:{payload:s},resource:u}}catch(o){throw o instanceof cn?o:Bo(o)?(process.env.MCP_USE_OAUTH_DEBUG&&Wo(r,o),v("JWT verification failed",o)):o}}}}function E(e,t){let n=typeof e=="string"&&!e.includes("://")?`https://${e}`:e,r;try{r=new URL(n)}catch{throw new TypeError(`${t} must be an absolute HTTP(S) URL`)}if(!pn(r))throw new TypeError(`${t} must use HTTPS, or HTTP for localhost, without credentials, query, or fragment`);return r.pathname=r.pathname.replace(/\/+$/,"")||"/",r}function h(e,t){let n=new URL(e);return n.pathname=`${n.pathname.replace(/\/+$/,"")}/`,new URL(t.replace(/^\/+/,""),n).href}function P(e){let t=e.extra?.payload;if(!N(t))throw v("Verified token payload is missing");return t}function b(e,t){let n=e[t];return typeof n=="string"&&n.trim().length>0?n:void 0}function f(e,t){let n=e[t];return typeof n=="string"?n:void 0}function S(e,t){let n=e[t];return typeof n=="boolean"?n:void 0}function qo(e,t){let n=e[t];return typeof n=="number"&&Number.isFinite(n)?n:void 0}function he(e,t){let n=e[t];return N(n)?n:void 0}function x(e){return typeof e=="string"?e.split(/\s+/).filter(Boolean):Array.isArray(e)?e.filter(t=>typeof t=="string"&&t.length>0):[]}function Do(e,t){let n=qo(e,t);if(n===void 0||n<=Date.now()/1e3)throw v(`Missing or expired ${t} claim`);return n}function v(e,t){let n=new cn(jo.InvalidToken,e);return t!==void 0&&(n.cause=t),n}function $o(e,t){let n=e.resource;if(n!==void 0){if(typeof n!="string")throw v("Token resource claim must be an absolute URL");if(ln(n).href!==t.href)throw v("Token resource claim does not match protected resource");return t}let r=e.aud;if(!Vo(r))throw v("Token audience claim must be a string or string array");if(!(typeof r=="string"?[r]:r).includes(t.href))throw v("Token audience does not include the protected resource");return t}function Vo(e){return typeof e=="string"||Array.isArray(e)&&e.length>0&&e.every(t=>typeof t=="string")}function ln(e){try{let t=new URL(e);if(!pn(t))throw new TypeError;return t.pathname=t.pathname==="/"?"/":t.pathname.replace(/\/+$/,""),t}catch{throw v("Token resource claim must be an absolute HTTPS URL, or HTTP URL for localhost")}}function pn(e){return/^https?:$/.test(e.protocol)&&!e.username&&!e.password&&!e.search&&!e.hash&&(e.protocol!=="http:"||W(e))}function Bo(e){return e instanceof H.JWTClaimValidationFailed||e instanceof H.JWTExpired||e instanceof H.JOSEAlgNotAllowed||e instanceof H.JOSENotSupported||e instanceof H.JWSInvalid||e instanceof H.JWTInvalid||e instanceof H.JWSSignatureVerificationFailed||e instanceof H.JWKSNoMatchingKey}var Fo=["iss","aud","azp","sub","exp","iat","nbf","client_id","scope","typ","jti"];function Ye(e){return e instanceof Error?e.message:String(e)}function Wo(e,t){try{let s=function(u,d){try{return Buffer.from(u,"base64url").toString("utf8")}catch(c){console.error(`[oauth-debug] ${d} decode failed: ${Ye(c)}`);return}};var n=s;let r=t instanceof Error?t.constructor.name:typeof t;console.error(`[oauth-debug] JWT verify failed: ${r}: ${Ye(t)}`),t instanceof H.JWTClaimValidationFailed&&console.error(`[oauth-debug] claim=${t.claim} reason=${t.reason}`);let o=e.split(".");if(console.error(`[oauth-debug] token segments: ${o.length}`),o.length!==3){let u=e.length>12?`${e.slice(0,12)}\u2026`:e;console.error(`[oauth-debug] non-JWT token preview=${u} length=${e.length}`);return}let i=s(o[0],"header");i!==void 0&&console.error(`[oauth-debug] header=${i}`);let a=s(o[1],"payload");if(a===void 0)return;try{let u=JSON.parse(a),d={};for(let c of Fo)c in u&&(d[c]=u[c]);d.now=Math.floor(Date.now()/1e3),console.error(`[oauth-debug] payload=${JSON.stringify(d)}`)}catch(u){console.error(`[oauth-debug] payload decode failed: ${Ye(u)}`)}}catch{}}function fn(e){let t=e.provider,n=et(e.basePath);if(t.resource!==void 0)return Xe(t.resource,n);if(e.mcpUrl!==void 0)return Xe(gn(hn(e.mcpUrl,"MCP_URL"),n),n)}function mn(e,t){let n=hn(e,"listen origin");if(!W(n))throw new Error("OAuth listen origin must be localhost or a loopback address");return Xe(gn(n,et(t)),t)}function Xe(e,t){let n=et(t),r=z(e,"OAuth resource");if(r.search!==""||r.hash!=="")throw new Error("OAuth resource must not include a query string or fragment");if(J(r,"OAuth resource"),yn(r.pathname)!==n)throw new Error(`OAuth resource path must exactly match basePath (${n})`);return r.pathname=n,r}function Ze(e,t){let n=Qe(t),r=e.createTokenVerifier(new URL(n.href));if(r===null||typeof r!="object"||typeof r.verifyAccessToken!="function")throw new TypeError("OAuth provider createTokenVerifier must return an OAuthTokenVerifier");return{async verifyAccessToken(o){let s=await r.verifyAccessToken(o);Ko(s),zo(s,n);let i;try{i=e.mapAuthInfo(s)}catch(a){throw v("Token identity mapping failed",a)}return Go(i),{...s,scopes:[...s.scopes],extra:{...s.extra,...i}}}}}function zo(e,t){if(e.resource===void 0)throw v("Token verifier did not return a validated protected resource");if(Jo(e.resource).href!==Qe(t).href)throw v("Token resource does not match the protected resource")}function Jo(e){if(!(e instanceof URL))throw v("Token resource must be an absolute HTTPS URL, or HTTP URL for localhost");let t=e;if(!/^https?:$/.test(t.protocol)||t.username!==""||t.password!==""||t.search!==""||t.hash!==""||t.protocol==="http:"&&!W(t))throw v("Token resource must be an absolute HTTPS URL, or HTTP URL for localhost");return Qe(t)}function Qe(e){let t=new URL(e);return t.pathname=t.pathname==="/"?"/":t.pathname.replace(/\/+$/,""),t}function Me(e){return{oauthMetadata:e.oauthMetadata,...e.requiredScopes!==void 0&&{requiredScopes:[...e.requiredScopes]},...e.scopesSupported!==void 0&&{scopesSupported:[...e.scopesSupported]},...e.resourceName!==void 0&&{resourceName:e.resourceName},...e.serviceDocumentationUrl!==void 0&&{serviceDocumentationUrl:e.serviceDocumentationUrl}}}function Ko(e){if(e===null||typeof e!="object"||typeof e.token!="string"||e.token.length===0||typeof e.clientId!="string"||!Array.isArray(e.scopes)||!e.scopes.every(t=>typeof t=="string")||typeof e.expiresAt!="number"||!Number.isFinite(e.expiresAt)||e.expiresAt<=Date.now()/1e3)throw v("Token verifier returned invalid authentication information")}function Go(e){if(e===null||typeof e!="object"||!("user"in e)||e.user===void 0||!N(e.payload)||!Array.isArray(e.permissions)||!e.permissions.every(t=>typeof t=="string"))throw v("Token identity mapping must return user, payload, and string permissions")}function hn(e,t){let n=z(e,t);if(n.pathname!=="/"||n.search!==""||n.hash!==""||n.username!==""||n.password!=="")throw new Error(`${t} must be an absolute origin without a path`);return n}function gn(e,t){let n=new URL(e.origin);return n.pathname=t,n}function et(e){if(!e.startsWith("/")||e.includes("?")||e.includes("#"))throw new Error("basePath must be an absolute URL pathname");return yn(e)}function yn(e){if(e==="/")return"/";let t=e.length;for(;t>0&&e.charCodeAt(t-1)===47;)t--;return e.slice(0,t)}function tt(e,t){let n=Me(e);return async(r,o)=>{let s=Yo(r,{oauthMetadata:n.oauthMetadata,resourceServerUrl:t,...n.scopesSupported!==void 0&&{scopesSupported:[...n.scopesSupported]},...n.resourceName!==void 0&&{resourceName:n.resourceName},...n.serviceDocumentationUrl!==void 0&&{serviceDocumentationUrl:n.serviceDocumentationUrl}});return s!==void 0?s:o()}}function wn(e){return M(e).authInfo}function O(e){if(e===null||typeof e!="object"||typeof e.createTokenVerifier!="function"||typeof e.mapAuthInfo!="function")throw new TypeError("oauthCustomProvider requires createTokenVerifier, oauthMetadata, and mapAuthInfo");if(Xo(e.oauthMetadata),e.resource!==void 0&&Zo(e.resource),vn(e.requiredScopes,"requiredScopes"),vn(e.scopesSupported,"scopesSupported"),e.resourceName!==void 0&&(typeof e.resourceName!="string"||e.resourceName.trim().length===0))throw new TypeError("resourceName must be a non-empty string");if(e.serviceDocumentationUrl!==void 0){if(!(e.serviceDocumentationUrl instanceof URL))throw new TypeError("serviceDocumentationUrl must be a URL");J(e.serviceDocumentationUrl,"serviceDocumentationUrl")}return{createTokenVerifier:e.createTokenVerifier,oauthMetadata:e.oauthMetadata,mapAuthInfo:e.mapAuthInfo,...e.resource!==void 0&&{resource:e.resource},...e.requiredScopes!==void 0&&{requiredScopes:[...e.requiredScopes]},...e.scopesSupported!==void 0&&{scopesSupported:[...e.scopesSupported]},...e.resourceName!==void 0&&{resourceName:e.resourceName},...e.serviceDocumentationUrl!==void 0&&{serviceDocumentationUrl:e.serviceDocumentationUrl}}}function Xo(e){if(e===null||typeof e!="object"||!("issuer"in e)||typeof e.issuer!="string")throw new TypeError("oauthMetadata must include a string issuer");J(z(e.issuer,"oauthMetadata.issuer"),"oauthMetadata.issuer")}function Zo(e){J(z(e,"resource"),"resource")}function vn(e,t){if(e!==void 0&&(!Array.isArray(e)||!e.every(n=>typeof n=="string")))throw new TypeError(`${t} must be an array of strings`)}function Mn(e){return e.inputSchema??e.schema}var Qo="mcp_use_sdk_event",es="https://eu.i.posthog.com/i/v0/e/",ts="phc_lyTtbYwvkdSbrcMQNPiKiiRWrrM1seyKIMjycSvItEI",ns=/(^|_)(arguments?|args|body|command|headers?|location|message|organization|path|query|response|secret|subject|token|uri|url|user_agent)(_|$)/i,rs=new Set("feature action sdk_generation telemetry_schema_version sdk_package sdk_version server_id runtime_id identity_stability distinct_id validation_run_id is_validation".split(" ")),rt=crypto.randomUUID(),bn=new Set,nt=new Set,xn=new Map;function ot(e){return[...e].some(t=>{let n=t.charCodeAt(0);return n<32||n===127})}function st(e){return typeof process>"u"?void 0:process.env?.[e]}function On(e){let t=st(e);return t!==void 0&&t.length>0&&t.length<=128&&!ot(t)?t:void 0}function os(){if(st("MCP_USE_ANONYMIZED_TELEMETRY")==="false")return!0;try{return globalThis.__MCP_USE_ANONYMIZED_TELEMETRY__===!1||typeof localStorage<"u"&&localStorage.getItem("MCP_USE_ANONYMIZED_TELEMETRY")==="false"}catch{return!1}}function ss(e){return Object.fromEntries(Object.entries(e).filter(([t,n])=>t.length>128||ot(t)||t.startsWith("$")||rs.has(t)||ns.test(t)||n===void 0?!1:typeof n=="string"?n.length<=128&&!ot(n):typeof n=="boolean"||typeof n=="number"&&Number.isFinite(n)))}async function is(e){let t=On("MCP_USE_TELEMETRY_PROJECT_ID");if(t!==void 0)return{id:t,stability:"project"};if(e===void 0||typeof process>"u")return{id:rt,stability:"process"};let n=xn.get(e);if(n!==void 0)return n;let r=(async()=>{try{let o=await import("fs/promises"),s=`${e}/.mcp-use`,i=`${s}/usage.json`,a=async()=>{try{let c=JSON.parse(await o.readFile(i,"utf8"));if(typeof c=="object"&&c!==null&&"schemaVersion"in c&&c.schemaVersion===1&&"serverId"in c&&typeof c.serverId=="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(c.serverId))return c.serverId}catch{}},u=await a();if(u!==void 0)return{id:u,stability:"server"};await o.mkdir(s,{recursive:!0,mode:448});let d=crypto.randomUUID();try{return await o.writeFile(i,`${JSON.stringify({schemaVersion:1,serverId:d})}
|
|
8
|
+
`,{flag:"wx",mode:384}),{id:d,stability:"server"}}catch{let c=await a();if(c!==void 0)return{id:c,stability:"server"}}}catch{}return{id:rt,stability:"process"}})();return xn.set(e,r),r}function as(e,t,n,r,o){let s=On("MCP_USE_TELEMETRY_VALIDATION_ID");if(os()||st("NODE_ENV")==="test"&&s===void 0||nt.size>=16)return;if(r.onceKey!==void 0){if(bn.has(r.onceKey))return;bn.add(r.onceKey)}let i=Math.max(0,Math.min(1,r.sampleRate??1));if(s===void 0&&Math.random()>=i)return;let a=(async()=>{try{let u=await o(),d=JSON.stringify({api_key:ts,event:Qo,properties:{...ss(n),feature:e,action:t,sdk_generation:"v2",telemetry_schema_version:2,sdk_package:"mcp-use",sdk_version:typeof __MCP_USE_PACKAGE_VERSION__>"u"?"development":__MCP_USE_PACKAGE_VERSION__,server_id:u.id,runtime_id:rt,identity_stability:u.stability,distinct_id:u.id,sample_rate:s===void 0?i:1,$process_person_profile:!1,$geoip_disable:!0,...s!==void 0&&{is_validation:!0,validation_run_id:s}}});await fetch(es,{method:"POST",headers:{"content-type":"application/json"},keepalive:!0,body:d})}catch{return}})();nt.add(a),a.then(()=>nt.delete(a))}function be(e,t,n={},r={}){as(e,t,n,r,()=>is(r.serverRoot))}var xe=Symbol("mcp-use/registerViews");function Cn(e,t){if(!e.startsWith("/"))throw new Error(`View manifest asset path must be origin-absolute (start with "/"); got ${JSON.stringify(e)}`);return`${t}${e}`}function us(e,t){return`${G(e,`_mcp-use/views/${t}`)}/`}function it(e,t,n,r){return e.startsWith("http://")||e.startsWith("https://")||e.startsWith("data:")?e:e.startsWith("/")?Cn(e,t):`${t}${us(n,r)}${e.replace(/^\/+/,"")}`}function ds(e,t){return`${e}${G(t,"_mcp-use/public")}/`}function cs(e){return e.replaceAll(/<\/script/gi,"<\\/script").replaceAll("<!--","\\x3C!--")}function ls(e){return e.replaceAll(/<\/style/gi,"<\\/style")}function at(e){return e.replaceAll("&","&").replaceAll('"',""").replaceAll("<","<").replaceAll(">",">")}var An="<style>html,body,#root{background:transparent}</style>";function ut(e,t,n,r){let o={publicBase:ds(t,n)},s=`<script>globalThis.__mcpUseViewConfig=${JSON.stringify(o)};</script>`;if(e.kind==="inline"){let d=e.css.length>0?`<style>${ls(e.css)}</style>`:"",c=`<script type="module">${cs(e.js)}</script>`;return`<!doctype html>
|
|
9
|
+
<html>
|
|
10
|
+
<head>
|
|
11
|
+
<meta charset="utf-8">
|
|
12
|
+
${s}
|
|
13
|
+
${An}
|
|
14
|
+
${d}
|
|
15
|
+
</head>
|
|
16
|
+
<body>
|
|
17
|
+
<div id="root"></div>
|
|
18
|
+
${c}
|
|
19
|
+
</body>
|
|
20
|
+
</html>`}if(r===void 0)throw new Error("viewName is required when synthesizing an external view document.");let i=e.css.map(d=>`<link rel="stylesheet" href="${at(it(d,t,n,r))}">`).join(`
|
|
21
|
+
`),a=(e.scripts??[]).map(d=>`<script type="module" src="${at(it(d,t,n,r))}"></script>`).join(`
|
|
22
|
+
`),u=it(e.entry,t,n,r);return`<!doctype html>
|
|
23
|
+
<html>
|
|
24
|
+
<head>
|
|
25
|
+
<meta charset="utf-8">
|
|
26
|
+
${s}
|
|
27
|
+
${An}
|
|
28
|
+
${i}
|
|
29
|
+
</head>
|
|
30
|
+
<body>
|
|
31
|
+
<div id="root"></div>
|
|
32
|
+
${a}
|
|
33
|
+
<script type="module" src="${at(u)}"></script>
|
|
34
|
+
</body>
|
|
35
|
+
</html>`}var ps={connectDomains:"CSP_CONNECT_DOMAINS",resourceDomains:"CSP_RESOURCE_DOMAINS",frameDomains:"CSP_FRAME_DOMAINS",baseUriDomains:"CSP_BASE_URI_DOMAINS"};function En(e){return e===void 0||e.trim()===""?[]:e.split(",").map(t=>t.trim()).filter(t=>t.length>0)}function Pn(e){if(typeof process>"u")return;let t=process.env[e];if(!(t===void 0||t.trim()===""))return En(t)}function fs(){return Pn("CSP_URLS")??[]}function Oe(e){let t=Pn(ps[e]);return t!==void 0?t:fs()}function Ae(...e){let t=new Set,n=[];for(let r of e)for(let o of r)t.has(o)||(t.add(o),n.push(o));return n}function ms(e){return e.startsWith("https://")?`wss://${e.slice(8)}`:e.startsWith("http://")?`ws://${e.slice(7)}`:e}function dt(e,t){let n=e?.csp,r=[];t.serverOrigin!==""&&(r.push(t.serverOrigin),t.hmrWs===!0&&r.push(ms(t.serverOrigin)));let o=[],s=t.explicitAssetsBase?t.assetsOrigin:t.serverOrigin;s!==""&&o.push(s);let i=Ae(n?.connectDomains??[],Oe("connectDomains"),r),a=Ae(n?.resourceDomains??[],Oe("resourceDomains"),o),u=Ae(n?.frameDomains??[],Oe("frameDomains")),d=Ae(n?.baseUriDomains??[],Oe("baseUriDomains"));return{...n,connectDomains:i,resourceDomains:a,frameDomains:u,baseUriDomains:d}}var hs=".mcp-use/build/views/public",gs="public",ys=".mcp-use/build/views";function ct(e,t,n){if(t.size===0)return;let r=G(e,"_mcp-use/views"),o=n?.projectRoot??process.cwd();return async s=>{if(s.method!=="GET"&&s.method!=="HEAD")return new Response("Method Not Allowed",{status:405});if(!Ne(s,r))return new Response("Not Found",{status:404});let a=ae(s).slice(r.length+1),u=a.indexOf("/");if(u<=0||u===a.length-1)return new Response("Not Found",{status:404});let d=a.slice(0,u),c=a.slice(u+1),l=t.get(d);if(l===void 0||l.kind!=="external")return new Response("Not Found",{status:404});let[{join:p},{resolvePublicFilePath:g,servePublicFile:T}]=await Promise.all([import("path"),import("./public-route-GWDSKOSN.js")]),y=p(o,ys,d),m=await g(y,c);return m===null?new Response("Not Found",{status:404}):await T(m,{...n?.deferCors===!0&&{deferCors:!0},...s.method==="HEAD"&&{head:!0}})}}function lt(e,t,n){if(t.size===0&&n?.enabled!==!0)return;let r=G(e,"_mcp-use/public"),o=n?.dev===!0?gs:hs,s=n?.projectRoot??process.cwd();return async i=>{if(i.method!=="GET"&&i.method!=="HEAD")return new Response("Method Not Allowed",{status:405});if(!Ne(i,r))return new Response("Not Found",{status:404});let u=ae(i).slice(r.length+1),d;try{d=decodeURIComponent(u)}catch{return new Response("Not Found",{status:404})}if(d.length===0)return new Response("Not Found",{status:404});let[{join:c},{resolvePublicFilePath:l,servePublicFile:p}]=await Promise.all([import("path"),import("./public-route-GWDSKOSN.js")]),g=c(s,o),T=await l(g,d);return T===null?new Response("Not Found",{status:404}):await p(T,{...n?.deferCors===!0&&{deferCors:!0},...i.method==="HEAD"&&{head:!0}})}}function pt(e,t,n){if(e===void 0&&t===void 0&&n===void 0)return;let r={...n},o=n?.["ui"],s=typeof o=="object"&&o!==null&&!Array.isArray(o),i=s?{...o}:{};if(e!==void 0){let a=Y(e);i.resourceUri=a,r[de]=a}else delete i.resourceUri,delete r[de];return t!==void 0?i.visibility=[t]:delete i.visibility,(e!==void 0||t!==void 0||s)&&(r["ui"]=i),r}function ft(e){let t=Y(e);return{ui:{resourceUri:t},[de]:t}}function ws(e){let t=e?.request,n=e?.serverOrigin??(t!==void 0?ke(t):""),r=e?.assetsBase??(t!==void 0?V(t):n);return{serverOrigin:n,assetsOrigin:_e(r),explicitAssetsBase:Ue(),...e?.hmrWs===!0?{hmrWs:!0}:{}}}function Ce(e,t){let r={csp:dt(e,ws(t))};return e?.permissions!==void 0&&(r.permissions=e.permissions),e?.domain!==void 0&&(r.domain=e.domain),e?.prefersBorder!==void 0&&(r.prefersBorder=e.prefersBorder),{ui:r}}function mt(e,t,n,r){return{mimeType:ue,...n?.description!==void 0&&{description:n.description},_meta:Ce(n,r)}}function Q(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:void 0}function ht(e,t){if(typeof e!="string")return t;let n=e.trim();return n.length>0&&n.length<=64&&![...n].some(r=>{let o=r.charCodeAt(0);return o<32||o===127})?n:t}function Un(e){if(!jn(e))return;let t=Q(e.params);if(e.method==="initialize"){let s=Q(t?.clientInfo),i=Q(t?.capabilities)??{};return In(s,i,t?.protocolVersion,"legacy")}let n=Q(t?._meta),r=Q(n?.[bs]),o=Q(n?.[Ms]);if(!(r===void 0||o===void 0))return In(r,o,n?.[xs],"modern")}function In(e,t,n,r){let o=t;return{client_name:ht(e?.name,"other"),client_version:ht(e?.version,"unknown"),protocol_era:r,protocol_version:ht(n,"unknown"),connection_mode:r==="modern"?"stateless_request":"legacy_session",sampling_capability:Object.hasOwn(t,"sampling"),elicitation_capability:Object.hasOwn(t,"elicitation"),roots_capability:Object.hasOwn(t,"roots"),extensions_capability:Object.hasOwn(t,"extensions"),views_capability:ce(o),capability_count:Object.keys(t).length}}function Ln(e){if(typeof e!="object"||e===null||Array.isArray(e)||!("$schema"in e))return e;let t={...e};return delete t.$schema,t}function Os(e){return e.map(t=>({...t,inputSchema:Ln(t.inputSchema),...t.outputSchema===void 0?{}:{outputSchema:Ln(t.outputSchema)}}))}function As(e,t){e.use("*",async(n,r)=>{let o=await t(n.req.raw,async()=>(await r(),n.res));return n.res=o,o})}var ye=class e{#e;#t;#n=new Map;#r=new Map;#l=new Map;#i=new Map;#o=new Map;#a=new Map;#h=!1;#p=!1;#u=process.cwd();#E;#_;#f;#R;#g;#M;#b=!1;#U=!1;#I=!1;#x=[];#y=[];#L=crypto.randomUUID();#w=new Set;#m=new Set;#O=new Set;#A=new Set;#j=0;#P=0;#N=0;#H=0;#q=0;#D=0;#$=[];#S=new Set;#V=!1;app;get;post;put;patch;delete;all;fetch;static fromOpenAPI(t){let n=new e({name:t.name??t.spec.info.title,version:t.version??t.spec.info.version??"1.0.0"});un(n,t);for(let r of n.#n.keys())n.#w.add(r);return n}constructor(t){if(Et(t),this.#e=t,this.#t=xt(t),this.app=new _n,this.app.use("*",async(n,r)=>{M(n.req.raw).honoContext=n,await r()}),this.get=this.app.get.bind(this.app),this.post=this.app.post.bind(this.app),this.put=this.app.put.bind(this.app),this.patch=this.app.patch.bind(this.app),this.delete=this.app.delete.bind(this.app),this.all=this.app.all.bind(this.app),this.fetch=async(n,r,o)=>(this.#c("handler"),this.#_.fetch(n,r,o)),t.oauth!==void 0){let n=typeof process>"u"?void 0:process.env.MCP_URL,r=fn({provider:t.oauth,basePath:this.#d(),...n!==void 0&&{mcpUrl:n}});this.#M=r,this.#b=r!==void 0,this.#U=r===void 0}}get basePath(){return this.#d()}get host(){return this.#e.host}get port(){return this.#e.port}get branding(){return this.#t}getHandler(){return this.fetch}tool(t,n){return this.#s("tool",t.name),this.#G(t),this.#w.delete(t.name),this.#m.delete(t.name),this.#n.set(t.name,{definition:t,callback:n}),Object.freeze({name:t.name})}[xe](t,n){if(this.#h)throw new Error("Cannot prime views: the views registry is already primed on this server instance.");this.#s("views","manifest"),this.#p=n?.dev===!0,n?.projectRoot!==void 0&&(this.#u=n.projectRoot);for(let[r,o]of Object.entries(t))this.#o.set(r,o);this.#h=!0}__primeViews(t,n){this[xe](t,n)}resource(t,n){this.#s("resource",t.name);let r=this.#r.get(t.name);return r!==void 0&&this.#O.delete(r.definition.uri),this.#r.set(t.name,{definition:t,callback:n}),this}resourceTemplate(t,n){this.#s("resourceTemplate",t.name);let r=t.complete===void 0?void 0:rn(t.complete);return this.#l.set(t.name,{definition:t,...r!==void 0&&{complete:r},callback:n}),this}prompt(t,n){return this.#s("prompt",t.name),this.#A.delete(t.name),this.#i.set(t.name,{definition:t,callback:n}),this}async proxy(t){this.#k("proxy()");let n=(async()=>{let{isProxyConnection:r,mountProxyConnection:o,mountProxyServers:s}=await import("./mcp-proxy-O6GLK2IL.js");if(r(t)){this.#P+=1,await o(this.#B(),t);return}this.#P+=Object.keys(t).length,await s(this.#B(),t)})();this.#S.add(n);try{await n}finally{this.#S.delete(n)}}use(t,...n){if(typeof t=="string"&&t.startsWith("mcp:")){this.#s("middleware",t);let o=n[0];return this.#x.push(Ft(t,o)),this}return this.app.use.call(this.app,t,...n),this.#j+=typeof t=="function"?1:n.length,this}on(t,n){return this.#s("event listener",t),this.#y.push(Wt(t,n)),this}__setEventBus(t){this.#s("event bus","shared"),this.#R=t}__mount(){this.#c("handler")}async notifyToolsChanged(){await this.#c("handler").handler.notify.toolsChanged()}async notifyPromptsChanged(){await this.#c("handler").handler.notify.promptsChanged()}async notifyResourcesChanged(){await this.#c("handler").handler.notify.resourcesChanged()}async notifyResourceUpdated(t){await this.#c("handler").handler.notify.resourceUpdated(t)}async listen(t=void 0,n={}){this.#k("listen()");let{createServer:r}=await import("http"),{toNodeHandler:o}=await import("./node-bridge-KQ3STLK5.js"),s=Pt(n.host,this.#e.host),i=St(t,this.#e.port);return this.#z(s),new Promise((a,u)=>{let d,c,l=new Promise((m,R)=>{d=m,c=R});l.catch(()=>{});let p=!1,g=m=>{p||(p=!0,u(m)),c?.(m),new Promise(R=>y.close(()=>R())).catch(()=>{}).finally(()=>{this.#g===y&&(this.#g=void 0)})},T=o({fetch:async m=>(await l)(m)}),y=r((m,R)=>{T(m,R)});y.once("error",g),y.listen(i,s,()=>{try{let m=y.address(),R=typeof m=="object"&&m!==null?m.port:i,{fetch:I}=this.#c("listen",R,s);d?.(I),p||(p=!0,a({port:R,url:`http://localhost:${R}${this.#d()}`}))}catch(m){g(m)}}),this.#g=y})}async close(){this.#V=!0,await Promise.allSettled([...this.#S]);let t=[],n=this.#$.splice(0),r=await Promise.allSettled(n.map(s=>s.close()));for(let s of r)s.status==="rejected"&&t.push(s.reason);try{await this.#f?.close()}catch(s){t.push(s)}let o=this.#g;if(o!==void 0)try{await new Promise((s,i)=>{o.close(a=>a?i(a):s())}),this.#g=void 0}catch(s){t.push(s)}if(t.length>0)throw new AggregateError(t,"Failed to close MCP server cleanly")}#k(t){if(this.#V)throw t!==void 0?new Error(`Cannot call ${t} after the server has closed.`):new Error("Cannot use the server after it has closed.")}#d(){return this.#e.basePath??"/mcp"}#W(t,n,r){if(this.#e.oauth===void 0)return;if(this.#b)return this.#M;let o=r??this.#e.host??"127.0.0.1",s=t==="listen"&&n!==void 0&&["127.0.0.1","localhost","::1"].includes(o);if(this.#U&&s)return this.#M=mn(`http://localhost:${n}`,this.#d()),this.#b=!0,this.#M;throw new Error("OAuth requires an explicit resource or MCP_URL when using server.fetch or listening on a non-local host")}#z(t){if(this.#e.oauth!==void 0&&!["127.0.0.1","localhost","::1"].includes(t)&&!this.#b)throw new Error("OAuth listen() on a public or wildcard host requires an explicit provider resource or valid MCP_URL.")}#s(t,n){if(this.#f!==void 0)throw new Error(`Cannot register ${t} "${n}" after the server has started: registrations are replayed per request from the registry, so register everything before listen()/server.fetch.`)}#J(){be("server","configured",{tools_total:this.#n.size,tools_local:this.#n.size-this.#w.size-this.#m.size,tools_openapi:this.#w.size,tools_proxied:this.#m.size,resources:this.#r.size,resource_templates:this.#l.size,prompts:this.#i.size,views:this.#o.size,proxy_servers_configured:this.#P,proxy_servers_connected:this.#N,proxy_tools_discovered:this.#H,proxy_resources_discovered:this.#q,proxy_prompts_discovered:this.#D,proxy_tools_mounted:this.#m.size,proxy_resources_mounted:this.#O.size,proxy_prompts_mounted:this.#A.size,http_middleware:this.#j,mcp_middleware:this.#x.length,observers_before:this.#y.filter(({phase:t})=>t==="before").length,observers_complete:this.#y.filter(({phase:t})=>t==="complete").length,oauth_configured:this.#e.oauth!==void 0,cors_configured:this.#e.cors!==void 0,request_state_configured:this.#e.requestState!==void 0,legacy_policy:this.#e.legacy??"stateless"},{onceKey:`${this.#L}:server`,serverRoot:this.#u})}#K(t){let n=Un(t);n!==void 0&&be("client","observed",{...n},{onceKey:`${this.#L}:client:${JSON.stringify(n)}`,serverRoot:this.#u})}#B(){return{isStarted:()=>this.#f!==void 0,hasTool:t=>this.#n.has(t),hasResource:t=>this.#r.has(t),hasPrompt:t=>this.#i.has(t),registerTool:(t,n)=>{this.#s("tool",t.name),this.#m.add(t.name),this.#n.set(t.name,{definition:t,callback:n})},registerResource:(t,n)=>{this.#s("resource",t.name),this.#O.add(t.uri),this.#r.set(t.name,{definition:t,callback:n})},registerPrompt:(t,n)=>{this.#s("prompt",t.name),this.#A.add(t.name),this.#i.set(t.name,{definition:t,callback:n})},trackOwner:t=>{this.#$.push(t)},trackNamespace:({tools:t,resources:n,prompts:r})=>{this.#N+=1,this.#H+=t,this.#q+=n,this.#D+=r}}}#F(t,n){let{allowedHosts:r,allowedOrigins:o}=this.#e,s=n??this.#e.host??"127.0.0.1",i=["127.0.0.1","localhost","::1"].includes(s),a=r!==void 0?[...new Set([...Sn(),...r])]:t==="listen"&&i?Sn():void 0,u=o!==void 0?[...new Set([...vs(),...o])]:void 0;return{hosts:a,origins:u}}#c(t,n,r){if(this.#k(),this.#E===void 0||this.#f===void 0){let{hosts:o,origins:s}=this.#F(t,r),i=this.#d(),a=i==="/"?"":i,u=new _n,d=[Ut(),en(this.#e.logging)],c=this.#e.cors;c!==void 0&&d.unshift(Dt(c));let l=$t(c);o!==void 0&&d.unshift(It(o)),s!==void 0&&d.push(Lt(s)),o===void 0&&t==="listen"&&console.warn(`[mcp-use] listen() is serving on ${r} without Host validation. Behind a platform edge that only routes your own domains this is expected; if this process is reachable directly, set allowedHosts to restrict it.`),this.#Y();let p=this.#W(t,n,r);if(p!==void 0){let w=this.#e.oauth;d.push(tt(w,p))}for(let w of d)As(u,w);let{handler:g,fetch:T}=tn(w=>this.#X(w),{path:i,...(this.#e.legacy!==void 0||this.#R!==void 0)&&{handler:{...this.#e.legacy!==void 0&&{legacy:this.#e.legacy},...this.#R!==void 0&&{bus:this.#R}}},...p!==void 0&&{authInfo:w=>wn(w)}}),y=async(w,_)=>_();if(p!==void 0){let w=this.#e.oauth,_=Me(w),Se=Rn({verifier:Ze(w,p),resourceMetadataUrl:Tn(p),..._.requiredScopes!==void 0&&{requiredScopes:_.requiredScopes}});y=async($,ie)=>{let K=await Se($);if(K instanceof Response)return K;let Yn=M($);return Yn.authInfo=K,ie()},u.use("*",async($,ie)=>{if(new URL($.req.url).pathname!==i){await ie();return}if(this.#e.publicLandingPage===!0&&He($.req.raw)){await ie();return}let K=await y($.req.raw,async()=>(await ie(),$.res));return $.res=K,K})}let m=w=>{let _=M(w).parsedBody;return jn(_)&&(this.#J(),this.#K(_)),T(w)},R=async w=>He(w)?(async()=>{let{createLandingPageResponse:Se}=await import("./landing-handler-2IDA43KU.js");return Se(w,i,this.#e,this.#t,this.#n.values(),this.#i.values(),this.#r.values())})():m(w),I=this.#h?this.#p:process.env.NODE_ENV!=="production",A=Ct(this.#t,{dev:I,projectRoot:this.#u,deferCors:l});A!==void 0&&this.app.all("/favicon.ico",w=>A(w.req.raw));let D=lt(i,this.#o,{dev:this.#h?this.#p:I,projectRoot:this.#u,enabled:At(this.#t),deferCors:l});if(D!==void 0&&this.app.on(["GET","HEAD"],`${a}/_mcp-use/public/*`,w=>D(w.req.raw)),!this.#p){let w=ct(i,this.#o,{projectRoot:this.#u,deferCors:l});w!==void 0&&this.app.on(["GET","HEAD"],`${a}/_mcp-use/views/*`,_=>w(_.req.raw))}this.app.all(i,w=>R(w.req.raw)),u.route("/",this.app),this.#_=u,this.#E=async w=>u.fetch(w),this.#f=g,this.#I=o!==void 0}else if(t==="listen"&&!this.#I&&this.#F("listen",r).hosts!==void 0)throw new Error("Cannot listen() on a localhost bind after server.fetch mounted the app without Host validation (server.fetch expects a platform edge in front). Call listen() first, or set allowedHosts.");return{fetch:this.#E,handler:this.#f}}#G(t){let n=t.view;if(n===void 0)return;if(t.outputSchema===void 0)throw new Error(`Tool "${t.name}" declares view "${n.name}" but has no outputSchema. View-bound tools require an outputSchema \u2014 the view reads structuredContent typed from it. Use outputSchema: z.object({}) for a view that takes no structured output.`);let r=this.#a.get(n.name);if(r!==void 0)throw new Error(`View "${n.name}" is already bound to tool "${r.toolName}"; tool "${t.name}" cannot bind the same view. Each view may be bound to one tool.`);this.#a.set(n.name,{toolName:t.name,config:n})}#Y(){if(this.#a.size>0&&!this.#h){let t=[...this.#n.values()].find(r=>r.definition.view!==void 0),n=t?.definition.view?.name??"unknown";throw new Error(`Tool "${t?.definition.name??"unknown"}" is bound to view "${n}" but no views were primed. Run \`mcp-use build\` and deploy the built entry, or in dev let the CLI prime views automatically.`)}for(let t of this.#n.values()){let n=t.definition.view?.name;if(n!==void 0&&!this.#o.has(n))throw new Error(`Tool "${t.definition.name}" is bound to view "${n}" which is not in the primed views registry. Run \`mcp-use build\` and deploy the built entry, or in dev let the CLI prime views automatically.`)}for(let t of this.#o.keys())this.#a.has(t)||console.warn(`[mcp-use] View "${t}" is registered but no tool binds it.`)}#X(t){let{name:n,version:r,title:o,description:s,instructions:i}=this.#e,a=t.authInfo,u=new Ts({name:n,version:r,...o!==void 0&&{title:o},...s!==void 0&&{description:s},...this.#t.websiteUrl!==void 0&&{websiteUrl:this.#t.websiteUrl},...this.#t.icons!==void 0&&{icons:Ot(this.#t.icons,t.requestInfo,this.#d())}},{capabilities:{logging:{},tools:{listChanged:!0},prompts:{listChanged:!0},resources:{listChanged:!0,subscribe:!0}},...i!==void 0&&{instructions:i},...a!==void 0&&{authInfo:a},...this.#e.requestState!==void 0&&{requestState:this.#e.requestState}}),d=t.requestInfo,c=d!==void 0?{request:d,hmrWs:this.#p}:{hmrWs:this.#p},l=this.#d();for(let p of this.#n.values())this.#ee(u,p);for(let p of this.#r.values())this.#ne(u,p);for(let p of this.#l.values())this.#re(u,p);for(let p of this.#i.values())this.#se(u,p);for(let[p,g]of this.#o.entries())this.#te(u,p,g,c,l);return this.#Q(u),u}#v(t,n,r){let o=we(r);return Object.assign(o,{method:t,params:n,...r.sessionId!==void 0&&{session:{sessionId:r.sessionId}},...r.http?.authInfo!==void 0&&{auth:r.http.authInfo},state:new Map})}#T(t,n,r){let o=performance.now(),s=this.#x.filter(c=>le(c.pattern,t)).length,i=c=>this.#y.filter(l=>l.phase===c&&le(l.pattern,t)).length,a=n.request?.raw,u=a===void 0?void 0:Un(M(a).parsedBody),d=(c,l)=>{be("operation","completed",{method:t,outcome:c,duration_ms:Math.max(0,Math.round(performance.now()-o)),primitive_origin:this.#Z(t,n.params),matched_middleware:s,observers_before:i("before"),observers_complete:l?i("complete"):0,...u?.protocol_era==="modern"?u:{client_name:"unknown",protocol_era:"legacy"}},{sampleRate:c==="success"?.1:1,serverRoot:this.#u})};return zt(this.#x,this.#y,t,n,r).then(c=>{let l=kn(c)?"input_required":t==="tools/call"&&typeof c=="object"&&c!==null&&"isError"in c&&c.isError===!0?"error":"success";return d(l,!0),c},c=>{throw d("error",!1),c})}#Z(t,n){if(t==="tools/call"){let r=String(n.name);return this.#m.has(r)?"proxied":this.#w.has(r)?"openapi":"local"}return t==="resources/read"?this.#O.has(String(n.uri))?"proxied":"local":t==="prompts/get"?this.#A.has(String(n.name))?"proxied":"local":"mixed"}#Q(t){let n=t.server._requestHandlers;if(n===void 0)return;let r=(o,s,i)=>{let a=n.get(o);if(a===void 0||a.__mcpListWrapped)return;let u=async(d,c)=>{let l=c,p=d.params??{},g=this.#v(o,p,l),T,y=async()=>{let I=Bt(d,g.params),A=await a(I,c);if(typeof A!="object"||A===null)throw new TypeError(`[mcp-use] ${o} handler returned a non-object result`);T=A;let D=T[s];if(!Array.isArray(D))throw new TypeError(`[mcp-use] ${o} handler result is missing a ${s} array`);return D},m=await this.#T(o,g,y);if(!Array.isArray(m))throw new TypeError(`[mcp-use] ${o} middleware must return a ${s} array`);let R=i?.(m)??m;return{...T,[s]:R}};u.__mcpListWrapped=!0,n.set(o,u)};r("tools/list","tools",Os),r("resources/list","resources"),r("prompts/list","prompts")}#ee(t,{definition:n,callback:r}){let o=n.view,s=pt(o?.name,n.visibility,n._meta),i={...n.title!==void 0&&{title:n.title},...n.description!==void 0&&{description:n.description},...n.annotations!==void 0&&{annotations:n.annotations},...n.outputSchema!==void 0&&{outputSchema:n.outputSchema},...s!==void 0&&{_meta:s}},a=o!==void 0?ft(o.name):void 0,u=Mn(n),d=async(c,l)=>{let p=this.#v("tools/call",{name:n.name,arguments:c,...l.mcpReq._meta!==void 0&&{_meta:l.mcpReq._meta}},l),g=async()=>{let T=p.params.arguments??{},y=await r(T,this.#C(l));return kn(y)||a===void 0||y.isError===!0?y:{...y,_meta:{...y._meta,...a}}};return await this.#T("tools/call",p,g)};u!==void 0?t.registerTool(n.name,{...i,inputSchema:u},async(c,l)=>d(c,l)):t.registerTool(n.name,i,async c=>d({},c))}#te(t,n,r,o,s){let i=Y(n),a=this.#oe(this.#a.get(n)?.config),u=mt(n,r,a,o);t.registerResource(n,i,u,async(d,c)=>{let l=c.http?.req,p=l!==void 0?{request:l,...o.hmrWs===!0?{hmrWs:!0}:{}}:o.hmrWs===!0?{hmrWs:!0}:{},g=l!==void 0?V(l):o.request!==void 0?V(o.request):"",T=ut(r,g,s,n);return{contents:[{uri:d.href,mimeType:u.mimeType,text:T,_meta:Ce(a,p)}]}})}#ne(t,{definition:n,callback:r}){t.registerResource(n.name,n.uri,{...n.title!==void 0&&{title:n.title},...n.description!==void 0&&{description:n.description},...n.mimeType!==void 0&&{mimeType:n.mimeType},...n.annotations!==void 0&&{annotations:n.annotations},...n._meta!==void 0&&{_meta:{...n._meta}}},async(o,s)=>{let i=this.#v("resources/read",{uri:o.href,...s.mcpReq._meta!==void 0&&{_meta:s.mcpReq._meta}},s),a=async()=>Be(await r(o,this.#C(s)),o.href);return await this.#T("resources/read",i,a)})}#re(t,{definition:n,callback:r,complete:o}){let s=new Rs(n.uriTemplate,{list:void 0,...o!==void 0&&{complete:o}});t.registerResource(n.name,s,{...n.title!==void 0&&{title:n.title},...n.description!==void 0&&{description:n.description},...n.mimeType!==void 0&&{mimeType:n.mimeType},...n.annotations!==void 0&&{annotations:n.annotations},...n._meta!==void 0&&{_meta:{...n._meta}}},async(i,a,u)=>{let d=this.#v("resources/read",{uri:i.href,...u.mcpReq._meta!==void 0&&{_meta:u.mcpReq._meta}},u),c=async()=>Be(await r(i,a,this.#C(u)),i.href);return await this.#T("resources/read",d,c)})}#oe(t){if(t!==void 0)return{...t.description!==void 0&&{description:t.description},...t.csp!==void 0&&{csp:t.csp},...t.permissions!==void 0&&{permissions:t.permissions},...t.domain!==void 0&&{domain:t.domain},...t.prefersBorder!==void 0&&{prefersBorder:t.prefersBorder}}}#se(t,{definition:n,callback:r}){let o={...n.title!==void 0&&{title:n.title},...n.description!==void 0&&{description:n.description}},s=async(i,a)=>{let u=this.#v("prompts/get",{name:n.name,arguments:i,...a.mcpReq._meta!==void 0&&{_meta:a.mcpReq._meta}},a),d=async()=>{let c=u.params.arguments??{};return qt(await r(c,this.#C(a)))};return await this.#T("prompts/get",u,d)};if(n.schema!==void 0)t.registerPrompt(n.name,{...o,argsSchema:n.schema},async(i,a)=>s(i,a));else{let i=async a=>s({},a);t.registerPrompt(n.name,o,i)}}#C(t){return this.#e.oauth===void 0?we(t):Ht(t)}};function Nn(e){let t=E(e.domain,"Auth0 domain").href;return O({...e,createTokenVerifier:n=>C({issuer:t,jwksUrl:new URL(h(t,".well-known/jwks.json")),resource:n}),oauthMetadata:{issuer:t,authorization_endpoint:h(t,"authorize"),token_endpoint:h(t,"oauth/token"),registration_endpoint:h(t,"oidc/register"),response_types_supported:["code"],grant_types_supported:["authorization_code","refresh_token"],code_challenge_methods_supported:["S256"]},mapAuthInfo:Cs})}function Cs(e){let t=P(e),n=b(t,"sub");if(n===void 0)throw v("Missing Auth0 subject");return{user:{id:n,...ee("email",f(t,"email")),...ee("name",f(t,"name")),...ee("nickname",f(t,"nickname")),...ee("picture",f(t,"picture")),...ee("emailVerified",S(t,"email_verified")),...ee("updatedAt",f(t,"updated_at")),roles:x(t.roles)},payload:t,permissions:x(t.permissions)}}function ee(e,t){return t===void 0?{}:{[e]:t}}function Hn(e){let t=E(e.authURL,"Better Auth authURL").href.replace(/\/$/,"");return O({...e,createTokenVerifier:n=>C({issuer:t,jwksUrl:new URL(h(t,"jwks")),resource:n}),oauthMetadata:Es(t,e.scopesSupported),mapAuthInfo:Ps})}function Es(e,t){return{issuer:e,authorization_endpoint:h(e,"oauth2/authorize"),token_endpoint:h(e,"oauth2/token"),registration_endpoint:h(e,"oauth2/register"),jwks_uri:h(e,"jwks"),response_types_supported:["code"],grant_types_supported:["authorization_code","client_credentials","refresh_token"],code_challenge_methods_supported:["S256"],scopes_supported:t===void 0?["openid","profile","email","offline_access"]:[...t]}}function Ps(e){let t=P(e),n=b(t,"sub");if(n===void 0)throw v("Missing Better Auth subject");return{user:{id:n,...te("email",f(t,"email")),...te("name",f(t,"name")),...te("picture",f(t,"picture")),...te("emailVerified",S(t,"email_verified")),...te("sessionId",f(t,"sid")),...te("isAnonymous",S(t,"is_anonymous")??S(t,"isAnonymous")),roles:x(t.roles)},payload:t,permissions:x(t.permissions)}}function te(e,t){return t===void 0?{}:{[e]:t}}function qn(e){let t=E(e.frontendApiUrl,"Clerk frontendApiUrl").href.replace(/\/$/,"");return O({...e,createTokenVerifier:n=>C({issuer:t,jwksUrl:new URL(h(t,".well-known/jwks.json")),resource:n}),oauthMetadata:ks(t),mapAuthInfo:n=>Ss(n)})}function Ss(e){let t=P(e),n=b(t,"sub");if(n===void 0)throw v("Missing Clerk subject");let r=f(t,"org_role");return{user:{id:n,...B("email",f(t,"email")),...B("name",f(t,"name")),...B("username",f(t,"username")),...B("picture",f(t,"picture")),...B("emailVerified",S(t,"email_verified")),...B("organizationId",f(t,"org_id")),...B("organizationRole",r),...B("organizationSlug",f(t,"org_slug")),roles:r===void 0?[]:[r]},payload:t,permissions:x(t.org_permissions)}}function ks(e){return{issuer:e,authorization_endpoint:h(e,"oauth/authorize"),token_endpoint:h(e,"oauth/token"),registration_endpoint:h(e,"oauth/register"),response_types_supported:["code"],grant_types_supported:["authorization_code","refresh_token"],code_challenge_methods_supported:["S256"]}}function B(e,t){return t===void 0?{}:{[e]:t}}function Dn(e){if(typeof e.realm!="string"||e.realm.trim().length===0||/[/?#]/.test(e.realm))throw new TypeError("Keycloak realm is invalid");let t=E(e.serverUrl,"Keycloak serverUrl"),n=h(t,`realms/${encodeURIComponent(e.realm)}`).replace(/\/$/,"");return O({...e,createTokenVerifier:r=>C({issuer:n,jwksUrl:new URL(h(n,"protocol/openid-connect/certs")),resource:r}),oauthMetadata:{issuer:n,authorization_endpoint:h(n,"protocol/openid-connect/auth"),token_endpoint:h(n,"protocol/openid-connect/token"),registration_endpoint:h(n,"clients-registrations/openid-connect"),response_types_supported:["code"],grant_types_supported:["authorization_code","refresh_token"],code_challenge_methods_supported:["S256"]},mapAuthInfo:_s})}function _s(e){let t=P(e),n=b(t,"sub");if(n===void 0)throw v("Missing Keycloak subject");let r=he(t,"realm_access"),o=he(t,"resource_access");return{user:{id:n,...ne("email",f(t,"email")),...ne("name",f(t,"name")),...ne("preferredUsername",f(t,"preferred_username")),...ne("givenName",f(t,"given_name")),...ne("familyName",f(t,"family_name")),...ne("emailVerified",S(t,"email_verified")),roles:r===void 0?[]:x(r.roles),...r!==void 0&&{realmAccess:r},...o!==void 0&&{resourceAccess:o}},payload:t,permissions:Us(o)}}function ne(e,t){return t===void 0?{}:{[e]:t}}function Us(e){return e===void 0?[]:Object.entries(e).flatMap(([t,n])=>N(n)?x(n.roles).map(r=>`${t}:${r}`):[])}function $n(e){let t=Ls(e),n=h(t,"auth/v1").replace(/\/$/,""),r=e.jwtSecret;if(r!==void 0&&new TextEncoder().encode(r).length<32)throw new TypeError("Supabase jwtSecret must be at least 32 bytes");return O({...e,createTokenVerifier:o=>C({issuer:n,jwksUrl:new URL(h(t,"auth/v1/.well-known/jwks.json")),...r!==void 0?{key:new TextEncoder().encode(r),algorithms:["HS256"]}:{algorithms:["ES256"]},resource:o}),oauthMetadata:{issuer:n,authorization_endpoint:h(t,"auth/v1/oauth/authorize"),token_endpoint:h(t,"auth/v1/oauth/token"),registration_endpoint:h(t,"auth/v1/oauth/clients/register"),response_types_supported:["code"],grant_types_supported:["authorization_code","refresh_token"],code_challenge_methods_supported:["S256"]},mapAuthInfo:Is})}function Is(e){let t=P(e),n=b(t,"sub")??b(t,"user_id");if(n===void 0)throw v("Missing Supabase subject");let r=he(t,"user_metadata")??{},o=f(t,"aal");return{user:{id:n,...F("email",f(t,"email")),...F("name",f(r,"name")),...F("fullName",f(r,"full_name")),...F("username",f(r,"username")),...F("avatarUrl",f(r,"avatar_url")),...F("role",f(t,"role")),...F("aal",o),amr:js(t.amr),...F("sessionId",f(t,"session_id"))},payload:t,permissions:o===void 0?[]:[`aal:${o}`]}}function F(e,t){return t===void 0?{}:{[e]:t}}function Ls(e){if(e.supabaseUrl!==void 0)return E(e.supabaseUrl,"supabaseUrl");if(e.projectId===void 0||!/^[a-z0-9-]+$/i.test(e.projectId))throw new TypeError("Supabase requires projectId or supabaseUrl");return new URL(`https://${e.projectId}.supabase.co`)}function js(e){return Array.isArray(e)?e.flatMap(t=>{if(!N(t))return[];let n=t.method,r=t.timestamp;return typeof n!="string"||n.length===0?[]:r!==void 0&&(typeof r!="number"||!Number.isFinite(r))?[]:[r===void 0?{method:n}:{method:n,timestamp:r}]}):[]}function Vn(e){let t=Hs(e.subdomain);return O({...e,createTokenVerifier:n=>C({issuer:t,jwksUrl:new URL(h(t,"oauth2/jwks")),resource:n}),oauthMetadata:{issuer:t,authorization_endpoint:h(t,"oauth2/authorize"),token_endpoint:h(t,"oauth2/token"),registration_endpoint:h(t,"oauth2/register"),response_types_supported:["code"],grant_types_supported:["authorization_code","refresh_token"],code_challenge_methods_supported:["S256"]},mapAuthInfo:Ns})}function Ns(e){let t=P(e),n=b(t,"sub");if(n===void 0)throw v("Missing WorkOS subject");return{user:{id:n,...q("email",f(t,"email")),...q("emailVerified",S(t,"email_verified")),...q("name",f(t,"name")),...q("preferredUsername",f(t,"preferred_username")),...q("firstName",f(t,"first_name")),...q("lastName",f(t,"last_name")),...q("picture",f(t,"picture")),roles:x(t.roles),...q("organizationId",f(t,"org_id")),...q("sessionId",f(t,"sid"))},payload:t,permissions:x(t.permissions)}}function q(e,t){return t===void 0?{}:{[e]:t}}function Hs(e){if(typeof e!="string"||e.trim().length===0)throw new TypeError("WorkOS subdomain is required");let t=E(e,"WorkOS subdomain");if(t.pathname!=="/")throw new TypeError("WorkOS subdomain must be a hostname or HTTPS origin");return t.href.replace(/\/$/,"")}function k(e){let t=process.env[e];return t===void 0||t.trim()===""?void 0:t}function re(e){if(typeof e=="object"&&e!==null&&e.verifyJwt===!1)throw new Error("[MCP_USE_V1_COMPAT] verifyJwt: false is not supported by the temporary v1 compatibility entry; v2 always verifies bearer tokens.")}function oe(e,t){return{...(t??e.resource)!==void 0&&{resource:t??e.resource},...e.requiredScopes!==void 0&&{requiredScopes:e.requiredScopes},...e.scopesSupported!==void 0&&{scopesSupported:e.scopesSupported},...e.resourceName!==void 0&&{resourceName:e.resourceName},...e.serviceDocumentationUrl!==void 0&&{serviceDocumentationUrl:e.serviceDocumentationUrl}}}function qs(e={}){re(e);let t=e.projectId??k("MCP_USE_OAUTH_SUPABASE_PROJECT_ID"),n=e.supabaseUrl??k("MCP_USE_OAUTH_SUPABASE_URL"),r=e.jwtSecret??k("MCP_USE_OAUTH_SUPABASE_JWT_SECRET");return $n({...oe(e),...t!==void 0&&{projectId:t},...n!==void 0&&{supabaseUrl:n},...r!==void 0&&{jwtSecret:r}})}function Ds(e={}){re(e);let t=e.domain??k("MCP_USE_OAUTH_AUTH0_DOMAIN"),n=e.audience??k("MCP_USE_OAUTH_AUTH0_AUDIENCE");if(t===void 0)throw new Error("Auth0 domain is required.");return Nn({...oe(e,e.resource??n),domain:t})}function $s(e={}){re(e);let t=e.serverUrl??k("MCP_USE_OAUTH_KEYCLOAK_SERVER_URL"),n=e.realm??k("MCP_USE_OAUTH_KEYCLOAK_REALM"),r=e.audience??k("MCP_USE_OAUTH_KEYCLOAK_AUDIENCE");if(t===void 0||n===void 0)throw new Error("Keycloak serverUrl and realm are required.");return Dn({...oe(e,e.resource??r),serverUrl:t,realm:n})}function Vs(e={}){re(e);let t=e.subdomain??k("MCP_USE_OAUTH_WORKOS_SUBDOMAIN");if(t===void 0)throw new Error("WorkOS subdomain is required.");return Vn({...oe(e),subdomain:t})}function Bs(e={}){re(e);let t=e.frontendApiUrl??k("MCP_USE_OAUTH_CLERK_FRONTEND_API_URL");if(t===void 0)throw new Error("Clerk frontendApiUrl is required.");return qn({...oe(e,e.resource??e.audience),frontendApiUrl:t})}function Fs(e={}){re(e);let t=e.authURL??k("MCP_USE_OAUTH_BETTER_AUTH_URL");if(t===void 0)throw new Error("Better Auth authURL is required.");return Hn({...oe(e),authURL:t})}var Bn='Deprecated temporary v1 compatibility. Use the native v2 API from "mcp-use". This entry will be removed in mcp-use v3.',gt="MCP_USE_V1_COMPAT",Fn="__mcpUseV1CompatServer",Wn=!1,yt=class{#e;#t=new Map;#n=new Map;#r=new Set;config;app;fetch;get;post;put;patch;delete;all;use;on;serverHost;serverPort;serverBaseUrl;constructor(t){Qs(),Xs(t),this.config=t,this.serverHost=t.host??"localhost",t.baseUrl!==void 0&&(this.serverBaseUrl=t.baseUrl),this.#e=new ye(Js(t)),this.app=this.#e.app,this.fetch=this.#e.fetch,this.get=this.#e.get,this.post=this.#e.post,this.put=this.#e.put,this.patch=this.#e.patch,this.delete=this.#e.delete,this.all=this.#e.all,this.use=this.#e.use.bind(this.#e),this.on=this.#e.on.bind(this.#e);let n=globalThis;if(process.env.MCP_USE_CLI_IMPORT==="1"&&n[Fn]!==void 0)throw se("multiple compatibility servers in one CLI entry","default-export one native v2 server or construct only one v1 server");n[Fn]=this}static fromOpenAPI(t){return ye.fromOpenAPI(t)}get basePath(){return this.#e.basePath}get host(){return this.#e.host}get port(){return this.#e.port}get branding(){return this.#e.branding}tool(t,n){if(t.inputs!==void 0)throw se("tool inputs[] schemas","use a Zod schema field");let r=t.cb;if(r!==void 0&&n!==void 0)throw new TypeError(`Tool "${t.name}" provides both cb and a separate callback.`);let o=n??r;if(o===void 0)throw new TypeError(`Tool "${t.name}" requires a callback.`);if(t.widget!==void 0){let s=t.widget.name;if(this.#t.has(s)||this.#r.has(s))throw se(`binding legacy widget "${s}" to multiple tools`,"use one tool per view or migrate the bindings to native v2");return this.#r.add(s),this.#t.set(s,{definition:t,callback:o}),this}return this.#l(t,o),this}resource(t,n){let r=n??t.readCallback;if(n!==void 0&&t.readCallback!==void 0)throw new TypeError(`Resource "${t.name}" provides both readCallback and a separate callback.`);if(r===void 0)throw new TypeError(`Resource "${t.name}" requires a callback.`);let{readCallback:o,callbacks:s,...i}=t;return this.#e.resource(i,async(a,u)=>r(Ee(u))),this}resourceTemplate(t,n){let r=n??t.readCallback;if(n!==void 0&&t.readCallback!==void 0)throw new TypeError(`Resource template "${t.name}" provides both readCallback and a separate callback.`);if(r===void 0)throw new TypeError(`Resource template "${t.name}" requires a callback.`);let o=t.resourceTemplate,s=t.uriTemplate??o?.uriTemplate;if(s===void 0)throw new TypeError(`Resource template "${t.name}" requires uriTemplate.`);let i=t.callbacks?.complete??o?.callbacks?.complete,a=t.description??o?.description,u=t.mimeType??o?.mimeType,d={name:t.name,uriTemplate:s,...t.title!==void 0&&{title:t.title},...a!==void 0&&{description:a},...u!==void 0&&{mimeType:u},...t.annotations!==void 0&&{annotations:t.annotations},...t._meta!==void 0&&{_meta:t._meta},...i!==void 0&&{complete:i}};return this.#e.resourceTemplate(d,async(c,l,p)=>r(c,l,Ee(p))),this}prompt(t,n){if(t.args!==void 0)throw se("prompt args[] schemas","use a Zod schema field");let r=t.cb;if(r!==void 0&&n!==void 0)throw new TypeError(`Prompt "${t.name}" provides both cb and a separate callback.`);let o=n??r;if(o===void 0)throw new TypeError(`Prompt "${t.name}" requires a callback.`);let{cb:s,args:i,...a}=t;return this.#e.prompt(a,async(u,d)=>o(u,Ee(d))),this}async listen(t,n){if(process.env.MCP_USE_CLI_IMPORT==="1")return;this.#o();let r=await this.#e.listen(t,n);return this.serverPort=r.port,r}async close(){await this.#e.close()}getHandler(){return this.fetch}async proxy(...t){await this.#e.proxy(...t)}async notifyResourceUpdated(t){await this.#e.notifyResourceUpdated(t)}__registerLegacyViews(t){for(let[n,r]of Object.entries(t)){let o=r.widgetMetadata??{};this.#n.set(n,o),this.#i(n),o.exposeAsTool===!0&&!this.#r.has(n)&&this.#a(n,o)}}__primeViews(t,n){this.#o(),this.#e.__primeViews(t,n)}__mount(){this.#o(),this.#e.__mount()}__setEventBus(t){this.#e.__setEventBus(t)}#l(t,n,r,o){let{cb:s,widget:i,inputs:a,...u}=t,d=r===void 0?void 0:Kn(r,o),c=u.outputSchema??(r===void 0?void 0:zn(o)??Jn),l=Gn(i,o),p={...u,...c!==void 0&&{outputSchema:c},...d!==void 0&&{view:d},...(u._meta!==void 0||l!==void 0)&&{_meta:{...u._meta,...l}}};this.#e.tool(p,async(g,T)=>n(g,Ee(T)))}#i(t){let n=this.#t.get(t);n!==void 0&&(this.#t.delete(t),this.#l(n.definition,n.callback,t,this.#n.get(t)))}#o(){for(let t of[...this.#t.keys()])this.#i(t)}#a(t,n){this.#r.add(t);let r=zn(n)??Jn,o={name:t,...n.title!==void 0&&{title:n.title},description:n.description??n.metadata?.description??`Display ${t}`,inputSchema:r,outputSchema:r,...n.annotations!==void 0&&{annotations:n.annotations},_meta:{...n._meta,...Gn(void 0,n)},view:Kn(t,n)};this.#e.tool(o,async s=>{let i=typeof n.toolOutput=="function"?await n.toolOutput(s):n.toolOutput;return{content:i?.content??[{type:"text",text:`${n.title??t} ready`}],structuredContent:s,...i?.isError===!0&&{isError:!0},...i?._meta!==void 0&&{_meta:i._meta}}})}};function Pu(e,t={}){return new yt({name:e,version:t.version??"1.0.0",...t})}function Su(e){return{...Ie(e),structuredContent:{data:e}}}function ku(e){let t=Tt(e);return{...t,structuredContent:t.structuredContent??e.props??e.data??{}}}function Pe(e){let t=e.auth;if(t!==void 0)return t;let n=e.get?.("auth");if(n!==void 0)return n;let r=e.req?.raw,o=r===void 0?void 0:M(r).authInfo;if(o!==void 0)return Ks(o);throw new Error("Authentication context is missing.")}function Ws(e,t){let n=Pe(e);return(Array.isArray(t)?t:[t]).every(o=>n.scopes.includes(o)||n.permissions.includes(o))}function zs(e,t){let n=Pe(e);return t.some(r=>n.scopes.includes(r)||n.permissions.includes(r))}function _u(e){return async(t,n)=>{if(Ws(t,e))return n();let r=Pe(t),o=Array.isArray(e)?e:[e];return t.json({error:"insufficient_scope",required:o,granted_scopes:r.scopes,granted_permissions:r.permissions},403)}}function Uu(e){return async(t,n)=>{if(zs(t,e))return n();let r=Pe(t);return t.json({error:"insufficient_scope",required_any:e,granted_scopes:r.scopes,granted_permissions:r.permissions},403)}}function Js(e){let t=e.baseUrl===void 0?void 0:new URL(e.baseUrl),n=t!==void 0&&t.pathname!=="/"?t.pathname.replace(/\/$/,""):void 0,r=e.oauth===void 0?void 0:{...e.oauth,...e.oauth.resource===void 0&&t!==void 0?{resource:new URL(n??"/mcp",t.origin)}:{}};return{name:e.name,version:e.version,...e.title!==void 0&&{title:e.title},...e.description!==void 0&&{description:e.description},...e.instructions!==void 0&&{instructions:e.instructions},...e.host!==void 0&&{host:e.host},...e.port!==void 0&&{port:e.port},...n!==void 0&&{basePath:n},...e.allowedOrigins!==void 0&&{allowedHosts:e.allowedOrigins.map(Ys)},cors:Gs(e.cors),...r!==void 0&&{oauth:r},...e.publicLandingPage!==void 0&&{publicLandingPage:e.publicLandingPage},...e.favicon!==void 0&&{favicon:e.favicon},...e.icons!==void 0&&{icons:e.icons},...e.websiteUrl!==void 0&&{websiteUrl:e.websiteUrl}}}function Ks(e){let t=e.extra;if(t===void 0||typeof t!="object"||t===null||!("user"in t)||typeof t.user!="object"||t.user===null||Array.isArray(t.user)||!("payload"in t)||typeof t.payload!="object"||t.payload===null||Array.isArray(t.payload)||!("permissions"in t)||!Array.isArray(t.permissions)||!t.permissions.every(o=>typeof o=="string"))throw new Error("Authentication context is missing mapped OAuth data.");let n=t.user,r=n.userId??n.id;return{user:{...n,...typeof r=="string"&&{userId:r},permissions:[...t.permissions],scopes:[...e.scopes]},payload:t.payload,accessToken:e.token,scopes:[...e.scopes],permissions:[...t.permissions]}}function Gs(e){return e===void 0?{origin:"*"}:{...e.origin!==void 0&&{origin:e.origin},...e.allowMethods!==void 0&&{methods:e.allowMethods},...e.allowHeaders!==void 0&&{allowedHeaders:e.allowHeaders},...e.credentials!==void 0&&{credentials:e.credentials}}}function Ys(e){try{return new URL(e).hostname}catch{return e.split(":")[0]??e}}function Xs(e){if(e.stateless===!1)throw se("stateless: false","v2 is stateless");for(let[t,n]of[["sessionIdleTimeoutMs",e.sessionIdleTimeoutMs],["autoCreateSessionOnInvalidId",e.autoCreateSessionOnInvalidId],["sessionStore",e.sessionStore],["streamManager",e.streamManager]])if(n!==void 0)throw se(t,"migrate to stateless v2")}function Ee(e){let t=e,n=e.client;n.supportsApps??=()=>n.supportsViews(),t.log=e.sendLog.bind(e);let r=t.auth;if(r!==void 0&&typeof r=="object"&&r!==null){let o=r,s=o.user,i=s.userId??s.id;o.user={...s,...typeof i=="string"&&{userId:i},...s.organizationId!==void 0&&{organization_id:s.organizationId,org_id:s.organizationId},...s.organizationRole!==void 0&&{org_role:s.organizationRole},...s.organizationSlug!==void 0&&{org_slug:s.organizationSlug},permissions:[...o.permissions],scopes:[...o.scopes]}}return t}function zn(e){let t=e?.props??e?.schema??e?.inputs;return Zs(t)?t:void 0}function Zs(e){return typeof e=="object"&&e!==null&&"~standard"in e&&typeof e["~standard"]?.validate=="function"}var Jn={"~standard":{version:1,vendor:"mcp-use-v1-compat",validate(e){return typeof e!="object"||e===null||Array.isArray(e)?{issues:[{message:"expected an object"}]}:{value:e}},jsonSchema:{input:()=>({type:"object",additionalProperties:!0}),output:()=>({type:"object",additionalProperties:!0})}}};function Kn(e,t){let n=t?.metadata,r=t?.appsSdkMetadata,o=r?.["openai/widgetCSP"],s=n?.csp??(o===void 0?void 0:{...o.connect_domains!==void 0&&{connectDomains:o.connect_domains},...o.resource_domains!==void 0&&{resourceDomains:o.resource_domains},...o.frame_domains!==void 0&&{frameDomains:o.frame_domains}}),i=n?.description??t?.description??r?.["openai/widgetDescription"],a=n?.prefersBorder??r?.["openai/widgetPrefersBorder"],u=n?.domain??r?.["openai/widgetDomain"];return{name:e,...i!==void 0&&{description:i},...s!==void 0&&{csp:s},...a!==void 0&&{prefersBorder:a},...u!==void 0&&{domain:u}}}function Gn(e,t){let n=e?.invoking??t?.metadata?.invoking,r=e?.invoked??t?.metadata?.invoked,o=e?.widgetAccessible,s=e?.resultCanProduceWidget;if(!(n===void 0&&r===void 0&&o===void 0&&s===void 0))return{...n!==void 0&&{"openai/toolInvocation/invoking":n},...r!==void 0&&{"openai/toolInvocation/invoked":r},...o!==void 0&&{"openai/widgetAccessible":o},...s!==void 0&&{"openai/resultCanProduceWidget":s}}}function Qs(){Wn||(Wn=!0,typeof process.emitWarning=="function"?process.emitWarning(Bn,{type:"DeprecationWarning",code:gt}):console.warn(`[${gt}] ${Bn}`))}function se(e,t){return new Error(`[${gt}] ${e} is not supported by the temporary v1 compatibility entry; ${t}.`)}export{yt as MCPServer,Su as array,or as audio,sr as binary,mo as completable,Pu as createMCPServer,tr as css,ar as error,Pe as getAuth,zs as hasAnyScope,Ws as hasScope,Qn as html,rr as image,nr as javascript,Zn as markdown,dr as mix,Ds as oauthAuth0Provider,Fs as oauthBetterAuthProvider,Bs as oauthClerkProvider,$s as oauthKeycloakProvider,qs as oauthSupabaseProvider,Vs as oauthWorkOSProvider,ur as object,Uu as requireAnyScope,_u as requireScope,ir as resource,Xn as text,ku as widget,er as xml};
|