mcp-use 2.8.2 → 2.9.0
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/index-node.js +6 -6
- package/dist/index.d.ts +2 -1
- package/dist/index.js +13 -13
- package/dist/internal/usage.js +1 -1
- package/dist/mentions.d.ts +64 -0
- package/dist/server.d.ts +15 -1
- package/package.json +3 -3
package/dist/index.d.ts
CHANGED
|
@@ -22,7 +22,7 @@ export type { LandingPageOptions, LandingPagePrompt, LandingPageResource, Landin
|
|
|
22
22
|
* tool envelope; resource/prompt registration still converts helper-shaped
|
|
23
23
|
* returns for upgrade compatibility.
|
|
24
24
|
*/
|
|
25
|
-
export type { CallToolResult, ContentBlock, GetPromptResult, InputRequest, InputRequiredResult, InputResponses, PromptMessage, ReadResourceResult, } from "@modelcontextprotocol/server";
|
|
25
|
+
export type { CallToolResult, ContentBlock, GetPromptResult, InputRequest, InputRequiredResult, InputResponses, PromptMessage, ReadResourceResult, ResourceLink, } from "@modelcontextprotocol/server";
|
|
26
26
|
/**
|
|
27
27
|
* Official SDK descriptor metadata contracts. Tools use
|
|
28
28
|
* {@link ToolAnnotations}; resources and resource templates use
|
|
@@ -75,3 +75,4 @@ export { array, audio, binary, css, error, html, image, javascript, markdown, mi
|
|
|
75
75
|
export type { ToolContentResult, TypedCallToolResult, WidgetResponseConfig, } from "./response-helpers.js";
|
|
76
76
|
export type { ProxyConnection, ProxyHttpConfig, ProxyProgress, ProxyPrompt, ProxyRequestOptions, ProxyResource, ProxyServerConfig, ProxyTool, } from "./mcp-proxy.js";
|
|
77
77
|
export type { SettingsField, SettingsFields, SettingsValues, SettingsLayoutGroup, SettingsRegistration, } from "./settings.js";
|
|
78
|
+
export type { MentionSearchParams, MentionSearchResult, MentionsRegistration, } from "./mentions.js";
|
package/dist/index.js
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
import{b as pt,c as ft}from"./chunk-TCIRBQPM.js";import{a as R,b as Dn,c as Y,d as le,e as X,f as _,g as pe,h as fe,i as me,j as he,k as ye,l as mt,m as ht,o as yt}from"./chunk-YI27EOFM.js";import{a as ut,b as ct,c as O,d as lt}from"./chunk-HAV435PF.js";import{a as o}from"./chunk-EI7MMDWY.js";var Nn=["inline","fullscreen","pip"],Hn=new Set(["inline","fullscreen","pip"]);function ge(e){let t=e?.autoResize??!0,n=e?.displayModes===void 0?Nn:e.displayModes;if(!Array.isArray(n)||n.length===0)throw new Error('viewConfig.displayModes must be a non-empty array that includes "inline"');let r=new Set,s=[];for(let a of n){if(typeof a!="string"||!Hn.has(a))throw new Error(`viewConfig.displayModes contains invalid mode ${JSON.stringify(a)}; expected "inline", "fullscreen", or "pip"`);if(r.has(a))throw new Error(`viewConfig.displayModes contains duplicate mode "${a}"`);r.add(a),s.push(a)}if(!r.has("inline"))throw new Error('viewConfig.displayModes must include "inline"');let i=e?.preferredDisplayMode;if(i!==void 0&&i!=="inline"&&i!=="fullscreen")throw new Error('viewConfig.preferredDisplayMode must be "inline" or "fullscreen"');if(i!==void 0&&!r.has(i))throw new Error("viewConfig.preferredDisplayMode must belong to displayModes");return{...i!==void 0&&{preferredDisplayMode:i},autoResize:t,displayModes:s}}o(ge,"normalizeViewConfig");import{localhostAllowedHostnames as An,localhostAllowedOrigins as ns,McpServer as rs,ResourceTemplate as os,CLIENT_CAPABILITIES_META_KEY as ss,CLIENT_INFO_META_KEY as is,PROTOCOL_VERSION_META_KEY as as,isJSONRPCRequest as _n,isInputRequiredResult as Pn}from"@modelcontextprotocol/server";import{createServer as ds}from"#mcp-use-node-http";import{Hono as kn}from"hono";var gt="public, max-age=31536000, immutable",$n="public, max-age=300";function Te(e){return/^([a-z][a-z\d+.-]*):/i.exec(e)?.[1]?.toLowerCase()}o(Te,"protocolOf");function Fn(e,t){return`${e==="/"?"":e}/_mcp-use/public/${t.split("/").map(r=>encodeURIComponent(r)).join("/")}`}o(Fn,"publicAssetPath");function we(e){return Te(e)===void 0}o(we,"isLocalPublicSource");function Vn(e){return e[0]}o(Vn,"selectFaviconFromIcons");function Bn(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/`)}o(Bn,"assertLocalPublicSource");function Tt(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),s=e.slice(n+1),i=r.split(";"),a=i[0]?.toLowerCase()??"";if(!a.startsWith("image/"))throw new TypeError(`${t} data URL must use an image MIME type`);try{if(i.includes("base64")){let d=atob(s);return{mimeType:a,bytes:Uint8Array.from(d,u=>u.charCodeAt(0))}}return{mimeType:a,bytes:new TextEncoder().encode(decodeURIComponent(s))}}catch{throw new TypeError(`${t} must be a valid image data URL`)}}o(Tt,"parseDataImage");function wt(e,t){if(typeof e!="string"||e.length===0)throw new TypeError(`${t} must be a non-empty string`);let n=Te(e);if(n===void 0)return Bn(e,t),e;if(n==="data")return Tt(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}o(wt,"assertBrandingSource");function Mt(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 d;try{d=new URL(e.websiteUrl)}catch{throw new TypeError("websiteUrl must be a non-empty absolute http(s) URL")}if(d.protocol!=="http:"&&d.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((d,u)=>{if(typeof d!="object"||d===null)throw new TypeError(`icons[${u}] must be an MCP Icon object`);let c=d,l=wt(c.src,`icons[${u}].src`),p=c.mimeType;if(p!==void 0&&(typeof p!="string"||!p.toLowerCase().startsWith("image/")))throw new TypeError(`icons[${u}].mimeType must be an image MIME type when provided`);let y=c.sizes;if(y!==void 0&&(!Array.isArray(y)||y.some(f=>typeof f!="string"||f.length===0)))throw new TypeError(`icons[${u}].sizes must be an array of non-empty strings when provided`);let h=y===void 0?void 0:y.map(f=>f),m=c.theme;if(m!==void 0&&m!=="light"&&m!=="dark")throw new TypeError(`icons[${u}].theme must be "light" or "dark" when provided`);return Object.freeze({src:l,...p!==void 0&&{mimeType:p},...h!==void 0&&{sizes:Object.freeze(h)},...m!==void 0&&{theme:m}})}))}let r=e.favicon===void 0?void 0:wt(e.favicon,"favicon"),s=r===void 0?Vn(n??[]):void 0,i=r??s?.src,a=s?.mimeType??n?.find(d=>d.src===r)?.mimeType;return Object.freeze({...i!==void 0&&{favicon:i},...a!==void 0&&{faviconMimeType:a},...n!==void 0&&{icons:n},...t!==void 0&&{websiteUrl:t}})}o(Mt,"normalizeServerBranding");function Me(e,t,n){return e.map(r=>({...r,src:t!==void 0&&we(r.src)?`${O(t)}${Fn(n,r.src)}`:r.src,...r.sizes!==void 0&&{sizes:[...r.sizes]}}))}o(Me,"resolveImplementationIcons");function Re(e){return e.favicon!==void 0&&we(e.favicon)||e.icons?.some(t=>we(t.src))===!0}o(Re,"hasLocalBrandingAsset");function Rt(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 s=Te(n);if(s==="http"||s==="https")return new Response(null,{status:307,headers:{Location:n,"Cache-Control":$n}});if(s==="data"){let c=Tt(n,"favicon");return new Response(r.method==="HEAD"?null:c.bytes.buffer,{status:200,headers:{"Content-Type":e.faviconMimeType??c.mimeType,"Cache-Control":gt,"X-Content-Type-Options":"nosniff"}})}let{join:i}=await import("path"),a=t.dev?i(t.projectRoot,"public"):i(t.projectRoot,".mcp-use/build/views/public"),d=await pt(a,n);if(d===null)return new Response("Not Found",{status:404,headers:{"Cache-Control":"no-store"}});let u=await ft(d,{...t.deferCors===!0&&{deferCors:!0},...r.method==="HEAD"&&{head:!0}});return u.headers.set("Cache-Control",gt),u.headers.set("X-Content-Type-Options","nosniff"),e.faviconMimeType!==void 0&&u.headers.set("Content-Type",e.faviconMimeType),u}}o(Rt,"createFaviconHandler");function Wn(e){if(typeof e!="object"||e===null)return!1;let t=e;return typeof t.createTokenVerifier=="function"&&typeof t.mapAuthInfo=="function"&&typeof t.oauthMetadata=="object"&&t.oauthMetadata!==null}o(Wn,"isOAuthProviderLike");function vt(e){if(e.mixedAuth!==void 0&&typeof e.mixedAuth!="boolean")throw new TypeError("mixedAuth must be a boolean");if(e.mixedAuth===!0&&!Wn(e.oauth))throw new TypeError("mixedAuth requires an OAuth provider; set oauth on the server");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");if(e.skills!==void 0&&typeof e.skills!="boolean"){if(typeof e.skills!="object"||e.skills===null||Array.isArray(e.skills))throw new TypeError("skills must be a boolean or configuration object");let t=e.skills.directory;if(t!==void 0&&typeof t!="string")throw new TypeError("skills.directory must be a string when provided")}}o(vt,"assertServerConfig");var zn="127.0.0.1";function xt(e,t,n=process.env){if(e!==void 0)return e;let r=n.HOST?.trim();return r!==void 0&&r!==""?r:t??zn}o(xt,"resolveListenHost");function bt(e,t,n=process.env){if(e!==void 0)return e;let r=Jn(n.PORT);return r!==void 0?r:t??3e3}o(bt,"resolveListenPort");function Jn(e){if(e===void 0||e.trim()==="")return;let t=Number(e);return Number.isInteger(t)&&t>=0&&t<=65535?t:void 0}o(Jn,"parsePort");import{isBufferedResponse as Kn}from"#mcp-use-buffered-response";function St(e,t){return async(n,r,s)=>{typeof s=="function"&&(s=void 0);let i=!1,a=new AbortController;r.on("close",()=>{i||a.abort()}),r.destroyed===!0&&a.abort();let d,u;try{d=await Gn(n,s,{signal:a.signal}),u=await e.fetch(d,{...n.auth!==void 0&&{authInfo:n.auth},...s!==void 0&&{parsedBody:s}})}catch(f){try{t?.onerror?.(f instanceof Error?f:new Error(String(f)))}catch{}u=Xn(Yn(s))}let c={},l=u.headers.getSetCookie?.();for(let[f,g]of u.headers){if(f==="set-cookie"&&l?.length){c[f]=l;continue}c[f]=g}if(r.writeHead(u.status,c),u.body===null){i=!0,r.end();return}if(Kn(u,d)){try{let f=new Uint8Array(await u.arrayBuffer());i=!0,r.end(f)}catch{i=!0,r.end()}return}let p,y=o(()=>{p?.(),p=void 0},"releaseDrainWait"),h=o(()=>new Promise(f=>{p=f}),"waitForDrain");r.on("drain",y);let m=new Promise(f=>{a.signal.addEventListener("abort",()=>f(),{once:!0})});try{for await(let f of u.body){if(a.signal.aborted)break;let g=f instanceof Uint8Array?f:new Uint8Array(f);r.write(g)===!1&&await Promise.race([h(),m])}}catch{}i=!0,r.end()}}o(St,"toNodeHandler");async function Gn(e,t,n){let r=(e.method??"GET").toUpperCase(),i=`http://${Et(e.headers.host)??Et(e.headers[":authority"])??"localhost"}${e.url??"/"}`,a=new Headers;for(let[u,c]of Object.entries(e.headers))if(!(c===void 0||u.startsWith(":")))if(Array.isArray(c))for(let l of c)a.append(u,l);else a.set(u,c);let d;if(r!=="GET"&&r!=="HEAD")if(t===void 0){let u=new TextDecoder,c="";for await(let l of e)c+=typeof l=="string"?l:u.decode(l,{stream:!0});c+=u.decode(),c.length>0&&(d=c)}else{let u=JSON.stringify(t);a.delete("content-encoding"),a.delete("transfer-encoding"),u===void 0?a.delete("content-length"):(d=u,a.set("content-length",String(new TextEncoder().encode(u).byteLength)))}return new Request(i,{method:r,headers:a,...n?.signal!==void 0&&{signal:n.signal},...d!==void 0&&{body:d}})}o(Gn,"toWebRequest");function Et(e){return Array.isArray(e)?e[0]:e}o(Et,"singleHeaderValue");function Yn(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}o(Yn,"echoableRequestId");function Xn(e){return Response.json({jsonrpc:"2.0",error:{code:-32603,message:"Internal server error"},id:e},{status:500})}o(Xn,"internalServerErrorResponse");import{CLIENT_CAPABILITIES_META_KEY as tr,CLIENT_INFO_META_KEY as nr}from"@modelcontextprotocol/server";import{HonoRequest as rr}from"hono/request";import{CLIENT_CAPABILITIES_META_KEY as Qn}from"@modelcontextprotocol/server";var Ct="io.modelcontextprotocol/ui",Z="text/html;profile=mcp-app",Zn="ui://views/";var Q="ui/resourceUri";function k(e){return`${Zn}${e}.html`}o(k,"viewResourceUri");var er=new WeakMap;function Ot(e,t){er.set(e,t)}o(Ot,"stashClientCapabilities");function At(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[Qn];if(!(typeof r!="object"||r===null))return r}o(At,"extractClientCapabilitiesFromBody");function ee(e){let t=e?.extensions;if(t===void 0)return!1;let n=t[Ct];if(typeof n!="object"||n===null)return!1;let r=n.mimeTypes;return Array.isArray(r)?r.includes(Z):!1}o(ee,"supportsViews");function or(e){if(e===void 0||e.extra===void 0||e.expiresAt===void 0)throw new Error("OAuth callback did not receive mapped AuthInfo.extra")}o(or,"requireOAuthAuthInfo");function b(e){return typeof e=="string"?e:void 0}o(b,"stringValue");function Pt(e){return typeof e=="string"||typeof e=="number"&&Number.isFinite(e)?e:void 0}o(Pt,"coordinateValue");function sr(e){if(e===void 0)return;let t=b(e["openai/locale"])??b(e["webplus/i18n"]),n=b(e["openai/userAgent"]),r=b(e["openai/subject"]),s=b(e["openai/session"]),i=b(e["openai/organization"]),a=e["openai/userLocation"],d;if(typeof a=="object"&&a!==null&&!Array.isArray(a)){let u=a,c={city:b(u.city),region:b(u.region),country:b(u.country),timezone:b(u.timezone),latitude:Pt(u.latitude),longitude:Pt(u.longitude)},l=Object.entries(c).filter(p=>p[1]!==void 0);l.length>0&&(d=Object.fromEntries(l))}if(!(t===void 0&&n===void 0&&d===void 0&&r===void 0&&s===void 0&&i===void 0))return{...t!==void 0&&{locale:t},...n!==void 0&&{userAgent:n},...d!==void 0&&{location:d},...r!==void 0&&{subject:r},...s!==void 0&&{conversationId:s},...i!==void 0&&{organizationId:i}}}o(sr,"normalizeUserContext");function kt(e){return e.mcpReq.envelope}o(kt,"requestEnvelope");function ve(e){return{...kt(e)?.[nr]??{}}}o(ve,"requestClientInfo");function ir(e){let n={...kt(e)?.[tr]??{}},r=ve(e),s=sr(e.mcpReq._meta);return{can(i){return Object.hasOwn(n,i)},capabilities(){return{...n}},extension(i){let a=n.extensions?.[i];return a===void 0?void 0:{...a}},info(){return{...r}},user(){return s===void 0?void 0:{...s,...s.location!==void 0&&{location:{...s.location}}}},supportsViews(){return ee(n)}}}o(ir,"toClientContext");function $(e){let t=e.http?.req,n=t===void 0?void 0:R(t).honoContext,r=n?.req??(t===void 0?void 0:new rr(t)),s={signal:e.mcpReq.signal,...r!==void 0&&{request:r},...e.mcpReq.inputResponses!==void 0&&{inputResponses:e.mcpReq.inputResponses},client:ir(e),requestState:o(()=>e.mcpReq.requestState(),"requestState"),async sendNotification(i,a){await e.mcpReq.notify({method:i,...a!==void 0&&{params:a}})},async reportProgress(i,a,d){let u=e.mcpReq._meta?.progressToken;return u===void 0?!1:(await e.mcpReq.notify({method:"notifications/progress",params:{progressToken:u,progress:i,...a!==void 0&&{total:a},...d!==void 0&&{message:d}}}),!0)},async sendLog(i,a,d){await e.mcpReq.notify({method:"notifications/message",params:{level:i,data:a,...d!==void 0&&{logger:d}}})}};return n!==void 0?Object.assign(n,s):{...s,...r!==void 0&&{req:r}}}o($,"toRequestContext");function xe(e){let t=e.http?.authInfo;return or(t),Object.assign($(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}}})}o(xe,"toAuthenticatedRequestContext");import{isInputRequiredResult as ar}from"@modelcontextprotocol/server";function dr(e){return"contents"in e&&Array.isArray(e.contents)}o(dr,"isReadResourceResult");function ur(e){return"messages"in e&&Array.isArray(e.messages)}o(ur,"isGetPromptResult");function be(e,t){if(dr(e))return e;let n=e._meta&&typeof e._meta=="object"&&typeof e._meta.mimeType=="string"?e._meta.mimeType:void 0,r=[];for(let s of e.content??[]){let i=cr(s,t,n);i!==void 0&&r.push(i)}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}}o(be,"toResourceResult");function cr(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}}o(cr,"contentBlockToResourceContents");function It(e){if(ar(e)||ur(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}}o(It,"toPromptResult");import{inheritBufferedResponse as lr}from"#mcp-use-buffered-response";var pr=["GET","HEAD","POST","OPTIONS"],fr=["Content-Type","Authorization","mcp-protocol-version","mcp-method","mcp-name"];function mr(e,t){return e===void 0?t:typeof e=="function"?e(t):e==="*"?"*":Array.isArray(e)?t!==null&&e.includes(t)?t:null:e}o(mr,"resolveAllowedOrigin");function hr(e,t){if(t.headers.has("Access-Control-Allow-Origin"))return;let n=t.headers.get("Origin"),r=mr(e.origin,n);if(r===null)return;let s={"Access-Control-Allow-Origin":r,"Access-Control-Allow-Methods":e.methods.join(", "),"Access-Control-Allow-Headers":e.allowedHeaders.join(", ")};return e.credentials&&(s["Access-Control-Allow-Credentials"]="true"),r!=="*"&&(s.Vary="Origin"),s}o(hr,"corsHeaders");function yr(e,t){if(e.headers.has("Access-Control-Allow-Origin"))return e;let n=new Headers(e.headers);return new Headers(t).forEach((s,i)=>{n.set(i,s)}),lr(e,new Response(e.body,{status:e.status,statusText:e.statusText,headers:n}))}o(yr,"mergeCorsHeaders");function Ut(e){if(!(e.enabled!==!1))return async(r,s)=>s();let n={...e.origin!==void 0&&{origin:e.origin},methods:e.methods??pr,allowedHeaders:e.allowedHeaders??fr,credentials:e.credentials??!1};return async(r,s)=>{let i=hr(n,r);if(i===void 0)return s();if(r.method==="OPTIONS")return new Response(null,{status:204,headers:i});let a=await s();return yr(a,i)}}o(Ut,"corsFetchMiddleware");function _t(e){return e!==void 0&&e.enabled!==!1}o(_t,"isGlobalCorsEnabled");import{CallToolResultSchema as gr,GetPromptResultSchema as wr,ListPromptsResultSchema as Tr,ListResourcesResultSchema as Mr,ListToolsResultSchema as Rr,ReadResourceResultSchema as vr}from"@modelcontextprotocol/core";import{isInputRequiredResult as xr}from"@modelcontextprotocol/server";var br=["tools/call","tools/list","resources/read","resources/list","prompts/get","prompts/list"];function jt(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}}o(jt,"withMcpMiddlewareParams");function Ce(e,t){let n=Ar(e),r=t;if(n!=="*"&&!Er(n))throw new TypeError(`Unsupported MCP middleware pattern "${e}". Use an exact MCP method or "mcp:*".`);return n==="*"?{pattern:n,handler:o(async(s,i)=>{let a=!1,d;if(await r(s,async()=>{d=await i(),a=!0}),!a)throw new Error(`Wildcard MCP middleware "${n}" must call next()`);return d},"handler")}:{pattern:n,handler:o((s,i)=>r(s,i),"handler")}}o(Ce,"createMcpMiddlewareEntry");function Oe(e,t){let{pattern:n,phase:r}=Or(e),s=t;return{pattern:n,phase:r,handler:o((i,a)=>s(i,a),"handler")}}o(Oe,"createMcpEventListenerEntry");function L(e,t){if(e==="*")return!0;if(e.endsWith("/*")){let n=e.slice(0,-1);return t.startsWith(n)}return e===t}o(L,"matchesPattern");function Er(e){return br.some(t=>t===e)}o(Er,"isMcpMiddlewareMethod");function qt(e,t,n){let r=e.filter(s=>L(s.pattern,t));return r.length===0?s=>n():s=>{let i=-1,a=o(d=>d<=i?Promise.reject(new Error("next() called multiple times")):(i=d,d===r.length?n():r[d].handler(s,()=>a(d+1))),"dispatch");return a(0)}}o(qt,"composeMiddleware");function Sr(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)})}o(Sr,"freezeMiddlewareContext");async function Dt(e,t,n,r,s){Lt(t,n,"before",r);let a=await qt(e,n,s)(r);return Cr(n,a),Lt(t,n,"complete",r,a),a}o(Dt,"runMcpOperation");function Cr(e,t){if((e==="tools/call"||e==="resources/read"||e==="prompts/get")&&xr(t))return;let n=(()=>{switch(e){case"tools/call":return Se(e,t,"content"),gr.safeParse(t);case"tools/list":return Ee(e,t),Rr.safeParse({tools:t});case"resources/read":return Se(e,t,"contents"),vr.safeParse(t);case"resources/list":return Ee(e,t),Mr.safeParse({resources:t});case"prompts/get":return Se(e,t,"messages"),wr.safeParse(t);case"prompts/list":return Ee(e,t),Tr.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}`)}o(Cr,"assertValidMiddlewareResult");function Ee(e,t){if(!Array.isArray(t))throw new TypeError(`[mcp-use] ${e} middleware returned an invalid result: expected an array`)}o(Ee,"assertArrayResult");function Se(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`)}o(Se,"assertArrayProperty");function Lt(e,t,n,r,s){let i=Sr(r);for(let a of e)if(!(a.phase!==n||!L(a.pattern,t)))try{a.handler(i,s)}catch(d){console.error(`[mcp-use] MCP event listener for "${a.pattern}" (${n}) threw:`,d)}}o(Lt,"dispatchMcpEvents");function Or(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"}}o(Or,"parseMcpPattern");function Ar(e){return e.startsWith("mcp:")?e.slice(4):e}o(Ar,"normalizeMcpMiddlewarePattern");import{CLIENT_INFO_META_KEY as Pr,isJSONRPCRequest as Nt}from"@modelcontextprotocol/server";import{isBufferedResponse as kr,trackBufferedResponse as Ir}from"#mcp-use-buffered-response";function Ur(){return typeof process>"u"||process.env?.NO_COLOR!==void 0?!1:process.stdout?.isTTY===!0}o(Ur,"colorsEnabled");function C(e,t){return n=>Ur()?`\x1B[${e}m${n}\x1B[${t}m`:n}o(C,"ansi");var Pe=C(1,22),ke=C(2,22),ne=C(31,39),Vt=C(32,39),S=C(33,39),_r=C(34,39),Bt=C(35,39),F=C(36,39),Lr=C(90,39);function jr(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"}o(jr,"resolveLogLevel");function Ie(e){if(!(e===void 0||typeof e.name!="string"))return typeof e.version=="string"&&e.version!==""?`${e.name}/${e.version}`:e.name}o(Ie,"formatClientInfo");var Wt={initialize:o(e=>({subject:Ie(e.clientInfo)}),"initialize"),ping:o(()=>({}),"ping"),"server/discover":o(()=>({}),"server/discover"),"completion/complete":o(e=>({subject:e.ref.type==="ref/prompt"?e.ref.name:e.ref.uri,input:e.argument}),"completion/complete"),"logging/setLevel":o(e=>({subject:e.level}),"logging/setLevel"),"prompts/get":o(e=>({subject:e.name,input:e.arguments}),"prompts/get"),"prompts/list":o(()=>({}),"prompts/list"),"resources/list":o(()=>({}),"resources/list"),"resources/templates/list":o(()=>({}),"resources/templates/list"),"resources/read":o(e=>({subject:e.uri}),"resources/read"),"resources/subscribe":o(e=>({subject:e.uri}),"resources/subscribe"),"resources/unsubscribe":o(e=>({subject:e.uri}),"resources/unsubscribe"),"subscriptions/listen":o(()=>({}),"subscriptions/listen"),"tools/call":o(e=>({subject:e.name,input:e.arguments}),"tools/call"),"tools/list":o(()=>({}),"tools/list"),"sampling/createMessage":o(()=>({}),"sampling/createMessage"),"elicitation/create":o(()=>({}),"elicitation/create"),"roots/list":o(()=>({}),"roots/list")};function qr(e){return Object.prototype.hasOwnProperty.call(Wt,e)}o(qr,"isKnownMethod");function Dr(e){if(!qr(e.method))return{};try{let t=Wt[e.method],n=t(e.params);return typeof n.subject=="string"||n.subject===void 0?n:{}}catch{return{}}}o(Dr,"formatDetail");var Ht=80;function $t(e){let t;try{t=JSON.stringify(e)??String(e)}catch{t=String(e)}return t.length>Ht?`${t.slice(0,Ht)}...`:t}o($t,"inlineJson");function Nr(e){let t=e.params?._meta;if(t===void 0)return;let n=t[Pr];if(!(typeof n!="object"||n===null||typeof n.name!="string"))return Ie(n)}o(Nr,"formatClientIdentity");function Hr(e){let t=Nr(e);if(t!==void 0)return t;if(e.method==="initialize")try{return Ie(e.params.clientInfo)}catch{return}}o(Hr,"formatMcpClient");function j(e){return e.replace(/[\u0000-\u001F\u007F-\u009F]+/g," ")}o(j,"sanitize");function $r(e){return e.startsWith("tools/")?F:e.startsWith("resources/")?Vt:e.startsWith("prompts/")?Bt:e==="initialize"||e==="ping"?Lr:_r}o($r,"methodStyle");function Fr(e,t,n,r){if(t!==n)return{method:e,client:void 0,mcpRequest:void 0,streaming:!1};let s=Array.isArray(r)?r.filter(Nt):Nt(r)?[r]:[],i=s[0];return i===void 0?{method:e,client:void 0,mcpRequest:void 0,streaming:!1}:{method:s.length===1?j(i.method):`batch(${s.map(d=>j(d.method)).join(",")})`,client:Hr(i)??"unknown",mcpRequest:i,streaming:i.method==="subscriptions/listen"}}o(Fr,"describeRequest");var Vr=new Set(["authorization","proxy-authorization","cookie","set-cookie","x-api-key"]);function Ft(e){return Object.fromEntries(Object.entries(e).map(([t,n])=>[t,Vr.has(t.toLowerCase())?"[REDACTED]":n]))}o(Ft,"redactHeaders");async function Br(e,t){if(!e.body)return{errorMessage:null};let n;try{let d=kr(e,t),u=e.clone();d&&Ir(t,e),n=await u.text()}catch{return{errorMessage:null}}if(!n)return{errorMessage:null};let r=(e.headers.get("content-type")??"").includes("text/event-stream"),s=[],i=o(d=>{try{s.push(JSON.parse(d))}catch{}},"tryParse");if(r){for(let d of n.split(/\r?\n/))if(d.startsWith("data:")){let u=d.slice(5).trim();u&&i(u)}}else i(n);let a;for(let d of s){if(d===null||typeof d!="object")continue;let u=d;if(typeof u.error?.message=="string")return{errorMessage:u.error.message};if(u.result?.isError===!0){let l=(Array.isArray(u.result.content)?u.result.content:[]).find(p=>p?.type==="text"&&typeof p.text=="string");return{errorMessage:l?String(l.text):"tool error"}}"result"in u&&(a=u.result)}return{errorMessage:null,result:a}}o(Br,"extractResponseOutcome");function Wr(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}o(Wr,"compactToolResult");function te(e){function t(n){return typeof n=="string"&&n.length>100?`${n.slice(0,100)}...`:Array.isArray(n)?n.map(t):n!==null&&typeof n=="object"?Object.fromEntries(Object.entries(n).map(([r,s])=>[r,t(s)])):n}o(t,"truncate");try{return JSON.stringify(t(e),null,2)}catch{return String(e)}}o(te,"formatForDump");var Ae=1e4;async function zr(e,t,n,r){console.log(`
|
|
2
|
-
${F("=".repeat(80))}`),console.log(Pe(F("[TRACE] Request Details"))),console.log(F("-".repeat(80))),Object.keys(t).length>0&&(console.log(S("Request Headers:")),console.log(te(
|
|
1
|
+
import{b as ft,c as mt}from"./chunk-TCIRBQPM.js";import{a as R,b as Fn,c as Y,d as le,e as X,f as _,g as pe,h as fe,i as me,j as he,k as ye,l as ht,m as yt,o as gt}from"./chunk-YI27EOFM.js";import{a as ct,b as lt,c as O,d as pt}from"./chunk-HAV435PF.js";import{a as o}from"./chunk-EI7MMDWY.js";var Vn=["inline","fullscreen","pip"],Bn=new Set(["inline","fullscreen","pip"]);function ge(e){let t=e?.autoResize??!0,n=e?.displayModes===void 0?Vn:e.displayModes;if(!Array.isArray(n)||n.length===0)throw new Error('viewConfig.displayModes must be a non-empty array that includes "inline"');let r=new Set,s=[];for(let a of n){if(typeof a!="string"||!Bn.has(a))throw new Error(`viewConfig.displayModes contains invalid mode ${JSON.stringify(a)}; expected "inline", "fullscreen", or "pip"`);if(r.has(a))throw new Error(`viewConfig.displayModes contains duplicate mode "${a}"`);r.add(a),s.push(a)}if(!r.has("inline"))throw new Error('viewConfig.displayModes must include "inline"');let i=e?.preferredDisplayMode;if(i!==void 0&&i!=="inline"&&i!=="fullscreen")throw new Error('viewConfig.preferredDisplayMode must be "inline" or "fullscreen"');if(i!==void 0&&!r.has(i))throw new Error("viewConfig.preferredDisplayMode must belong to displayModes");return{...i!==void 0&&{preferredDisplayMode:i},autoResize:t,displayModes:s}}o(ge,"normalizeViewConfig");import{localhostAllowedHostnames as Un,localhostAllowedOrigins as us,McpServer as cs,ResourceTemplate as ls,CLIENT_CAPABILITIES_META_KEY as ps,CLIENT_INFO_META_KEY as fs,PROTOCOL_VERSION_META_KEY as ms,isJSONRPCRequest as Nn,isInputRequiredResult as _n}from"@modelcontextprotocol/server";import{createServer as hs}from"#mcp-use-node-http";import{Hono as Ln}from"hono";var wt="public, max-age=31536000, immutable",Wn="public, max-age=300";function Te(e){return/^([a-z][a-z\d+.-]*):/i.exec(e)?.[1]?.toLowerCase()}o(Te,"protocolOf");function zn(e,t){return`${e==="/"?"":e}/_mcp-use/public/${t.split("/").map(r=>encodeURIComponent(r)).join("/")}`}o(zn,"publicAssetPath");function we(e){return Te(e)===void 0}o(we,"isLocalPublicSource");function Jn(e){return e[0]}o(Jn,"selectFaviconFromIcons");function Kn(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/`)}o(Kn,"assertLocalPublicSource");function Mt(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),s=e.slice(n+1),i=r.split(";"),a=i[0]?.toLowerCase()??"";if(!a.startsWith("image/"))throw new TypeError(`${t} data URL must use an image MIME type`);try{if(i.includes("base64")){let d=atob(s);return{mimeType:a,bytes:Uint8Array.from(d,u=>u.charCodeAt(0))}}return{mimeType:a,bytes:new TextEncoder().encode(decodeURIComponent(s))}}catch{throw new TypeError(`${t} must be a valid image data URL`)}}o(Mt,"parseDataImage");function Tt(e,t){if(typeof e!="string"||e.length===0)throw new TypeError(`${t} must be a non-empty string`);let n=Te(e);if(n===void 0)return Kn(e,t),e;if(n==="data")return Mt(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}o(Tt,"assertBrandingSource");function Rt(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 d;try{d=new URL(e.websiteUrl)}catch{throw new TypeError("websiteUrl must be a non-empty absolute http(s) URL")}if(d.protocol!=="http:"&&d.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((d,u)=>{if(typeof d!="object"||d===null)throw new TypeError(`icons[${u}] must be an MCP Icon object`);let c=d,l=Tt(c.src,`icons[${u}].src`),p=c.mimeType;if(p!==void 0&&(typeof p!="string"||!p.toLowerCase().startsWith("image/")))throw new TypeError(`icons[${u}].mimeType must be an image MIME type when provided`);let y=c.sizes;if(y!==void 0&&(!Array.isArray(y)||y.some(f=>typeof f!="string"||f.length===0)))throw new TypeError(`icons[${u}].sizes must be an array of non-empty strings when provided`);let h=y===void 0?void 0:y.map(f=>f),m=c.theme;if(m!==void 0&&m!=="light"&&m!=="dark")throw new TypeError(`icons[${u}].theme must be "light" or "dark" when provided`);return Object.freeze({src:l,...p!==void 0&&{mimeType:p},...h!==void 0&&{sizes:Object.freeze(h)},...m!==void 0&&{theme:m}})}))}let r=e.favicon===void 0?void 0:Tt(e.favicon,"favicon"),s=r===void 0?Jn(n??[]):void 0,i=r??s?.src,a=s?.mimeType??n?.find(d=>d.src===r)?.mimeType;return Object.freeze({...i!==void 0&&{favicon:i},...a!==void 0&&{faviconMimeType:a},...n!==void 0&&{icons:n},...t!==void 0&&{websiteUrl:t}})}o(Rt,"normalizeServerBranding");function Me(e,t,n){return e.map(r=>({...r,src:t!==void 0&&we(r.src)?`${O(t)}${zn(n,r.src)}`:r.src,...r.sizes!==void 0&&{sizes:[...r.sizes]}}))}o(Me,"resolveImplementationIcons");function Re(e){return e.favicon!==void 0&&we(e.favicon)||e.icons?.some(t=>we(t.src))===!0}o(Re,"hasLocalBrandingAsset");function vt(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 s=Te(n);if(s==="http"||s==="https")return new Response(null,{status:307,headers:{Location:n,"Cache-Control":Wn}});if(s==="data"){let c=Mt(n,"favicon");return new Response(r.method==="HEAD"?null:c.bytes.buffer,{status:200,headers:{"Content-Type":e.faviconMimeType??c.mimeType,"Cache-Control":wt,"X-Content-Type-Options":"nosniff"}})}let{join:i}=await import("path"),a=t.dev?i(t.projectRoot,"public"):i(t.projectRoot,".mcp-use/build/views/public"),d=await ft(a,n);if(d===null)return new Response("Not Found",{status:404,headers:{"Cache-Control":"no-store"}});let u=await mt(d,{...t.deferCors===!0&&{deferCors:!0},...r.method==="HEAD"&&{head:!0}});return u.headers.set("Cache-Control",wt),u.headers.set("X-Content-Type-Options","nosniff"),e.faviconMimeType!==void 0&&u.headers.set("Content-Type",e.faviconMimeType),u}}o(vt,"createFaviconHandler");function Gn(e){if(typeof e!="object"||e===null)return!1;let t=e;return typeof t.createTokenVerifier=="function"&&typeof t.mapAuthInfo=="function"&&typeof t.oauthMetadata=="object"&&t.oauthMetadata!==null}o(Gn,"isOAuthProviderLike");function xt(e){if(e.mixedAuth!==void 0&&typeof e.mixedAuth!="boolean")throw new TypeError("mixedAuth must be a boolean");if(e.mixedAuth===!0&&!Gn(e.oauth))throw new TypeError("mixedAuth requires an OAuth provider; set oauth on the server");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");if(e.skills!==void 0&&typeof e.skills!="boolean"){if(typeof e.skills!="object"||e.skills===null||Array.isArray(e.skills))throw new TypeError("skills must be a boolean or configuration object");let t=e.skills.directory;if(t!==void 0&&typeof t!="string")throw new TypeError("skills.directory must be a string when provided")}}o(xt,"assertServerConfig");var Yn="127.0.0.1";function bt(e,t,n=process.env){if(e!==void 0)return e;let r=n.HOST?.trim();return r!==void 0&&r!==""?r:t??Yn}o(bt,"resolveListenHost");function Et(e,t,n=process.env){if(e!==void 0)return e;let r=Xn(n.PORT);return r!==void 0?r:t??3e3}o(Et,"resolveListenPort");function Xn(e){if(e===void 0||e.trim()==="")return;let t=Number(e);return Number.isInteger(t)&&t>=0&&t<=65535?t:void 0}o(Xn,"parsePort");import{isBufferedResponse as Zn}from"#mcp-use-buffered-response";function Ct(e,t){return async(n,r,s)=>{typeof s=="function"&&(s=void 0);let i=!1,a=new AbortController;r.on("close",()=>{i||a.abort()}),r.destroyed===!0&&a.abort();let d,u;try{d=await Qn(n,s,{signal:a.signal}),u=await e.fetch(d,{...n.auth!==void 0&&{authInfo:n.auth},...s!==void 0&&{parsedBody:s}})}catch(f){try{t?.onerror?.(f instanceof Error?f:new Error(String(f)))}catch{}u=tr(er(s))}let c={},l=u.headers.getSetCookie?.();for(let[f,g]of u.headers){if(f==="set-cookie"&&l?.length){c[f]=l;continue}c[f]=g}if(r.writeHead(u.status,c),u.body===null){i=!0,r.end();return}if(Zn(u,d)){try{let f=new Uint8Array(await u.arrayBuffer());i=!0,r.end(f)}catch{i=!0,r.end()}return}let p,y=o(()=>{p?.(),p=void 0},"releaseDrainWait"),h=o(()=>new Promise(f=>{p=f}),"waitForDrain");r.on("drain",y);let m=new Promise(f=>{a.signal.addEventListener("abort",()=>f(),{once:!0})});try{for await(let f of u.body){if(a.signal.aborted)break;let g=f instanceof Uint8Array?f:new Uint8Array(f);r.write(g)===!1&&await Promise.race([h(),m])}}catch{}i=!0,r.end()}}o(Ct,"toNodeHandler");async function Qn(e,t,n){let r=(e.method??"GET").toUpperCase(),i=`http://${St(e.headers.host)??St(e.headers[":authority"])??"localhost"}${e.url??"/"}`,a=new Headers;for(let[u,c]of Object.entries(e.headers))if(!(c===void 0||u.startsWith(":")))if(Array.isArray(c))for(let l of c)a.append(u,l);else a.set(u,c);let d;if(r!=="GET"&&r!=="HEAD")if(t===void 0){let u=new TextDecoder,c="";for await(let l of e)c+=typeof l=="string"?l:u.decode(l,{stream:!0});c+=u.decode(),c.length>0&&(d=c)}else{let u=JSON.stringify(t);a.delete("content-encoding"),a.delete("transfer-encoding"),u===void 0?a.delete("content-length"):(d=u,a.set("content-length",String(new TextEncoder().encode(u).byteLength)))}return new Request(i,{method:r,headers:a,...n?.signal!==void 0&&{signal:n.signal},...d!==void 0&&{body:d}})}o(Qn,"toWebRequest");function St(e){return Array.isArray(e)?e[0]:e}o(St,"singleHeaderValue");function er(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}o(er,"echoableRequestId");function tr(e){return Response.json({jsonrpc:"2.0",error:{code:-32603,message:"Internal server error"},id:e},{status:500})}o(tr,"internalServerErrorResponse");import{CLIENT_CAPABILITIES_META_KEY as sr,CLIENT_INFO_META_KEY as ir}from"@modelcontextprotocol/server";import{HonoRequest as ar}from"hono/request";import{CLIENT_CAPABILITIES_META_KEY as rr}from"@modelcontextprotocol/server";var Ot="io.modelcontextprotocol/ui",Z="text/html;profile=mcp-app",nr="ui://views/";var Q="ui/resourceUri";function k(e){return`${nr}${e}.html`}o(k,"viewResourceUri");var or=new WeakMap;function At(e,t){or.set(e,t)}o(At,"stashClientCapabilities");function Pt(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[rr];if(!(typeof r!="object"||r===null))return r}o(Pt,"extractClientCapabilitiesFromBody");function ee(e){let t=e?.extensions;if(t===void 0)return!1;let n=t[Ot];if(typeof n!="object"||n===null)return!1;let r=n.mimeTypes;return Array.isArray(r)?r.includes(Z):!1}o(ee,"supportsViews");function dr(e){if(e===void 0||e.extra===void 0||e.expiresAt===void 0)throw new Error("OAuth callback did not receive mapped AuthInfo.extra")}o(dr,"requireOAuthAuthInfo");function b(e){return typeof e=="string"?e:void 0}o(b,"stringValue");function kt(e){return typeof e=="string"||typeof e=="number"&&Number.isFinite(e)?e:void 0}o(kt,"coordinateValue");function ur(e){if(e===void 0)return;let t=b(e["openai/locale"])??b(e["webplus/i18n"]),n=b(e["openai/userAgent"]),r=b(e["openai/subject"]),s=b(e["openai/session"]),i=b(e["openai/organization"]),a=e["openai/userLocation"],d;if(typeof a=="object"&&a!==null&&!Array.isArray(a)){let u=a,c={city:b(u.city),region:b(u.region),country:b(u.country),timezone:b(u.timezone),latitude:kt(u.latitude),longitude:kt(u.longitude)},l=Object.entries(c).filter(p=>p[1]!==void 0);l.length>0&&(d=Object.fromEntries(l))}if(!(t===void 0&&n===void 0&&d===void 0&&r===void 0&&s===void 0&&i===void 0))return{...t!==void 0&&{locale:t},...n!==void 0&&{userAgent:n},...d!==void 0&&{location:d},...r!==void 0&&{subject:r},...s!==void 0&&{conversationId:s},...i!==void 0&&{organizationId:i}}}o(ur,"normalizeUserContext");function It(e){return e.mcpReq.envelope}o(It,"requestEnvelope");function ve(e){return{...It(e)?.[ir]??{}}}o(ve,"requestClientInfo");function cr(e){let n={...It(e)?.[sr]??{}},r=ve(e),s=ur(e.mcpReq._meta);return{can(i){return Object.hasOwn(n,i)},capabilities(){return{...n}},extension(i){let a=n.extensions?.[i];return a===void 0?void 0:{...a}},info(){return{...r}},user(){return s===void 0?void 0:{...s,...s.location!==void 0&&{location:{...s.location}}}},supportsViews(){return ee(n)}}}o(cr,"toClientContext");function $(e){let t=e.http?.req,n=t===void 0?void 0:R(t).honoContext,r=n?.req??(t===void 0?void 0:new ar(t)),s={signal:e.mcpReq.signal,...r!==void 0&&{request:r},...e.mcpReq.inputResponses!==void 0&&{inputResponses:e.mcpReq.inputResponses},client:cr(e),requestState:o(()=>e.mcpReq.requestState(),"requestState"),async sendNotification(i,a){await e.mcpReq.notify({method:i,...a!==void 0&&{params:a}})},async reportProgress(i,a,d){let u=e.mcpReq._meta?.progressToken;return u===void 0?!1:(await e.mcpReq.notify({method:"notifications/progress",params:{progressToken:u,progress:i,...a!==void 0&&{total:a},...d!==void 0&&{message:d}}}),!0)},async sendLog(i,a,d){await e.mcpReq.notify({method:"notifications/message",params:{level:i,data:a,...d!==void 0&&{logger:d}}})}};return n!==void 0?Object.assign(n,s):{...s,...r!==void 0&&{req:r}}}o($,"toRequestContext");function xe(e){let t=e.http?.authInfo;return dr(t),Object.assign($(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}}})}o(xe,"toAuthenticatedRequestContext");import{isInputRequiredResult as lr}from"@modelcontextprotocol/server";function pr(e){return"contents"in e&&Array.isArray(e.contents)}o(pr,"isReadResourceResult");function fr(e){return"messages"in e&&Array.isArray(e.messages)}o(fr,"isGetPromptResult");function be(e,t){if(pr(e))return e;let n=e._meta&&typeof e._meta=="object"&&typeof e._meta.mimeType=="string"?e._meta.mimeType:void 0,r=[];for(let s of e.content??[]){let i=mr(s,t,n);i!==void 0&&r.push(i)}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}}o(be,"toResourceResult");function mr(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}}o(mr,"contentBlockToResourceContents");function Ut(e){if(lr(e)||fr(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}}o(Ut,"toPromptResult");import{inheritBufferedResponse as hr}from"#mcp-use-buffered-response";var yr=["GET","HEAD","POST","OPTIONS"],gr=["Content-Type","Authorization","mcp-protocol-version","mcp-method","mcp-name"];function wr(e,t){return e===void 0?t:typeof e=="function"?e(t):e==="*"?"*":Array.isArray(e)?t!==null&&e.includes(t)?t:null:e}o(wr,"resolveAllowedOrigin");function Tr(e,t){if(t.headers.has("Access-Control-Allow-Origin"))return;let n=t.headers.get("Origin"),r=wr(e.origin,n);if(r===null)return;let s={"Access-Control-Allow-Origin":r,"Access-Control-Allow-Methods":e.methods.join(", "),"Access-Control-Allow-Headers":e.allowedHeaders.join(", ")};return e.credentials&&(s["Access-Control-Allow-Credentials"]="true"),r!=="*"&&(s.Vary="Origin"),s}o(Tr,"corsHeaders");function Mr(e,t){if(e.headers.has("Access-Control-Allow-Origin"))return e;let n=new Headers(e.headers);return new Headers(t).forEach((s,i)=>{n.set(i,s)}),hr(e,new Response(e.body,{status:e.status,statusText:e.statusText,headers:n}))}o(Mr,"mergeCorsHeaders");function _t(e){if(!(e.enabled!==!1))return async(r,s)=>s();let n={...e.origin!==void 0&&{origin:e.origin},methods:e.methods??yr,allowedHeaders:e.allowedHeaders??gr,credentials:e.credentials??!1};return async(r,s)=>{let i=Tr(n,r);if(i===void 0)return s();if(r.method==="OPTIONS")return new Response(null,{status:204,headers:i});let a=await s();return Mr(a,i)}}o(_t,"corsFetchMiddleware");function Lt(e){return e!==void 0&&e.enabled!==!1}o(Lt,"isGlobalCorsEnabled");import{CallToolResultSchema as Rr,GetPromptResultSchema as vr,ListPromptsResultSchema as xr,ListResourcesResultSchema as br,ListToolsResultSchema as Er,ReadResourceResultSchema as Sr}from"@modelcontextprotocol/core";import{isInputRequiredResult as Cr}from"@modelcontextprotocol/server";var Or=["tools/call","tools/list","resources/read","resources/list","prompts/get","prompts/list"];function qt(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}}o(qt,"withMcpMiddlewareParams");function Ce(e,t){let n=Ur(e),r=t;if(n!=="*"&&!Ar(n))throw new TypeError(`Unsupported MCP middleware pattern "${e}". Use an exact MCP method or "mcp:*".`);return n==="*"?{pattern:n,handler:o(async(s,i)=>{let a=!1,d;if(await r(s,async()=>{d=await i(),a=!0}),!a)throw new Error(`Wildcard MCP middleware "${n}" must call next()`);return d},"handler")}:{pattern:n,handler:o((s,i)=>r(s,i),"handler")}}o(Ce,"createMcpMiddlewareEntry");function Oe(e,t){let{pattern:n,phase:r}=Ir(e),s=t;return{pattern:n,phase:r,handler:o((i,a)=>s(i,a),"handler")}}o(Oe,"createMcpEventListenerEntry");function L(e,t){if(e==="*")return!0;if(e.endsWith("/*")){let n=e.slice(0,-1);return t.startsWith(n)}return e===t}o(L,"matchesPattern");function Ar(e){return Or.some(t=>t===e)}o(Ar,"isMcpMiddlewareMethod");function Nt(e,t,n){let r=e.filter(s=>L(s.pattern,t));return r.length===0?s=>n():s=>{let i=-1,a=o(d=>d<=i?Promise.reject(new Error("next() called multiple times")):(i=d,d===r.length?n():r[d].handler(s,()=>a(d+1))),"dispatch");return a(0)}}o(Nt,"composeMiddleware");function Pr(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)})}o(Pr,"freezeMiddlewareContext");async function Dt(e,t,n,r,s){jt(t,n,"before",r);let a=await Nt(e,n,s)(r);return kr(n,a),jt(t,n,"complete",r,a),a}o(Dt,"runMcpOperation");function kr(e,t){if((e==="tools/call"||e==="resources/read"||e==="prompts/get")&&Cr(t))return;let n=(()=>{switch(e){case"tools/call":return Se(e,t,"content"),Rr.safeParse(t);case"tools/list":return Ee(e,t),Er.safeParse({tools:t});case"resources/read":return Se(e,t,"contents"),Sr.safeParse(t);case"resources/list":return Ee(e,t),br.safeParse({resources:t});case"prompts/get":return Se(e,t,"messages"),vr.safeParse(t);case"prompts/list":return Ee(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}`)}o(kr,"assertValidMiddlewareResult");function Ee(e,t){if(!Array.isArray(t))throw new TypeError(`[mcp-use] ${e} middleware returned an invalid result: expected an array`)}o(Ee,"assertArrayResult");function Se(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`)}o(Se,"assertArrayProperty");function jt(e,t,n,r,s){let i=Pr(r);for(let a of e)if(!(a.phase!==n||!L(a.pattern,t)))try{a.handler(i,s)}catch(d){console.error(`[mcp-use] MCP event listener for "${a.pattern}" (${n}) threw:`,d)}}o(jt,"dispatchMcpEvents");function Ir(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"}}o(Ir,"parseMcpPattern");function Ur(e){return e.startsWith("mcp:")?e.slice(4):e}o(Ur,"normalizeMcpMiddlewarePattern");import{CLIENT_INFO_META_KEY as _r,isJSONRPCRequest as Ht}from"@modelcontextprotocol/server";import{isBufferedResponse as Lr,trackBufferedResponse as jr}from"#mcp-use-buffered-response";function qr(){return typeof process>"u"||process.env?.NO_COLOR!==void 0?!1:process.stdout?.isTTY===!0}o(qr,"colorsEnabled");function C(e,t){return n=>qr()?`\x1B[${e}m${n}\x1B[${t}m`:n}o(C,"ansi");var Pe=C(1,22),ke=C(2,22),ne=C(31,39),Bt=C(32,39),S=C(33,39),Nr=C(34,39),Wt=C(35,39),F=C(36,39),Dr=C(90,39);function Hr(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"}o(Hr,"resolveLogLevel");function Ie(e){if(!(e===void 0||typeof e.name!="string"))return typeof e.version=="string"&&e.version!==""?`${e.name}/${e.version}`:e.name}o(Ie,"formatClientInfo");var zt={initialize:o(e=>({subject:Ie(e.clientInfo)}),"initialize"),ping:o(()=>({}),"ping"),"server/discover":o(()=>({}),"server/discover"),"completion/complete":o(e=>({subject:e.ref.type==="ref/prompt"?e.ref.name:e.ref.uri,input:e.argument}),"completion/complete"),"logging/setLevel":o(e=>({subject:e.level}),"logging/setLevel"),"prompts/get":o(e=>({subject:e.name,input:e.arguments}),"prompts/get"),"prompts/list":o(()=>({}),"prompts/list"),"resources/list":o(()=>({}),"resources/list"),"resources/templates/list":o(()=>({}),"resources/templates/list"),"resources/read":o(e=>({subject:e.uri}),"resources/read"),"resources/subscribe":o(e=>({subject:e.uri}),"resources/subscribe"),"resources/unsubscribe":o(e=>({subject:e.uri}),"resources/unsubscribe"),"subscriptions/listen":o(()=>({}),"subscriptions/listen"),"tools/call":o(e=>({subject:e.name,input:e.arguments}),"tools/call"),"tools/list":o(()=>({}),"tools/list"),"sampling/createMessage":o(()=>({}),"sampling/createMessage"),"elicitation/create":o(()=>({}),"elicitation/create"),"roots/list":o(()=>({}),"roots/list")};function $r(e){return Object.prototype.hasOwnProperty.call(zt,e)}o($r,"isKnownMethod");function Fr(e){if(!$r(e.method))return{};try{let t=zt[e.method],n=t(e.params);return typeof n.subject=="string"||n.subject===void 0?n:{}}catch{return{}}}o(Fr,"formatDetail");var $t=80;function Ft(e){let t;try{t=JSON.stringify(e)??String(e)}catch{t=String(e)}return t.length>$t?`${t.slice(0,$t)}...`:t}o(Ft,"inlineJson");function Vr(e){let t=e.params?._meta;if(t===void 0)return;let n=t[_r];if(!(typeof n!="object"||n===null||typeof n.name!="string"))return Ie(n)}o(Vr,"formatClientIdentity");function Br(e){let t=Vr(e);if(t!==void 0)return t;if(e.method==="initialize")try{return Ie(e.params.clientInfo)}catch{return}}o(Br,"formatMcpClient");function j(e){return e.replace(/[\u0000-\u001F\u007F-\u009F]+/g," ")}o(j,"sanitize");function Wr(e){return e.startsWith("tools/")?F:e.startsWith("resources/")?Bt:e.startsWith("prompts/")?Wt:e==="initialize"||e==="ping"?Dr:Nr}o(Wr,"methodStyle");function zr(e,t,n,r){if(t!==n)return{method:e,client:void 0,mcpRequest:void 0,streaming:!1};let s=Array.isArray(r)?r.filter(Ht):Ht(r)?[r]:[],i=s[0];return i===void 0?{method:e,client:void 0,mcpRequest:void 0,streaming:!1}:{method:s.length===1?j(i.method):`batch(${s.map(d=>j(d.method)).join(",")})`,client:Br(i)??"unknown",mcpRequest:i,streaming:i.method==="subscriptions/listen"}}o(zr,"describeRequest");var Jr=new Set(["authorization","proxy-authorization","cookie","set-cookie","x-api-key"]);function Vt(e){return Object.fromEntries(Object.entries(e).map(([t,n])=>[t,Jr.has(t.toLowerCase())?"[REDACTED]":n]))}o(Vt,"redactHeaders");async function Kr(e,t){if(!e.body)return{errorMessage:null};let n;try{let d=Lr(e,t),u=e.clone();d&&jr(t,e),n=await u.text()}catch{return{errorMessage:null}}if(!n)return{errorMessage:null};let r=(e.headers.get("content-type")??"").includes("text/event-stream"),s=[],i=o(d=>{try{s.push(JSON.parse(d))}catch{}},"tryParse");if(r){for(let d of n.split(/\r?\n/))if(d.startsWith("data:")){let u=d.slice(5).trim();u&&i(u)}}else i(n);let a;for(let d of s){if(d===null||typeof d!="object")continue;let u=d;if(typeof u.error?.message=="string")return{errorMessage:u.error.message};if(u.result?.isError===!0){let l=(Array.isArray(u.result.content)?u.result.content:[]).find(p=>p?.type==="text"&&typeof p.text=="string");return{errorMessage:l?String(l.text):"tool error"}}"result"in u&&(a=u.result)}return{errorMessage:null,result:a}}o(Kr,"extractResponseOutcome");function Gr(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}o(Gr,"compactToolResult");function te(e){function t(n){return typeof n=="string"&&n.length>100?`${n.slice(0,100)}...`:Array.isArray(n)?n.map(t):n!==null&&typeof n=="object"?Object.fromEntries(Object.entries(n).map(([r,s])=>[r,t(s)])):n}o(t,"truncate");try{return JSON.stringify(t(e),null,2)}catch{return String(e)}}o(te,"formatForDump");var Ae=1e4;async function Yr(e,t,n,r){console.log(`
|
|
2
|
+
${F("=".repeat(80))}`),console.log(Pe(F("[TRACE] Request Details"))),console.log(F("-".repeat(80))),Object.keys(t).length>0&&(console.log(S("Request Headers:")),console.log(te(Vt(t)))),n!==void 0&&(console.log(S("Request Body:")),console.log(typeof n=="string"?n:te(n)));let s={};if(e.headers.forEach((i,a)=>{s[a]=i}),Object.keys(s).length>0&&(console.log(S("Response Headers:")),console.log(te(Vt(s)))),!r)console.log(`${S("Response Body:")} (streaming \u2014 not dumped)`);else if(e.body===null)console.log(`${S("Response Body:")} (no body)`);else try{let i=await e.clone().text();if(i.length===0)console.log(`${S("Response Body:")} (empty)`);else{console.log(S("Response Body:"));try{console.log(te(JSON.parse(i)))}catch{console.log(i.length>Ae?`${i.slice(0,Ae)}
|
|
3
3
|
... (truncated, ${i.length-Ae} more characters)`:i)}}}catch{console.log(`${S("Response Body:")} (unable to read)`)}console.log(`${F("=".repeat(80))}
|
|
4
|
-
`)}o(zr,"printTraceDump");function Jr(e){let t=String(e);return e>=500?Bt(t):e>=400?ne(t):e>=300?S(t):Vt(t)}o(Jr,"styleStatus");function Kr(e,t){return e!=="GET"&&e!=="HEAD"?!1:t.endsWith("/favicon.ico")}o(Kr,"isNoisyRequest");function Gr(e){let{description:t,detail:n}=e;return[...e.prefix===void 0?[]:[Pe(e.prefix)],$r(t.method)(t.method),...n?.subject===void 0?[]:[Pe(j(n.subject))],e.pathname,Jr(e.status),...t.client===void 0?[]:[ke(`client=${j(t.client)}`)],ke(`${e.durationMs}ms`),...e.suffix].join(" ")}o(Gr,"formatRequestLogLine");function Ue(e={}){return e.enabled===!1?(t,n)=>n():async(t,n)=>{let r=jr(e.level),s=Date.now(),i=t.method,a=new URL(t.url).pathname;if(Kr(i,a))return n();let d={};r==="trace"&&t.headers.forEach((f,g)=>{d[g]=f});let u;if(i!=="GET"&&i!=="HEAD"){let f=R(t).parsedBody;if(f!==void 0)u=f;else try{u=await t.clone().json(),(t.headers.get("content-type")??"").includes("application/json")&&(R(t).parsedBody=u)}catch{}}let c=Fr(i,a,e.mcpPath,u),l=o((f,g,T=[])=>{console.log(Gr({prefix:e.prefix,description:c,detail:g,pathname:a,status:f,durationMs:Date.now()-s,suffix:T}))},"logLine"),p;try{p=await n()}catch(f){throw l(500,void 0,[ne(`ERROR ${j(f instanceof Error?f.message:String(f))}`)]),f}let y=c.streaming||p.headers.get("content-type")?.split(";",1)[0]?.trim().toLowerCase()==="text/event-stream",h=c.mcpRequest===void 0?void 0:Dr(c.mcpRequest),m=[];if(c.mcpRequest!==void 0&&h!==void 0){let f=r!=="info";f&&h.input!==void 0&&m.push($t(h.input));let g=y?{errorMessage:null}:await Br(p,t);f&&c.mcpRequest.method==="tools/call"&&g.errorMessage===null&&g.result!==void 0&&m.push(ke("->"),$t(Wr(g.result))),g.errorMessage!==null?m.push(ne(`ERROR ${j(g.errorMessage)}`)):p.status>=400&&m.push(ne(`ERROR (HTTP ${p.status})`))}return l(p.status,h,m),r==="trace"&&await zr(p,d,u,!y),p}}o(Ue,"requestLogger");import{createMcpHandler as Yr}from"@modelcontextprotocol/server";import{trackBufferedResponse as Xr}from"#mcp-use-buffered-response";function _e(e,t={}){let{path:n="/mcp",handler:r,authInfo:s}=t,i=r?.legacy??"stateless",a=Yr(e,{legacy:"stateless",...r});return{handler:a,fetch:o(async u=>{if(!le(u,n))return new Response("Not Found",{status:404});if(i==="stateless"){let f=u.method.toUpperCase();if(f==="GET"||f==="DELETE"||f==="HEAD")return new Response(null,{status:204})}let c=R(u),l=c.parsedBody;if(l===void 0)try{l=await u.clone().json()}catch{}let p=At(l);p!==void 0&&Ot(u,p);let y=s?.(u)??c.authInfo,h=await a.fetch(u,{...l!==void 0&&{parsedBody:l},...y!==void 0&&{authInfo:y}});return h.headers.get("content-type")?.toLowerCase().includes("application/json")?"Bun"in globalThis&&h.body!==null?new Response(await h.arrayBuffer(),{status:h.status,statusText:h.statusText,headers:h.headers}):Xr(u,h):h},"fetch")}}o(_e,"createMcpMount");function A(e,t){if(e===null||typeof e!="object"||Array.isArray(e))throw new TypeError(`${t} must be an object`);return e}o(A,"object");function zt(e,t){if(!Array.isArray(e))throw new TypeError(`${t} must be an array`);return e}o(zt,"array");function I(e,t){if(typeof e!="string"||!e.trim())throw new TypeError(`${t} must be a non-blank string`)}o(I,"nonBlank");function re(e,t){return{"~standard":{version:1,vendor:"mcp-use",jsonSchema:{input:o(()=>e,"input"),output:o(()=>e,"output")},async validate(n){try{return{value:await t(n)}}catch(r){return{issues:[{message:r instanceof Error?r.message:String(r)}]}}}}}}o(re,"standard");function Jt(e){let t=e.readTool??"settings.read",n=e.updateTool??"settings.update";if(I(t,"readTool"),I(n,"updateTool"),t===n)throw new TypeError("Settings read and update tools must have different names");A(e.fields,"fields");let r=Object.entries(e.fields).map(([h,m])=>[h,{...m}]);if(!r.length)throw new TypeError("Settings require at least one field");let s={};for(let[h,m]of r){if(I(m.title,`Setting ${h} title`),m.description!==void 0&&typeof m.description!="string")throw new TypeError(`Setting ${h} description must be a string`);let f=m.schema["~standard"].jsonSchema.output({target:"draft-2020-12"}),g=m.schema["~standard"].jsonSchema.input({target:"draft-2020-12"});if(!["boolean","string","number","integer"].includes(String(g.type))||f.type!==g.type||["$ref","anyOf","oneOf","allOf"].some(v=>v in g)||g.enum!==void 0&&(g.type!=="string"||!Array.isArray(g.enum)||!g.enum.length||!g.enum.every(v=>typeof v=="string")))throw new TypeError(`Unsupported native setting ${h}: use boolean, string, string enum, number, or integer`);let T=structuredClone(g);delete T.default,Object.defineProperty(s,h,{enumerable:!0,value:{...T,title:m.title,...m.description!==void 0&&{description:m.description}}})}let i={type:"object",properties:s,required:r.map(([h])=>h),additionalProperties:!1},a=e.layout===void 0?void 0:structuredClone(e.layout);if(a!==void 0)for(let h of zt(a,"Settings layout")){let m=A(h,"Settings layout group");if(m.kind!=="group")throw new TypeError("Settings layout groups must have kind 'group'");I(m.title,"Settings layout group title");for(let f of zt(m.items,"Settings layout group items")){let g=A(f,"Settings layout item");if(g.kind==="property"){if(I(g.property,"Settings layout property"),!Object.hasOwn(s,g.property))throw new TypeError(`Settings layout references unknown setting: ${g.property}`)}else if(g.kind==="tool"){if(I(g.tool,"Settings layout action tool"),I(g.title,"Settings layout action title"),g.description!==void 0&&typeof g.description!="string")throw new TypeError("Settings layout action description must be a string")}else throw new TypeError("Settings layout items must have kind 'property' or 'tool'")}}let d=o(async(h,m=!1)=>{let f=A(h,m?"set":"values");for(let T of Object.keys(f))if(!Object.hasOwn(s,T))throw new TypeError(`Unknown setting: ${T}`);if(m&&!Object.keys(f).length)throw new TypeError("Set at least one setting");let g={};for(let[T,v]of r){if(!Object.hasOwn(f,T)){if(!m)throw new TypeError(`Missing effective setting: ${T}`);continue}let M=await v.schema["~standard"].validate(f[T]);if(M.issues!==void 0)throw new TypeError(`Invalid setting ${T}: ${M.issues.map(w=>w.message).join(", ")}`);if(M.value===void 0||!["string","boolean","number"].includes(typeof M.value)||typeof M.value=="number"&&!Number.isFinite(M.value))throw new TypeError(`Invalid primitive setting: ${T}`);if(!Object.is(M.value,f[T]))throw new TypeError(`Setting ${T} schema must not transform values`);Object.defineProperty(g,T,{enumerable:!0,value:M.value})}return g},"validateValues"),u=re({type:"object",additionalProperties:!1},h=>{if(Object.keys(A(h,"arguments")).length)throw new TypeError("Settings read accepts empty arguments");return{}}),c=re({type:"object",properties:{set:{...i,required:[],minProperties:1}},required:["set"],additionalProperties:!1},async h=>{let m=A(h,"arguments");if(Object.keys(m).some(f=>f!=="set"))throw new TypeError("Unknown settings update argument");return{set:await d(m.set,!0)}}),p=re({type:"object",properties:{schema:{type:"object"},values:i,layout:{type:"array",items:{type:"object",properties:{kind:{const:"group"},title:{type:"string"},items:{type:"array",items:{type:"object"}}},required:["kind","title","items"]}}},required:["schema","values"]},async h=>{let m=A(h,"settings result");return{...m,values:await d(m.values)}}),y=re({type:"object",properties:{values:i},required:["values"]},async h=>({values:await d(A(h,"settings result").values)}));return{capability:{readTool:t,updateTool:n},schema:i,layout:a,readDefinition:{name:t,inputSchema:u,outputSchema:p,annotations:{readOnlyHint:!0}},updateDefinition:{name:n,inputSchema:c,outputSchema:y}}}o(Jt,"prepareSettings");import{completable as Kt}from"@modelcontextprotocol/server";function Le(e){let t=e.map(String);return n=>{let r=String(n??"").toLowerCase();return t.filter(s=>s.toLowerCase().startsWith(r))}}o(Le,"createPrefixCompletion");function Zr(e,t){return typeof t=="function"?Kt(e,(n,r)=>t(String(n??""),r)):Kt(e,Le(t))}o(Zr,"completable");function Gt(e){let t=Object.create(null);for(let[n,r]of Object.entries(e))r!==void 0&&(t[n]=Array.isArray(r)?Le(r):r);return t}o(Gt,"normalizeCompletions");import{fromJsonSchema as Qr}from"@modelcontextprotocol/server";var eo=["get","put","post","delete","options","head","patch","trace"];function Qt(e,t){let n=to(t.spec,t),r=so(n),s=n.length>0?go(t):void 0;for(let[i,a]of n.entries()){let d=r[i];if(d===void 0||s===void 0)continue;let u=co(a);e.tool({name:d,description:io(a),inputSchema:uo(t.spec,a,u)},async c=>mo(a,c,t,u,s))}}o(Qt,"registerOpenAPITools");function to(e,t){let n=[];for(let[r,s]of Object.entries(e.paths??{})){let i=q(e,s);if(i===void 0||B(i))continue;let a=Yt(e,i.parameters);for(let d of eo){let u=i[d];if(u===void 0)continue;let c=q(e,u);if(c===void 0||B(c))continue;let l=Yt(e,c.parameters),p=c.requestBody===void 0?void 0:q(e,c.requestBody),y={method:d,path:r,operation:c,parameters:no(a,l),...p!==void 0&&!B(p)&&{requestBody:p}};ro(y,t)&&n.push(y)}}return n}o(to,"collectOperations");function Yt(e,t){let n=[];for(let r of t??[]){let s=q(e,r);s!==void 0&&!B(s)&&n.push(s)}return n}o(Yt,"resolveParameters");function no(e,t){let n=new Map;for(let r of[...e,...t])n.set(`${r.in}:${r.name}`,r);return[...n.values()]}o(no,"mergeParameters");function ro(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=>oo(e,n))}o(ro,"isIncluded");function oo(e,t){if(t.method&&t.method.toLowerCase()!==e.method||t.operationId&&!Xt(t.operationId,e.operation.operationId??"")||t.path&&!Xt(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}o(oo,"matchesExcludeRule");function Xt(e,t){return typeof e=="string"?e===t:(e.lastIndex=0,e.test(t))}o(Xt,"matchesPattern");function so(e){let t=new Map;return e.map(n=>{let r=ao(n.operation.operationId??`${n.method}_${n.path.replace(/[{}]/g,"").replace(/\//g,"_")}`),s=t.get(r)??0;if(t.set(r,s+1),s===0)return r;let i=`_${s+1}`;return`${r.slice(0,64-i.length)}${i}`})}o(so,"createToolNames");function io(e){return[e.operation.summary,e.operation.description,`HTTP: ${e.method.toUpperCase()} ${e.path}`].filter(t=>!!t).join(`
|
|
4
|
+
`)}o(Yr,"printTraceDump");function Xr(e){let t=String(e);return e>=500?Wt(t):e>=400?ne(t):e>=300?S(t):Bt(t)}o(Xr,"styleStatus");function Zr(e,t){return e!=="GET"&&e!=="HEAD"?!1:t.endsWith("/favicon.ico")}o(Zr,"isNoisyRequest");function Qr(e){let{description:t,detail:n}=e;return[...e.prefix===void 0?[]:[Pe(e.prefix)],Wr(t.method)(t.method),...n?.subject===void 0?[]:[Pe(j(n.subject))],e.pathname,Xr(e.status),...t.client===void 0?[]:[ke(`client=${j(t.client)}`)],ke(`${e.durationMs}ms`),...e.suffix].join(" ")}o(Qr,"formatRequestLogLine");function Ue(e={}){return e.enabled===!1?(t,n)=>n():async(t,n)=>{let r=Hr(e.level),s=Date.now(),i=t.method,a=new URL(t.url).pathname;if(Zr(i,a))return n();let d={};r==="trace"&&t.headers.forEach((f,g)=>{d[g]=f});let u;if(i!=="GET"&&i!=="HEAD"){let f=R(t).parsedBody;if(f!==void 0)u=f;else try{u=await t.clone().json(),(t.headers.get("content-type")??"").includes("application/json")&&(R(t).parsedBody=u)}catch{}}let c=zr(i,a,e.mcpPath,u),l=o((f,g,T=[])=>{console.log(Qr({prefix:e.prefix,description:c,detail:g,pathname:a,status:f,durationMs:Date.now()-s,suffix:T}))},"logLine"),p;try{p=await n()}catch(f){throw l(500,void 0,[ne(`ERROR ${j(f instanceof Error?f.message:String(f))}`)]),f}let y=c.streaming||p.headers.get("content-type")?.split(";",1)[0]?.trim().toLowerCase()==="text/event-stream",h=c.mcpRequest===void 0?void 0:Fr(c.mcpRequest),m=[];if(c.mcpRequest!==void 0&&h!==void 0){let f=r!=="info";f&&h.input!==void 0&&m.push(Ft(h.input));let g=y?{errorMessage:null}:await Kr(p,t);f&&c.mcpRequest.method==="tools/call"&&g.errorMessage===null&&g.result!==void 0&&m.push(ke("->"),Ft(Gr(g.result))),g.errorMessage!==null?m.push(ne(`ERROR ${j(g.errorMessage)}`)):p.status>=400&&m.push(ne(`ERROR (HTTP ${p.status})`))}return l(p.status,h,m),r==="trace"&&await Yr(p,d,u,!y),p}}o(Ue,"requestLogger");import{createMcpHandler as eo}from"@modelcontextprotocol/server";import{trackBufferedResponse as to}from"#mcp-use-buffered-response";function _e(e,t={}){let{path:n="/mcp",handler:r,authInfo:s}=t,i=r?.legacy??"stateless",a=eo(e,{legacy:"stateless",...r});return{handler:a,fetch:o(async u=>{if(!le(u,n))return new Response("Not Found",{status:404});if(i==="stateless"){let f=u.method.toUpperCase();if(f==="GET"||f==="DELETE"||f==="HEAD")return new Response(null,{status:204})}let c=R(u),l=c.parsedBody;if(l===void 0)try{l=await u.clone().json()}catch{}let p=Pt(l);p!==void 0&&At(u,p);let y=s?.(u)??c.authInfo,h=await a.fetch(u,{...l!==void 0&&{parsedBody:l},...y!==void 0&&{authInfo:y}});return h.headers.get("content-type")?.toLowerCase().includes("application/json")?"Bun"in globalThis&&h.body!==null?new Response(await h.arrayBuffer(),{status:h.status,statusText:h.statusText,headers:h.headers}):to(u,h):h},"fetch")}}o(_e,"createMcpMount");function A(e,t){if(e===null||typeof e!="object"||Array.isArray(e))throw new TypeError(`${t} must be an object`);return e}o(A,"object");function Jt(e,t){if(!Array.isArray(e))throw new TypeError(`${t} must be an array`);return e}o(Jt,"array");function I(e,t){if(typeof e!="string"||!e.trim())throw new TypeError(`${t} must be a non-blank string`)}o(I,"nonBlank");function re(e,t){return{"~standard":{version:1,vendor:"mcp-use",jsonSchema:{input:o(()=>e,"input"),output:o(()=>e,"output")},async validate(n){try{return{value:await t(n)}}catch(r){return{issues:[{message:r instanceof Error?r.message:String(r)}]}}}}}}o(re,"standard");function Kt(e){let t=e.readTool??"settings.read",n=e.updateTool??"settings.update";if(I(t,"readTool"),I(n,"updateTool"),t===n)throw new TypeError("Settings read and update tools must have different names");A(e.fields,"fields");let r=Object.entries(e.fields).map(([h,m])=>[h,{...m}]);if(!r.length)throw new TypeError("Settings require at least one field");let s={};for(let[h,m]of r){if(I(m.title,`Setting ${h} title`),m.description!==void 0&&typeof m.description!="string")throw new TypeError(`Setting ${h} description must be a string`);let f=m.schema["~standard"].jsonSchema.output({target:"draft-2020-12"}),g=m.schema["~standard"].jsonSchema.input({target:"draft-2020-12"});if(!["boolean","string","number","integer"].includes(String(g.type))||f.type!==g.type||["$ref","anyOf","oneOf","allOf"].some(v=>v in g)||g.enum!==void 0&&(g.type!=="string"||!Array.isArray(g.enum)||!g.enum.length||!g.enum.every(v=>typeof v=="string")))throw new TypeError(`Unsupported native setting ${h}: use boolean, string, string enum, number, or integer`);let T=structuredClone(g);delete T.default,Object.defineProperty(s,h,{enumerable:!0,value:{...T,title:m.title,...m.description!==void 0&&{description:m.description}}})}let i={type:"object",properties:s,required:r.map(([h])=>h),additionalProperties:!1},a=e.layout===void 0?void 0:structuredClone(e.layout);if(a!==void 0)for(let h of Jt(a,"Settings layout")){let m=A(h,"Settings layout group");if(m.kind!=="group")throw new TypeError("Settings layout groups must have kind 'group'");I(m.title,"Settings layout group title");for(let f of Jt(m.items,"Settings layout group items")){let g=A(f,"Settings layout item");if(g.kind==="property"){if(I(g.property,"Settings layout property"),!Object.hasOwn(s,g.property))throw new TypeError(`Settings layout references unknown setting: ${g.property}`)}else if(g.kind==="tool"){if(I(g.tool,"Settings layout action tool"),I(g.title,"Settings layout action title"),g.description!==void 0&&typeof g.description!="string")throw new TypeError("Settings layout action description must be a string")}else throw new TypeError("Settings layout items must have kind 'property' or 'tool'")}}let d=o(async(h,m=!1)=>{let f=A(h,m?"set":"values");for(let T of Object.keys(f))if(!Object.hasOwn(s,T))throw new TypeError(`Unknown setting: ${T}`);if(m&&!Object.keys(f).length)throw new TypeError("Set at least one setting");let g={};for(let[T,v]of r){if(!Object.hasOwn(f,T)){if(!m)throw new TypeError(`Missing effective setting: ${T}`);continue}let M=await v.schema["~standard"].validate(f[T]);if(M.issues!==void 0)throw new TypeError(`Invalid setting ${T}: ${M.issues.map(w=>w.message).join(", ")}`);if(M.value===void 0||!["string","boolean","number"].includes(typeof M.value)||typeof M.value=="number"&&!Number.isFinite(M.value))throw new TypeError(`Invalid primitive setting: ${T}`);if(!Object.is(M.value,f[T]))throw new TypeError(`Setting ${T} schema must not transform values`);Object.defineProperty(g,T,{enumerable:!0,value:M.value})}return g},"validateValues"),u=re({type:"object",additionalProperties:!1},h=>{if(Object.keys(A(h,"arguments")).length)throw new TypeError("Settings read accepts empty arguments");return{}}),c=re({type:"object",properties:{set:{...i,required:[],minProperties:1}},required:["set"],additionalProperties:!1},async h=>{let m=A(h,"arguments");if(Object.keys(m).some(f=>f!=="set"))throw new TypeError("Unknown settings update argument");return{set:await d(m.set,!0)}}),p=re({type:"object",properties:{schema:{type:"object"},values:i,layout:{type:"array",items:{type:"object",properties:{kind:{const:"group"},title:{type:"string"},items:{type:"array",items:{type:"object"}}},required:["kind","title","items"]}}},required:["schema","values"]},async h=>{let m=A(h,"settings result");return{...m,values:await d(m.values)}}),y=re({type:"object",properties:{values:i},required:["values"]},async h=>({values:await d(A(h,"settings result").values)}));return{capability:{readTool:t,updateTool:n},schema:i,layout:a,readDefinition:{name:t,inputSchema:u,outputSchema:p,annotations:{readOnlyHint:!0}},updateDefinition:{name:n,inputSchema:c,outputSchema:y}}}o(Kt,"prepareSettings");import{completable as Gt}from"@modelcontextprotocol/server";function Le(e){let t=e.map(String);return n=>{let r=String(n??"").toLowerCase();return t.filter(s=>s.toLowerCase().startsWith(r))}}o(Le,"createPrefixCompletion");function no(e,t){return typeof t=="function"?Gt(e,(n,r)=>t(String(n??""),r)):Gt(e,Le(t))}o(no,"completable");function Yt(e){let t=Object.create(null);for(let[n,r]of Object.entries(e))r!==void 0&&(t[n]=Array.isArray(r)?Le(r):r);return t}o(Yt,"normalizeCompletions");import{ResourceLinkSchema as ro}from"@modelcontextprotocol/core";import{fromJsonSchema as Xt}from"@modelcontextprotocol/server";var oo=Xt({type:"object",properties:{query:{type:"string"}},required:["query"]}),so=Xt({type:"object",properties:{items:{type:"array",items:ro["~standard"].jsonSchema.output({target:"draft-2020-12"})}},required:["items"]});function je(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:{}}o(je,"record");function Zt(e){if(typeof e.name!="string"||!e.name.trim())throw new TypeError("Mention tool name must be a non-blank string");if(typeof e.search!="function")throw new TypeError("Mention search must be a callback");let{search:t,...n}=e;return{...n,inputSchema:oo,outputSchema:so,annotations:{readOnlyHint:!0,...e.annotations},_meta:{...e._meta,"openai/extensions":{...je(e._meta?.["openai/extensions"]),"mentions/search":{}}}}}o(Zt,"prepareMentions");function Qt(e,t){let n=je(e._meta?.ui),r=e.visibility!==void 0?[e.visibility]:Array.isArray(n.visibility)?n.visibility:[];return{...t,ui:{...je(t?.ui),visibility:[...new Set([...r,"app"])]}}}o(Qt,"finalizeMentionsMeta");import{fromJsonSchema as io}from"@modelcontextprotocol/server";var ao=["get","put","post","delete","options","head","patch","trace"];function rn(e,t){let n=uo(t.spec,t),r=fo(n),s=n.length>0?bo(t):void 0;for(let[i,a]of n.entries()){let d=r[i];if(d===void 0||s===void 0)continue;let u=go(a);e.tool({name:d,description:mo(a),inputSchema:yo(t.spec,a,u)},async c=>Ro(a,c,t,u,s))}}o(rn,"registerOpenAPITools");function uo(e,t){let n=[];for(let[r,s]of Object.entries(e.paths??{})){let i=q(e,s);if(i===void 0||B(i))continue;let a=en(e,i.parameters);for(let d of ao){let u=i[d];if(u===void 0)continue;let c=q(e,u);if(c===void 0||B(c))continue;let l=en(e,c.parameters),p=c.requestBody===void 0?void 0:q(e,c.requestBody),y={method:d,path:r,operation:c,parameters:co(a,l),...p!==void 0&&!B(p)&&{requestBody:p}};lo(y,t)&&n.push(y)}}return n}o(uo,"collectOperations");function en(e,t){let n=[];for(let r of t??[]){let s=q(e,r);s!==void 0&&!B(s)&&n.push(s)}return n}o(en,"resolveParameters");function co(e,t){let n=new Map;for(let r of[...e,...t])n.set(`${r.in}:${r.name}`,r);return[...n.values()]}o(co,"mergeParameters");function lo(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=>po(e,n))}o(lo,"isIncluded");function po(e,t){if(t.method&&t.method.toLowerCase()!==e.method||t.operationId&&!tn(t.operationId,e.operation.operationId??"")||t.path&&!tn(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}o(po,"matchesExcludeRule");function tn(e,t){return typeof e=="string"?e===t:(e.lastIndex=0,e.test(t))}o(tn,"matchesPattern");function fo(e){let t=new Map;return e.map(n=>{let r=ho(n.operation.operationId??`${n.method}_${n.path.replace(/[{}]/g,"").replace(/\//g,"_")}`),s=t.get(r)??0;if(t.set(r,s+1),s===0)return r;let i=`_${s+1}`;return`${r.slice(0,64-i.length)}${i}`})}o(fo,"createToolNames");function mo(e){return[e.operation.summary,e.operation.description,`HTTP: ${e.method.toUpperCase()} ${e.path}`].filter(t=>!!t).join(`
|
|
5
5
|
|
|
6
|
-
`)}o(io,"createToolDescription");function ao(e){return e.trim().replace(/[^a-zA-Z0-9_-]+/g,"_").replace(/_+/g,"_").replace(/^_/,"").replace(/_$/,"").slice(0,64)||"openapi_tool"}o(ao,"slugifyToolName");function uo(e,t,n){let r={},s=[];for(let{parameter:u,inputName:c}of n.parameters){let l=Zt(e,u.schema??{});r[c]={...l,description:u.description??`${u.in} parameter`},(u.required||u.in==="path")&&s.push(c)}let i=en(t.requestBody);i!==void 0&&n.bodyInputName!==void 0&&(r[n.bodyInputName]=Zt(e,i),t.requestBody?.required&&s.push(n.bodyInputName));let a=po(e),d={type:"object",properties:r,additionalProperties:!1,...s.length>0&&{required:s},...a!==void 0&&{$defs:a}};return Qr(d)}o(uo,"createToolInputSchema");function co(e){let t=e.parameters.filter(a=>a.in!=="cookie"),n=en(e.requestBody)===void 0?void 0:"body",r=new Map;for(let a of t)r.set(a.name,(r.get(a.name)??0)+1);let s=new Set(n===void 0?[]:[n]);return{parameters:t.map(a=>{let u=(r.get(a.name)??0)>1||a.name===n?`${a.name}_${a.in}`:a.name;return{parameter:a,inputName:lo(u,s)}}),...n!==void 0&&{bodyInputName:n}}}o(co,"createInputBindings");function lo(e,t){let n=e,r=2;for(;t.has(n);)n=`${e}_${r}`,r+=1;return t.add(n),n}o(lo,"claimInputName");function po(e){let t=D(e.components?.schemas);if(t===void 0)return;let n={};for(let[r,s]of Object.entries(t))n[r]=V(e,s,new Set);return n}o(po,"createSchemaDefinitions");function Zt(e,t){let n=V(e,t,new Set);return D(n)??{}}o(Zt,"transformSchema");function V(e,t,n){if(Array.isArray(t))return t.map(d=>V(e,d,n));let r=D(t);if(r===void 0)return t;let s=typeof r.$ref=="string"?r.$ref:void 0,i={};for(let[d,u]of Object.entries(r))d!=="$ref"&&(d==="nullable"&&typeof u=="boolean"||(i[d]=V(e,u,n)));let a=i;if(s!==void 0){let d=fo(e,s);if(d!==void 0)a={$ref:d,...i};else if(!n.has(s)){let u=q(e,{$ref:s});if(u!==void 0){let c=new Set(n);c.add(s),a={...D(V(e,u,c))??{},...i}}}}return r.nullable===!0?{anyOf:[a,{type:"null"}]}:a}o(V,"transformSchemaNode");function fo(e,t){let n="#/components/schemas/";if(t.startsWith(n))return q(e,{$ref:t})===void 0?void 0:`#/$defs/${t.slice(n.length)}`}o(fo,"rewriteSchemaRef");function en(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}o(en,"getJsonRequestBodySchema");async function mo(e,t,n,r,s){let i=n.fetch??globalThis.fetch,a=ho(e,t,r.parameters,s),d=yo(r.parameters,t,n),u=r.bodyInputName,c=u===void 0||t[u]===void 0?void 0:JSON.stringify(t[u]);c!==void 0&&!Mo(d,"content-type")&&(d["content-type"]="application/json");let l=await i(a,{method:e.method.toUpperCase(),headers:d,...c!==void 0&&{body:c}}),p=l.headers.get("content-type")??"";if(!l.ok)return{content:[{type:"text",text:await l.text()}],isError:!0};if(p.includes("application/json")||p.includes("+json")){let y=await l.text();try{let h=JSON.parse(y);return{content:[{type:"text",text:JSON.stringify(h)}],structuredContent:h}}catch{return{content:[{type:"text",text:y}]}}}return{content:[{type:"text",text:await l.text()}]}}o(mo,"callOpenAPIOperation");function ho(e,t,n,r){let s=e.path.replace(/{([^}]+)}/g,(a,d)=>{let u=n.find(({parameter:c})=>c.in==="path"&&c.name===d);return encodeURIComponent(String(u===void 0?"":t[u.inputName]??""))}),i=new URL(s.replace(/^\/+/,""),To(r));for(let{parameter:a,inputName:d}of n){if(a.in!=="query")continue;let u=t[d];u==null||u===""||wo(i,a.name,u)}return i.toString()}o(ho,"buildUrl");function yo(e,t,n){let r={...n.headers??{}};for(let{parameter:s,inputName:i}of e){if(s.in!=="header")continue;let a=t[i];a==null||a===""||(r[s.name]=String(a))}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}o(yo,"buildHeaders");function go(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}o(go,"resolveBaseUrl");function wo(e,t,n){if(Array.isArray(n)){for(let r of n)r!=null&&r!==""&&e.searchParams.append(t,String(r));return}e.searchParams.set(t,String(n))}o(wo,"appendQueryParam");function To(e){return e.endsWith("/")?e:`${e}/`}o(To,"ensureTrailingSlash");function Mo(e,t){return Object.keys(e).some(n=>n.toLowerCase()===t)}o(Mo,"hasHeader");function B(e){let t=D(e);return t!==void 0&&typeof t.$ref=="string"}o(B,"isReferenceObject");function q(e,t){if(!B(t))return t;if(!t.$ref.startsWith("#/"))return;let n=t.$ref.slice(2).split("/").map(s=>s.replace(/~1/g,"/").replace(/~0/g,"~")),r=e;for(let s of n){let i=D(r);if(i===void 0||!(s in i))return;r=i[s]}return r}o(q,"resolveRef");function D(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:void 0}o(D,"readRecord");import{OAuthError as ua,OAuthErrorCode as ca,bearerAuthChallengeResponse as la,getOAuthProtectedResourceMetadataUrl as dn,oauthMetadataResponse as pa,requireBearerAuth as fa,verifyBearerToken as ma}from"@modelcontextprotocol/server";import{getOAuthProtectedResourceMetadataUrl as Di,oauthMetadataResponse as Co,requireBearerAuth as Ni}from"@modelcontextprotocol/server";function je(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}o(je,"isRecord");function N(e){let t=e.hostname.toLowerCase();return t==="localhost"||t.endsWith(".localhost")||t==="[::1]"||/^127(?:\.\d{1,3}){3}$/.test(t)}o(N,"isLocalhost");function W(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}o(W,"parseAbsoluteUrl");function oe(e,t){if(e.protocol!=="https:"&&!(e.protocol==="http:"&&N(e)))throw new Error(`${t} must use HTTPS, or HTTP for localhost`)}o(oe,"assertSecureHttpUrl");import{OAuthError as Ro,OAuthErrorCode as vo}from"@modelcontextprotocol/server";function E(e,t){let n=new Ro(vo.InvalidToken,e);return t!==void 0&&(n.cause=t),n}o(E,"invalidToken");function tn(e){let t=e.provider,n=He(e.basePath);if(t.resource!==void 0)return qe(t.resource,n);if(e.mcpUrl!==void 0)return qe(on(rn(e.mcpUrl,"MCP_URL"),n),n)}o(tn,"resolveConfiguredOAuthResource");function nn(e,t){let n=rn(e,"listen origin");if(!N(n))throw new Error("OAuth listen origin must be localhost or a loopback address");return qe(on(n,He(t)),t)}o(nn,"resolveLocalOAuthResource");function qe(e,t){let n=He(t),r=W(e,"OAuth resource");if(r.search!==""||r.hash!=="")throw new Error("OAuth resource must not include a query string or fragment");if(oe(r,"OAuth resource"),sn(r.pathname)!==n)throw new Error(`OAuth resource path must exactly match basePath (${n})`);return r.pathname=n,r}o(qe,"validateOAuthResource");function De(e,t){let n=Ne(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(s){let i=await r.verifyAccessToken(s);Eo(i),xo(i,n);let a;try{a=e.mapAuthInfo(i)}catch(d){throw E("Token identity mapping failed",d)}return So(a),{...i,scopes:[...i.scopes],extra:{...i.extra,...a}}}}}o(De,"wrapOAuthTokenVerifier");function xo(e,t){if(e.resource===void 0)throw E("Token verifier did not return a validated protected resource");if(bo(e.resource).href!==Ne(t).href)throw E("Token resource does not match the protected resource")}o(xo,"assertResourceBinding");function bo(e){if(!(e instanceof URL))throw E("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:"&&!N(t))throw E("Token resource must be an absolute HTTPS URL, or HTTP URL for localhost");return Ne(t)}o(bo,"parseTokenResource");function Ne(e){let t=new URL(e);return t.pathname=t.pathname==="/"?"/":t.pathname.replace(/\/+$/,""),t}o(Ne,"normalizeResourceUrl");function se(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}}}o(se,"getOAuthProviderOptions");function Eo(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 E("Token verifier returned invalid authentication information")}o(Eo,"assertVerifiedAuthInfo");function So(e){if(e===null||typeof e!="object"||!("user"in e)||e.user===void 0||!je(e.payload)||!Array.isArray(e.permissions)||!e.permissions.every(t=>typeof t=="string"))throw E("Token identity mapping must return user, payload, and string permissions")}o(So,"assertMappedExtra");function rn(e,t){let n=W(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}o(rn,"requireAbsoluteOrigin");function on(e,t){let n=new URL(e.origin);return n.pathname=t,n}o(on,"appendBasePath");function He(e){if(!e.startsWith("/")||e.includes("?")||e.includes("#"))throw new Error("basePath must be an absolute URL pathname");return sn(e)}o(He,"normalizeBasePath");function sn(e){if(e==="/")return"/";let t=e.length;for(;t>0&&e.charCodeAt(t-1)===47;)t--;return e.slice(0,t)}o(sn,"normalizePathname");function $e(e,t){let n=se(e);return async(r,s)=>{let i=Co(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 i!==void 0?i:s()}}o($e,"oauthMetadata");function an(e){return R(e).authInfo}o(an,"authInfoFromRequest");import{OAuthError as Wi}from"@modelcontextprotocol/server";import{createRemoteJWKSet as Ji,jwtVerify as Ki,errors as Gi}from"jose";function ie(e){return e.inputSchema??e.schema}o(ie,"resolveToolInputSchema");import{fromJsonSchema as Oo}from"@modelcontextprotocol/server";var un="openai/ui";function Ao(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}o(Ao,"record");function cn(e){let t=e.view?.entrypoints;if(!t?.length)return;let n=ie(e),r=n?Oo(n["~standard"].jsonSchema.input({target:"draft-2020-12"}))["~standard"].validate:void 0;for(let s of t){let i=s.type==="file"?s.extensions.map(a=>({file:{name:`file${a}`,resourceUri:"host-resource://opaque-handle"}})):[{}];if(s.type==="file"&&!r)throw new TypeError(`Tool "${e.name}" file entrypoint requires an inputSchema accepting { file: { name, resourceUri } }.`);for(let a of i){let d=r?.(a);if(d&&("then"in d||d.issues))throw new TypeError(`Tool "${e.name}" ${s.type} entrypoint launch arguments do not satisfy its inputSchema.`)}}}o(cn,"validateEntrypointInput");function ln(e){let t=e.view?.entrypoints;if(t===void 0)return e._meta;let n=e._meta?.[un];return{...e._meta,[un]:{...Ao(n)?n:{},entrypoints:t.map(r=>r.type==="file"?{type:r.type,extensions:[...r.extensions]}:{type:r.type})}}}o(ln,"buildEntrypointMeta");var Po="mcp_use_sdk_event",ko="https://eu.i.posthog.com/i/v0/e/",Io="phc_lyTtbYwvkdSbrcMQNPiKiiRWrrM1seyKIMjycSvItEI",Uo=/(^|_)(arguments?|args|body|command|headers?|location|message|organization|path|query|response|secret|subject|token|uri|url|user_agent)(_|$)/i,_o=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(" ")),pn;function Ve(){return pn??=crypto.randomUUID(),pn}o(Ve,"getRuntimeId");var fn=new Set,Fe=new Set,mn=new Map;function Be(e){return[...e].some(t=>{let n=t.charCodeAt(0);return n<32||n===127})}o(Be,"hasControl");function We(e){return typeof process>"u"?void 0:process.env?.[e]}o(We,"env");function hn(e){let t=We(e);return t!==void 0&&t.length>0&&t.length<=128&&!Be(t)?t:void 0}o(hn,"safeEnv");function Lo(){return typeof process>"u"||process.versions?.node===void 0?!1:!("Deno"in globalThis)}o(Lo,"canPersistTelemetryIdentity");function yn(){if(We("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}}o(yn,"disabled");function gn(){return yn()}o(gn,"isUsageDisabled");function jo(e){return Object.fromEntries(Object.entries(e).filter(([t,n])=>t.length>128||Be(t)||t.startsWith("$")||_o.has(t)||Uo.test(t)||n===void 0?!1:typeof n=="string"?n.length<=128&&!Be(n):typeof n=="boolean"||typeof n=="number"&&Number.isFinite(n)))}o(jo,"clean");async function qo(e){let t=hn("MCP_USE_TELEMETRY_PROJECT_ID");if(t!==void 0)return{id:t,stability:"project"};if(e===void 0||!Lo())return{id:Ve(),stability:"process"};let n=mn.get(e);if(n!==void 0)return n;let r=(async()=>{try{let s=await import("fs/promises"),i=`${e}/.mcp-use`,a=`${i}/usage.json`,d=o(async()=>{try{let l=JSON.parse(await s.readFile(a,"utf8"));if(typeof l=="object"&&l!==null&&"schemaVersion"in l&&l.schemaVersion===1&&"serverId"in l&&typeof l.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(l.serverId))return l.serverId}catch{}},"read"),u=await d();if(u!==void 0)return{id:u,stability:"server"};await s.mkdir(i,{recursive:!0,mode:448});let c=crypto.randomUUID();try{return await s.writeFile(a,`${JSON.stringify({schemaVersion:1,serverId:c})}
|
|
7
|
-
`,{flag:"wx",mode:384}),{id:c,stability:"server"}}catch{let l=await d();if(l!==void 0)return{id:l,stability:"server"}}}catch{}return{id:
|
|
6
|
+
`)}o(mo,"createToolDescription");function ho(e){return e.trim().replace(/[^a-zA-Z0-9_-]+/g,"_").replace(/_+/g,"_").replace(/^_/,"").replace(/_$/,"").slice(0,64)||"openapi_tool"}o(ho,"slugifyToolName");function yo(e,t,n){let r={},s=[];for(let{parameter:u,inputName:c}of n.parameters){let l=nn(e,u.schema??{});r[c]={...l,description:u.description??`${u.in} parameter`},(u.required||u.in==="path")&&s.push(c)}let i=on(t.requestBody);i!==void 0&&n.bodyInputName!==void 0&&(r[n.bodyInputName]=nn(e,i),t.requestBody?.required&&s.push(n.bodyInputName));let a=To(e),d={type:"object",properties:r,additionalProperties:!1,...s.length>0&&{required:s},...a!==void 0&&{$defs:a}};return io(d)}o(yo,"createToolInputSchema");function go(e){let t=e.parameters.filter(a=>a.in!=="cookie"),n=on(e.requestBody)===void 0?void 0:"body",r=new Map;for(let a of t)r.set(a.name,(r.get(a.name)??0)+1);let s=new Set(n===void 0?[]:[n]);return{parameters:t.map(a=>{let u=(r.get(a.name)??0)>1||a.name===n?`${a.name}_${a.in}`:a.name;return{parameter:a,inputName:wo(u,s)}}),...n!==void 0&&{bodyInputName:n}}}o(go,"createInputBindings");function wo(e,t){let n=e,r=2;for(;t.has(n);)n=`${e}_${r}`,r+=1;return t.add(n),n}o(wo,"claimInputName");function To(e){let t=N(e.components?.schemas);if(t===void 0)return;let n={};for(let[r,s]of Object.entries(t))n[r]=V(e,s,new Set);return n}o(To,"createSchemaDefinitions");function nn(e,t){let n=V(e,t,new Set);return N(n)??{}}o(nn,"transformSchema");function V(e,t,n){if(Array.isArray(t))return t.map(d=>V(e,d,n));let r=N(t);if(r===void 0)return t;let s=typeof r.$ref=="string"?r.$ref:void 0,i={};for(let[d,u]of Object.entries(r))d!=="$ref"&&(d==="nullable"&&typeof u=="boolean"||(i[d]=V(e,u,n)));let a=i;if(s!==void 0){let d=Mo(e,s);if(d!==void 0)a={$ref:d,...i};else if(!n.has(s)){let u=q(e,{$ref:s});if(u!==void 0){let c=new Set(n);c.add(s),a={...N(V(e,u,c))??{},...i}}}}return r.nullable===!0?{anyOf:[a,{type:"null"}]}:a}o(V,"transformSchemaNode");function Mo(e,t){let n="#/components/schemas/";if(t.startsWith(n))return q(e,{$ref:t})===void 0?void 0:`#/$defs/${t.slice(n.length)}`}o(Mo,"rewriteSchemaRef");function on(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}o(on,"getJsonRequestBodySchema");async function Ro(e,t,n,r,s){let i=n.fetch??globalThis.fetch,a=vo(e,t,r.parameters,s),d=xo(r.parameters,t,n),u=r.bodyInputName,c=u===void 0||t[u]===void 0?void 0:JSON.stringify(t[u]);c!==void 0&&!Co(d,"content-type")&&(d["content-type"]="application/json");let l=await i(a,{method:e.method.toUpperCase(),headers:d,...c!==void 0&&{body:c}}),p=l.headers.get("content-type")??"";if(!l.ok)return{content:[{type:"text",text:await l.text()}],isError:!0};if(p.includes("application/json")||p.includes("+json")){let y=await l.text();try{let h=JSON.parse(y);return{content:[{type:"text",text:JSON.stringify(h)}],structuredContent:h}}catch{return{content:[{type:"text",text:y}]}}}return{content:[{type:"text",text:await l.text()}]}}o(Ro,"callOpenAPIOperation");function vo(e,t,n,r){let s=e.path.replace(/{([^}]+)}/g,(a,d)=>{let u=n.find(({parameter:c})=>c.in==="path"&&c.name===d);return encodeURIComponent(String(u===void 0?"":t[u.inputName]??""))}),i=new URL(s.replace(/^\/+/,""),So(r));for(let{parameter:a,inputName:d}of n){if(a.in!=="query")continue;let u=t[d];u==null||u===""||Eo(i,a.name,u)}return i.toString()}o(vo,"buildUrl");function xo(e,t,n){let r={...n.headers??{}};for(let{parameter:s,inputName:i}of e){if(s.in!=="header")continue;let a=t[i];a==null||a===""||(r[s.name]=String(a))}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}o(xo,"buildHeaders");function bo(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}o(bo,"resolveBaseUrl");function Eo(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))}o(Eo,"appendQueryParam");function So(e){return e.endsWith("/")?e:`${e}/`}o(So,"ensureTrailingSlash");function Co(e,t){return Object.keys(e).some(n=>n.toLowerCase()===t)}o(Co,"hasHeader");function B(e){let t=N(e);return t!==void 0&&typeof t.$ref=="string"}o(B,"isReferenceObject");function q(e,t){if(!B(t))return t;if(!t.$ref.startsWith("#/"))return;let n=t.$ref.slice(2).split("/").map(s=>s.replace(/~1/g,"/").replace(/~0/g,"~")),r=e;for(let s of n){let i=N(r);if(i===void 0||!(s in i))return;r=i[s]}return r}o(q,"resolveRef");function N(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:void 0}o(N,"readRecord");import{OAuthError as Ma,OAuthErrorCode as Ra,bearerAuthChallengeResponse as va,getOAuthProtectedResourceMetadataUrl as pn,oauthMetadataResponse as xa,requireBearerAuth as ba,verifyBearerToken as Ea}from"@modelcontextprotocol/server";import{getOAuthProtectedResourceMetadataUrl as Gi,oauthMetadataResponse as _o,requireBearerAuth as Yi}from"@modelcontextprotocol/server";function qe(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}o(qe,"isRecord");function D(e){let t=e.hostname.toLowerCase();return t==="localhost"||t.endsWith(".localhost")||t==="[::1]"||/^127(?:\.\d{1,3}){3}$/.test(t)}o(D,"isLocalhost");function W(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}o(W,"parseAbsoluteUrl");function oe(e,t){if(e.protocol!=="https:"&&!(e.protocol==="http:"&&D(e)))throw new Error(`${t} must use HTTPS, or HTTP for localhost`)}o(oe,"assertSecureHttpUrl");import{OAuthError as Oo,OAuthErrorCode as Ao}from"@modelcontextprotocol/server";function E(e,t){let n=new Oo(Ao.InvalidToken,e);return t!==void 0&&(n.cause=t),n}o(E,"invalidToken");function sn(e){let t=e.provider,n=$e(e.basePath);if(t.resource!==void 0)return Ne(t.resource,n);if(e.mcpUrl!==void 0)return Ne(un(dn(e.mcpUrl,"MCP_URL"),n),n)}o(sn,"resolveConfiguredOAuthResource");function an(e,t){let n=dn(e,"listen origin");if(!D(n))throw new Error("OAuth listen origin must be localhost or a loopback address");return Ne(un(n,$e(t)),t)}o(an,"resolveLocalOAuthResource");function Ne(e,t){let n=$e(t),r=W(e,"OAuth resource");if(r.search!==""||r.hash!=="")throw new Error("OAuth resource must not include a query string or fragment");if(oe(r,"OAuth resource"),cn(r.pathname)!==n)throw new Error(`OAuth resource path must exactly match basePath (${n})`);return r.pathname=n,r}o(Ne,"validateOAuthResource");function De(e,t){let n=He(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(s){let i=await r.verifyAccessToken(s);Io(i),Po(i,n);let a;try{a=e.mapAuthInfo(i)}catch(d){throw E("Token identity mapping failed",d)}return Uo(a),{...i,scopes:[...i.scopes],extra:{...i.extra,...a}}}}}o(De,"wrapOAuthTokenVerifier");function Po(e,t){if(e.resource===void 0)throw E("Token verifier did not return a validated protected resource");if(ko(e.resource).href!==He(t).href)throw E("Token resource does not match the protected resource")}o(Po,"assertResourceBinding");function ko(e){if(!(e instanceof URL))throw E("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:"&&!D(t))throw E("Token resource must be an absolute HTTPS URL, or HTTP URL for localhost");return He(t)}o(ko,"parseTokenResource");function He(e){let t=new URL(e);return t.pathname=t.pathname==="/"?"/":t.pathname.replace(/\/+$/,""),t}o(He,"normalizeResourceUrl");function se(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}}}o(se,"getOAuthProviderOptions");function Io(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 E("Token verifier returned invalid authentication information")}o(Io,"assertVerifiedAuthInfo");function Uo(e){if(e===null||typeof e!="object"||!("user"in e)||e.user===void 0||!qe(e.payload)||!Array.isArray(e.permissions)||!e.permissions.every(t=>typeof t=="string"))throw E("Token identity mapping must return user, payload, and string permissions")}o(Uo,"assertMappedExtra");function dn(e,t){let n=W(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}o(dn,"requireAbsoluteOrigin");function un(e,t){let n=new URL(e.origin);return n.pathname=t,n}o(un,"appendBasePath");function $e(e){if(!e.startsWith("/")||e.includes("?")||e.includes("#"))throw new Error("basePath must be an absolute URL pathname");return cn(e)}o($e,"normalizeBasePath");function cn(e){if(e==="/")return"/";let t=e.length;for(;t>0&&e.charCodeAt(t-1)===47;)t--;return e.slice(0,t)}o(cn,"normalizePathname");function Fe(e,t){let n=se(e);return async(r,s)=>{let i=_o(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 i!==void 0?i:s()}}o(Fe,"oauthMetadata");function ln(e){return R(e).authInfo}o(ln,"authInfoFromRequest");import{OAuthError as na}from"@modelcontextprotocol/server";import{createRemoteJWKSet as oa,jwtVerify as sa,errors as ia}from"jose";function ie(e){return e.inputSchema??e.schema}o(ie,"resolveToolInputSchema");import{fromJsonSchema as Lo}from"@modelcontextprotocol/server";var fn="openai/ui";function jo(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}o(jo,"record");function mn(e){let t=e.view?.entrypoints;if(!t?.length)return;let n=ie(e),r=n?Lo(n["~standard"].jsonSchema.input({target:"draft-2020-12"}))["~standard"].validate:void 0;for(let s of t){let i=s.type==="file"?s.extensions.map(a=>({file:{name:`file${a}`,resourceUri:"host-resource://opaque-handle"}})):[{}];if(s.type==="file"&&!r)throw new TypeError(`Tool "${e.name}" file entrypoint requires an inputSchema accepting { file: { name, resourceUri } }.`);for(let a of i){let d=r?.(a);if(d&&("then"in d||d.issues))throw new TypeError(`Tool "${e.name}" ${s.type} entrypoint launch arguments do not satisfy its inputSchema.`)}}}o(mn,"validateEntrypointInput");function hn(e){let t=e.view?.entrypoints;if(t===void 0)return e._meta;let n=e._meta?.[fn];return{...e._meta,[fn]:{...jo(n)?n:{},entrypoints:t.map(r=>r.type==="file"?{type:r.type,extensions:[...r.extensions]}:{type:r.type})}}}o(hn,"buildEntrypointMeta");var qo="mcp_use_sdk_event",No="https://eu.i.posthog.com/i/v0/e/",Do="phc_lyTtbYwvkdSbrcMQNPiKiiRWrrM1seyKIMjycSvItEI",Ho=/(^|_)(arguments?|args|body|command|headers?|location|message|organization|path|query|response|secret|subject|token|uri|url|user_agent)(_|$)/i,$o=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(" ")),yn;function Be(){return yn??=crypto.randomUUID(),yn}o(Be,"getRuntimeId");var gn=new Set,Ve=new Set,wn=new Map;function We(e){return[...e].some(t=>{let n=t.charCodeAt(0);return n<32||n===127})}o(We,"hasControl");function ze(e){return typeof process>"u"?void 0:process.env?.[e]}o(ze,"env");function Tn(e){let t=ze(e);return t!==void 0&&t.length>0&&t.length<=128&&!We(t)?t:void 0}o(Tn,"safeEnv");function Fo(){return typeof process>"u"||process.versions?.node===void 0?!1:!("Deno"in globalThis)}o(Fo,"canPersistTelemetryIdentity");function Mn(){if(ze("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}}o(Mn,"disabled");function Rn(){return Mn()}o(Rn,"isUsageDisabled");function Vo(e){return Object.fromEntries(Object.entries(e).filter(([t,n])=>t.length>128||We(t)||t.startsWith("$")||$o.has(t)||Ho.test(t)||n===void 0?!1:typeof n=="string"?n.length<=128&&!We(n):typeof n=="boolean"||typeof n=="number"&&Number.isFinite(n)))}o(Vo,"clean");async function Bo(e){let t=Tn("MCP_USE_TELEMETRY_PROJECT_ID");if(t!==void 0)return{id:t,stability:"project"};if(e===void 0||!Fo())return{id:Be(),stability:"process"};let n=wn.get(e);if(n!==void 0)return n;let r=(async()=>{try{let s=await import("fs/promises"),i=`${e}/.mcp-use`,a=`${i}/usage.json`,d=o(async()=>{try{let l=JSON.parse(await s.readFile(a,"utf8"));if(typeof l=="object"&&l!==null&&"schemaVersion"in l&&l.schemaVersion===1&&"serverId"in l&&typeof l.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(l.serverId))return l.serverId}catch{}},"read"),u=await d();if(u!==void 0)return{id:u,stability:"server"};await s.mkdir(i,{recursive:!0,mode:448});let c=crypto.randomUUID();try{return await s.writeFile(a,`${JSON.stringify({schemaVersion:1,serverId:c})}
|
|
7
|
+
`,{flag:"wx",mode:384}),{id:c,stability:"server"}}catch{let l=await d();if(l!==void 0)return{id:l,stability:"server"}}}catch{}return{id:Be(),stability:"process"}})();return wn.set(e,r),r}o(Bo,"identity");function Wo(e,t,n,r,s){let i=Tn("MCP_USE_TELEMETRY_VALIDATION_ID");if(Mn()||ze("NODE_ENV")==="test"&&i===void 0||Ve.size>=16)return;if(r.onceKey!==void 0){if(gn.has(r.onceKey))return;gn.add(r.onceKey)}let a=Math.max(0,Math.min(1,r.sampleRate??1));if(i===void 0&&Math.random()>=a)return;let d=(async()=>{try{let u=await s(),c=JSON.stringify({api_key:Do,event:qo,properties:{...Vo(n),feature:e,action:t,sdk_generation:"v2",telemetry_schema_version:2,sdk_package:"mcp-use",sdk_version:"2.9.0",server_id:u.id,runtime_id:Be(),identity_stability:u.stability,distinct_id:u.id,sample_rate:i===void 0?a:1,$process_person_profile:!1,$geoip_disable:!0,...i!==void 0&&{is_validation:!0,validation_run_id:i}}});await fetch(No,{method:"POST",headers:{"content-type":"application/json"},keepalive:!0,body:c})}catch{return}})();Ve.add(d),d.then(()=>Ve.delete(d))}o(Wo,"capture");function ae(e,t,n={},r={}){Wo(e,t,n,r,()=>Bo(r.serverRoot))}o(ae,"recordUsage");import{INVALID_PARAMS as vn,ProtocolError as xn}from"@modelcontextprotocol/server";function Ke(e){return{"~standard":{version:1,vendor:"mcp-use",validate(t){try{return{value:e(t)}}catch(n){return{issues:[{message:n instanceof Error?n.message:String(n)}]}}}}}}o(Ke,"schema");function Ge(e){if(typeof e!="object"||e===null||Array.isArray(e))throw new TypeError("params must be an object");return e}o(Ge,"object");var zo=Ke(e=>{let n=Ge(e).cursor;if(n!==void 0&&typeof n!="string")throw new TypeError("cursor must be a string");return n===void 0?{}:{cursor:n}}),bn=Ke(e=>{let t=Ge(e);if(typeof t.uri!="string")throw new TypeError("uri must be a string");if(t.cursor!==void 0&&typeof t.cursor!="string")throw new TypeError("cursor must be a string");return{uri:t.uri,...typeof t.cursor=="string"&&{cursor:t.cursor}}}),Je=Ke(e=>Ge(e));function Jo(e){try{return decodeURIComponent(e)}catch{return e}}o(Jo,"decodePathSegment");function En(e,t){let n=new Map(t.skills.map(r=>[r.uri,r]));for(let r of t.resources)e.registerResource(r.uri,r.uri,{title:r.name,mimeType:r.mimeType},async()=>({contents:[{uri:r.uri,mimeType:r.mimeType,...r.text!==void 0?{text:r.text}:{blob:r.blob}}]}));e.server.setRequestHandler("skills/list",{params:zo,result:Je},async()=>({skills:t.skills})),e.server.setRequestHandler("skills/get",{params:bn,result:Je},async({uri:r})=>{let s=n.get(r);if(s===void 0)throw new xn(vn,`Unknown skill: ${r}`);return{skill:s}}),e.server.setRequestHandler("resources/directory/read",{params:bn,result:Je},async({uri:r})=>{let s=r.replace(/\/$/,""),i=new Set(t.directories.map(u=>u.uri)),a=`${s}/`,d=new Map;for(let u of t.resources){if(!u.uri.startsWith(a))continue;let c=u.uri.slice(a.length),[l]=c.split("/");if(l===void 0||l==="")continue;let p=`${s}/${l}`;d.set(p,{uri:p,name:Jo(l),mimeType:c.includes("/")?"inode/directory":u.mimeType})}for(let u of t.directories){if(!u.uri.startsWith(a))continue;let c=u.uri.slice(a.length);c===""||c.includes("/")||d.set(u.uri,{uri:u.uri,name:u.name,mimeType:"inode/directory"})}if(!i.has(s))throw new xn(vn,`Unknown skill directory: ${r}`);return{resources:[...d.values()].sort((u,c)=>u.uri.localeCompare(c.uri))}})}o(En,"registerSkillsRuntime");var Ye="io.modelcontextprotocol/skills",z=Symbol.for("mcp-use.registerSkills");var J=Symbol("mcp-use/registerViews");function Ko(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}`}o(Ko,"resolveAssetUrl");function Go(e,t){return`${_(e,`_mcp-use/views/${t}`)}/`}o(Go,"viewAssetsBasePath");function Xe(e,t,n,r){return e.startsWith("http://")||e.startsWith("https://")||e.startsWith("data:")?e:e.startsWith("/")?Ko(e,t):`${t}${Go(n,r)}${e.replace(/^\/+/,"")}`}o(Xe,"resolveExternalAssetUrl");function Yo(e,t){return`${e}${_(t,"_mcp-use/public")}/`}o(Yo,"resolvePublicBase");function Sn(e){return e.replaceAll(/<\/script/gi,"<\\/script").replaceAll("<!--","\\x3C!--")}o(Sn,"escapeInlineScript");function Xo(e){return e.replaceAll(/<\/style/gi,"<\\/style")}o(Xo,"escapeInlineStyle");function Ze(e){return e.replaceAll("&","&").replaceAll('"',""").replaceAll("<","<").replaceAll(">",">")}o(Ze,"escapeHtml");var Cn=`<style>
|
|
8
8
|
html,body,#root{background:transparent}
|
|
9
9
|
html,body{margin:0}
|
|
10
10
|
#root[data-mcp-use-loading]{display:flex;min-height:100vh;align-items:center;justify-content:center;flex-direction:column;gap:10px;color:rgba(127,127,127,.9)}
|
|
@@ -12,32 +12,32 @@ html,body{margin:0}
|
|
|
12
12
|
#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}
|
|
13
13
|
@keyframes mcp-use-view-spin{to{transform:rotate(360deg)}}
|
|
14
14
|
@media (prefers-reduced-motion:reduce){#root[data-mcp-use-loading]::before{animation-duration:1.4s}}
|
|
15
|
-
</style>`;function
|
|
15
|
+
</style>`;function Qe(e,t,n,r){let s={publicBase:Yo(t,n)},i=`<script>globalThis.__mcpUseViewConfig=${JSON.stringify(s)};</script>`;if(e.kind==="inline"){let l=e.css.length>0?`<style>${Xo(e.css)}</style>`:"",p=`<script type="module">${Sn(e.js)}</script>`;return`<!doctype html>
|
|
16
16
|
<html>
|
|
17
17
|
<head>
|
|
18
18
|
<meta charset="utf-8">
|
|
19
19
|
${i}
|
|
20
|
-
${
|
|
20
|
+
${Cn}
|
|
21
21
|
${l}
|
|
22
22
|
</head>
|
|
23
23
|
<body>
|
|
24
24
|
<div id="root" data-mcp-use-loading></div>
|
|
25
25
|
${p}
|
|
26
26
|
</body>
|
|
27
|
-
</html>`}if(r===void 0)throw new Error("viewName is required when synthesizing an external view document.");let a=e.css.map(l=>`<link rel="stylesheet" href="${Xe(
|
|
28
|
-
`),d=(e.scripts??[]).map(l=>`<script type="module" src="${Xe(
|
|
29
|
-
`),u=e.entry.startsWith("/")&&(e.scripts??[]).some(l=>l.endsWith("/@vite/client"))?`<script type="importmap">${
|
|
27
|
+
</html>`}if(r===void 0)throw new Error("viewName is required when synthesizing an external view document.");let a=e.css.map(l=>`<link rel="stylesheet" href="${Ze(Xe(l,t,n,r))}">`).join(`
|
|
28
|
+
`),d=(e.scripts??[]).map(l=>`<script type="module" src="${Ze(Xe(l,t,n,r))}"></script>`).join(`
|
|
29
|
+
`),u=e.entry.startsWith("/")&&(e.scripts??[]).some(l=>l.endsWith("/@vite/client"))?`<script type="importmap">${Sn(JSON.stringify({imports:{"/":`${t.replace(/\/+$/,"")}/`}}))}</script>`:"",c=Xe(e.entry,t,n,r);return`<!doctype html>
|
|
30
30
|
<html>
|
|
31
31
|
<head>
|
|
32
32
|
<meta charset="utf-8">
|
|
33
33
|
${i}
|
|
34
34
|
${u}
|
|
35
|
-
${
|
|
35
|
+
${Cn}
|
|
36
36
|
${a}
|
|
37
37
|
</head>
|
|
38
38
|
<body>
|
|
39
39
|
<div id="root" data-mcp-use-loading></div>
|
|
40
40
|
${d}
|
|
41
|
-
<script type="module" src="${
|
|
41
|
+
<script type="module" src="${Ze(c)}"></script>
|
|
42
42
|
</body>
|
|
43
|
-
</html>`}o(Ze,"synthesizeViewDocument");var Wo=".mcp-use/build/views/public",zo="public",Jo=".mcp-use/build/views",bn=new WeakMap;function En(e,t,n,r){let s;try{s=decodeURIComponent(t)}catch{return new Response("Not Found",{status:404})}if(s.includes("\\")||s.split("/").includes(".."))return new Response("Not Found",{status:404});let i=Object.hasOwn(e,s)?e[s]:void 0;if(i===void 0)return new Response("Not Found",{status:404});let a=null;return n.method!=="HEAD"&&(a=bn.get(i)??null,a===null&&(a=Uint8Array.from(atob(i.body),d=>d.charCodeAt(0)),bn.set(i,a))),new Response(a,{headers:{"Content-Type":i.contentType,"Cache-Control":"public, max-age=0, must-revalidate",...r!==!0&&{"Access-Control-Allow-Origin":"*"}}})}o(En,"serveEmbeddedAsset");function Qe(e,t,n){if(t.size===0)return;let r=_(e,"_mcp-use/views"),s=n?.projectRoot??process.cwd();return async i=>{if(i.method!=="GET"&&i.method!=="HEAD")return new Response("Method Not Allowed",{status:405});if(!X(i,r))return new Response("Not Found",{status:404});let d=Y(i).slice(r.length+1),u=d.indexOf("/");if(u<=0||u===d.length-1)return new Response("Not Found",{status:404});let c=d.slice(0,u),l=d.slice(u+1),p=t.get(c);if(p===void 0||p.kind!=="external")return new Response("Not Found",{status:404});if(n?.assets!==void 0)return En(n.assets,d,i,n.deferCors);let[{join:y},{resolvePublicFilePath:h,servePublicFile:m}]=await Promise.all([import("path"),import("./public-route-AVKCGJDQ.js")]),f=y(s,Jo,c),g=await h(f,l);return g===null?new Response("Not Found",{status:404}):await m(g,{...n?.deferCors===!0&&{deferCors:!0},...i.method==="HEAD"&&{head:!0}})}}o(Qe,"createViewAssetsHandler");function et(e,t,n){if(t.size===0&&n?.enabled!==!0)return;let r=_(e,"_mcp-use/public"),s=n?.dev===!0?zo:Wo,i=n?.projectRoot??process.cwd();return async a=>{if(a.method!=="GET"&&a.method!=="HEAD")return new Response("Method Not Allowed",{status:405});if(!X(a,r))return new Response("Not Found",{status:404});let u=Y(a).slice(r.length+1),c;try{c=decodeURIComponent(u)}catch{return new Response("Not Found",{status:404})}if(c.length===0)return new Response("Not Found",{status:404});if(n?.assets!==void 0)return En(n.assets,`public/${u}`,a,n.deferCors);let[{join:l},{resolvePublicFilePath:p,servePublicFile:y}]=await Promise.all([import("path"),import("./public-route-AVKCGJDQ.js")]),h=l(i,s),m=await p(h,c);return m===null?new Response("Not Found",{status:404}):await y(m,{...n?.deferCors===!0&&{deferCors:!0},...a.method==="HEAD"&&{head:!0}})}}o(et,"createViewPublicHandler");var Ko={connectDomains:"CSP_CONNECT_DOMAINS",resourceDomains:"CSP_RESOURCE_DOMAINS",frameDomains:"CSP_FRAME_DOMAINS",baseUriDomains:"CSP_BASE_URI_DOMAINS"};function Go(e){return e===void 0||e.trim()===""?[]:e.split(",").map(t=>t.trim()).filter(t=>t.length>0)}o(Go,"parseDomainList");function Sn(e){if(typeof process>"u")return;let t=process.env[e];if(!(t===void 0||t.trim()===""))return Go(t)}o(Sn,"readEnvDomains");function Yo(){return Sn("CSP_URLS")??[]}o(Yo,"readCspUrlsShortcut");function de(e){let t=Sn(Ko[e]);return t!==void 0?t:Yo()}o(de,"readEnvDomainsForCategory");function K(...e){let t=new Set,n=[];for(let r of e)for(let s of r)t.has(s)||(t.add(s),n.push(s));return n}o(K,"mergeDomainLists");function Xo(e){return e.startsWith("https://")?`wss://${e.slice(8)}`:e.startsWith("http://")?`ws://${e.slice(7)}`:e}o(Xo,"toWebSocketOrigin");function Cn(e,t){let n=e?.csp,r=[];t.serverOrigin!==""&&(r.push(t.serverOrigin),t.hmrWs===!0&&r.push(Xo(t.serverOrigin)));let s=[],i=t.explicitAssetsBase?t.assetsOrigin:t.serverOrigin;i!==""&&s.push(i);let a=K(n?.connectDomains??[],de("connectDomains"),r),d=K(n?.resourceDomains??[],de("resourceDomains"),s),u=K(n?.frameDomains??[],de("frameDomains")),c=K(n?.baseUriDomains??[],de("baseUriDomains")),l=K(n?.scriptDirectives??[],t.hmrWs===!0?["'unsafe-eval'"]:[]);return{...n,connectDomains:a,resourceDomains:d,frameDomains:u,baseUriDomains:c,...l.length>0?{scriptDirectives:l}:{}}}o(Cn,"buildMergedResourceCsp");function tt(e,t,n){if(e===void 0&&t===void 0&&n===void 0)return;let r={...n},s=n?.["ui"],i=typeof s=="object"&&s!==null&&!Array.isArray(s),a=i?{...s}:{};if(e!==void 0){let d=k(e);a.resourceUri=d,r[Q]=d}else delete a.resourceUri,delete r[Q];return t!==void 0?a.visibility=[t]:delete a.visibility,(e!==void 0||t!==void 0||i)&&(r["ui"]=a),r}o(tt,"buildToolUiMeta");function nt(e){let t=k(e);return{ui:{resourceUri:t},[Q]:t}}o(nt,"buildToolResultUiMeta");function Zo(e){let t=e?.request,n=e?.serverOrigin??(t!==void 0?ut(t):""),r=e?.assetsBase??(t!==void 0?O(t):n);return{serverOrigin:n,assetsOrigin:ct(r),explicitAssetsBase:lt(),...e?.hmrWs===!0?{hmrWs:!0}:{}}}o(Zo,"resolveCspOptions");function ue(e,t){let r={csp:Cn(e,Zo(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,...e?.displayModes!==void 0&&{"openai/ui":{availableDisplayModes:e.displayModes.filter(s=>s==="inline"||s==="fullscreen"),...e.preferredDisplayMode!==void 0&&{preferredDisplayMode:e.preferredDisplayMode}}}}}o(ue,"buildResourceUiMeta");function rt(e,t,n,r){return{mimeType:Z,...n?.description!==void 0&&{description:n.description},_meta:ue(n,r)}}o(rt,"viewResourceConfig");var On=".claudemcpcontent.com",Qo=32;function es(e){let t=e?.name;return typeof t=="string"&&t.toLowerCase().includes("claude")}o(es,"isClaudeClient");async function ts(e){if(e.endsWith(On))return e;let t=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(e));return`${Array.from(new Uint8Array(t),r=>r.toString(16).padStart(2,"0")).join("").slice(0,Qo)}${On}`}o(ts,"computeClaudeResourceDomain");async function ot(e,t,n){let r=typeof t?.name=="string"||typeof n!="string"||n.trim().length===0?t:{...t,name:n.trim()};if(!es(r))return e;let s=e["ui"];if(typeof s!="object"||s===null||Array.isArray(s))return e;let i=s.domain;return typeof i!="string"||i.length===0?e:{...e,ui:{...s,domain:await ts(i)}}}o(ot,"applyClaudeResourceDomain");function H(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:void 0}o(H,"record");function st(e,t){if(typeof e!="string")return t;let n=e.trim();return n.length>0&&n.length<=64&&![...n].some(r=>{let s=r.charCodeAt(0);return s<32||s===127})?n:t}o(st,"productId");function In(e){if(!_n(e))return;let t=H(e.params);if(e.method==="initialize"){let i=H(t?.clientInfo),a=H(t?.capabilities)??{};return Un(i,a,t?.protocolVersion,"legacy")}let n=H(t?._meta),r=H(n?.[is]),s=H(n?.[ss]);if(!(r===void 0||s===void 0))return Un(r,s,n?.[as],"modern")}o(In,"clientUsageFromBody");function Un(e,t,n,r){let s=t;return{client_name:st(e?.name,"other"),client_version:st(e?.version,"unknown"),protocol_era:r,protocol_version:st(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:ee(s),capability_count:Object.keys(t).length}}o(Un,"clientUsage");function us(e,t){e.use("*",async(n,r)=>{let s=await t(n.req.raw,async()=>(await r(),n.res));return n.res=s,s})}o(us,"registerFetchMiddleware");var it=class e{static{o(this,"MCPServer")}#e;#N;#o;#t=new Map;#s=new Map;#E=new Map;#a=new Map;#d=new Map;#r;#g;#k=!1;#H;#l=new Map;#w=!1;#T;#p=!1;#u=process.cwd();#I;#$;#f;#S;#M;#C;#O=!1;#F=!1;#U;#V=!1;#_;#B=!1;#R=[];#m=[];#W;#v=new Set;#h=new Set;#A=new Set;#P=new Set;#z=0;#L=0;#J=0;#K=0;#G=0;#Y=0;#X=[];#j=new Set;#Z=!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"});Qt(n,t);for(let r of n.#t.keys())n.#v.add(r);return n}constructor(t){if(vt(t),this.#e=t,this.#o=Mt(t),this.app=new kn,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,s)=>(await this.#y(),this.#c("handler"),this.#$.fetch(n,r,s)),t.oauth!==void 0){let n=typeof process>"u"?void 0:process.env.MCP_URL,r=tn({provider:t.oauth,basePath:this.#i(),...n!==void 0&&{mcpUrl:n}});this.#C=r,this.#O=r!==void 0,this.#F=r===void 0}}get basePath(){return this.#i()}get host(){return this.#e.host}get port(){return this.#e.port}get branding(){return this.#o}getHandler(){return this.fetch}tool(t,n){if(this.#n("tool",t.name),this.#r!==void 0&&[this.#r.capability.readTool,this.#r.capability.updateTool].includes(t.name))throw new Error(`Tool "${t.name}" is reserved for settings`);let r=this.#ne(t);return cn(t),this.#ce(t),this.#v.delete(t.name),this.#h.delete(t.name),this.#t.set(t.name,{definition:t,callback:n,schemes:r}),Object.freeze({name:t.name})}settings(t){if(this.#n("settings",t.readTool??"settings.read"),this.#r!==void 0)throw new Error("Settings are already registered on this server");let n=Jt(t);for(let i of[n.capability.readTool,n.capability.updateTool])if(this.#t.has(i))throw new Error(`Settings tool "${i}" is already registered`);let r=t.read,s=t.update;this.tool(n.readDefinition,async(i,a)=>({content:[],structuredContent:{schema:n.schema,...n.layout!==void 0&&{layout:n.layout},values:await r(a)}})),this.tool(n.updateDefinition,async({set:i},a)=>({content:[],structuredContent:{values:await s(i,a)}})),this.#r=n}[J](t,n){if(this.#w)throw new Error("Cannot prime views: the views registry is already primed on this server instance.");this.#n("views","manifest");for(let[r,s]of Object.entries(t))try{ge(s.viewConfig)}catch(i){throw new Error(`View "${r}" has an invalid viewConfig: ${i instanceof Error?i.message:String(i)}`,{cause:i})}this.#p=n?.dev===!0,this.#T=n?.assets,n?.projectRoot!==void 0&&(this.#u=n.projectRoot);for(let[r,s]of Object.entries(t))this.#d.set(r,s);this.#w=!0}__primeViews(t,n){this[J](t,n)}[z](t){this.#n("skills","snapshot"),this.#g=t,this.#k=!0}__primeSkills(t){this[z](t)}__skillsConfig(){return this.#e.skills}async#oe(t,n){let{discoverConfiguredSkills:r}=await import("#mcp-use-skills-loader"),s=r(this.#e.skills,t,n);return this[z](s),s}resource(t,n){this.#n("resource",t.name);let r=this.#s.get(t.name);return r!==void 0&&this.#A.delete(r.definition.uri),this.#s.set(t.name,{definition:t,callback:n}),this}resourceTemplate(t,n){this.#n("resourceTemplate",t.name);let r=t.complete===void 0?void 0:Gt(t.complete);return this.#E.set(t.name,{definition:t,...r!==void 0&&{complete:r},callback:n}),this}prompt(t,n){return this.#n("prompt",t.name),this.#P.delete(t.name),this.#a.set(t.name,{definition:t,callback:n}),this}async proxy(t){this.#q("proxy()");let n=(async()=>{let{isProxyConnection:r,mountProxyConnection:s,mountProxyServers:i}=await import("./mcp-proxy-YSI2UFBY.js");if(r(t)){this.#L+=1,await s(this.#ee(),t);return}this.#L+=Object.keys(t).length,await i(this.#ee(),t)})();this.#j.add(n);try{await n}finally{this.#j.delete(n)}}use(t,...n){if(typeof t=="string"&&t.startsWith("mcp:")){this.#n("middleware",t);let s=n[0];return this.#R.push(Ce(t,s)),this}return this.app.use.call(this.app,t,...n),this.#z+=typeof t=="function"?1:n.length,this}on(t,n){return this.#n("event listener",t),this.#m.push(Oe(t,n)),this}__setEventBus(t){this.#n("event bus","shared"),this.#S=t}__setRequestLogPrefix(t){this.#n("request log prefix","development"),this.#N=t}__mount(){if(!this.#k)throw new Error("Cannot mount before skills discovery. CLI tooling must call __primeSkills first.");this.#c("handler")}async notifyToolsChanged(){await this.#y(),await this.#c("handler").handler.notify.toolsChanged()}async notifyPromptsChanged(){await this.#y(),await this.#c("handler").handler.notify.promptsChanged()}async notifyResourcesChanged(){await this.#y(),await this.#c("handler").handler.notify.resourcesChanged()}async notifyResourceUpdated(t){await this.#y(),await this.#c("handler").handler.notify.resourceUpdated(t)}async listen(t=void 0,n={}){this.#q("listen()"),await this.#y();let r=xt(n.host,this.#e.host),s=bt(t,this.#e.port);return this.#ie(r),new Promise((i,a)=>{let d,u,c=new Promise((m,f)=>{d=m,u=f});c.catch(()=>{});let l=!1,p=o(m=>{l||(l=!0,a(m)),u?.(m),new Promise(f=>h.close(()=>f())).catch(()=>{}).finally(()=>{this.#M===h&&(this.#M=void 0)})},"rejectAndClose"),y=St({fetch:o(async m=>(await c)(m),"fetch")}),h=ds((m,f)=>{y(m,f)});h.once("error",p),h.listen(s,r,()=>{try{let m=h.address(),f=typeof m=="object"&&m!==null?m.port:s,{fetch:g}=this.#c("listen",f,r);d?.(g),l||(l=!0,i({port:f,url:`http://localhost:${f}${this.#i()}`}))}catch(m){p(m)}}),this.#M=h})}async close(){this.#Z=!0,await Promise.allSettled([...this.#j]);let t=[],n=this.#X.splice(0),r=await Promise.allSettled(n.map(i=>i.close()));for(let i of r)i.status==="rejected"&&t.push(i.reason);try{await this.#f?.close()}catch(i){t.push(i)}let s=this.#M;if(s!==void 0)try{await new Promise((i,a)=>{s.close(d=>d?a(d):i())}),this.#M=void 0}catch(i){t.push(i)}if(t.length>0)throw new AggregateError(t,"Failed to close MCP server cleanly")}#q(t){if(this.#Z)throw t!==void 0?new Error(`Cannot call ${t} after the server has closed.`):new Error("Cannot use the server after it has closed.")}#i(){return this.#e.basePath??"/mcp"}#se(t,n,r){if(this.#e.oauth===void 0)return;if(this.#O)return this.#C;let s=r??this.#e.host??"127.0.0.1",i=t==="listen"&&n!==void 0&&["127.0.0.1","localhost","::1"].includes(s);if(this.#F&&i)return this.#C=nn(`http://localhost:${n}`,this.#i()),this.#O=!0,this.#C;throw new Error("OAuth requires an explicit resource or MCP_URL when using server.fetch or listening on a non-local host")}#ie(t){if(this.#e.oauth!==void 0&&!["127.0.0.1","localhost","::1"].includes(t)&&!this.#O)throw new Error("OAuth listen() on a public or wildcard host requires an explicit provider resource or valid MCP_URL.")}#n(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.`)}#ae(){ae("server","configured",{tools_total:this.#t.size,tools_local:this.#t.size-this.#v.size-this.#h.size,tools_openapi:this.#v.size,tools_proxied:this.#h.size,resources:this.#s.size,resource_templates:this.#E.size,prompts:this.#a.size,views:this.#d.size,proxy_servers_configured:this.#L,proxy_servers_connected:this.#J,proxy_tools_discovered:this.#K,proxy_resources_discovered:this.#G,proxy_prompts_discovered:this.#Y,proxy_tools_mounted:this.#h.size,proxy_resources_mounted:this.#A.size,proxy_prompts_mounted:this.#P.size,http_middleware:this.#z,mcp_middleware:this.#R.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.#Q()}:server`,serverRoot:this.#u})}#de(t){let n=In(t);n!==void 0&&ae("client","observed",{...n},{onceKey:`${this.#Q()}:client:${JSON.stringify(n)}`,serverRoot:this.#u})}#Q(){return this.#W??=crypto.randomUUID(),this.#W}#ue(t,n){let r=this.#e.oauth?.setup;if(r===void 0||this.#V)return;if(this.#_!==void 0)throw this.#_.error;let s=!0,i=o(d=>{if(!s)throw new Error(`[mcp-use] OAuthProviderHost.${d}() called after the provider's setup hook returned; call it from setup().`)},"assertActive"),a={resourceUrl:t,basePath:n,mixedAuth:this.#e.mixedAuth===!0,use:o((d,u)=>{i("use"),this.use(d,u)},"use"),tool:o((d,u)=>{if(i("tool"),this.#t.has(d.name))throw new Error(`[mcp-use] Tool "${d.name}" is reserved by the OAuth provider; rename the application tool.`);return this.tool(d,u)},"tool"),resource:o((d,u)=>{if(i("resource"),this.#s.has(d.name))throw new Error(`[mcp-use] Resource "${d.name}" is reserved by the OAuth provider; rename the application resource.`);this.resource(d,u)},"resource"),resourceTemplate:o((d,u)=>{if(i("resourceTemplate"),this.#E.has(d.name))throw new Error(`[mcp-use] Resource template "${d.name}" is reserved by the OAuth provider; rename the application resource template.`);this.resourceTemplate(d,u)},"resourceTemplate"),prompt:o((d,u)=>{if(i("prompt"),this.#a.has(d.name))throw new Error(`[mcp-use] Prompt "${d.name}" is reserved by the OAuth provider; rename the application prompt.`);this.prompt(d,u)},"prompt"),listTools:o(()=>(i("listTools"),[...this.#t.values()].map(({definition:d})=>d)),"listTools"),instructions:o(d=>{i("instructions"),this.#U=d(this.#U??this.#e.instructions)},"instructions")};try{let d=r(a);if(typeof d?.then=="function")throw Promise.resolve(d).catch(()=>{}),new TypeError("[mcp-use] The OAuth provider's setup hook must be synchronous but returned a promise. Do async work before creating the provider.")}catch(d){throw this.#_={error:d},d}finally{s=!1}this.#V=!0}#ee(){return{isStarted:o(()=>this.#f!==void 0,"isStarted"),hasTool:o(t=>this.#t.has(t),"hasTool"),hasResource:o(t=>this.#s.has(t),"hasResource"),hasPrompt:o(t=>this.#a.has(t),"hasPrompt"),registerTool:o((t,n)=>{this.#n("tool",t.name),this.#h.add(t.name),this.#t.set(t.name,{definition:t,callback:n,schemes:this.#ne(t)})},"registerTool"),registerResource:o((t,n)=>{this.#n("resource",t.name),this.#A.add(t.uri),this.#s.set(t.name,{definition:t,callback:n})},"registerResource"),registerPrompt:o((t,n)=>{this.#n("prompt",t.name),this.#P.add(t.name),this.#a.set(t.name,{definition:t,callback:n})},"registerPrompt"),trackOwner:o(t=>{this.#X.push(t)},"trackOwner"),trackNamespace:o(({tools:t,resources:n,prompts:r})=>{this.#J+=1,this.#K+=t,this.#G+=n,this.#Y+=r},"trackNamespace")}}async#y(){this.#k||(this.#H??=this.#oe(typeof process>"u"?".":process.cwd(),"skills").then(()=>{}),await this.#H)}#te(t,n){let{allowedHosts:r,allowedOrigins:s}=this.#e,i=n??this.#e.host??"127.0.0.1",a=["127.0.0.1","localhost","::1"].includes(i),d=r!==void 0?[...new Set([...An(),...r])]:t==="listen"&&a?An():void 0,u=s!==void 0?[...new Set([...ns(),...s])]:void 0;return{hosts:d,origins:u}}#c(t,n,r){if(this.#q(),this.#I===void 0||this.#f===void 0){let{hosts:s,origins:i}=this.#te(t,r),a=this.#i(),d=a==="/"?"":a,u=new kn,c=[Ue({...this.#e.logging,mcpPath:a,prefix:this.#N}),fe()],l=this.#e.cors;l!==void 0&&c.unshift(Ut(l));let p=_t(l);s!==void 0&&c.unshift(me(s)),i!==void 0&&c.push(he(i)),s===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.`);let y=this.#se(t,n,r);if(y!==void 0){let w=this.#e.oauth;c.push($e(w,y))}for(let w of c)us(u,w);y!==void 0&&this.#ue(y,a);for(let w of this.#r?.layout??[])for(let x of w.items)if(x.kind==="tool"&&!this.#t.has(x.tool))throw new Error(`Settings action tool "${x.tool}" is not registered on this server`);this.#le();let{handler:h,fetch:m}=_e(w=>this.#pe(w),{path:a,...(this.#e.legacy!==void 0||this.#S!==void 0)&&{handler:{...this.#e.legacy!==void 0&&{legacy:this.#e.legacy},...this.#S!==void 0&&{bus:this.#S}}},...y!==void 0&&{authInfo:o(w=>an(w),"authInfo")}});if(y!==void 0){let w=this.#e.oauth,x=se(w),G=this.#e.mixedAuth===!0,jn={verifier:De(w,y),resourceMetadataUrl:dn(y),baselineScopes:x.requiredScopes??[],mixedAuth:G,toolSchemes:o(P=>this.#t.get(P)?.schemes,"toolSchemes"),openResourceUris:[...this.#l.keys()].map(k)},at;u.use("*",async(P,ce)=>{if(new URL(P.req.url).pathname!==a){await ce();return}if((this.#e.publicLandingPage===!0||G)&&pe(P.req.raw)){await ce();return}at??=import("./gate-GHSM72MD.js").then(({createOAuthGate:qn})=>qn(jn));let dt=await(await at)(P.req.raw,async()=>(await ce(),P.res));return P.res=dt,dt})}let f=o(w=>{let x=R(w).parsedBody;return _n(x)&&(this.#ae(),this.#de(x)),m(w)},"mcpRouteHandler"),g=o(async w=>pe(w)?o(async()=>{let{createLandingPageResponse:G}=await import("./landing-handler-3ZBRKAI2.js");return G(w,a,this.#e,this.#o,this.#t.values(),this.#a.values(),this.#s.values())},"respond")():f(w),"endpointHandler"),T=this.#w?this.#p:process.env.NODE_ENV!=="production",v=Rt(this.#o,{dev:T,projectRoot:this.#u,deferCors:p});v!==void 0&&this.app.all("/favicon.ico",w=>v(w.req.raw));let M=et(a,this.#d,{dev:this.#w?this.#p:T,projectRoot:this.#u,enabled:Re(this.#o)||[...this.#t.values()].some(w=>w.definition.icons!==void 0&&Re({icons:w.definition.icons})),deferCors:p,...this.#T!==void 0&&{assets:this.#T}});if(M!==void 0&&this.app.on(["GET","HEAD"],`${d}/_mcp-use/public/*`,w=>M(w.req.raw)),!this.#p){let w=Qe(a,this.#d,{projectRoot:this.#u,deferCors:p,...this.#T!==void 0&&{assets:this.#T}});w!==void 0&&this.app.on(["GET","HEAD"],`${d}/_mcp-use/views/*`,x=>w(x.req.raw))}this.app.all(a,w=>g(w.req.raw)),u.route("/",this.app),this.#$=u,this.#I=async w=>u.fetch(w),this.#f=h,this.#B=s!==void 0}else if(t==="listen"&&!this.#B&&this.#te("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.#I,handler:this.#f}}#ce(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.#l.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.#l.set(n.name,{toolName:t.name,config:n})}#le(){if(this.#l.size>0&&!this.#w){let t=[...this.#t.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.#t.values()){let n=t.definition.view?.name;if(n!==void 0&&!this.#d.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.#d.keys())this.#l.has(t)||console.warn(`[mcp-use] View "${t}" is registered but no tool binds it.`)}#pe(t){let{name:n,version:r,title:s,description:i}=this.#e,a=this.#U??this.#e.instructions,d=t.authInfo,u=new rs({name:n,version:r,...s!==void 0&&{title:s},...i!==void 0&&{description:i},...this.#o.websiteUrl!==void 0&&{websiteUrl:this.#o.websiteUrl},...this.#o.icons!==void 0&&{icons:Me(this.#o.icons,t.requestInfo,this.#i())}},{capabilities:{logging:{},tools:{listChanged:!0},prompts:{listChanged:!0},resources:{listChanged:!0,subscribe:!0},...(this.#g!==void 0||this.#r!==void 0)&&{extensions:{...this.#g!==void 0&&{[Ge]:{directoryRead:!0}},...this.#r!==void 0&&{"openai/settings":this.#r.capability}}},...this.#r!==void 0&&{experimental:{"openai/settings":this.#r.capability}}},...a!==void 0&&{instructions:a},...d!==void 0&&{authInfo:d},...this.#e.requestState!==void 0&&{requestState:this.#e.requestState}}),c=t.requestInfo,l=c!==void 0?{request:c,hmrWs:this.#p}:{hmrWs:this.#p},p=this.#i();for(let y of this.#t.values())this.#he(u,y,c);for(let y of this.#s.values())this.#ge(u,y);for(let y of this.#E.values())this.#we(u,y);for(let y of this.#a.values())this.#Me(u,y);for(let[y,h]of this.#d.entries())this.#ye(u,y,h,l,p);return this.#g!==void 0&&Rn(u,this.#g),this.#me(u),u}#x(t,n,r){let s=$(r);return Object.assign(s,{method:t,params:n,...r.sessionId!==void 0&&{session:{sessionId:r.sessionId}},...r.http?.authInfo!==void 0&&{auth:r.http.authInfo},state:new Map})}#b(t,n,r){let s=t==="tools/call"&&this.#R.length===0&&this.#m.length===0?r:()=>Dt(this.#R,this.#m,t,n,r);if(gn())return s();let i=performance.now(),a=this.#R.filter(p=>L(p.pattern,t)).length,d=o(p=>this.#m.filter(y=>y.phase===p&&L(y.pattern,t)).length,"matchedObservers"),u=n.request?.raw,c=u===void 0?void 0:In(R(u).parsedBody),l=o((p,y)=>{ae("operation","completed",{method:t,outcome:p,duration_ms:Math.max(0,Math.round(performance.now()-i)),primitive_origin:this.#fe(t,n.params),matched_middleware:a,observers_before:d("before"),observers_complete:y?d("complete"):0,...c?.protocol_era==="modern"?c:{client_name:"unknown",protocol_era:"legacy"}},{sampleRate:p==="success"?.1:1,serverRoot:this.#u})},"capture");return s().then(p=>{let y=Pn(p)?"input_required":t==="tools/call"&&typeof p=="object"&&p!==null&&"isError"in p&&p.isError===!0?"error":"success";return l(y,!0),p},p=>{throw l("error",!1),p})}#fe(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.#A.has(String(n.uri))?"proxied":"local":t==="prompts/get"?this.#P.has(String(n.name))?"proxied":"local":"mixed"}#me(t){let n=t.server._requestHandlers;if(n===void 0)return;let r=o((s,i,a)=>{let d=n.get(s);if(d===void 0||d.__mcpListWrapped)return;let u=o(async(c,l)=>{let p=l,y=c.params??{},h=this.#x(s,y,p),m,f=o(async()=>{let v=jt(c,h.params),M=await d(v,l);if(typeof M!="object"||M===null)throw new TypeError(`[mcp-use] ${s} handler returned a non-object result`);m=M;let w=m[i];if(!Array.isArray(w))throw new TypeError(`[mcp-use] ${s} handler result is missing a ${i} array`);return w},"innerFn"),g=await this.#b(s,h,f);if(!Array.isArray(g))throw new TypeError(`[mcp-use] ${s} middleware must return a ${i} array`);let T=a?.(g)??g;return{...m,[i]:T}},"wrapped");u.__mcpListWrapped=!0,n.set(s,u)},"wrapListMethod");r("tools/list","tools",s=>s.map(i=>{let a=this.#t.get(i.name),d=a!==void 0&&this.#re(a)?a.schemes:void 0;return d===void 0?i:{...i,securitySchemes:d}})),r("resources/list","resources"),r("prompts/list","prompts")}#he(t,n,r){let{definition:s,callback:i,schemes:a}=n,d=s.view,u=tt(d?.name,s.visibility,ln(s)),c=this.#re(n)?{...u,[ye]:a}:u,l={...s.title!==void 0&&{title:s.title},...s.icons!==void 0&&{icons:Me(s.icons,r,this.#i())},...s.description!==void 0&&{description:s.description},...s.annotations!==void 0&&{annotations:s.annotations},...s.outputSchema!==void 0&&{outputSchema:s.outputSchema},...c!==void 0&&{_meta:c}},p=d!==void 0?nt(d.name):void 0,y=ie(s),h=o(async(m,f)=>{let g=this.#x("tools/call",{name:s.name,arguments:m,...f.mcpReq._meta!==void 0&&{_meta:f.mcpReq._meta}},f),T=o(async()=>{let v=g.params.arguments??{},M=await i(v,this.#Re(f,a));return Pn(M)||p===void 0||M.isError===!0?M:{...M,_meta:{...M._meta,...p}}},"innerFn");return await this.#b("tools/call",g,T)},"invokeTool");y!==void 0?t.registerTool(s.name,{...l,inputSchema:y},async(m,f)=>h(m,f)):t.registerTool(s.name,l,async m=>h({},m))}#ye(t,n,r,s,i){let a=k(n),d=ge(r.viewConfig),u={...this.#Te(this.#l.get(n)?.config),displayModes:d.displayModes,...d.preferredDisplayMode!==void 0&&{preferredDisplayMode:d.preferredDisplayMode}},c=rt(n,r,u,s);t.registerResource(n,a,c,async(l,p)=>{let y=p.http?.req,h=y!==void 0?{request:y,...s.hmrWs===!0?{hmrWs:!0}:{}}:s.hmrWs===!0?{hmrWs:!0}:{},m=y!==void 0?O(y):s.request!==void 0?O(s.request):"",f=Ze(r,m,i,n),g=await ot(ue(u,h),ve(p),(y??s.request)?.headers.get("user-agent"));return{contents:[{uri:l.href,mimeType:c.mimeType,text:f,_meta:g}]}})}#ge(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(s,i)=>{let a=this.#x("resources/read",{uri:s.href,...i.mcpReq._meta!==void 0&&{_meta:i.mcpReq._meta}},i),d=o(async()=>be(await r(s,this.#D(i)),s.href),"innerFn");return await this.#b("resources/read",a,d)})}#we(t,{definition:n,callback:r,complete:s}){let i=new os(n.uriTemplate,{list:void 0,...s!==void 0&&{complete:s}});t.registerResource(n.name,i,{...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(a,d,u)=>{let c=this.#x("resources/read",{uri:a.href,...u.mcpReq._meta!==void 0&&{_meta:u.mcpReq._meta}},u),l=o(async()=>be(await r(a,d,this.#D(u)),a.href),"innerFn");return await this.#b("resources/read",c,l)})}#Te(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}}}#Me(t,{definition:n,callback:r}){let s={...n.title!==void 0&&{title:n.title},...n.description!==void 0&&{description:n.description}},i=o(async(a,d)=>{let u=this.#x("prompts/get",{name:n.name,arguments:a,...d.mcpReq._meta!==void 0&&{_meta:d.mcpReq._meta}},d),c=o(async()=>{let l=u.params.arguments??{};return It(await r(l,this.#D(d)))},"innerFn");return await this.#b("prompts/get",u,c)},"invokePrompt");if(n.schema!==void 0)t.registerPrompt(n.name,{...s,argsSchema:n.schema},async(a,d)=>i(a,d));else{let a=o(async d=>i({},d),"handler");t.registerPrompt(n.name,s,a)}}#D(t){return this.#e.oauth===void 0?$(t):xe(t)}#Re(t,n){return this.#e.oauth===void 0||!ht(n)&&t.http?.authInfo===void 0?$(t):xe(t)}#ve(){return{hasOAuth:this.#e.oauth!==void 0,mixedAuth:this.#e.mixedAuth===!0,baselineScopes:this.#e.oauth?.requiredScopes??[]}}#ne(t){let n=this.#ve(),r=mt(t.name,t.securitySchemes,n),s=yt(t.name,t,n);return s!==void 0&&console.warn(s),r}#re(t){let{definition:n}=t;return n.securitySchemes!==void 0?!0:this.#e.mixedAuth===!0&&n._meta?.[ye]===void 0}};import{acceptedContent as $d,createRequestStateCodec as Fd,inputRequired as Vd,inputResponse as Bd,isInputRequiredResult as Wd}from"@modelcontextprotocol/server";function cs(e){return{content:[{type:"text",text:e}],_meta:{mimeType:"text/plain"}}}o(cs,"text");function ls(e){return{content:[{type:"text",text:e}],_meta:{mimeType:"text/markdown"}}}o(ls,"markdown");function ps(e){return{content:[{type:"text",text:e}],_meta:{mimeType:"text/html"}}}o(ps,"html");function fs(e){return{content:[{type:"text",text:e}],_meta:{mimeType:"text/xml"}}}o(fs,"xml");function ms(e){return{content:[{type:"text",text:e}],_meta:{mimeType:"text/css"}}}o(ms,"css");function hs(e){return{content:[{type:"text",text:e}],_meta:{mimeType:"text/javascript"}}}o(hs,"javascript");function ys(e,t="image/png"){return{content:[{type:"image",data:e,mimeType:t}],_meta:{mimeType:t,isImage:!0}}}o(ys,"image");function gs(e,t="audio/wav"){return{content:[{type:"audio",data:e,mimeType:t}],_meta:{mimeType:t,isAudio:!0}}}o(gs,"audio");function ws(e,t){return{content:[{type:"text",text:e}],_meta:{mimeType:t,isBinary:!0}}}o(ws,"binary");function Ts(e,t,n){if(typeof t=="object"&&t!==null&&"content"in t){let s=t,i,a;if(s._meta&&typeof s._meta=="object"){let u=s._meta;typeof u.mimeType=="string"&&(a=u.mimeType)}let d=s.content?.[0];return d?.type==="text"&&"text"in d&&(i=d.text),{content:[{type:"resource",resource:{uri:e,...a!==void 0&&{mimeType:a},text:i??""}}]}}let r=t;return{content:[{type:"resource",resource:{uri:e,...r!==void 0&&r!==""&&{mimeType:r},text:n??""}}]}}o(Ts,"resource");function Ms(e){return{isError:!0,content:[{type:"text",text:e}]}}o(Ms,"error");function Rs(e){return Array.isArray(e)?Ln(e):{content:[{type:"text",text:JSON.stringify(e,null,2)}],structuredContent:e,_meta:{mimeType:"application/json"}}}o(Rs,"object");function Ln(e){return{content:[{type:"text",text:JSON.stringify(e,null,2)}],structuredContent:e}}o(Ln,"array");function vs(e){let t=e.props??e.data??{},{output:n,message:r,metadata:s}=e,a={content:r?[{type:"text",text:r}]:Array.isArray(n?.content)&&n.content.length>0?n.content:[{type:"text",text:""}]};return s!==void 0&&Object.keys(s).length>0&&(a._meta=s),n?.structuredContent!==void 0?a.structuredContent=n.structuredContent:Object.keys(t).length>0&&(a.structuredContent=t),a}o(vs,"widget");function xs(...e){let t=e.filter(i=>i.structuredContent!==void 0),n=t.length>0?t.map(i=>i.structuredContent).reduce((i,a)=>({...i,...typeof a=="object"&&a!==null?a:{}}),{}):void 0,r=e.filter(i=>i._meta!==void 0),s=r.length>0?r.map(i=>i._meta).reduce((i,a)=>({...i,...a!==void 0?a:{}}),{}):void 0;return{content:e.flatMap(i=>i.content),...n!==void 0&&Object.keys(n).length>0&&{structuredContent:n},...s!==void 0&&Object.keys(s).length>0&&{_meta:s}}}o(xs,"mix");export{it as MCPServer,Ge as SKILLS_EXTENSION_ID,$d as acceptedContent,Ln as array,gs as audio,ws as binary,Zr as completable,Dn as composeFetch,qt as composeMiddleware,Oe as createMcpEventListenerEntry,Ce as createMcpMiddlewareEntry,_e as createMcpMount,Fd as createRequestStateCodec,ms as css,Ms as error,R as getRequestBag,me as hostValidationMiddleware,ps as html,ys as image,Vd as inputRequired,Bd as inputResponse,Wd as isInputRequiredResult,hs as javascript,fe as jsonBodyMiddleware,ls as markdown,le as matchesPath,X as matchesPathPrefix,L as matchesPattern,xs as mix,Rs as object,he as originValidationMiddleware,Y as pathnameOf,z as registerSkills,J as registerViews,Ue as requestLogger,Ts as resource,cs as text,vs as widget,fs as xml};
|
|
43
|
+
</html>`}o(Qe,"synthesizeViewDocument");var Zo=".mcp-use/build/views/public",Qo="public",es=".mcp-use/build/views",On=new WeakMap;function An(e,t,n,r){let s;try{s=decodeURIComponent(t)}catch{return new Response("Not Found",{status:404})}if(s.includes("\\")||s.split("/").includes(".."))return new Response("Not Found",{status:404});let i=Object.hasOwn(e,s)?e[s]:void 0;if(i===void 0)return new Response("Not Found",{status:404});let a=null;return n.method!=="HEAD"&&(a=On.get(i)??null,a===null&&(a=Uint8Array.from(atob(i.body),d=>d.charCodeAt(0)),On.set(i,a))),new Response(a,{headers:{"Content-Type":i.contentType,"Cache-Control":"public, max-age=0, must-revalidate",...r!==!0&&{"Access-Control-Allow-Origin":"*"}}})}o(An,"serveEmbeddedAsset");function et(e,t,n){if(t.size===0)return;let r=_(e,"_mcp-use/views"),s=n?.projectRoot??process.cwd();return async i=>{if(i.method!=="GET"&&i.method!=="HEAD")return new Response("Method Not Allowed",{status:405});if(!X(i,r))return new Response("Not Found",{status:404});let d=Y(i).slice(r.length+1),u=d.indexOf("/");if(u<=0||u===d.length-1)return new Response("Not Found",{status:404});let c=d.slice(0,u),l=d.slice(u+1),p=t.get(c);if(p===void 0||p.kind!=="external")return new Response("Not Found",{status:404});if(n?.assets!==void 0)return An(n.assets,d,i,n.deferCors);let[{join:y},{resolvePublicFilePath:h,servePublicFile:m}]=await Promise.all([import("path"),import("./public-route-AVKCGJDQ.js")]),f=y(s,es,c),g=await h(f,l);return g===null?new Response("Not Found",{status:404}):await m(g,{...n?.deferCors===!0&&{deferCors:!0},...i.method==="HEAD"&&{head:!0}})}}o(et,"createViewAssetsHandler");function tt(e,t,n){if(t.size===0&&n?.enabled!==!0)return;let r=_(e,"_mcp-use/public"),s=n?.dev===!0?Qo:Zo,i=n?.projectRoot??process.cwd();return async a=>{if(a.method!=="GET"&&a.method!=="HEAD")return new Response("Method Not Allowed",{status:405});if(!X(a,r))return new Response("Not Found",{status:404});let u=Y(a).slice(r.length+1),c;try{c=decodeURIComponent(u)}catch{return new Response("Not Found",{status:404})}if(c.length===0)return new Response("Not Found",{status:404});if(n?.assets!==void 0)return An(n.assets,`public/${u}`,a,n.deferCors);let[{join:l},{resolvePublicFilePath:p,servePublicFile:y}]=await Promise.all([import("path"),import("./public-route-AVKCGJDQ.js")]),h=l(i,s),m=await p(h,c);return m===null?new Response("Not Found",{status:404}):await y(m,{...n?.deferCors===!0&&{deferCors:!0},...a.method==="HEAD"&&{head:!0}})}}o(tt,"createViewPublicHandler");var ts={connectDomains:"CSP_CONNECT_DOMAINS",resourceDomains:"CSP_RESOURCE_DOMAINS",frameDomains:"CSP_FRAME_DOMAINS",baseUriDomains:"CSP_BASE_URI_DOMAINS"};function ns(e){return e===void 0||e.trim()===""?[]:e.split(",").map(t=>t.trim()).filter(t=>t.length>0)}o(ns,"parseDomainList");function Pn(e){if(typeof process>"u")return;let t=process.env[e];if(!(t===void 0||t.trim()===""))return ns(t)}o(Pn,"readEnvDomains");function rs(){return Pn("CSP_URLS")??[]}o(rs,"readCspUrlsShortcut");function de(e){let t=Pn(ts[e]);return t!==void 0?t:rs()}o(de,"readEnvDomainsForCategory");function K(...e){let t=new Set,n=[];for(let r of e)for(let s of r)t.has(s)||(t.add(s),n.push(s));return n}o(K,"mergeDomainLists");function os(e){return e.startsWith("https://")?`wss://${e.slice(8)}`:e.startsWith("http://")?`ws://${e.slice(7)}`:e}o(os,"toWebSocketOrigin");function kn(e,t){let n=e?.csp,r=[];t.serverOrigin!==""&&(r.push(t.serverOrigin),t.hmrWs===!0&&r.push(os(t.serverOrigin)));let s=[],i=t.explicitAssetsBase?t.assetsOrigin:t.serverOrigin;i!==""&&s.push(i);let a=K(n?.connectDomains??[],de("connectDomains"),r),d=K(n?.resourceDomains??[],de("resourceDomains"),s),u=K(n?.frameDomains??[],de("frameDomains")),c=K(n?.baseUriDomains??[],de("baseUriDomains")),l=K(n?.scriptDirectives??[],t.hmrWs===!0?["'unsafe-eval'"]:[]);return{...n,connectDomains:a,resourceDomains:d,frameDomains:u,baseUriDomains:c,...l.length>0?{scriptDirectives:l}:{}}}o(kn,"buildMergedResourceCsp");function nt(e,t,n){if(e===void 0&&t===void 0&&n===void 0)return;let r={...n},s=n?.["ui"],i=typeof s=="object"&&s!==null&&!Array.isArray(s),a=i?{...s}:{};if(e!==void 0){let d=k(e);a.resourceUri=d,r[Q]=d}else delete a.resourceUri,delete r[Q];return t!==void 0?a.visibility=[t]:delete a.visibility,(e!==void 0||t!==void 0||i)&&(r["ui"]=a),r}o(nt,"buildToolUiMeta");function rt(e){let t=k(e);return{ui:{resourceUri:t},[Q]:t}}o(rt,"buildToolResultUiMeta");function ss(e){let t=e?.request,n=e?.serverOrigin??(t!==void 0?ct(t):""),r=e?.assetsBase??(t!==void 0?O(t):n);return{serverOrigin:n,assetsOrigin:lt(r),explicitAssetsBase:pt(),...e?.hmrWs===!0?{hmrWs:!0}:{}}}o(ss,"resolveCspOptions");function ue(e,t){let r={csp:kn(e,ss(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,...e?.displayModes!==void 0&&{"openai/ui":{availableDisplayModes:e.displayModes.filter(s=>s==="inline"||s==="fullscreen"),...e.preferredDisplayMode!==void 0&&{preferredDisplayMode:e.preferredDisplayMode}}}}}o(ue,"buildResourceUiMeta");function ot(e,t,n,r){return{mimeType:Z,...n?.description!==void 0&&{description:n.description},_meta:ue(n,r)}}o(ot,"viewResourceConfig");var In=".claudemcpcontent.com",is=32;function as(e){let t=e?.name;return typeof t=="string"&&t.toLowerCase().includes("claude")}o(as,"isClaudeClient");async function ds(e){if(e.endsWith(In))return e;let t=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(e));return`${Array.from(new Uint8Array(t),r=>r.toString(16).padStart(2,"0")).join("").slice(0,is)}${In}`}o(ds,"computeClaudeResourceDomain");async function st(e,t,n){let r=typeof t?.name=="string"||typeof n!="string"||n.trim().length===0?t:{...t,name:n.trim()};if(!as(r))return e;let s=e["ui"];if(typeof s!="object"||s===null||Array.isArray(s))return e;let i=s.domain;return typeof i!="string"||i.length===0?e:{...e,ui:{...s,domain:await ds(i)}}}o(st,"applyClaudeResourceDomain");function H(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:void 0}o(H,"record");function it(e,t){if(typeof e!="string")return t;let n=e.trim();return n.length>0&&n.length<=64&&![...n].some(r=>{let s=r.charCodeAt(0);return s<32||s===127})?n:t}o(it,"productId");function jn(e){if(!Nn(e))return;let t=H(e.params);if(e.method==="initialize"){let i=H(t?.clientInfo),a=H(t?.capabilities)??{};return qn(i,a,t?.protocolVersion,"legacy")}let n=H(t?._meta),r=H(n?.[fs]),s=H(n?.[ps]);if(!(r===void 0||s===void 0))return qn(r,s,n?.[ms],"modern")}o(jn,"clientUsageFromBody");function qn(e,t,n,r){let s=t;return{client_name:it(e?.name,"other"),client_version:it(e?.version,"unknown"),protocol_era:r,protocol_version:it(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:ee(s),capability_count:Object.keys(t).length}}o(qn,"clientUsage");function ys(e,t){e.use("*",async(n,r)=>{let s=await t(n.req.raw,async()=>(await r(),n.res));return n.res=s,s})}o(ys,"registerFetchMiddleware");var at=class e{static{o(this,"MCPServer")}#e;#D;#o;#t=new Map;#s=new Map;#E=new Map;#a=new Map;#d=new Map;#r;#g;#k=!1;#H;#l=new Map;#w=!1;#T;#p=!1;#u=process.cwd();#I;#$;#f;#S;#M;#C;#O=!1;#F=!1;#U;#V=!1;#_;#B=!1;#R=[];#m=[];#W;#v=new Set;#h=new Set;#A=new Set;#P=new Set;#z=0;#L=0;#J=0;#K=0;#G=0;#Y=0;#X=[];#j=new Set;#Z=!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"});rn(n,t);for(let r of n.#t.keys())n.#v.add(r);return n}constructor(t){if(xt(t),this.#e=t,this.#o=Rt(t),this.app=new Ln,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,s)=>(await this.#y(),this.#c("handler"),this.#$.fetch(n,r,s)),t.oauth!==void 0){let n=typeof process>"u"?void 0:process.env.MCP_URL,r=sn({provider:t.oauth,basePath:this.#i(),...n!==void 0&&{mcpUrl:n}});this.#C=r,this.#O=r!==void 0,this.#F=r===void 0}}get basePath(){return this.#i()}get host(){return this.#e.host}get port(){return this.#e.port}get branding(){return this.#o}getHandler(){return this.fetch}tool(t,n){if(this.#n("tool",t.name),this.#r!==void 0&&[this.#r.capability.readTool,this.#r.capability.updateTool].includes(t.name))throw new Error(`Tool "${t.name}" is reserved for settings`);let r=this.#ne(t);return mn(t),this.#ce(t),this.#v.delete(t.name),this.#h.delete(t.name),this.#t.set(t.name,{definition:t,callback:n,schemes:r}),Object.freeze({name:t.name})}settings(t){if(this.#n("settings",t.readTool??"settings.read"),this.#r!==void 0)throw new Error("Settings are already registered on this server");let n=Kt(t);for(let i of[n.capability.readTool,n.capability.updateTool])if(this.#t.has(i))throw new Error(`Settings tool "${i}" is already registered`);let r=t.read,s=t.update;this.tool(n.readDefinition,async(i,a)=>({content:[],structuredContent:{schema:n.schema,...n.layout!==void 0&&{layout:n.layout},values:await r(a)}})),this.tool(n.updateDefinition,async({set:i},a)=>({content:[],structuredContent:{values:await s(i,a)}})),this.#r=n}mentions(t){this.#n("mentions",t.name);let n=Zt(t);if(this.#t.has(t.name))throw new Error(`Mention tool "${t.name}" is already registered`);let r=t.search,s=this.tool(n,async(i,a)=>({content:[],structuredContent:await r(i,a)}));return this.#t.get(t.name).mentions=!0,s}[J](t,n){if(this.#w)throw new Error("Cannot prime views: the views registry is already primed on this server instance.");this.#n("views","manifest");for(let[r,s]of Object.entries(t))try{ge(s.viewConfig)}catch(i){throw new Error(`View "${r}" has an invalid viewConfig: ${i instanceof Error?i.message:String(i)}`,{cause:i})}this.#p=n?.dev===!0,this.#T=n?.assets,n?.projectRoot!==void 0&&(this.#u=n.projectRoot);for(let[r,s]of Object.entries(t))this.#d.set(r,s);this.#w=!0}__primeViews(t,n){this[J](t,n)}[z](t){this.#n("skills","snapshot"),this.#g=t,this.#k=!0}__primeSkills(t){this[z](t)}__skillsConfig(){return this.#e.skills}async#oe(t,n){let{discoverConfiguredSkills:r}=await import("#mcp-use-skills-loader"),s=r(this.#e.skills,t,n);return this[z](s),s}resource(t,n){this.#n("resource",t.name);let r=this.#s.get(t.name);return r!==void 0&&this.#A.delete(r.definition.uri),this.#s.set(t.name,{definition:t,callback:n}),this}resourceTemplate(t,n){this.#n("resourceTemplate",t.name);let r=t.complete===void 0?void 0:Yt(t.complete);return this.#E.set(t.name,{definition:t,...r!==void 0&&{complete:r},callback:n}),this}prompt(t,n){return this.#n("prompt",t.name),this.#P.delete(t.name),this.#a.set(t.name,{definition:t,callback:n}),this}async proxy(t){this.#q("proxy()");let n=(async()=>{let{isProxyConnection:r,mountProxyConnection:s,mountProxyServers:i}=await import("./mcp-proxy-YSI2UFBY.js");if(r(t)){this.#L+=1,await s(this.#ee(),t);return}this.#L+=Object.keys(t).length,await i(this.#ee(),t)})();this.#j.add(n);try{await n}finally{this.#j.delete(n)}}use(t,...n){if(typeof t=="string"&&t.startsWith("mcp:")){this.#n("middleware",t);let s=n[0];return this.#R.push(Ce(t,s)),this}return this.app.use.call(this.app,t,...n),this.#z+=typeof t=="function"?1:n.length,this}on(t,n){return this.#n("event listener",t),this.#m.push(Oe(t,n)),this}__setEventBus(t){this.#n("event bus","shared"),this.#S=t}__setRequestLogPrefix(t){this.#n("request log prefix","development"),this.#D=t}__mount(){if(!this.#k)throw new Error("Cannot mount before skills discovery. CLI tooling must call __primeSkills first.");this.#c("handler")}async notifyToolsChanged(){await this.#y(),await this.#c("handler").handler.notify.toolsChanged()}async notifyPromptsChanged(){await this.#y(),await this.#c("handler").handler.notify.promptsChanged()}async notifyResourcesChanged(){await this.#y(),await this.#c("handler").handler.notify.resourcesChanged()}async notifyResourceUpdated(t){await this.#y(),await this.#c("handler").handler.notify.resourceUpdated(t)}async listen(t=void 0,n={}){this.#q("listen()"),await this.#y();let r=bt(n.host,this.#e.host),s=Et(t,this.#e.port);return this.#ie(r),new Promise((i,a)=>{let d,u,c=new Promise((m,f)=>{d=m,u=f});c.catch(()=>{});let l=!1,p=o(m=>{l||(l=!0,a(m)),u?.(m),new Promise(f=>h.close(()=>f())).catch(()=>{}).finally(()=>{this.#M===h&&(this.#M=void 0)})},"rejectAndClose"),y=Ct({fetch:o(async m=>(await c)(m),"fetch")}),h=hs((m,f)=>{y(m,f)});h.once("error",p),h.listen(s,r,()=>{try{let m=h.address(),f=typeof m=="object"&&m!==null?m.port:s,{fetch:g}=this.#c("listen",f,r);d?.(g),l||(l=!0,i({port:f,url:`http://localhost:${f}${this.#i()}`}))}catch(m){p(m)}}),this.#M=h})}async close(){this.#Z=!0,await Promise.allSettled([...this.#j]);let t=[],n=this.#X.splice(0),r=await Promise.allSettled(n.map(i=>i.close()));for(let i of r)i.status==="rejected"&&t.push(i.reason);try{await this.#f?.close()}catch(i){t.push(i)}let s=this.#M;if(s!==void 0)try{await new Promise((i,a)=>{s.close(d=>d?a(d):i())}),this.#M=void 0}catch(i){t.push(i)}if(t.length>0)throw new AggregateError(t,"Failed to close MCP server cleanly")}#q(t){if(this.#Z)throw t!==void 0?new Error(`Cannot call ${t} after the server has closed.`):new Error("Cannot use the server after it has closed.")}#i(){return this.#e.basePath??"/mcp"}#se(t,n,r){if(this.#e.oauth===void 0)return;if(this.#O)return this.#C;let s=r??this.#e.host??"127.0.0.1",i=t==="listen"&&n!==void 0&&["127.0.0.1","localhost","::1"].includes(s);if(this.#F&&i)return this.#C=an(`http://localhost:${n}`,this.#i()),this.#O=!0,this.#C;throw new Error("OAuth requires an explicit resource or MCP_URL when using server.fetch or listening on a non-local host")}#ie(t){if(this.#e.oauth!==void 0&&!["127.0.0.1","localhost","::1"].includes(t)&&!this.#O)throw new Error("OAuth listen() on a public or wildcard host requires an explicit provider resource or valid MCP_URL.")}#n(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.`)}#ae(){ae("server","configured",{tools_total:this.#t.size,tools_local:this.#t.size-this.#v.size-this.#h.size,tools_openapi:this.#v.size,tools_proxied:this.#h.size,resources:this.#s.size,resource_templates:this.#E.size,prompts:this.#a.size,views:this.#d.size,proxy_servers_configured:this.#L,proxy_servers_connected:this.#J,proxy_tools_discovered:this.#K,proxy_resources_discovered:this.#G,proxy_prompts_discovered:this.#Y,proxy_tools_mounted:this.#h.size,proxy_resources_mounted:this.#A.size,proxy_prompts_mounted:this.#P.size,http_middleware:this.#z,mcp_middleware:this.#R.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.#Q()}:server`,serverRoot:this.#u})}#de(t){let n=jn(t);n!==void 0&&ae("client","observed",{...n},{onceKey:`${this.#Q()}:client:${JSON.stringify(n)}`,serverRoot:this.#u})}#Q(){return this.#W??=crypto.randomUUID(),this.#W}#ue(t,n){let r=this.#e.oauth?.setup;if(r===void 0||this.#V)return;if(this.#_!==void 0)throw this.#_.error;let s=!0,i=o(d=>{if(!s)throw new Error(`[mcp-use] OAuthProviderHost.${d}() called after the provider's setup hook returned; call it from setup().`)},"assertActive"),a={resourceUrl:t,basePath:n,mixedAuth:this.#e.mixedAuth===!0,use:o((d,u)=>{i("use"),this.use(d,u)},"use"),tool:o((d,u)=>{if(i("tool"),this.#t.has(d.name))throw new Error(`[mcp-use] Tool "${d.name}" is reserved by the OAuth provider; rename the application tool.`);return this.tool(d,u)},"tool"),resource:o((d,u)=>{if(i("resource"),this.#s.has(d.name))throw new Error(`[mcp-use] Resource "${d.name}" is reserved by the OAuth provider; rename the application resource.`);this.resource(d,u)},"resource"),resourceTemplate:o((d,u)=>{if(i("resourceTemplate"),this.#E.has(d.name))throw new Error(`[mcp-use] Resource template "${d.name}" is reserved by the OAuth provider; rename the application resource template.`);this.resourceTemplate(d,u)},"resourceTemplate"),prompt:o((d,u)=>{if(i("prompt"),this.#a.has(d.name))throw new Error(`[mcp-use] Prompt "${d.name}" is reserved by the OAuth provider; rename the application prompt.`);this.prompt(d,u)},"prompt"),listTools:o(()=>(i("listTools"),[...this.#t.values()].map(({definition:d})=>d)),"listTools"),instructions:o(d=>{i("instructions"),this.#U=d(this.#U??this.#e.instructions)},"instructions")};try{let d=r(a);if(typeof d?.then=="function")throw Promise.resolve(d).catch(()=>{}),new TypeError("[mcp-use] The OAuth provider's setup hook must be synchronous but returned a promise. Do async work before creating the provider.")}catch(d){throw this.#_={error:d},d}finally{s=!1}this.#V=!0}#ee(){return{isStarted:o(()=>this.#f!==void 0,"isStarted"),hasTool:o(t=>this.#t.has(t),"hasTool"),hasResource:o(t=>this.#s.has(t),"hasResource"),hasPrompt:o(t=>this.#a.has(t),"hasPrompt"),registerTool:o((t,n)=>{this.#n("tool",t.name),this.#h.add(t.name),this.#t.set(t.name,{definition:t,callback:n,schemes:this.#ne(t)})},"registerTool"),registerResource:o((t,n)=>{this.#n("resource",t.name),this.#A.add(t.uri),this.#s.set(t.name,{definition:t,callback:n})},"registerResource"),registerPrompt:o((t,n)=>{this.#n("prompt",t.name),this.#P.add(t.name),this.#a.set(t.name,{definition:t,callback:n})},"registerPrompt"),trackOwner:o(t=>{this.#X.push(t)},"trackOwner"),trackNamespace:o(({tools:t,resources:n,prompts:r})=>{this.#J+=1,this.#K+=t,this.#G+=n,this.#Y+=r},"trackNamespace")}}async#y(){this.#k||(this.#H??=this.#oe(typeof process>"u"?".":process.cwd(),"skills").then(()=>{}),await this.#H)}#te(t,n){let{allowedHosts:r,allowedOrigins:s}=this.#e,i=n??this.#e.host??"127.0.0.1",a=["127.0.0.1","localhost","::1"].includes(i),d=r!==void 0?[...new Set([...Un(),...r])]:t==="listen"&&a?Un():void 0,u=s!==void 0?[...new Set([...us(),...s])]:void 0;return{hosts:d,origins:u}}#c(t,n,r){if(this.#q(),this.#I===void 0||this.#f===void 0){let{hosts:s,origins:i}=this.#te(t,r),a=this.#i(),d=a==="/"?"":a,u=new Ln,c=[Ue({...this.#e.logging,mcpPath:a,prefix:this.#D}),fe()],l=this.#e.cors;l!==void 0&&c.unshift(_t(l));let p=Lt(l);s!==void 0&&c.unshift(me(s)),i!==void 0&&c.push(he(i)),s===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.`);let y=this.#se(t,n,r);if(y!==void 0){let w=this.#e.oauth;c.push(Fe(w,y))}for(let w of c)ys(u,w);y!==void 0&&this.#ue(y,a);for(let w of this.#r?.layout??[])for(let x of w.items)if(x.kind==="tool"&&!this.#t.has(x.tool))throw new Error(`Settings action tool "${x.tool}" is not registered on this server`);this.#le();let{handler:h,fetch:m}=_e(w=>this.#pe(w),{path:a,...(this.#e.legacy!==void 0||this.#S!==void 0)&&{handler:{...this.#e.legacy!==void 0&&{legacy:this.#e.legacy},...this.#S!==void 0&&{bus:this.#S}}},...y!==void 0&&{authInfo:o(w=>ln(w),"authInfo")}});if(y!==void 0){let w=this.#e.oauth,x=se(w),G=this.#e.mixedAuth===!0,Hn={verifier:De(w,y),resourceMetadataUrl:pn(y),baselineScopes:x.requiredScopes??[],mixedAuth:G,toolSchemes:o(P=>this.#t.get(P)?.schemes,"toolSchemes"),openResourceUris:[...this.#l.keys()].map(k)},dt;u.use("*",async(P,ce)=>{if(new URL(P.req.url).pathname!==a){await ce();return}if((this.#e.publicLandingPage===!0||G)&&pe(P.req.raw)){await ce();return}dt??=import("./gate-GHSM72MD.js").then(({createOAuthGate:$n})=>$n(Hn));let ut=await(await dt)(P.req.raw,async()=>(await ce(),P.res));return P.res=ut,ut})}let f=o(w=>{let x=R(w).parsedBody;return Nn(x)&&(this.#ae(),this.#de(x)),m(w)},"mcpRouteHandler"),g=o(async w=>pe(w)?o(async()=>{let{createLandingPageResponse:G}=await import("./landing-handler-3ZBRKAI2.js");return G(w,a,this.#e,this.#o,this.#t.values(),this.#a.values(),this.#s.values())},"respond")():f(w),"endpointHandler"),T=this.#w?this.#p:process.env.NODE_ENV!=="production",v=vt(this.#o,{dev:T,projectRoot:this.#u,deferCors:p});v!==void 0&&this.app.all("/favicon.ico",w=>v(w.req.raw));let M=tt(a,this.#d,{dev:this.#w?this.#p:T,projectRoot:this.#u,enabled:Re(this.#o)||[...this.#t.values()].some(w=>w.definition.icons!==void 0&&Re({icons:w.definition.icons})),deferCors:p,...this.#T!==void 0&&{assets:this.#T}});if(M!==void 0&&this.app.on(["GET","HEAD"],`${d}/_mcp-use/public/*`,w=>M(w.req.raw)),!this.#p){let w=et(a,this.#d,{projectRoot:this.#u,deferCors:p,...this.#T!==void 0&&{assets:this.#T}});w!==void 0&&this.app.on(["GET","HEAD"],`${d}/_mcp-use/views/*`,x=>w(x.req.raw))}this.app.all(a,w=>g(w.req.raw)),u.route("/",this.app),this.#$=u,this.#I=async w=>u.fetch(w),this.#f=h,this.#B=s!==void 0}else if(t==="listen"&&!this.#B&&this.#te("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.#I,handler:this.#f}}#ce(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.#l.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.#l.set(n.name,{toolName:t.name,config:n})}#le(){if(this.#l.size>0&&!this.#w){let t=[...this.#t.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.#t.values()){let n=t.definition.view?.name;if(n!==void 0&&!this.#d.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.#d.keys())this.#l.has(t)||console.warn(`[mcp-use] View "${t}" is registered but no tool binds it.`)}#pe(t){let{name:n,version:r,title:s,description:i}=this.#e,a=this.#U??this.#e.instructions,d=t.authInfo,u=new cs({name:n,version:r,...s!==void 0&&{title:s},...i!==void 0&&{description:i},...this.#o.websiteUrl!==void 0&&{websiteUrl:this.#o.websiteUrl},...this.#o.icons!==void 0&&{icons:Me(this.#o.icons,t.requestInfo,this.#i())}},{capabilities:{logging:{},tools:{listChanged:!0},prompts:{listChanged:!0},resources:{listChanged:!0,subscribe:!0},...(this.#g!==void 0||this.#r!==void 0)&&{extensions:{...this.#g!==void 0&&{[Ye]:{directoryRead:!0}},...this.#r!==void 0&&{"openai/settings":this.#r.capability}}},...this.#r!==void 0&&{experimental:{"openai/settings":this.#r.capability}}},...a!==void 0&&{instructions:a},...d!==void 0&&{authInfo:d},...this.#e.requestState!==void 0&&{requestState:this.#e.requestState}}),c=t.requestInfo,l=c!==void 0?{request:c,hmrWs:this.#p}:{hmrWs:this.#p},p=this.#i();for(let y of this.#t.values())this.#he(u,y,c);for(let y of this.#s.values())this.#ge(u,y);for(let y of this.#E.values())this.#we(u,y);for(let y of this.#a.values())this.#Me(u,y);for(let[y,h]of this.#d.entries())this.#ye(u,y,h,l,p);return this.#g!==void 0&&En(u,this.#g),this.#me(u),u}#x(t,n,r){let s=$(r);return Object.assign(s,{method:t,params:n,...r.sessionId!==void 0&&{session:{sessionId:r.sessionId}},...r.http?.authInfo!==void 0&&{auth:r.http.authInfo},state:new Map})}#b(t,n,r){let s=t==="tools/call"&&this.#R.length===0&&this.#m.length===0?r:()=>Dt(this.#R,this.#m,t,n,r);if(Rn())return s();let i=performance.now(),a=this.#R.filter(p=>L(p.pattern,t)).length,d=o(p=>this.#m.filter(y=>y.phase===p&&L(y.pattern,t)).length,"matchedObservers"),u=n.request?.raw,c=u===void 0?void 0:jn(R(u).parsedBody),l=o((p,y)=>{ae("operation","completed",{method:t,outcome:p,duration_ms:Math.max(0,Math.round(performance.now()-i)),primitive_origin:this.#fe(t,n.params),matched_middleware:a,observers_before:d("before"),observers_complete:y?d("complete"):0,...c?.protocol_era==="modern"?c:{client_name:"unknown",protocol_era:"legacy"}},{sampleRate:p==="success"?.1:1,serverRoot:this.#u})},"capture");return s().then(p=>{let y=_n(p)?"input_required":t==="tools/call"&&typeof p=="object"&&p!==null&&"isError"in p&&p.isError===!0?"error":"success";return l(y,!0),p},p=>{throw l("error",!1),p})}#fe(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.#A.has(String(n.uri))?"proxied":"local":t==="prompts/get"?this.#P.has(String(n.name))?"proxied":"local":"mixed"}#me(t){let n=t.server._requestHandlers;if(n===void 0)return;let r=o((s,i,a)=>{let d=n.get(s);if(d===void 0||d.__mcpListWrapped)return;let u=o(async(c,l)=>{let p=l,y=c.params??{},h=this.#x(s,y,p),m,f=o(async()=>{let v=qt(c,h.params),M=await d(v,l);if(typeof M!="object"||M===null)throw new TypeError(`[mcp-use] ${s} handler returned a non-object result`);m=M;let w=m[i];if(!Array.isArray(w))throw new TypeError(`[mcp-use] ${s} handler result is missing a ${i} array`);return w},"innerFn"),g=await this.#b(s,h,f);if(!Array.isArray(g))throw new TypeError(`[mcp-use] ${s} middleware must return a ${i} array`);let T=a?.(g)??g;return{...m,[i]:T}},"wrapped");u.__mcpListWrapped=!0,n.set(s,u)},"wrapListMethod");r("tools/list","tools",s=>s.map(i=>{let a=this.#t.get(i.name),d=a!==void 0&&this.#re(a)?a.schemes:void 0;return d===void 0?i:{...i,securitySchemes:d}})),r("resources/list","resources"),r("prompts/list","prompts")}#he(t,n,r){let{definition:s,callback:i,schemes:a}=n,d=s.view,u=nt(d?.name,s.visibility,hn(s)),c=n.mentions?Qt(s,u):u,l=this.#re(n)?{...c,[ye]:a}:c,p={...s.title!==void 0&&{title:s.title},...s.icons!==void 0&&{icons:Me(s.icons,r,this.#i())},...s.description!==void 0&&{description:s.description},...s.annotations!==void 0&&{annotations:s.annotations},...s.outputSchema!==void 0&&{outputSchema:s.outputSchema},...l!==void 0&&{_meta:l}},y=d!==void 0?rt(d.name):void 0,h=ie(s),m=o(async(f,g)=>{let T=this.#x("tools/call",{name:s.name,arguments:f,...g.mcpReq._meta!==void 0&&{_meta:g.mcpReq._meta}},g),v=o(async()=>{let M=T.params.arguments??{},w=await i(M,this.#Re(g,a));return _n(w)||y===void 0||w.isError===!0?w:{...w,_meta:{...w._meta,...y}}},"innerFn");return await this.#b("tools/call",T,v)},"invokeTool");h!==void 0?t.registerTool(s.name,{...p,inputSchema:h},async(f,g)=>m(f,g)):t.registerTool(s.name,p,async f=>m({},f))}#ye(t,n,r,s,i){let a=k(n),d=ge(r.viewConfig),u={...this.#Te(this.#l.get(n)?.config),displayModes:d.displayModes,...d.preferredDisplayMode!==void 0&&{preferredDisplayMode:d.preferredDisplayMode}},c=ot(n,r,u,s);t.registerResource(n,a,c,async(l,p)=>{let y=p.http?.req,h=y!==void 0?{request:y,...s.hmrWs===!0?{hmrWs:!0}:{}}:s.hmrWs===!0?{hmrWs:!0}:{},m=y!==void 0?O(y):s.request!==void 0?O(s.request):"",f=Qe(r,m,i,n),g=await st(ue(u,h),ve(p),(y??s.request)?.headers.get("user-agent"));return{contents:[{uri:l.href,mimeType:c.mimeType,text:f,_meta:g}]}})}#ge(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(s,i)=>{let a=this.#x("resources/read",{uri:s.href,...i.mcpReq._meta!==void 0&&{_meta:i.mcpReq._meta}},i),d=o(async()=>be(await r(s,this.#N(i)),s.href),"innerFn");return await this.#b("resources/read",a,d)})}#we(t,{definition:n,callback:r,complete:s}){let i=new ls(n.uriTemplate,{list:void 0,...s!==void 0&&{complete:s}});t.registerResource(n.name,i,{...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(a,d,u)=>{let c=this.#x("resources/read",{uri:a.href,...u.mcpReq._meta!==void 0&&{_meta:u.mcpReq._meta}},u),l=o(async()=>be(await r(a,d,this.#N(u)),a.href),"innerFn");return await this.#b("resources/read",c,l)})}#Te(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}}}#Me(t,{definition:n,callback:r}){let s={...n.title!==void 0&&{title:n.title},...n.description!==void 0&&{description:n.description}},i=o(async(a,d)=>{let u=this.#x("prompts/get",{name:n.name,arguments:a,...d.mcpReq._meta!==void 0&&{_meta:d.mcpReq._meta}},d),c=o(async()=>{let l=u.params.arguments??{};return Ut(await r(l,this.#N(d)))},"innerFn");return await this.#b("prompts/get",u,c)},"invokePrompt");if(n.schema!==void 0)t.registerPrompt(n.name,{...s,argsSchema:n.schema},async(a,d)=>i(a,d));else{let a=o(async d=>i({},d),"handler");t.registerPrompt(n.name,s,a)}}#N(t){return this.#e.oauth===void 0?$(t):xe(t)}#Re(t,n){return this.#e.oauth===void 0||!yt(n)&&t.http?.authInfo===void 0?$(t):xe(t)}#ve(){return{hasOAuth:this.#e.oauth!==void 0,mixedAuth:this.#e.mixedAuth===!0,baselineScopes:this.#e.oauth?.requiredScopes??[]}}#ne(t){let n=this.#ve(),r=ht(t.name,t.securitySchemes,n),s=gt(t.name,t,n);return s!==void 0&&console.warn(s),r}#re(t){let{definition:n}=t;return n.securitySchemes!==void 0?!0:this.#e.mixedAuth===!0&&n._meta?.[ye]===void 0}};import{acceptedContent as Qd,createRequestStateCodec as eu,inputRequired as tu,inputResponse as nu,isInputRequiredResult as ru}from"@modelcontextprotocol/server";function gs(e){return{content:[{type:"text",text:e}],_meta:{mimeType:"text/plain"}}}o(gs,"text");function ws(e){return{content:[{type:"text",text:e}],_meta:{mimeType:"text/markdown"}}}o(ws,"markdown");function Ts(e){return{content:[{type:"text",text:e}],_meta:{mimeType:"text/html"}}}o(Ts,"html");function Ms(e){return{content:[{type:"text",text:e}],_meta:{mimeType:"text/xml"}}}o(Ms,"xml");function Rs(e){return{content:[{type:"text",text:e}],_meta:{mimeType:"text/css"}}}o(Rs,"css");function vs(e){return{content:[{type:"text",text:e}],_meta:{mimeType:"text/javascript"}}}o(vs,"javascript");function xs(e,t="image/png"){return{content:[{type:"image",data:e,mimeType:t}],_meta:{mimeType:t,isImage:!0}}}o(xs,"image");function bs(e,t="audio/wav"){return{content:[{type:"audio",data:e,mimeType:t}],_meta:{mimeType:t,isAudio:!0}}}o(bs,"audio");function Es(e,t){return{content:[{type:"text",text:e}],_meta:{mimeType:t,isBinary:!0}}}o(Es,"binary");function Ss(e,t,n){if(typeof t=="object"&&t!==null&&"content"in t){let s=t,i,a;if(s._meta&&typeof s._meta=="object"){let u=s._meta;typeof u.mimeType=="string"&&(a=u.mimeType)}let d=s.content?.[0];return d?.type==="text"&&"text"in d&&(i=d.text),{content:[{type:"resource",resource:{uri:e,...a!==void 0&&{mimeType:a},text:i??""}}]}}let r=t;return{content:[{type:"resource",resource:{uri:e,...r!==void 0&&r!==""&&{mimeType:r},text:n??""}}]}}o(Ss,"resource");function Cs(e){return{isError:!0,content:[{type:"text",text:e}]}}o(Cs,"error");function Os(e){return Array.isArray(e)?Dn(e):{content:[{type:"text",text:JSON.stringify(e,null,2)}],structuredContent:e,_meta:{mimeType:"application/json"}}}o(Os,"object");function Dn(e){return{content:[{type:"text",text:JSON.stringify(e,null,2)}],structuredContent:e}}o(Dn,"array");function As(e){let t=e.props??e.data??{},{output:n,message:r,metadata:s}=e,a={content:r?[{type:"text",text:r}]:Array.isArray(n?.content)&&n.content.length>0?n.content:[{type:"text",text:""}]};return s!==void 0&&Object.keys(s).length>0&&(a._meta=s),n?.structuredContent!==void 0?a.structuredContent=n.structuredContent:Object.keys(t).length>0&&(a.structuredContent=t),a}o(As,"widget");function Ps(...e){let t=e.filter(i=>i.structuredContent!==void 0),n=t.length>0?t.map(i=>i.structuredContent).reduce((i,a)=>({...i,...typeof a=="object"&&a!==null?a:{}}),{}):void 0,r=e.filter(i=>i._meta!==void 0),s=r.length>0?r.map(i=>i._meta).reduce((i,a)=>({...i,...a!==void 0?a:{}}),{}):void 0;return{content:e.flatMap(i=>i.content),...n!==void 0&&Object.keys(n).length>0&&{structuredContent:n},...s!==void 0&&Object.keys(s).length>0&&{_meta:s}}}o(Ps,"mix");export{at as MCPServer,Ye as SKILLS_EXTENSION_ID,Qd as acceptedContent,Dn as array,bs as audio,Es as binary,no as completable,Fn as composeFetch,Nt as composeMiddleware,Oe as createMcpEventListenerEntry,Ce as createMcpMiddlewareEntry,_e as createMcpMount,eu as createRequestStateCodec,Rs as css,Cs as error,R as getRequestBag,me as hostValidationMiddleware,Ts as html,xs as image,tu as inputRequired,nu as inputResponse,ru as isInputRequiredResult,vs as javascript,fe as jsonBodyMiddleware,ws as markdown,le as matchesPath,X as matchesPathPrefix,L as matchesPattern,Ps as mix,Os as object,he as originValidationMiddleware,Y as pathnameOf,z as registerSkills,J as registerViews,Ue as requestLogger,Ss as resource,gs as text,As as widget,Ms as xml};
|
package/dist/internal/usage.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
var EVENT="mcp_use_sdk_event",ENDPOINT="https://eu.i.posthog.com/i/v0/e/",TOKEN="phc_lyTtbYwvkdSbrcMQNPiKiiRWrrM1seyKIMjycSvItEI",CONTENT=/(^|_)(arguments?|args|body|command|headers?|location|message|organization|path|query|response|secret|subject|token|uri|url|user_agent)(_|$)/i,RESERVED=new Set("feature action sdk_generation telemetry_schema_version sdk_package sdk_version server_id runtime_id identity_stability distinct_id validation_run_id is_validation".split(" ")),runtimeId;function getRuntimeId(){return runtimeId??=crypto.randomUUID(),runtimeId}var once=new Set,pending=new Set,identities=new Map;function hasControl(value){return[...value].some(character=>{let code=character.charCodeAt(0);return code<32||code===127})}function env(name){return typeof process>"u"?void 0:process.env?.[name]}function safeEnv(name){let value=env(name);return value!==void 0&&value.length>0&&value.length<=128&&!hasControl(value)?value:void 0}function canPersistTelemetryIdentity(){return typeof process>"u"||process.versions?.node===void 0?!1:!("Deno"in globalThis)}function disabled(){if(env("MCP_USE_ANONYMIZED_TELEMETRY")==="false")return!0;try{return globalThis.__MCP_USE_ANONYMIZED_TELEMETRY__===!1||typeof localStorage<"u"&&localStorage.getItem("MCP_USE_ANONYMIZED_TELEMETRY")==="false"}catch{return!1}}function isUsageDisabled(){return disabled()}function clean(properties){return Object.fromEntries(Object.entries(properties).filter(([key,value])=>key.length>128||hasControl(key)||key.startsWith("$")||RESERVED.has(key)||CONTENT.test(key)||value===void 0?!1:typeof value=="string"?value.length<=128&&!hasControl(value):typeof value=="boolean"||typeof value=="number"&&Number.isFinite(value)))}async function identity(serverRoot){let projectId=safeEnv("MCP_USE_TELEMETRY_PROJECT_ID");if(projectId!==void 0)return{id:projectId,stability:"project"};if(serverRoot===void 0||!canPersistTelemetryIdentity())return{id:getRuntimeId(),stability:"process"};let existing=identities.get(serverRoot);if(existing!==void 0)return existing;let resolving=(async()=>{try{let fs=await import("fs/promises"),directory=`${serverRoot}/.mcp-use`,file=`${directory}/usage.json`,read=async()=>{try{let value=JSON.parse(await fs.readFile(file,"utf8"));if(typeof value=="object"&&value!==null&&"schemaVersion"in value&&value.schemaVersion===1&&"serverId"in value&&typeof value.serverId=="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(value.serverId))return value.serverId}catch{}},stored=await read();if(stored!==void 0)return{id:stored,stability:"server"};await fs.mkdir(directory,{recursive:!0,mode:448});let created=crypto.randomUUID();try{return await fs.writeFile(file,`${JSON.stringify({schemaVersion:1,serverId:created})}
|
|
2
|
-
`,{flag:"wx",mode:384}),{id:created,stability:"server"}}catch{let raced=await read();if(raced!==void 0)return{id:raced,stability:"server"}}}catch{}return{id:getRuntimeId(),stability:"process"}})();return identities.set(serverRoot,resolving),resolving}function capture(feature,action,properties,options,resolveIdentity){let validationId=safeEnv("MCP_USE_TELEMETRY_VALIDATION_ID");if(disabled()||env("NODE_ENV")==="test"&&validationId===void 0||pending.size>=16)return;if(options.onceKey!==void 0){if(once.has(options.onceKey))return;once.add(options.onceKey)}let rate=Math.max(0,Math.min(1,options.sampleRate??1));if(validationId===void 0&&Math.random()>=rate)return;let request=(async()=>{try{let resolvedIdentity=await resolveIdentity(),body=JSON.stringify({api_key:TOKEN,event:EVENT,properties:{...clean(properties),feature,action,sdk_generation:"v2",telemetry_schema_version:2,sdk_package:"mcp-use",sdk_version:"2.
|
|
2
|
+
`,{flag:"wx",mode:384}),{id:created,stability:"server"}}catch{let raced=await read();if(raced!==void 0)return{id:raced,stability:"server"}}}catch{}return{id:getRuntimeId(),stability:"process"}})();return identities.set(serverRoot,resolving),resolving}function capture(feature,action,properties,options,resolveIdentity){let validationId=safeEnv("MCP_USE_TELEMETRY_VALIDATION_ID");if(disabled()||env("NODE_ENV")==="test"&&validationId===void 0||pending.size>=16)return;if(options.onceKey!==void 0){if(once.has(options.onceKey))return;once.add(options.onceKey)}let rate=Math.max(0,Math.min(1,options.sampleRate??1));if(validationId===void 0&&Math.random()>=rate)return;let request=(async()=>{try{let resolvedIdentity=await resolveIdentity(),body=JSON.stringify({api_key:TOKEN,event:EVENT,properties:{...clean(properties),feature,action,sdk_generation:"v2",telemetry_schema_version:2,sdk_package:"mcp-use",sdk_version:"2.9.0",server_id:resolvedIdentity.id,runtime_id:getRuntimeId(),identity_stability:resolvedIdentity.stability,distinct_id:resolvedIdentity.id,sample_rate:validationId===void 0?rate:1,$process_person_profile:!1,$geoip_disable:!0,...validationId!==void 0&&{is_validation:!0,validation_run_id:validationId}}});await fetch(ENDPOINT,{method:"POST",headers:{"content-type":"application/json"},keepalive:!0,body})}catch{return}})();pending.add(request),request.then(()=>pending.delete(request))}function recordUsage(feature,action,properties={},options={}){capture(feature,action,properties,options,()=>identity(options.serverRoot))}async function flushUsage(){await Promise.all([...pending])}export{flushUsage,isUsageDisabled,recordUsage};
|