mcp-use 2.12.0 → 2.12.1
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/README.md +50 -0
- package/dist/bin.js +1 -1
- package/dist/index-node.js +47 -54
- package/dist/index.js +1 -1
- package/dist/internal/usage.js +1 -1
- package/package.json +5 -5
package/dist/index.js
CHANGED
|
@@ -4,7 +4,7 @@ ${z("=".repeat(80))}`),console.log(Oe(z("[TRACE] Request Details"))),console.log
|
|
|
4
4
|
`)}o(co,"printTraceDump");function uo(e){let t=String(e);return e>=500?Xt(t):e>=400?se(t):e>=300?P(t):Yt(t)}o(uo,"styleStatus");function lo(e,t){return e!=="GET"&&e!=="HEAD"?!1:t.endsWith("/favicon.ico")}o(lo,"isNoisyRequest");function po(e){let{description:t,detail:n}=e;return[...e.prefix===void 0?[]:[Oe(e.prefix)],ro(t.method)(t.method),...n?.subject===void 0?[]:[Oe(H(n.subject))],e.pathname,uo(e.status),...t.client===void 0?[]:[Ue(`client=${H(t.client)}`)],Ue(`${e.durationMs}ms`),...e.suffix].join(" ")}o(po,"formatRequestLogLine");function Ie(e={}){return e.enabled===!1?(t,n)=>n():async(t,n)=>{let r=Zr(e.level),s=Date.now(),i=t.method,a=new URL(t.url).pathname;if(lo(i,a))return n();let c={};r==="trace"&&t.headers.forEach((y,T)=>{c[T]=y});let d;if(i!=="GET"&&i!=="HEAD"){let y=v(t).parsedBody;if(y!==void 0)d=y;else try{d=await t.clone().json(),(t.headers.get("content-type")??"").includes("application/json")&&(v(t).parsedBody=d)}catch{}}let u=oo(i,a,e.mcpPath,d),l=o((y,T,x=[])=>{console.log(po({prefix:e.prefix,description:u,detail:T,pathname:a,status:y,durationMs:Date.now()-s,suffix:x}))},"logLine"),p;try{p=await n()}catch(y){throw l(500,void 0,[se(`ERROR ${H(y instanceof Error?y.message:String(y))}`)]),y}let f=u.streaming||p.headers.get("content-type")?.split(";",1)[0]?.trim().toLowerCase()==="text/event-stream",m=u.mcpRequest===void 0?void 0:eo(u.mcpRequest),h=[];if(u.mcpRequest!==void 0&&m!==void 0){let y=r!=="info";y&&m.input!==void 0&&h.push(Jt(m.input));let T=f?{errorMessage:null}:await io(p,t);y&&u.mcpRequest.method==="tools/call"&&T.errorMessage===null&&T.result!==void 0&&h.push(Ue("->"),Jt(ao(T.result))),T.errorMessage!==null?h.push(se(`ERROR ${H(T.errorMessage)}`)):p.status>=400&&h.push(se(`ERROR (HTTP ${p.status})`))}l(p.status,m,h);let g=e.mcpPath!==void 0&&a.startsWith(C(e.mcpPath,"oauth/"));return r==="trace"&&!g&&await co(p,c,d,!f),p}}o(Ie,"requestLogger");import{createMcpHandler as fo}from"@modelcontextprotocol/server";import{trackBufferedResponse as mo}from"#mcp-use-buffered-response";function Le(e,t={}){let{path:n="/mcp",handler:r,authInfo:s}=t,i=r?.legacy??"stateless",a=fo(e,{legacy:"stateless",...r});return{handler:a,fetch:o(async d=>{if(!pe(d,n))return new Response("Not Found",{status:404});if(i==="stateless"){let g=d.method.toUpperCase();if(g==="GET"||g==="DELETE"||g==="HEAD")return new Response(null,{status:204})}let u=v(d),l=u.parsedBody;if(l===void 0)try{l=await d.clone().json()}catch{}let p=$t(l);p!==void 0&&Lt(d,p);let f=s?.(d)??u.authInfo,m=await a.fetch(d,{...l!==void 0&&{parsedBody:l},...f!==void 0&&{authInfo:f}});return m.headers.get("content-type")?.toLowerCase().includes("application/json")?"Bun"in globalThis&&m.body!==null?new Response(await m.arrayBuffer(),{status:m.status,statusText:m.statusText,headers:m.headers}):mo(d,m):m},"fetch")}}o(Le,"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 Qt(e,t){if(!Array.isArray(e))throw new TypeError(`${t} must be an array`);return e}o(Qt,"array");function L(e,t){if(typeof e!="string"||!e.trim())throw new TypeError(`${t} must be a non-blank string`)}o(L,"nonBlank");function ie(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(ie,"standard");function en(e){let t=e.readTool??"settings.read",n=e.updateTool??"settings.update";if(L(t,"readTool"),L(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(([m,h])=>[m,{...h}]);if(!r.length)throw new TypeError("Settings require at least one field");let s={};for(let[m,h]of r){if(L(h.title,`Setting ${m} title`),h.description!==void 0&&typeof h.description!="string")throw new TypeError(`Setting ${m} description must be a string`);let g=h.schema["~standard"].jsonSchema.output({target:"draft-2020-12"}),y=h.schema["~standard"].jsonSchema.input({target:"draft-2020-12"});if(!["boolean","string","number","integer"].includes(String(y.type))||g.type!==y.type||["$ref","anyOf","oneOf","allOf"].some(x=>x in y)||y.enum!==void 0&&(y.type!=="string"||!Array.isArray(y.enum)||!y.enum.length||!y.enum.every(x=>typeof x=="string")))throw new TypeError(`Unsupported native setting ${m}: use boolean, string, string enum, number, or integer`);let T=structuredClone(y);delete T.default,Object.defineProperty(s,m,{enumerable:!0,value:{...T,title:h.title,...h.description!==void 0&&{description:h.description}}})}let i={type:"object",properties:s,required:r.map(([m])=>m),additionalProperties:!1},a=e.layout===void 0?void 0:structuredClone(e.layout);if(a!==void 0)for(let m of Qt(a,"Settings layout")){let h=A(m,"Settings layout group");if(h.kind!=="group")throw new TypeError("Settings layout groups must have kind 'group'");L(h.title,"Settings layout group title");for(let g of Qt(h.items,"Settings layout group items")){let y=A(g,"Settings layout item");if(y.kind==="property"){if(L(y.property,"Settings layout property"),!Object.hasOwn(s,y.property))throw new TypeError(`Settings layout references unknown setting: ${y.property}`)}else if(y.kind==="tool"){if(L(y.tool,"Settings layout action tool"),L(y.title,"Settings layout action title"),y.description!==void 0&&typeof y.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 c=o(async(m,h=!1)=>{let g=A(m,h?"set":"values");for(let T of Object.keys(g))if(!Object.hasOwn(s,T))throw new TypeError(`Unknown setting: ${T}`);if(h&&!Object.keys(g).length)throw new TypeError("Set at least one setting");let y={};for(let[T,x]of r){if(!Object.hasOwn(g,T)){if(!h)throw new TypeError(`Missing effective setting: ${T}`);continue}let b=await x.schema["~standard"].validate(g[T]);if(b.issues!==void 0)throw new TypeError(`Invalid setting ${T}: ${b.issues.map(w=>w.message).join(", ")}`);if(b.value===void 0||!["string","boolean","number"].includes(typeof b.value)||typeof b.value=="number"&&!Number.isFinite(b.value))throw new TypeError(`Invalid primitive setting: ${T}`);if(!Object.is(b.value,g[T]))throw new TypeError(`Setting ${T} schema must not transform values`);Object.defineProperty(y,T,{enumerable:!0,value:b.value})}return y},"validateValues"),d=ie({type:"object",additionalProperties:!1},m=>{if(Object.keys(A(m,"arguments")).length)throw new TypeError("Settings read accepts empty arguments");return{}}),u=ie({type:"object",properties:{set:{...i,required:[],minProperties:1}},required:["set"],additionalProperties:!1},async m=>{let h=A(m,"arguments");if(Object.keys(h).some(g=>g!=="set"))throw new TypeError("Unknown settings update argument");return{set:await c(h.set,!0)}}),p=ie({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 m=>{let h=A(m,"settings result");return{...h,values:await c(h.values)}}),f=ie({type:"object",properties:{values:i},required:["values"]},async m=>({values:await c(A(m,"settings result").values)}));return{capability:{readTool:t,updateTool:n},schema:i,layout:a,readDefinition:{name:t,inputSchema:d,outputSchema:p,annotations:{readOnlyHint:!0}},updateDefinition:{name:n,inputSchema:u,outputSchema:f}}}o(en,"prepareSettings");import{completable as tn}from"@modelcontextprotocol/server";function $e(e){let t=e.map(String);return n=>{let r=String(n??"").toLowerCase();return t.filter(s=>s.toLowerCase().startsWith(r))}}o($e,"createPrefixCompletion");function ho(e,t){return typeof t=="function"?tn(e,(n,r)=>t(String(n??""),r)):tn(e,$e(t))}o(ho,"completable");function nn(e){let t=Object.create(null);for(let[n,r]of Object.entries(e))r!==void 0&&(t[n]=Array.isArray(r)?$e(r):r);return t}o(nn,"normalizeCompletions");import{ResourceLinkSchema as go}from"@modelcontextprotocol/core";import{fromJsonSchema as rn}from"@modelcontextprotocol/server";var yo=rn({type:"object",properties:{query:{type:"string"}},required:["query"]}),wo=rn({type:"object",properties:{items:{type:"array",items:go["~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 on(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:yo,outputSchema:wo,annotations:{readOnlyHint:!0,...e.annotations},_meta:{...e._meta,"openai/extensions":{...je(e._meta?.["openai/extensions"]),"mentions/search":{}}}}}o(on,"prepareMentions");function sn(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(sn,"finalizeMentionsMeta");import{fromJsonSchema as To}from"@modelcontextprotocol/server";var bo=["get","put","post","delete","options","head","patch","trace"];function un(e,t){let n=Ro(t.spec,t),r=Eo(n),s=n.length>0?Ho(t):void 0;for(let[i,a]of n.entries()){let c=r[i];if(c===void 0||s===void 0)continue;let d=Co(a);e.tool({name:c,description:Po(a),inputSchema:So(t.spec,a,d)},async u=>Lo(a,u,t,d,s))}}o(un,"registerOpenAPITools");function Ro(e,t){let n=[];for(let[r,s]of Object.entries(e.paths??{})){let i=N(e,s);if(i===void 0||K(i))continue;let a=an(e,i.parameters);for(let c of bo){let d=i[c];if(d===void 0)continue;let u=N(e,d);if(u===void 0||K(u))continue;let l=an(e,u.parameters),p=u.requestBody===void 0?void 0:N(e,u.requestBody),f={method:c,path:r,operation:u,parameters:xo(a,l),...p!==void 0&&!K(p)&&{requestBody:p}};vo(f,t)&&n.push(f)}}return n}o(Ro,"collectOperations");function an(e,t){let n=[];for(let r of t??[]){let s=N(e,r);s!==void 0&&!K(s)&&n.push(s)}return n}o(an,"resolveParameters");function xo(e,t){let n=new Map;for(let r of[...e,...t])n.set(`${r.in}:${r.name}`,r);return[...n.values()]}o(xo,"mergeParameters");function vo(e,t){if(t.tags?.length){let n=new Set(e.operation.tags??[]);if(!t.tags.some(r=>n.has(r)))return!1}return!(t.exclude??[]).some(n=>Mo(e,n))}o(vo,"isIncluded");function Mo(e,t){if(t.method&&t.method.toLowerCase()!==e.method||t.operationId&&!cn(t.operationId,e.operation.operationId??"")||t.path&&!cn(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(Mo,"matchesExcludeRule");function cn(e,t){return typeof e=="string"?e===t:(e.lastIndex=0,e.test(t))}o(cn,"matchesPattern");function Eo(e){let t=new Map;return e.map(n=>{let r=ko(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(Eo,"createToolNames");function Po(e){return[e.operation.summary,e.operation.description,`HTTP: ${e.method.toUpperCase()} ${e.path}`].filter(t=>!!t).join(`
|
|
5
5
|
|
|
6
6
|
`)}o(Po,"createToolDescription");function ko(e){return e.trim().replace(/[^a-zA-Z0-9_-]+/g,"_").replace(/_+/g,"_").replace(/^_/,"").replace(/_$/,"").slice(0,64)||"openapi_tool"}o(ko,"slugifyToolName");function So(e,t,n){let r={},s=[];for(let{parameter:d,inputName:u}of n.parameters){let l=dn(e,d.schema??{});r[u]={...l,description:d.description??`${d.in} parameter`},(d.required||d.in==="path")&&s.push(u)}let i=ln(t.requestBody);i!==void 0&&n.bodyInputName!==void 0&&(r[n.bodyInputName]=dn(e,i),t.requestBody?.required&&s.push(n.bodyInputName));let a=Oo(e),c={type:"object",properties:r,additionalProperties:!1,...s.length>0&&{required:s},...a!==void 0&&{$defs:a}};return To(c)}o(So,"createToolInputSchema");function Co(e){let t=e.parameters.filter(a=>a.in!=="cookie"),n=ln(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 d=(r.get(a.name)??0)>1||a.name===n?`${a.name}_${a.in}`:a.name;return{parameter:a,inputName:Ao(d,s)}}),...n!==void 0&&{bodyInputName:n}}}o(Co,"createInputBindings");function Ao(e,t){let n=e,r=2;for(;t.has(n);)n=`${e}_${r}`,r+=1;return t.add(n),n}o(Ao,"claimInputName");function Oo(e){let t=D(e.components?.schemas);if(t===void 0)return;let n={};for(let[r,s]of Object.entries(t))n[r]=W(e,s,new Set);return n}o(Oo,"createSchemaDefinitions");function dn(e,t){let n=W(e,t,new Set);return D(n)??{}}o(dn,"transformSchema");function W(e,t,n){if(Array.isArray(t))return t.map(c=>W(e,c,n));let r=D(t);if(r===void 0)return t;let s=typeof r.$ref=="string"?r.$ref:void 0,i={};for(let[c,d]of Object.entries(r))c!=="$ref"&&(c==="nullable"&&typeof d=="boolean"||_o(c)&&typeof d=="boolean"||(i[c]=W(e,d,n)));for(let[c,d]of Uo)r[d]===!0&&typeof r[c]=="number"&&(i[d]=r[c],delete i[c]);let a=i;if(s!==void 0){let c=Io(e,s);if(c!==void 0)a={$ref:c,...i};else if(!n.has(s)){let d=N(e,{$ref:s});if(d!==void 0){let u=new Set(n);u.add(s),a={...D(W(e,d,u))??{},...i}}}}return r.nullable===!0?{anyOf:[a,{type:"null"}]}:a}o(W,"transformSchemaNode");var Uo=[["minimum","exclusiveMinimum"],["maximum","exclusiveMaximum"]];function _o(e){return e==="exclusiveMinimum"||e==="exclusiveMaximum"}o(_o,"isExclusiveBoundKey");function Io(e,t){let n="#/components/schemas/";if(t.startsWith(n))return N(e,{$ref:t})===void 0?void 0:`#/$defs/${t.slice(n.length)}`}o(Io,"rewriteSchemaRef");function ln(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(ln,"getJsonRequestBodySchema");async function Lo(e,t,n,r,s){let i=n.fetch??globalThis.fetch,a=$o(e,t,r.parameters,s),c=jo(r.parameters,t,n),d=r.bodyInputName,u=d===void 0||t[d]===void 0?void 0:JSON.stringify(t[d]);u!==void 0&&!qo(c,"content-type")&&(c["content-type"]="application/json");let l=await i(a,{method:e.method.toUpperCase(),headers:c,...u!==void 0&&{body:u}}),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 f=await l.text();try{let m=JSON.parse(f);return{content:[{type:"text",text:JSON.stringify(m)}],structuredContent:m}}catch{return{content:[{type:"text",text:f}]}}}return{content:[{type:"text",text:await l.text()}]}}o(Lo,"callOpenAPIOperation");function $o(e,t,n,r){let s=e.path.replace(/{([^}]+)}/g,(a,c)=>{let d=n.find(({parameter:u})=>u.in==="path"&&u.name===c);return encodeURIComponent(String(d===void 0?"":t[d.inputName]??""))}),i=new URL(s.replace(/^\/+/,""),Do(r));for(let{parameter:a,inputName:c}of n){if(a.in!=="query")continue;let d=t[c];d==null||d===""||No(i,a.name,d)}return i.toString()}o($o,"buildUrl");function jo(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(jo,"buildHeaders");function Ho(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(Ho,"resolveBaseUrl");function No(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(No,"appendQueryParam");function Do(e){return e.endsWith("/")?e:`${e}/`}o(Do,"ensureTrailingSlash");function qo(e,t){return Object.keys(e).some(n=>n.toLowerCase()===t)}o(qo,"hasHeader");function K(e){let t=D(e);return t!==void 0&&typeof t.$ref=="string"}o(K,"isReferenceObject");function N(e,t){if(!K(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(N,"resolveRef");function D(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:void 0}o(D,"readRecord");import{OAuthError as Ad,OAuthErrorCode as Od,bearerAuthChallengeResponse as Ud,getOAuthProtectedResourceMetadataUrl as xn,oauthMetadataResponse as _d,requireBearerAuth as Id,verifyBearerToken as Ld}from"@modelcontextprotocol/server";import{getOAuthProtectedResourceMetadataUrl as ya,oauthMetadataResponse as Jo,requireBearerAuth as wa}from"@modelcontextprotocol/server";function q(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}o(q,"isRecord");function O(e){let t=e.hostname.toLowerCase();return t==="localhost"||t.endsWith(".localhost")||t==="[::1]"||/^127(?:\.\d{1,3}){3}$/.test(t)}o(O,"isLocalhost");function V(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(V,"parseAbsoluteUrl");function J(e,t){if(e.protocol!=="https:"&&!(e.protocol==="http:"&&O(e)))throw new Error(`${t} must use HTTPS, or HTTP for localhost`)}o(J,"assertSecureHttpUrl");function He(e){if(e===null||typeof e!="object"||!("issuer"in e)||typeof e.issuer!="string")throw new TypeError("oauthMetadata must include a string issuer");J(V(e.issuer,"oauthMetadata.issuer"),"oauthMetadata.issuer")}o(He,"assertOAuthMetadata");import{OAuthError as Vo,OAuthErrorCode as Fo}from"@modelcontextprotocol/server";function M(e,t){let n=new Vo(Fo.InvalidToken,e);return t!==void 0&&(n.cause=t),n}o(M,"invalidToken");function pn(e){let t=e.provider,n=Ve(e.basePath);if(t.resource!==void 0)return Ne(t.resource,n);if(e.mcpUrl!==void 0)return Ne(gn(hn(e.mcpUrl,"MCP_URL"),n),n)}o(pn,"resolveConfiguredOAuthResource");function fn(e,t){let n=hn(e,"listen origin");if(!O(n))throw new Error("OAuth listen origin must be localhost or a loopback address");return Ne(gn(n,Ve(t)),t)}o(fn,"resolveLocalOAuthResource");function Ne(e,t){let n=Ve(t),r=V(e,"OAuth resource");if(r.search!==""||r.hash!=="")throw new Error("OAuth resource must not include a query string or fragment");if(J(r,"OAuth resource"),yn(r.pathname)!==n)throw new Error(`OAuth resource path must exactly match basePath (${n})`);return r.pathname=n,r}o(Ne,"validateOAuthResource");function De(e,t){let n=qe(t),r=e.createTokenVerifier(new URL(n.href));if(r===null||typeof r!="object"||typeof r.verifyAccessToken!="function")throw new TypeError("OAuth provider createTokenVerifier must return an OAuthTokenVerifier");return{async verifyAccessToken(s){let i=await r.verifyAccessToken(s);Wo(i),Bo(i,n);let a;try{a=e.mapAuthInfo(i)}catch(c){throw M("Token identity mapping failed",c)}return Ko(a),{...i,scopes:[...i.scopes],extra:{...i.extra,...a}}}}}o(De,"wrapOAuthTokenVerifier");function Bo(e,t){if(e.resource===void 0)throw M("Token verifier did not return a validated protected resource");if(zo(e.resource).href!==qe(t).href)throw M("Token resource does not match the protected resource")}o(Bo,"assertResourceBinding");function zo(e){if(!(e instanceof URL))throw M("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:"&&!O(t))throw M("Token resource must be an absolute HTTPS URL, or HTTP URL for localhost");return qe(t)}o(zo,"parseTokenResource");function qe(e){let t=new URL(e);return t.pathname=t.pathname==="/"?"/":t.pathname.replace(/\/+$/,""),t}o(qe,"normalizeResourceUrl");function mn(e,t){let n=e.oauthMetadata;if(typeof n!="function")return n;let r=n(new URL(t.href));return He(r),r}o(mn,"resolveOAuthMetadata");function ae(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(ae,"getOAuthProviderOptions");function Wo(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 M("Token verifier returned invalid authentication information")}o(Wo,"assertVerifiedAuthInfo");function Ko(e){if(e===null||typeof e!="object"||!("user"in e)||e.user===void 0||!q(e.payload)||!Array.isArray(e.permissions)||!e.permissions.every(t=>typeof t=="string"))throw M("Token identity mapping must return user, payload, and string permissions")}o(Ko,"assertMappedExtra");function hn(e,t){let n=V(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(hn,"requireAbsoluteOrigin");function gn(e,t){let n=new URL(e.origin);return n.pathname=t,n}o(gn,"appendBasePath");function Ve(e){if(!e.startsWith("/")||e.includes("?")||e.includes("#"))throw new Error("basePath must be an absolute URL pathname");return yn(e)}o(Ve,"normalizeBasePath");function yn(e){if(e==="/")return"/";let t=e.length;for(;t>0&&e.charCodeAt(t-1)===47;)t--;return e.slice(0,t)}o(yn,"normalizePathname");function Fe(e,t){let n=ae(e),r=mn(e,t);return async(s,i)=>{let a=Jo(s,{oauthMetadata:r,resourceServerUrl:t,...n.scopesSupported!==void 0&&{scopesSupported:[...n.scopesSupported]},...n.resourceName!==void 0&&{resourceName:n.resourceName},...n.serviceDocumentationUrl!==void 0&&{serviceDocumentationUrl:n.serviceDocumentationUrl}});return a!==void 0?a:i()}}o(Fe,"oauthMetadata");function wn(e){return v(e).authInfo}o(wn,"authInfoFromRequest");import{OAuthError as Ma}from"@modelcontextprotocol/server";import{createRemoteJWKSet as Pa,jwtVerify as ka,errors as Sa}from"jose";import{OAuthClientMetadataSchema as Za}from"@modelcontextprotocol/core";var Na=new TextEncoder,Da=new TextDecoder("utf-8",{fatal:!0});function Be(){return typeof process>"u"||process.env===void 0?!1:process.env.MCP_USE_PHASE==="build"}o(Be,"isBuilding");var rc=365*24*60*60;var oc=5*1024;var sc=300*1e3;import{deleteCookie as Mc,getCookie as Ec,getSignedCookie as Pc,setSignedCookie as kc}from"hono/cookie";var Ic=720*60*60;var Lc=1440*60*60,$c=365*24*60*60;function ce(e){return e.inputSchema??e.schema}o(ce,"resolveToolInputSchema");import{fromJsonSchema as ts}from"@modelcontextprotocol/server";var vn="openai/ui";function ns(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}o(ns,"record");function Mn(e){let t=e.view?.entrypoints;if(!t?.length)return;let n=ce(e),r=n?ts(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 c=r?.(a);if(c&&("then"in c||c.issues))throw new TypeError(`Tool "${e.name}" ${s.type} entrypoint launch arguments do not satisfy its inputSchema.`)}}}o(Mn,"validateEntrypointInput");function En(e){let t=e.view?.entrypoints;if(t===void 0)return e._meta;let n=e._meta?.[vn];return{...e._meta,[vn]:{...ns(n)?n:{},entrypoints:t.map(r=>r.type==="file"?{type:r.type,extensions:[...r.extensions]}:{type:r.type})}}}o(En,"buildEntrypointMeta");var rs="mcp_use_sdk_event",os="https://eu.i.posthog.com/i/v0/e/",ss="phc_lyTtbYwvkdSbrcMQNPiKiiRWrrM1seyKIMjycSvItEI",is=/(^|_)(arguments?|args|body|command|headers?|location|message|organization|path|query|response|secret|subject|token|uri|url|user_agent)(_|$)/i,as=new Set("feature action sdk_generation telemetry_schema_version sdk_package sdk_version server_id runtime_id identity_stability distinct_id validation_run_id is_validation".split(" ")),Pn;function We(){return Pn??=crypto.randomUUID(),Pn}o(We,"getRuntimeId");var kn=new Set,ze=new Set,Sn=new Map;function Ke(e){return[...e].some(t=>{let n=t.charCodeAt(0);return n<32||n===127})}o(Ke,"hasControl");function Je(e){return typeof process>"u"?void 0:process.env?.[e]}o(Je,"env");function Cn(e){let t=Je(e);return t!==void 0&&t.length>0&&t.length<=128&&!Ke(t)?t:void 0}o(Cn,"safeEnv");function cs(){return typeof process>"u"||process.versions?.node===void 0?!1:!("Deno"in globalThis)}o(cs,"canPersistTelemetryIdentity");function An(){if(Je("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(An,"disabled");function On(){return An()}o(On,"isUsageDisabled");function ds(e){return Object.fromEntries(Object.entries(e).filter(([t,n])=>t.length>128||Ke(t)||t.startsWith("$")||as.has(t)||is.test(t)||n===void 0?!1:typeof n=="string"?n.length<=128&&!Ke(n):typeof n=="boolean"||typeof n=="number"&&Number.isFinite(n)))}o(ds,"clean");async function us(e){let t=Cn("MCP_USE_TELEMETRY_PROJECT_ID");if(t!==void 0)return{id:t,stability:"project"};if(e===void 0||!cs())return{id:We(),stability:"process"};let n=Sn.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`,c=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"),d=await c();if(d!==void 0)return{id:d,stability:"server"};await s.mkdir(i,{recursive:!0,mode:448});let u=crypto.randomUUID();try{return await s.writeFile(a,`${JSON.stringify({schemaVersion:1,serverId:u})}
|
|
7
|
-
`,{flag:"wx",mode:384}),{id:u,stability:"server"}}catch{let l=await c();if(l!==void 0)return{id:l,stability:"server"}}}catch{}return{id:We(),stability:"process"}})();return Sn.set(e,r),r}o(us,"identity");function ls(e,t,n,r,s){let i=Cn("MCP_USE_TELEMETRY_VALIDATION_ID");if(An()||Je("NODE_ENV")==="test"&&i===void 0||ze.size>=16)return;if(r.onceKey!==void 0){if(kn.has(r.onceKey))return;kn.add(r.onceKey)}let a=Math.max(0,Math.min(1,r.sampleRate??1));if(i===void 0&&Math.random()>=a)return;let c=(async()=>{try{let d=await s(),u=JSON.stringify({api_key:ss,event:rs,properties:{...ds(n),feature:e,action:t,sdk_generation:"v2",telemetry_schema_version:2,sdk_package:"mcp-use",sdk_version:"2.12.
|
|
7
|
+
`,{flag:"wx",mode:384}),{id:u,stability:"server"}}catch{let l=await c();if(l!==void 0)return{id:l,stability:"server"}}}catch{}return{id:We(),stability:"process"}})();return Sn.set(e,r),r}o(us,"identity");function ls(e,t,n,r,s){let i=Cn("MCP_USE_TELEMETRY_VALIDATION_ID");if(An()||Je("NODE_ENV")==="test"&&i===void 0||ze.size>=16)return;if(r.onceKey!==void 0){if(kn.has(r.onceKey))return;kn.add(r.onceKey)}let a=Math.max(0,Math.min(1,r.sampleRate??1));if(i===void 0&&Math.random()>=a)return;let c=(async()=>{try{let d=await s(),u=JSON.stringify({api_key:ss,event:rs,properties:{...ds(n),feature:e,action:t,sdk_generation:"v2",telemetry_schema_version:2,sdk_package:"mcp-use",sdk_version:"2.12.1",server_id:d.id,runtime_id:We(),identity_stability:d.stability,distinct_id:d.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(os,{method:"POST",headers:{"content-type":"application/json"},keepalive:!0,body:u})}catch{return}})();ze.add(c),c.then(()=>ze.delete(c))}o(ls,"capture");var ps=/bot|crawl|spider|slurp|preview|facebookexternalhit|embedly|headless|curl|wget|python-requests|go-http-client/i;function Un(e){return e===null||ps.test(e)}o(Un,"isLikelyBot");function G(e,t,n={},r={}){ls(e,t,n,r,()=>us(r.serverRoot))}o(G,"recordUsage");import{INVALID_PARAMS as _n,ProtocolError as In}from"@modelcontextprotocol/server";function Ye(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(Ye,"schema");function Xe(e){if(typeof e!="object"||e===null||Array.isArray(e))throw new TypeError("params must be an object");return e}o(Xe,"object");var fs=Ye(e=>{let n=Xe(e).cursor;if(n!==void 0&&typeof n!="string")throw new TypeError("cursor must be a string");return n===void 0?{}:{cursor:n}}),Ln=Ye(e=>{let t=Xe(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}}}),Ge=Ye(e=>Xe(e));function ms(e){try{return decodeURIComponent(e)}catch{return e}}o(ms,"decodePathSegment");function $n(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:fs,result:Ge},async()=>({skills:t.skills})),e.server.setRequestHandler("skills/get",{params:Ln,result:Ge},async({uri:r})=>{let s=n.get(r);if(s===void 0)throw new In(_n,`Unknown skill: ${r}`);return{skill:s}}),e.server.setRequestHandler("resources/directory/read",{params:Ln,result:Ge},async({uri:r})=>{let s=r.replace(/\/$/,""),i=new Set(t.directories.map(d=>d.uri)),a=`${s}/`,c=new Map;for(let d of t.resources){if(!d.uri.startsWith(a))continue;let u=d.uri.slice(a.length),[l]=u.split("/");if(l===void 0||l==="")continue;let p=`${s}/${l}`;c.set(p,{uri:p,name:ms(l),mimeType:u.includes("/")?"inode/directory":d.mimeType})}for(let d of t.directories){if(!d.uri.startsWith(a))continue;let u=d.uri.slice(a.length);u===""||u.includes("/")||c.set(d.uri,{uri:d.uri,name:d.name,mimeType:"inode/directory"})}if(!i.has(s))throw new In(_n,`Unknown skill directory: ${r}`);return{resources:[...c.values()].sort((d,u)=>d.uri.localeCompare(u.uri))}})}o($n,"registerSkillsRuntime");var Ze="io.modelcontextprotocol/skills",Y=Symbol.for("mcp-use.registerSkills");var X=Symbol("mcp-use/registerViews");function hs(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(hs,"resolveAssetUrl");function gs(e,t){return`${C(e,`_mcp-use/views/${t}`)}/`}o(gs,"viewAssetsBasePath");function Qe(e,t,n,r){return e.startsWith("http://")||e.startsWith("https://")||e.startsWith("data:")?e:e.startsWith("/")?hs(e,t):`${t}${gs(n,r)}${e.replace(/^\/+/,"")}`}o(Qe,"resolveExternalAssetUrl");function ys(e,t){return`${e}${C(t,"_mcp-use/public")}/`}o(ys,"resolvePublicBase");function jn(e){return e.replaceAll(/<\/script/gi,"<\\/script").replaceAll("<!--","\\x3C!--")}o(jn,"escapeInlineScript");function ws(e){return e.replaceAll(/<\/style/gi,"<\\/style")}o(ws,"escapeInlineStyle");function et(e){return e.replaceAll("&","&").replaceAll('"',""").replaceAll("<","<").replaceAll(">",">")}o(et,"escapeHtml");var Hn=`<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)}
|
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.12.
|
|
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.12.1",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))}var BOT=/bot|crawl|spider|slurp|preview|facebookexternalhit|embedly|headless|curl|wget|python-requests|go-http-client/i;function isLikelyBot(userAgent){return userAgent===null||BOT.test(userAgent)}function recordUsage(feature,action,properties={},options={}){capture(feature,action,properties,options,()=>identity(options.serverRoot))}async function flushUsage(){await Promise.all([...pending])}export{flushUsage,isLikelyBot,isUsageDisabled,recordUsage};
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "mcp-use",
|
|
3
3
|
"type": "module",
|
|
4
|
-
"version": "2.12.
|
|
4
|
+
"version": "2.12.1",
|
|
5
5
|
"description": "MCP framework and CLI built on the official v2 SDK",
|
|
6
6
|
"author": "mcp-use, Inc.",
|
|
7
7
|
"license": "MIT",
|
|
@@ -137,8 +137,8 @@
|
|
|
137
137
|
"hono": "^4.13.7",
|
|
138
138
|
"jose": "^6.1.3",
|
|
139
139
|
"oauth4webapi": "^3.8.8",
|
|
140
|
-
"@mcp-use/inspector": "20.3.
|
|
141
|
-
"@mcp-use/cli": "4.5.
|
|
140
|
+
"@mcp-use/inspector": "20.3.26",
|
|
141
|
+
"@mcp-use/cli": "4.5.4"
|
|
142
142
|
},
|
|
143
143
|
"peerDependencies": {
|
|
144
144
|
"@mcp-use/client": "^2.0.1 || ^2.1.0 || ^2.1.1 || ^2.1.2 || ^2.1.3 || ^2.1.4 || ^2.1.5 || ^2.2.0 || ^2.2.1 || ^2.2.2 || ^2.2.3 || ^2.2.4 || ^2.2.5 || ^2.3.0 || ^2.3.1 || ^2.3.2 || ^2.3.3 || ^2.3.4 || ^2.3.5 || ^2.4.0 || ^2.4.1 || ^2.4.2 || ^2.4.3 || ^2.4.4 || ^2.4.5",
|
|
@@ -167,12 +167,12 @@
|
|
|
167
167
|
"@types/react-dom": "^19.2.3",
|
|
168
168
|
"emulate": "0.12.1",
|
|
169
169
|
"es-module-lexer": "^2.3.0",
|
|
170
|
-
"happy-dom": "^
|
|
170
|
+
"happy-dom": "^21.0.4",
|
|
171
171
|
"react": "^19.2.7",
|
|
172
172
|
"react-dom": "^19.2.7",
|
|
173
173
|
"typescript": "^7.0.2",
|
|
174
174
|
"vitest": "^4.1.12",
|
|
175
|
-
"zod": "^4.
|
|
175
|
+
"zod": "^4.6.6",
|
|
176
176
|
"vite": "8.1.6",
|
|
177
177
|
"@mcp-use/client": "2.4.5"
|
|
178
178
|
},
|