mcp-use 2.0.0-beta.42 → 2.0.0-beta.44
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/bin.js +1 -1
- package/dist/{chunk-OZAFG2BM.js → chunk-LZNRJXOI.js} +2 -2
- package/dist/index.js +1 -1
- package/dist/internal/usage.js +1 -1
- package/dist/react/index.js +138 -23
- package/dist/react/runtime/view-runtime-context.d.ts +3 -1
- package/dist/usage.d.ts +6 -3
- package/package.json +4 -4
package/dist/bin.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
var{main}=await import("@mcp-use/cli");main(process.argv.slice(2),{frameworkVersion:"2.0.0-beta.
|
|
2
|
+
var{main}=await import("@mcp-use/cli");main(process.argv.slice(2),{frameworkVersion:"2.0.0-beta.44"}).then(code=>{process.exitCode=code},error=>{console.error(error instanceof Error?error.message:String(error)),process.exitCode=1});
|
|
@@ -1,2 +1,2 @@
|
|
|
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=crypto.randomUUID(),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 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||typeof process>"u")return{id:runtimeId,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:runtimeId,stability:"process"}})();return identities.set(serverRoot,resolving),resolving}function
|
|
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=crypto.randomUUID(),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 disabled(){if(env("MCP_USE_ANONYMIZED_TELEMETRY")==="false"||typeof __MCP_USE_VIEW_USAGE_DISABLED__<"u"&&__MCP_USE_VIEW_USAGE_DISABLED__)return!0;try{return globalThis.__MCP_USE_ANONYMIZED_TELEMETRY__===!1||typeof localStorage<"u"&&localStorage.getItem("MCP_USE_ANONYMIZED_TELEMETRY")==="false"}catch{return!1}}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||typeof process>"u")return{id:runtimeId,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:runtimeId,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.0.0-beta.44",server_id:resolvedIdentity.id,runtime_id:runtimeId,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))}function recordRuntimeUsage(feature,action,properties={},options={}){capture(feature,action,properties,options,async()=>({id:runtimeId,stability:"process"}))}async function flushUsage(){await Promise.all([...pending])}export{recordUsage,recordRuntimeUsage,flushUsage};
|
package/dist/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{hasExplicitAssetsBase,originFromAssetsBase,resolveAssetsBase,resolveServerOrigin}from"./chunk-PSKSL567.js";import{registerOpenAPITools}from"./chunk-Y26DNVWA.js";import{completable,normalizeCompletions}from"./chunk-OJF6B5EU.js";import{recordUsage}from"./chunk-OZAFG2BM.js";import{resolvePublicFilePath,servePublicFile}from"./chunk-ZMU5USAZ.js";import{authInfoFromRequest,composeFetch,getOAuthProtectedResourceMetadataUrl,getRequestBag,hostValidationMiddleware,isHtmlNavigationRequest,jsonBodyMiddleware,matchesPath,matchesPathPrefix,oauthMetadata,originValidationMiddleware,pathUnderBase,pathnameOf,requireBearerAuth}from"./chunk-GYZ3NHFQ.js";import{getOAuthProviderOptions,resolveConfiguredOAuthResource,resolveLocalOAuthResource,wrapOAuthTokenVerifier}from"./chunk-Q3UZSROW.js";import{localhostAllowedHostnames,localhostAllowedOrigins,McpServer as SdkMcpServer,ResourceTemplate,CLIENT_CAPABILITIES_META_KEY as CLIENT_CAPABILITIES_META_KEY3,CLIENT_INFO_META_KEY as CLIENT_INFO_META_KEY3,PROTOCOL_VERSION_META_KEY,isJSONRPCRequest as isJSONRPCRequest2,isInputRequiredResult as isInputRequiredResult2}from"@modelcontextprotocol/server";import{Hono}from"hono";var FAVICON_CACHE_CONTROL="public, max-age=31536000, immutable",FAVICON_REDIRECT_CACHE_CONTROL="public, max-age=300";function protocolOf(value){return/^([a-z][a-z\d+.-]*):/i.exec(value)?.[1]?.toLowerCase()}function publicAssetPath(basePath,source){return`${basePath==="/"?"":basePath}/_mcp-use/public/${source.split("/").map(segment=>encodeURIComponent(segment)).join("/")}`}function isLocalPublicSource(source){return protocolOf(source)===void 0}function selectFaviconFromIcons(icons){return icons[0]}function assertLocalPublicSource(source,field){if(source.startsWith("/")||source.includes("\\")||source.includes("?")||source.includes("#")||source.split("/").some(segment=>segment===""||segment===".."))throw new TypeError(`${field} must be an http(s) URL, image data URL, or safe path relative to public/`)}function parseDataImage(source,field){let comma=source.indexOf(",");if(comma<0)throw new TypeError(`${field} must be a valid image data URL`);let metadata=source.slice(5,comma),payload=source.slice(comma+1),parts=metadata.split(";"),mimeType=parts[0]?.toLowerCase()??"";if(!mimeType.startsWith("image/"))throw new TypeError(`${field} data URL must use an image MIME type`);try{if(parts.includes("base64")){let binary2=atob(payload);return{mimeType,bytes:Uint8Array.from(binary2,character=>character.charCodeAt(0))}}return{mimeType,bytes:new TextEncoder().encode(decodeURIComponent(payload))}}catch{throw new TypeError(`${field} must be a valid image data URL`)}}function assertBrandingSource(source,field){if(typeof source!="string"||source.length===0)throw new TypeError(`${field} must be a non-empty string`);let protocol=protocolOf(source);if(protocol===void 0)return assertLocalPublicSource(source,field),source;if(protocol==="data")return parseDataImage(source,field),source;if(protocol!=="http"&&protocol!=="https")throw new TypeError(`${field} must be an http(s) URL, image data URL, or safe path relative to public/`);try{new URL(source)}catch{throw new TypeError(`${field} must be a valid absolute http(s) URL`)}return source}function normalizeServerBranding(config){let websiteUrl;if(config.websiteUrl!==void 0){if(typeof config.websiteUrl!="string"||config.websiteUrl.length===0)throw new TypeError("websiteUrl must be a non-empty absolute http(s) URL");let parsed;try{parsed=new URL(config.websiteUrl)}catch{throw new TypeError("websiteUrl must be a non-empty absolute http(s) URL")}if(parsed.protocol!=="http:"&&parsed.protocol!=="https:")throw new TypeError("websiteUrl must be a non-empty absolute http(s) URL");websiteUrl=config.websiteUrl}let icons;if(config.icons!==void 0){if(!Array.isArray(config.icons))throw new TypeError("icons must be an array of MCP Icon objects");icons=Object.freeze(config.icons.map((value,index)=>{if(typeof value!="object"||value===null)throw new TypeError(`icons[${index}] must be an MCP Icon object`);let icon=value,src=assertBrandingSource(icon.src,`icons[${index}].src`),mimeType=icon.mimeType;if(mimeType!==void 0&&(typeof mimeType!="string"||!mimeType.toLowerCase().startsWith("image/")))throw new TypeError(`icons[${index}].mimeType must be an image MIME type when provided`);let sizes=icon.sizes;if(sizes!==void 0&&(!Array.isArray(sizes)||sizes.some(size=>typeof size!="string"||size.length===0)))throw new TypeError(`icons[${index}].sizes must be an array of non-empty strings when provided`);let normalizedSizes=sizes===void 0?void 0:sizes.map(size=>size),theme=icon.theme;if(theme!==void 0&&theme!=="light"&&theme!=="dark")throw new TypeError(`icons[${index}].theme must be "light" or "dark" when provided`);return Object.freeze({src,...mimeType!==void 0&&{mimeType},...normalizedSizes!==void 0&&{sizes:Object.freeze(normalizedSizes)},...theme!==void 0&&{theme}})}))}let explicitFavicon=config.favicon===void 0?void 0:assertBrandingSource(config.favicon,"favicon"),inferred=explicitFavicon===void 0?selectFaviconFromIcons(icons??[]):void 0,favicon=explicitFavicon??inferred?.src,faviconMimeType=inferred?.mimeType??icons?.find(icon=>icon.src===explicitFavicon)?.mimeType;return Object.freeze({...favicon!==void 0&&{favicon},...faviconMimeType!==void 0&&{faviconMimeType},...icons!==void 0&&{icons},...websiteUrl!==void 0&&{websiteUrl}})}function resolveImplementationIcons(icons,request,basePath){if(icons!==void 0)return icons.map(icon=>({...icon,src:request!==void 0&&isLocalPublicSource(icon.src)?`${resolveAssetsBase(request)}${publicAssetPath(basePath,icon.src)}`:icon.src,...icon.sizes!==void 0&&{sizes:[...icon.sizes]}}))}function hasLocalBrandingAsset(branding){return branding.favicon!==void 0&&isLocalPublicSource(branding.favicon)||branding.icons?.some(icon=>isLocalPublicSource(icon.src))===!0}function createFaviconHandler(branding,options){let source=branding.favicon;if(source!==void 0)return async request=>{if(request.method!=="GET"&&request.method!=="HEAD")return new Response("Method Not Allowed",{status:405,headers:{Allow:"GET, HEAD"}});if(new URL(request.url).pathname!=="/favicon.ico")return new Response("Not Found",{status:404});let protocol=protocolOf(source);if(protocol==="http"||protocol==="https")return new Response(null,{status:307,headers:{Location:source,"Cache-Control":FAVICON_REDIRECT_CACHE_CONTROL}});if(protocol==="data"){let data=parseDataImage(source,"favicon");return new Response(request.method==="HEAD"?null:data.bytes.buffer,{status:200,headers:{"Content-Type":branding.faviconMimeType??data.mimeType,"Cache-Control":FAVICON_CACHE_CONTROL,"X-Content-Type-Options":"nosniff"}})}let{join}=await import("path"),publicRoot=options.dev?join(options.projectRoot,"public"):join(options.projectRoot,".mcp-use/build/views/public"),diskPath=await resolvePublicFilePath(publicRoot,source);if(diskPath===null)return new Response("Not Found",{status:404,headers:{"Cache-Control":"no-store"}});let response=await servePublicFile(diskPath,{...options.deferCors===!0&&{deferCors:!0},...request.method==="HEAD"&&{head:!0}});return response.headers.set("Cache-Control",FAVICON_CACHE_CONTROL),response.headers.set("X-Content-Type-Options","nosniff"),branding.faviconMimeType!==void 0&&response.headers.set("Content-Type",branding.faviconMimeType),response}}function assertServerConfig(config){if(config.basePath!==void 0){if(typeof config.basePath!="string")throw new TypeError("basePath must be an absolute URL pathname without empty segments, trailing slash, query, fragment, or whitespace");let{basePath}=config;if(!basePath.startsWith("/")||basePath.includes("?")||basePath.includes("#")||/\s/.test(basePath)||basePath.includes("//")||basePath.length>1&&basePath.endsWith("/"))throw new TypeError("basePath must be an absolute URL pathname without empty segments, trailing slash, query, fragment, or whitespace")}if(config.port!==void 0&&(typeof config.port!="number"||!Number.isInteger(config.port)||config.port<0||config.port>65535))throw new TypeError("port must be an integer between 0 and 65535")}var DEFAULT_LISTEN_HOST="127.0.0.1";function resolveListenHost(explicitHost,configuredHost,env=process.env){if(explicitHost!==void 0)return explicitHost;let envHost=env.HOST?.trim();return envHost!==void 0&&envHost!==""?envHost:configuredHost??DEFAULT_LISTEN_HOST}function resolveListenPort(explicitPort,configuredPort,env=process.env){if(explicitPort!==void 0)return explicitPort;let envPort=parsePort(env.PORT);return envPort!==void 0?envPort:configuredPort??3e3}function parsePort(value){if(value===void 0||value.trim()==="")return;let port=Number(value);return Number.isInteger(port)&&port>=0&&port<=65535?port:void 0}import{CLIENT_CAPABILITIES_META_KEY as CLIENT_CAPABILITIES_META_KEY2,CLIENT_INFO_META_KEY,inputRequired,inputResponse}from"@modelcontextprotocol/server";import{HonoRequest}from"hono/request";import{CLIENT_CAPABILITIES_META_KEY}from"@modelcontextprotocol/server";var UI_EXTENSION_ID="io.modelcontextprotocol/ui",UI_MIME_TYPE="text/html;profile=mcp-app",UI_RESOURCE_URI_PREFIX="ui://views/";var UI_RESOURCE_URI_META_KEY="ui/resourceUri";function viewResourceUri(viewName){return`${UI_RESOURCE_URI_PREFIX}${viewName}.html`}var clientCapabilitiesByRequest=new WeakMap;function stashClientCapabilities(request,capabilities){clientCapabilitiesByRequest.set(request,capabilities)}function extractClientCapabilitiesFromBody(body){if(typeof body!="object"||body===null)return;let params=body.params;if(typeof params!="object"||params===null)return;let meta=params._meta;if(typeof meta!="object"||meta===null)return;let capabilities=meta[CLIENT_CAPABILITIES_META_KEY];if(!(typeof capabilities!="object"||capabilities===null))return capabilities}function supportsViews(capabilities){let extensions=capabilities?.extensions;if(extensions===void 0)return!1;let uiExtension=extensions[UI_EXTENSION_ID];if(typeof uiExtension!="object"||uiExtension===null)return!1;let mimeTypes=uiExtension.mimeTypes;return Array.isArray(mimeTypes)?mimeTypes.includes(UI_MIME_TYPE):!1}function requireOAuthAuthInfo(authInfo){if(authInfo===void 0||authInfo.extra===void 0||authInfo.expiresAt===void 0)throw new Error("OAuth callback did not receive mapped AuthInfo.extra")}function stringValue(value){return typeof value=="string"?value:void 0}function coordinateValue(value){return typeof value=="string"||typeof value=="number"&&Number.isFinite(value)?value:void 0}function normalizeUserContext(meta){if(meta===void 0)return;let locale=stringValue(meta["openai/locale"])??stringValue(meta["webplus/i18n"]),userAgent=stringValue(meta["openai/userAgent"]),subject=stringValue(meta["openai/subject"]),conversationId=stringValue(meta["openai/session"]),organizationId=stringValue(meta["openai/organization"]),rawLocation=meta["openai/userLocation"],location;if(typeof rawLocation=="object"&&rawLocation!==null&&!Array.isArray(rawLocation)){let values=rawLocation,normalized={city:stringValue(values.city),region:stringValue(values.region),country:stringValue(values.country),timezone:stringValue(values.timezone),latitude:coordinateValue(values.latitude),longitude:coordinateValue(values.longitude)},entries=Object.entries(normalized).filter(entry=>entry[1]!==void 0);entries.length>0&&(location=Object.fromEntries(entries))}if(!(locale===void 0&&userAgent===void 0&&location===void 0&&subject===void 0&&conversationId===void 0&&organizationId===void 0))return{...locale!==void 0&&{locale},...userAgent!==void 0&&{userAgent},...location!==void 0&&{location},...subject!==void 0&&{subject},...conversationId!==void 0&&{conversationId},...organizationId!==void 0&&{organizationId}}}function toClientContext(ctx){let envelope=ctx.mcpReq.envelope,capabilities={...envelope?.[CLIENT_CAPABILITIES_META_KEY2]??{}},info={...envelope?.[CLIENT_INFO_META_KEY]??{}},user=normalizeUserContext(ctx.mcpReq._meta);return{can(capability){return Object.hasOwn(capabilities,capability)},capabilities(){return{...capabilities}},extension(id){let settings=capabilities.extensions?.[id];return settings===void 0?void 0:{...settings}},info(){return{...info}},user(){return user===void 0?void 0:{...user,...user.location!==void 0&&{location:{...user.location}}}},supportsViews(){return supportsViews(capabilities)}}}function createElicit(inputResponses){return async function(key,message,schemaOrUrl){let request,formSchema;if(typeof schemaOrUrl=="string")request=inputRequired.elicitUrl({message,url:schemaOrUrl});else if(schemaOrUrl!==void 0)formSchema=schemaOrUrl,request=inputRequired.elicit({message,requestedSchema:schemaOrUrl});else throw new TypeError("ctx.elicit(key, message, value) requires a form schema or URL string");let response=inputResponse(inputResponses,key);if(response.kind==="elicit"){if(response.action!=="accept")return{status:response.action};if(formSchema===void 0)return{status:"accept"};if(response.content!==void 0){let outcome=await formSchema["~standard"].validate(response.content);if(outcome.issues===void 0)return{status:"accept",data:outcome.value}}}return{status:"required",result:inputRequired({inputRequests:{[key]:request}})}}}function toRequestContext(ctx){let rawRequest=ctx.http?.req,http=rawRequest===void 0?void 0:getRequestBag(rawRequest).honoContext,request=http?.req??(rawRequest===void 0?void 0:new HonoRequest(rawRequest)),additions={signal:ctx.mcpReq.signal,...request!==void 0&&{request},...ctx.mcpReq.inputResponses!==void 0&&{inputResponses:ctx.mcpReq.inputResponses},client:toClientContext(ctx),elicit:createElicit(ctx.mcpReq.inputResponses),requestState:()=>ctx.mcpReq.requestState(),async sendNotification(method,params){await ctx.mcpReq.notify({method,...params!==void 0&&{params}})},async reportProgress(progress,total,message){let progressToken=ctx.mcpReq._meta?.progressToken;return progressToken===void 0?!1:(await ctx.mcpReq.notify({method:"notifications/progress",params:{progressToken,progress,...total!==void 0&&{total},...message!==void 0&&{message}}}),!0)},async sendLog(level,data,logger){await ctx.mcpReq.notify({method:"notifications/message",params:{level,data,...logger!==void 0&&{logger}}})}};return http!==void 0?Object.assign(http,additions):{...additions,...request!==void 0&&{req:request}}}function toAuthenticatedRequestContext(ctx){let authInfo=ctx.http?.authInfo;return requireOAuthAuthInfo(authInfo),Object.assign(toRequestContext(ctx),{auth:{user:authInfo.extra.user,payload:authInfo.extra.payload,accessToken:authInfo.token,scopes:[...authInfo.scopes],permissions:[...authInfo.extra.permissions],...authInfo.clientId.length>0&&{clientId:authInfo.clientId},expiresAt:authInfo.expiresAt,...authInfo.resource!==void 0&&{resource:authInfo.resource}}})}function isReadResourceResult(result){return"contents"in result&&Array.isArray(result.contents)}function isGetPromptResult(result){return"messages"in result&&Array.isArray(result.messages)}function toResourceResult(result,uri){if(isReadResourceResult(result))return result;let mime=result._meta&&typeof result._meta=="object"&&typeof result._meta.mimeType=="string"?result._meta.mimeType:void 0,contents=[];for(let block of result.content??[]){let mapped=contentBlockToResourceContents(block,uri,mime);mapped!==void 0&&contents.push(mapped)}return contents.length===0&&result.structuredContent!==void 0&&contents.push({uri,mimeType:"application/json",text:JSON.stringify(result.structuredContent)}),contents.length===0&&contents.push({uri,mimeType:"text/plain",text:""}),{contents}}function contentBlockToResourceContents(block,uri,mimeHint){if(block.type==="text")return{uri,mimeType:mimeHint??"text/plain",text:block.text};if(block.type==="image"||block.type==="audio")return{uri,mimeType:block.mimeType,blob:block.data};if(block.type==="resource")return{...block.resource}}function toPromptResult(result){if(isGetPromptResult(result))return result;let messages=(result.content??[]).map(content=>({role:"user",content}));return messages.length===0&&result.structuredContent!==void 0&&messages.push({role:"user",content:{type:"text",text:JSON.stringify(result.structuredContent)}}),messages.length===0&&messages.push({role:"user",content:{type:"text",text:""}}),{messages}}var DEFAULT_METHODS=["GET","HEAD","POST","OPTIONS"],DEFAULT_ALLOWED_HEADERS=["Content-Type","Authorization","mcp-protocol-version","mcp-method","mcp-name"];function resolveAllowedOrigin(origin,requestOrigin){return origin===void 0?requestOrigin:typeof origin=="function"?origin(requestOrigin):origin==="*"?"*":Array.isArray(origin)?requestOrigin!==null&&origin.includes(requestOrigin)?requestOrigin:null:origin}function corsHeaders(options,request){if(request.headers.has("Access-Control-Allow-Origin"))return;let requestOrigin=request.headers.get("Origin"),allowedOrigin=resolveAllowedOrigin(options.origin,requestOrigin);if(allowedOrigin===null)return;let headers={"Access-Control-Allow-Origin":allowedOrigin,"Access-Control-Allow-Methods":options.methods.join(", "),"Access-Control-Allow-Headers":options.allowedHeaders.join(", ")};return options.credentials&&(headers["Access-Control-Allow-Credentials"]="true"),allowedOrigin!=="*"&&(headers.Vary="Origin"),headers}function mergeCorsHeaders(response,headers){if(response.headers.has("Access-Control-Allow-Origin"))return response;let merged=new Headers(response.headers);return new Headers(headers).forEach((value,key)=>{merged.set(key,value)}),new Response(response.body,{status:response.status,statusText:response.statusText,headers:merged})}function corsFetchMiddleware(options){if(!(options.enabled!==!1))return async(_request,next)=>next();let resolved={...options.origin!==void 0&&{origin:options.origin},methods:options.methods??DEFAULT_METHODS,allowedHeaders:options.allowedHeaders??DEFAULT_ALLOWED_HEADERS,credentials:options.credentials??!1};return async(request,next)=>{let headers=corsHeaders(resolved,request);if(headers===void 0)return next();if(request.method==="OPTIONS")return new Response(null,{status:204,headers});let response=await next();return mergeCorsHeaders(response,headers)}}function isGlobalCorsEnabled(cors){return cors!==void 0&&cors.enabled!==!1}import{CallToolResultSchema,GetPromptResultSchema,ListPromptsResultSchema,ListResourcesResultSchema,ListToolsResultSchema,ReadResourceResultSchema}from"@modelcontextprotocol/core";import{isInputRequiredResult}from"@modelcontextprotocol/server";var MCP_MIDDLEWARE_METHODS=["tools/call","tools/list","resources/read","resources/list","prompts/get","prompts/list"];function withMcpMiddlewareParams(request,params){if(typeof request!="object"||request===null||Array.isArray(request))throw new TypeError("[mcp-use] MCP middleware received an invalid downstream request");return{...request,params}}function createMcpMiddlewareEntry(pattern,handler){let normalizedPattern=normalizeMcpMiddlewarePattern(pattern),invoke=handler;if(normalizedPattern!=="*"&&!isMcpMiddlewareMethod(normalizedPattern))throw new TypeError(`Unsupported MCP middleware pattern "${pattern}". Use an exact MCP method or "mcp:*".`);return normalizedPattern==="*"?{pattern:normalizedPattern,handler:async(ctx,next)=>{let downstreamCalled=!1,downstreamResult;if(await invoke(ctx,async()=>{downstreamResult=await next(),downstreamCalled=!0}),!downstreamCalled)throw new Error(`Wildcard MCP middleware "${normalizedPattern}" must call next()`);return downstreamResult}}:{pattern:normalizedPattern,handler:(ctx,next)=>invoke(ctx,next)}}function createMcpEventListenerEntry(pattern,handler){let{pattern:normalizedPattern,phase}=parseMcpPattern(pattern),invoke=handler;return{pattern:normalizedPattern,phase,handler:(ctx,result)=>invoke(ctx,result)}}function matchesPattern(pattern,method){if(pattern==="*")return!0;if(pattern.endsWith("/*")){let prefix=pattern.slice(0,-1);return method.startsWith(prefix)}return pattern===method}function isMcpMiddlewareMethod(value){return MCP_MIDDLEWARE_METHODS.some(method=>method===value)}function composeMiddleware(entries,method,innerFn){let matching=entries.filter(entry=>matchesPattern(entry.pattern,method));return matching.length===0?_ctx=>innerFn():ctx=>{let index=-1,dispatch=i=>i<=index?Promise.reject(new Error("next() called multiple times")):(index=i,i===matching.length?innerFn():matching[i].handler(ctx,()=>dispatch(i+1)));return dispatch(0)}}function freezeMiddlewareContext(ctx){return Object.freeze({method:ctx.method,params:Object.freeze({...ctx.params}),...ctx.request!==void 0&&{request:ctx.request},...ctx.req!==void 0&&{req:ctx.req},...ctx.session!==void 0&&{session:Object.freeze({...ctx.session})},...ctx.auth!==void 0&&{auth:ctx.auth},state:new Map(ctx.state)})}async function runMcpOperation(middlewares,events,method,ctx,innerFn){dispatchMcpEvents(events,method,"before",ctx);let result=await composeMiddleware(middlewares,method,innerFn)(ctx);return assertValidMiddlewareResult(method,result),dispatchMcpEvents(events,method,"complete",ctx,result),result}function assertValidMiddlewareResult(method,result){if((method==="tools/call"||method==="resources/read"||method==="prompts/get")&&isInputRequiredResult(result))return;let validation=(()=>{switch(method){case"tools/call":return assertArrayProperty(method,result,"content"),CallToolResultSchema.safeParse(result);case"tools/list":return assertArrayResult(method,result),ListToolsResultSchema.safeParse({tools:result});case"resources/read":return assertArrayProperty(method,result,"contents"),ReadResourceResultSchema.safeParse(result);case"resources/list":return assertArrayResult(method,result),ListResourcesResultSchema.safeParse({resources:result});case"prompts/get":return assertArrayProperty(method,result,"messages"),GetPromptResultSchema.safeParse(result);case"prompts/list":return assertArrayResult(method,result),ListPromptsResultSchema.safeParse({prompts:result});default:throw new TypeError(`Unsupported MCP middleware method "${method}"`)}})();if(!validation.success)throw new TypeError(`[mcp-use] ${method} middleware returned an invalid result: ${validation.error.message}`)}function assertArrayResult(method,result){if(!Array.isArray(result))throw new TypeError(`[mcp-use] ${method} middleware returned an invalid result: expected an array`)}function assertArrayProperty(method,result,property){if(typeof result!="object"||result===null||!Array.isArray(result[property]))throw new TypeError(`[mcp-use] ${method} middleware returned an invalid result: expected a ${property} array`)}function dispatchMcpEvents(events,method,phase,ctx,result){let frozen=freezeMiddlewareContext(ctx);for(let entry of events)if(!(entry.phase!==phase||!matchesPattern(entry.pattern,method)))try{entry.handler(frozen,result)}catch(error2){console.error(`[mcp-use] MCP event listener for "${entry.pattern}" (${phase}) threw:`,error2)}}function parseMcpPattern(raw){let pattern=raw.startsWith("mcp:")?raw.slice(4):raw;return pattern.endsWith(":complete")?{pattern:pattern.slice(0,-9),phase:"complete"}:{pattern,phase:"before"}}function normalizeMcpMiddlewarePattern(raw){return raw.startsWith("mcp:")?raw.slice(4):raw}import{CLIENT_INFO_META_KEY as CLIENT_INFO_META_KEY2,isJSONRPCRequest}from"@modelcontextprotocol/server";function colorsEnabled(){return typeof process>"u"||process.env?.NO_COLOR!==void 0?!1:process.stdout?.isTTY===!0}function ansi(open,close){return text2=>colorsEnabled()?`\x1B[${open}m${text2}\x1B[${close}m`:text2}var bold=ansi(1,22),dim=ansi(2,22),red=ansi(31,39),green=ansi(32,39),yellow=ansi(33,39),blue=ansi(34,39),magenta=ansi(35,39),cyan=ansi(36,39),gray=ansi(90,39);function resolveLogLevel(configured){let raw=typeof process>"u"?void 0:process.env?.MCP_USE_LOG_LEVEL?.toLowerCase();return raw==="info"||raw==="debug"||raw==="trace"?raw:configured??"info"}function formatClientInfo(info){if(info!==void 0)return typeof info.version=="string"&&info.version!==""?`${info.name}/${info.version}`:info.name}var detailFormatters={initialize:p=>({subject:formatClientInfo(p.clientInfo)}),ping:()=>({}),"server/discover":()=>({}),"completion/complete":p=>({subject:p.ref.type==="ref/prompt"?p.ref.name:p.ref.uri,input:p.argument}),"logging/setLevel":p=>({subject:p.level}),"prompts/get":p=>({subject:p.name,input:p.arguments}),"prompts/list":()=>({}),"resources/list":()=>({}),"resources/templates/list":()=>({}),"resources/read":p=>({subject:p.uri}),"resources/subscribe":p=>({subject:p.uri}),"resources/unsubscribe":p=>({subject:p.uri}),"subscriptions/listen":()=>({}),"tools/call":p=>({subject:p.name,input:p.arguments}),"tools/list":()=>({}),"sampling/createMessage":()=>({}),"elicitation/create":()=>({}),"roots/list":()=>({})};function isKnownMethod(method){return Object.prototype.hasOwnProperty.call(detailFormatters,method)}function formatDetail(message){if(!isKnownMethod(message.method))return{};try{let formatter=detailFormatters[message.method],detail=formatter(message.params);return typeof detail.subject=="string"||detail.subject===void 0?detail:{}}catch{return{}}}var INLINE_JSON_MAX_LENGTH=80;function inlineJson(value){let text2;try{text2=JSON.stringify(value)??String(value)}catch{text2=String(value)}return text2.length>INLINE_JSON_MAX_LENGTH?`${text2.slice(0,INLINE_JSON_MAX_LENGTH)}...`:text2}function formatClientIdentity(message){let meta=message.params?._meta;if(meta===void 0)return;let info=meta[CLIENT_INFO_META_KEY2];if(!(typeof info!="object"||info===null||typeof info.name!="string"))return formatClientInfo(info)}function sanitize(text2){return text2.replace(/[\u0000-\u001F\u007F-\u009F]+/g," ")}function methodStyle(method){return method.startsWith("tools/")?cyan:method.startsWith("resources/")?green:method.startsWith("prompts/")?magenta:method==="initialize"||method==="ping"?gray:blue}var REDACTED_HEADERS=new Set(["authorization","proxy-authorization","cookie","set-cookie","x-api-key"]);function redactHeaders(headers){return Object.fromEntries(Object.entries(headers).map(([name,value])=>[name,REDACTED_HEADERS.has(name.toLowerCase())?"[REDACTED]":value]))}async function extractResponseOutcome(res){if(!res.body)return{errorMessage:null};let text2;try{text2=await res.clone().text()}catch{return{errorMessage:null}}if(!text2)return{errorMessage:null};let isSse=(res.headers.get("content-type")??"").includes("text/event-stream"),payloads=[],tryParse=raw=>{try{payloads.push(JSON.parse(raw))}catch{}};if(isSse){for(let line of text2.split(/\r?\n/))if(line.startsWith("data:")){let data=line.slice(5).trim();data&&tryParse(data)}}else tryParse(text2);let result;for(let payload of payloads){if(payload===null||typeof payload!="object")continue;let message=payload;if(typeof message.error?.message=="string")return{errorMessage:message.error.message};if(message.result?.isError===!0){let textBlock=(Array.isArray(message.result.content)?message.result.content:[]).find(b=>b?.type==="text"&&typeof b.text=="string");return{errorMessage:textBlock?String(textBlock.text):"tool error"}}"result"in message&&(result=message.result)}return{errorMessage:null,result}}function compactToolResult(result){if(result===null||typeof result!="object")return result;let{structuredContent,content}=result;if(structuredContent!==void 0)return structuredContent;if(Array.isArray(content)){let[block]=content;if(content.length===1&&block?.type==="text")return block.text}return content}function formatForDump(value){function truncate(val){return typeof val=="string"&&val.length>100?`${val.slice(0,100)}...`:Array.isArray(val)?val.map(truncate):val!==null&&typeof val=="object"?Object.fromEntries(Object.entries(val).map(([k,v])=>[k,truncate(v)])):val}try{return JSON.stringify(truncate(value),null,2)}catch{return String(value)}}var DUMP_BODY_MAX_LENGTH=1e4;async function printTraceDump(response,requestHeaders,requestBody,readResponseBody){console.log(`
|
|
1
|
+
import{hasExplicitAssetsBase,originFromAssetsBase,resolveAssetsBase,resolveServerOrigin}from"./chunk-PSKSL567.js";import{registerOpenAPITools}from"./chunk-Y26DNVWA.js";import{completable,normalizeCompletions}from"./chunk-OJF6B5EU.js";import{recordUsage}from"./chunk-LZNRJXOI.js";import{resolvePublicFilePath,servePublicFile}from"./chunk-ZMU5USAZ.js";import{authInfoFromRequest,composeFetch,getOAuthProtectedResourceMetadataUrl,getRequestBag,hostValidationMiddleware,isHtmlNavigationRequest,jsonBodyMiddleware,matchesPath,matchesPathPrefix,oauthMetadata,originValidationMiddleware,pathUnderBase,pathnameOf,requireBearerAuth}from"./chunk-GYZ3NHFQ.js";import{getOAuthProviderOptions,resolveConfiguredOAuthResource,resolveLocalOAuthResource,wrapOAuthTokenVerifier}from"./chunk-Q3UZSROW.js";import{localhostAllowedHostnames,localhostAllowedOrigins,McpServer as SdkMcpServer,ResourceTemplate,CLIENT_CAPABILITIES_META_KEY as CLIENT_CAPABILITIES_META_KEY3,CLIENT_INFO_META_KEY as CLIENT_INFO_META_KEY3,PROTOCOL_VERSION_META_KEY,isJSONRPCRequest as isJSONRPCRequest2,isInputRequiredResult as isInputRequiredResult2}from"@modelcontextprotocol/server";import{Hono}from"hono";var FAVICON_CACHE_CONTROL="public, max-age=31536000, immutable",FAVICON_REDIRECT_CACHE_CONTROL="public, max-age=300";function protocolOf(value){return/^([a-z][a-z\d+.-]*):/i.exec(value)?.[1]?.toLowerCase()}function publicAssetPath(basePath,source){return`${basePath==="/"?"":basePath}/_mcp-use/public/${source.split("/").map(segment=>encodeURIComponent(segment)).join("/")}`}function isLocalPublicSource(source){return protocolOf(source)===void 0}function selectFaviconFromIcons(icons){return icons[0]}function assertLocalPublicSource(source,field){if(source.startsWith("/")||source.includes("\\")||source.includes("?")||source.includes("#")||source.split("/").some(segment=>segment===""||segment===".."))throw new TypeError(`${field} must be an http(s) URL, image data URL, or safe path relative to public/`)}function parseDataImage(source,field){let comma=source.indexOf(",");if(comma<0)throw new TypeError(`${field} must be a valid image data URL`);let metadata=source.slice(5,comma),payload=source.slice(comma+1),parts=metadata.split(";"),mimeType=parts[0]?.toLowerCase()??"";if(!mimeType.startsWith("image/"))throw new TypeError(`${field} data URL must use an image MIME type`);try{if(parts.includes("base64")){let binary2=atob(payload);return{mimeType,bytes:Uint8Array.from(binary2,character=>character.charCodeAt(0))}}return{mimeType,bytes:new TextEncoder().encode(decodeURIComponent(payload))}}catch{throw new TypeError(`${field} must be a valid image data URL`)}}function assertBrandingSource(source,field){if(typeof source!="string"||source.length===0)throw new TypeError(`${field} must be a non-empty string`);let protocol=protocolOf(source);if(protocol===void 0)return assertLocalPublicSource(source,field),source;if(protocol==="data")return parseDataImage(source,field),source;if(protocol!=="http"&&protocol!=="https")throw new TypeError(`${field} must be an http(s) URL, image data URL, or safe path relative to public/`);try{new URL(source)}catch{throw new TypeError(`${field} must be a valid absolute http(s) URL`)}return source}function normalizeServerBranding(config){let websiteUrl;if(config.websiteUrl!==void 0){if(typeof config.websiteUrl!="string"||config.websiteUrl.length===0)throw new TypeError("websiteUrl must be a non-empty absolute http(s) URL");let parsed;try{parsed=new URL(config.websiteUrl)}catch{throw new TypeError("websiteUrl must be a non-empty absolute http(s) URL")}if(parsed.protocol!=="http:"&&parsed.protocol!=="https:")throw new TypeError("websiteUrl must be a non-empty absolute http(s) URL");websiteUrl=config.websiteUrl}let icons;if(config.icons!==void 0){if(!Array.isArray(config.icons))throw new TypeError("icons must be an array of MCP Icon objects");icons=Object.freeze(config.icons.map((value,index)=>{if(typeof value!="object"||value===null)throw new TypeError(`icons[${index}] must be an MCP Icon object`);let icon=value,src=assertBrandingSource(icon.src,`icons[${index}].src`),mimeType=icon.mimeType;if(mimeType!==void 0&&(typeof mimeType!="string"||!mimeType.toLowerCase().startsWith("image/")))throw new TypeError(`icons[${index}].mimeType must be an image MIME type when provided`);let sizes=icon.sizes;if(sizes!==void 0&&(!Array.isArray(sizes)||sizes.some(size=>typeof size!="string"||size.length===0)))throw new TypeError(`icons[${index}].sizes must be an array of non-empty strings when provided`);let normalizedSizes=sizes===void 0?void 0:sizes.map(size=>size),theme=icon.theme;if(theme!==void 0&&theme!=="light"&&theme!=="dark")throw new TypeError(`icons[${index}].theme must be "light" or "dark" when provided`);return Object.freeze({src,...mimeType!==void 0&&{mimeType},...normalizedSizes!==void 0&&{sizes:Object.freeze(normalizedSizes)},...theme!==void 0&&{theme}})}))}let explicitFavicon=config.favicon===void 0?void 0:assertBrandingSource(config.favicon,"favicon"),inferred=explicitFavicon===void 0?selectFaviconFromIcons(icons??[]):void 0,favicon=explicitFavicon??inferred?.src,faviconMimeType=inferred?.mimeType??icons?.find(icon=>icon.src===explicitFavicon)?.mimeType;return Object.freeze({...favicon!==void 0&&{favicon},...faviconMimeType!==void 0&&{faviconMimeType},...icons!==void 0&&{icons},...websiteUrl!==void 0&&{websiteUrl}})}function resolveImplementationIcons(icons,request,basePath){if(icons!==void 0)return icons.map(icon=>({...icon,src:request!==void 0&&isLocalPublicSource(icon.src)?`${resolveAssetsBase(request)}${publicAssetPath(basePath,icon.src)}`:icon.src,...icon.sizes!==void 0&&{sizes:[...icon.sizes]}}))}function hasLocalBrandingAsset(branding){return branding.favicon!==void 0&&isLocalPublicSource(branding.favicon)||branding.icons?.some(icon=>isLocalPublicSource(icon.src))===!0}function createFaviconHandler(branding,options){let source=branding.favicon;if(source!==void 0)return async request=>{if(request.method!=="GET"&&request.method!=="HEAD")return new Response("Method Not Allowed",{status:405,headers:{Allow:"GET, HEAD"}});if(new URL(request.url).pathname!=="/favicon.ico")return new Response("Not Found",{status:404});let protocol=protocolOf(source);if(protocol==="http"||protocol==="https")return new Response(null,{status:307,headers:{Location:source,"Cache-Control":FAVICON_REDIRECT_CACHE_CONTROL}});if(protocol==="data"){let data=parseDataImage(source,"favicon");return new Response(request.method==="HEAD"?null:data.bytes.buffer,{status:200,headers:{"Content-Type":branding.faviconMimeType??data.mimeType,"Cache-Control":FAVICON_CACHE_CONTROL,"X-Content-Type-Options":"nosniff"}})}let{join}=await import("path"),publicRoot=options.dev?join(options.projectRoot,"public"):join(options.projectRoot,".mcp-use/build/views/public"),diskPath=await resolvePublicFilePath(publicRoot,source);if(diskPath===null)return new Response("Not Found",{status:404,headers:{"Cache-Control":"no-store"}});let response=await servePublicFile(diskPath,{...options.deferCors===!0&&{deferCors:!0},...request.method==="HEAD"&&{head:!0}});return response.headers.set("Cache-Control",FAVICON_CACHE_CONTROL),response.headers.set("X-Content-Type-Options","nosniff"),branding.faviconMimeType!==void 0&&response.headers.set("Content-Type",branding.faviconMimeType),response}}function assertServerConfig(config){if(config.basePath!==void 0){if(typeof config.basePath!="string")throw new TypeError("basePath must be an absolute URL pathname without empty segments, trailing slash, query, fragment, or whitespace");let{basePath}=config;if(!basePath.startsWith("/")||basePath.includes("?")||basePath.includes("#")||/\s/.test(basePath)||basePath.includes("//")||basePath.length>1&&basePath.endsWith("/"))throw new TypeError("basePath must be an absolute URL pathname without empty segments, trailing slash, query, fragment, or whitespace")}if(config.port!==void 0&&(typeof config.port!="number"||!Number.isInteger(config.port)||config.port<0||config.port>65535))throw new TypeError("port must be an integer between 0 and 65535")}var DEFAULT_LISTEN_HOST="127.0.0.1";function resolveListenHost(explicitHost,configuredHost,env=process.env){if(explicitHost!==void 0)return explicitHost;let envHost=env.HOST?.trim();return envHost!==void 0&&envHost!==""?envHost:configuredHost??DEFAULT_LISTEN_HOST}function resolveListenPort(explicitPort,configuredPort,env=process.env){if(explicitPort!==void 0)return explicitPort;let envPort=parsePort(env.PORT);return envPort!==void 0?envPort:configuredPort??3e3}function parsePort(value){if(value===void 0||value.trim()==="")return;let port=Number(value);return Number.isInteger(port)&&port>=0&&port<=65535?port:void 0}import{CLIENT_CAPABILITIES_META_KEY as CLIENT_CAPABILITIES_META_KEY2,CLIENT_INFO_META_KEY,inputRequired,inputResponse}from"@modelcontextprotocol/server";import{HonoRequest}from"hono/request";import{CLIENT_CAPABILITIES_META_KEY}from"@modelcontextprotocol/server";var UI_EXTENSION_ID="io.modelcontextprotocol/ui",UI_MIME_TYPE="text/html;profile=mcp-app",UI_RESOURCE_URI_PREFIX="ui://views/";var UI_RESOURCE_URI_META_KEY="ui/resourceUri";function viewResourceUri(viewName){return`${UI_RESOURCE_URI_PREFIX}${viewName}.html`}var clientCapabilitiesByRequest=new WeakMap;function stashClientCapabilities(request,capabilities){clientCapabilitiesByRequest.set(request,capabilities)}function extractClientCapabilitiesFromBody(body){if(typeof body!="object"||body===null)return;let params=body.params;if(typeof params!="object"||params===null)return;let meta=params._meta;if(typeof meta!="object"||meta===null)return;let capabilities=meta[CLIENT_CAPABILITIES_META_KEY];if(!(typeof capabilities!="object"||capabilities===null))return capabilities}function supportsViews(capabilities){let extensions=capabilities?.extensions;if(extensions===void 0)return!1;let uiExtension=extensions[UI_EXTENSION_ID];if(typeof uiExtension!="object"||uiExtension===null)return!1;let mimeTypes=uiExtension.mimeTypes;return Array.isArray(mimeTypes)?mimeTypes.includes(UI_MIME_TYPE):!1}function requireOAuthAuthInfo(authInfo){if(authInfo===void 0||authInfo.extra===void 0||authInfo.expiresAt===void 0)throw new Error("OAuth callback did not receive mapped AuthInfo.extra")}function stringValue(value){return typeof value=="string"?value:void 0}function coordinateValue(value){return typeof value=="string"||typeof value=="number"&&Number.isFinite(value)?value:void 0}function normalizeUserContext(meta){if(meta===void 0)return;let locale=stringValue(meta["openai/locale"])??stringValue(meta["webplus/i18n"]),userAgent=stringValue(meta["openai/userAgent"]),subject=stringValue(meta["openai/subject"]),conversationId=stringValue(meta["openai/session"]),organizationId=stringValue(meta["openai/organization"]),rawLocation=meta["openai/userLocation"],location;if(typeof rawLocation=="object"&&rawLocation!==null&&!Array.isArray(rawLocation)){let values=rawLocation,normalized={city:stringValue(values.city),region:stringValue(values.region),country:stringValue(values.country),timezone:stringValue(values.timezone),latitude:coordinateValue(values.latitude),longitude:coordinateValue(values.longitude)},entries=Object.entries(normalized).filter(entry=>entry[1]!==void 0);entries.length>0&&(location=Object.fromEntries(entries))}if(!(locale===void 0&&userAgent===void 0&&location===void 0&&subject===void 0&&conversationId===void 0&&organizationId===void 0))return{...locale!==void 0&&{locale},...userAgent!==void 0&&{userAgent},...location!==void 0&&{location},...subject!==void 0&&{subject},...conversationId!==void 0&&{conversationId},...organizationId!==void 0&&{organizationId}}}function toClientContext(ctx){let envelope=ctx.mcpReq.envelope,capabilities={...envelope?.[CLIENT_CAPABILITIES_META_KEY2]??{}},info={...envelope?.[CLIENT_INFO_META_KEY]??{}},user=normalizeUserContext(ctx.mcpReq._meta);return{can(capability){return Object.hasOwn(capabilities,capability)},capabilities(){return{...capabilities}},extension(id){let settings=capabilities.extensions?.[id];return settings===void 0?void 0:{...settings}},info(){return{...info}},user(){return user===void 0?void 0:{...user,...user.location!==void 0&&{location:{...user.location}}}},supportsViews(){return supportsViews(capabilities)}}}function createElicit(inputResponses){return async function(key,message,schemaOrUrl){let request,formSchema;if(typeof schemaOrUrl=="string")request=inputRequired.elicitUrl({message,url:schemaOrUrl});else if(schemaOrUrl!==void 0)formSchema=schemaOrUrl,request=inputRequired.elicit({message,requestedSchema:schemaOrUrl});else throw new TypeError("ctx.elicit(key, message, value) requires a form schema or URL string");let response=inputResponse(inputResponses,key);if(response.kind==="elicit"){if(response.action!=="accept")return{status:response.action};if(formSchema===void 0)return{status:"accept"};if(response.content!==void 0){let outcome=await formSchema["~standard"].validate(response.content);if(outcome.issues===void 0)return{status:"accept",data:outcome.value}}}return{status:"required",result:inputRequired({inputRequests:{[key]:request}})}}}function toRequestContext(ctx){let rawRequest=ctx.http?.req,http=rawRequest===void 0?void 0:getRequestBag(rawRequest).honoContext,request=http?.req??(rawRequest===void 0?void 0:new HonoRequest(rawRequest)),additions={signal:ctx.mcpReq.signal,...request!==void 0&&{request},...ctx.mcpReq.inputResponses!==void 0&&{inputResponses:ctx.mcpReq.inputResponses},client:toClientContext(ctx),elicit:createElicit(ctx.mcpReq.inputResponses),requestState:()=>ctx.mcpReq.requestState(),async sendNotification(method,params){await ctx.mcpReq.notify({method,...params!==void 0&&{params}})},async reportProgress(progress,total,message){let progressToken=ctx.mcpReq._meta?.progressToken;return progressToken===void 0?!1:(await ctx.mcpReq.notify({method:"notifications/progress",params:{progressToken,progress,...total!==void 0&&{total},...message!==void 0&&{message}}}),!0)},async sendLog(level,data,logger){await ctx.mcpReq.notify({method:"notifications/message",params:{level,data,...logger!==void 0&&{logger}}})}};return http!==void 0?Object.assign(http,additions):{...additions,...request!==void 0&&{req:request}}}function toAuthenticatedRequestContext(ctx){let authInfo=ctx.http?.authInfo;return requireOAuthAuthInfo(authInfo),Object.assign(toRequestContext(ctx),{auth:{user:authInfo.extra.user,payload:authInfo.extra.payload,accessToken:authInfo.token,scopes:[...authInfo.scopes],permissions:[...authInfo.extra.permissions],...authInfo.clientId.length>0&&{clientId:authInfo.clientId},expiresAt:authInfo.expiresAt,...authInfo.resource!==void 0&&{resource:authInfo.resource}}})}function isReadResourceResult(result){return"contents"in result&&Array.isArray(result.contents)}function isGetPromptResult(result){return"messages"in result&&Array.isArray(result.messages)}function toResourceResult(result,uri){if(isReadResourceResult(result))return result;let mime=result._meta&&typeof result._meta=="object"&&typeof result._meta.mimeType=="string"?result._meta.mimeType:void 0,contents=[];for(let block of result.content??[]){let mapped=contentBlockToResourceContents(block,uri,mime);mapped!==void 0&&contents.push(mapped)}return contents.length===0&&result.structuredContent!==void 0&&contents.push({uri,mimeType:"application/json",text:JSON.stringify(result.structuredContent)}),contents.length===0&&contents.push({uri,mimeType:"text/plain",text:""}),{contents}}function contentBlockToResourceContents(block,uri,mimeHint){if(block.type==="text")return{uri,mimeType:mimeHint??"text/plain",text:block.text};if(block.type==="image"||block.type==="audio")return{uri,mimeType:block.mimeType,blob:block.data};if(block.type==="resource")return{...block.resource}}function toPromptResult(result){if(isGetPromptResult(result))return result;let messages=(result.content??[]).map(content=>({role:"user",content}));return messages.length===0&&result.structuredContent!==void 0&&messages.push({role:"user",content:{type:"text",text:JSON.stringify(result.structuredContent)}}),messages.length===0&&messages.push({role:"user",content:{type:"text",text:""}}),{messages}}var DEFAULT_METHODS=["GET","HEAD","POST","OPTIONS"],DEFAULT_ALLOWED_HEADERS=["Content-Type","Authorization","mcp-protocol-version","mcp-method","mcp-name"];function resolveAllowedOrigin(origin,requestOrigin){return origin===void 0?requestOrigin:typeof origin=="function"?origin(requestOrigin):origin==="*"?"*":Array.isArray(origin)?requestOrigin!==null&&origin.includes(requestOrigin)?requestOrigin:null:origin}function corsHeaders(options,request){if(request.headers.has("Access-Control-Allow-Origin"))return;let requestOrigin=request.headers.get("Origin"),allowedOrigin=resolveAllowedOrigin(options.origin,requestOrigin);if(allowedOrigin===null)return;let headers={"Access-Control-Allow-Origin":allowedOrigin,"Access-Control-Allow-Methods":options.methods.join(", "),"Access-Control-Allow-Headers":options.allowedHeaders.join(", ")};return options.credentials&&(headers["Access-Control-Allow-Credentials"]="true"),allowedOrigin!=="*"&&(headers.Vary="Origin"),headers}function mergeCorsHeaders(response,headers){if(response.headers.has("Access-Control-Allow-Origin"))return response;let merged=new Headers(response.headers);return new Headers(headers).forEach((value,key)=>{merged.set(key,value)}),new Response(response.body,{status:response.status,statusText:response.statusText,headers:merged})}function corsFetchMiddleware(options){if(!(options.enabled!==!1))return async(_request,next)=>next();let resolved={...options.origin!==void 0&&{origin:options.origin},methods:options.methods??DEFAULT_METHODS,allowedHeaders:options.allowedHeaders??DEFAULT_ALLOWED_HEADERS,credentials:options.credentials??!1};return async(request,next)=>{let headers=corsHeaders(resolved,request);if(headers===void 0)return next();if(request.method==="OPTIONS")return new Response(null,{status:204,headers});let response=await next();return mergeCorsHeaders(response,headers)}}function isGlobalCorsEnabled(cors){return cors!==void 0&&cors.enabled!==!1}import{CallToolResultSchema,GetPromptResultSchema,ListPromptsResultSchema,ListResourcesResultSchema,ListToolsResultSchema,ReadResourceResultSchema}from"@modelcontextprotocol/core";import{isInputRequiredResult}from"@modelcontextprotocol/server";var MCP_MIDDLEWARE_METHODS=["tools/call","tools/list","resources/read","resources/list","prompts/get","prompts/list"];function withMcpMiddlewareParams(request,params){if(typeof request!="object"||request===null||Array.isArray(request))throw new TypeError("[mcp-use] MCP middleware received an invalid downstream request");return{...request,params}}function createMcpMiddlewareEntry(pattern,handler){let normalizedPattern=normalizeMcpMiddlewarePattern(pattern),invoke=handler;if(normalizedPattern!=="*"&&!isMcpMiddlewareMethod(normalizedPattern))throw new TypeError(`Unsupported MCP middleware pattern "${pattern}". Use an exact MCP method or "mcp:*".`);return normalizedPattern==="*"?{pattern:normalizedPattern,handler:async(ctx,next)=>{let downstreamCalled=!1,downstreamResult;if(await invoke(ctx,async()=>{downstreamResult=await next(),downstreamCalled=!0}),!downstreamCalled)throw new Error(`Wildcard MCP middleware "${normalizedPattern}" must call next()`);return downstreamResult}}:{pattern:normalizedPattern,handler:(ctx,next)=>invoke(ctx,next)}}function createMcpEventListenerEntry(pattern,handler){let{pattern:normalizedPattern,phase}=parseMcpPattern(pattern),invoke=handler;return{pattern:normalizedPattern,phase,handler:(ctx,result)=>invoke(ctx,result)}}function matchesPattern(pattern,method){if(pattern==="*")return!0;if(pattern.endsWith("/*")){let prefix=pattern.slice(0,-1);return method.startsWith(prefix)}return pattern===method}function isMcpMiddlewareMethod(value){return MCP_MIDDLEWARE_METHODS.some(method=>method===value)}function composeMiddleware(entries,method,innerFn){let matching=entries.filter(entry=>matchesPattern(entry.pattern,method));return matching.length===0?_ctx=>innerFn():ctx=>{let index=-1,dispatch=i=>i<=index?Promise.reject(new Error("next() called multiple times")):(index=i,i===matching.length?innerFn():matching[i].handler(ctx,()=>dispatch(i+1)));return dispatch(0)}}function freezeMiddlewareContext(ctx){return Object.freeze({method:ctx.method,params:Object.freeze({...ctx.params}),...ctx.request!==void 0&&{request:ctx.request},...ctx.req!==void 0&&{req:ctx.req},...ctx.session!==void 0&&{session:Object.freeze({...ctx.session})},...ctx.auth!==void 0&&{auth:ctx.auth},state:new Map(ctx.state)})}async function runMcpOperation(middlewares,events,method,ctx,innerFn){dispatchMcpEvents(events,method,"before",ctx);let result=await composeMiddleware(middlewares,method,innerFn)(ctx);return assertValidMiddlewareResult(method,result),dispatchMcpEvents(events,method,"complete",ctx,result),result}function assertValidMiddlewareResult(method,result){if((method==="tools/call"||method==="resources/read"||method==="prompts/get")&&isInputRequiredResult(result))return;let validation=(()=>{switch(method){case"tools/call":return assertArrayProperty(method,result,"content"),CallToolResultSchema.safeParse(result);case"tools/list":return assertArrayResult(method,result),ListToolsResultSchema.safeParse({tools:result});case"resources/read":return assertArrayProperty(method,result,"contents"),ReadResourceResultSchema.safeParse(result);case"resources/list":return assertArrayResult(method,result),ListResourcesResultSchema.safeParse({resources:result});case"prompts/get":return assertArrayProperty(method,result,"messages"),GetPromptResultSchema.safeParse(result);case"prompts/list":return assertArrayResult(method,result),ListPromptsResultSchema.safeParse({prompts:result});default:throw new TypeError(`Unsupported MCP middleware method "${method}"`)}})();if(!validation.success)throw new TypeError(`[mcp-use] ${method} middleware returned an invalid result: ${validation.error.message}`)}function assertArrayResult(method,result){if(!Array.isArray(result))throw new TypeError(`[mcp-use] ${method} middleware returned an invalid result: expected an array`)}function assertArrayProperty(method,result,property){if(typeof result!="object"||result===null||!Array.isArray(result[property]))throw new TypeError(`[mcp-use] ${method} middleware returned an invalid result: expected a ${property} array`)}function dispatchMcpEvents(events,method,phase,ctx,result){let frozen=freezeMiddlewareContext(ctx);for(let entry of events)if(!(entry.phase!==phase||!matchesPattern(entry.pattern,method)))try{entry.handler(frozen,result)}catch(error2){console.error(`[mcp-use] MCP event listener for "${entry.pattern}" (${phase}) threw:`,error2)}}function parseMcpPattern(raw){let pattern=raw.startsWith("mcp:")?raw.slice(4):raw;return pattern.endsWith(":complete")?{pattern:pattern.slice(0,-9),phase:"complete"}:{pattern,phase:"before"}}function normalizeMcpMiddlewarePattern(raw){return raw.startsWith("mcp:")?raw.slice(4):raw}import{CLIENT_INFO_META_KEY as CLIENT_INFO_META_KEY2,isJSONRPCRequest}from"@modelcontextprotocol/server";function colorsEnabled(){return typeof process>"u"||process.env?.NO_COLOR!==void 0?!1:process.stdout?.isTTY===!0}function ansi(open,close){return text2=>colorsEnabled()?`\x1B[${open}m${text2}\x1B[${close}m`:text2}var bold=ansi(1,22),dim=ansi(2,22),red=ansi(31,39),green=ansi(32,39),yellow=ansi(33,39),blue=ansi(34,39),magenta=ansi(35,39),cyan=ansi(36,39),gray=ansi(90,39);function resolveLogLevel(configured){let raw=typeof process>"u"?void 0:process.env?.MCP_USE_LOG_LEVEL?.toLowerCase();return raw==="info"||raw==="debug"||raw==="trace"?raw:configured??"info"}function formatClientInfo(info){if(info!==void 0)return typeof info.version=="string"&&info.version!==""?`${info.name}/${info.version}`:info.name}var detailFormatters={initialize:p=>({subject:formatClientInfo(p.clientInfo)}),ping:()=>({}),"server/discover":()=>({}),"completion/complete":p=>({subject:p.ref.type==="ref/prompt"?p.ref.name:p.ref.uri,input:p.argument}),"logging/setLevel":p=>({subject:p.level}),"prompts/get":p=>({subject:p.name,input:p.arguments}),"prompts/list":()=>({}),"resources/list":()=>({}),"resources/templates/list":()=>({}),"resources/read":p=>({subject:p.uri}),"resources/subscribe":p=>({subject:p.uri}),"resources/unsubscribe":p=>({subject:p.uri}),"subscriptions/listen":()=>({}),"tools/call":p=>({subject:p.name,input:p.arguments}),"tools/list":()=>({}),"sampling/createMessage":()=>({}),"elicitation/create":()=>({}),"roots/list":()=>({})};function isKnownMethod(method){return Object.prototype.hasOwnProperty.call(detailFormatters,method)}function formatDetail(message){if(!isKnownMethod(message.method))return{};try{let formatter=detailFormatters[message.method],detail=formatter(message.params);return typeof detail.subject=="string"||detail.subject===void 0?detail:{}}catch{return{}}}var INLINE_JSON_MAX_LENGTH=80;function inlineJson(value){let text2;try{text2=JSON.stringify(value)??String(value)}catch{text2=String(value)}return text2.length>INLINE_JSON_MAX_LENGTH?`${text2.slice(0,INLINE_JSON_MAX_LENGTH)}...`:text2}function formatClientIdentity(message){let meta=message.params?._meta;if(meta===void 0)return;let info=meta[CLIENT_INFO_META_KEY2];if(!(typeof info!="object"||info===null||typeof info.name!="string"))return formatClientInfo(info)}function sanitize(text2){return text2.replace(/[\u0000-\u001F\u007F-\u009F]+/g," ")}function methodStyle(method){return method.startsWith("tools/")?cyan:method.startsWith("resources/")?green:method.startsWith("prompts/")?magenta:method==="initialize"||method==="ping"?gray:blue}var REDACTED_HEADERS=new Set(["authorization","proxy-authorization","cookie","set-cookie","x-api-key"]);function redactHeaders(headers){return Object.fromEntries(Object.entries(headers).map(([name,value])=>[name,REDACTED_HEADERS.has(name.toLowerCase())?"[REDACTED]":value]))}async function extractResponseOutcome(res){if(!res.body)return{errorMessage:null};let text2;try{text2=await res.clone().text()}catch{return{errorMessage:null}}if(!text2)return{errorMessage:null};let isSse=(res.headers.get("content-type")??"").includes("text/event-stream"),payloads=[],tryParse=raw=>{try{payloads.push(JSON.parse(raw))}catch{}};if(isSse){for(let line of text2.split(/\r?\n/))if(line.startsWith("data:")){let data=line.slice(5).trim();data&&tryParse(data)}}else tryParse(text2);let result;for(let payload of payloads){if(payload===null||typeof payload!="object")continue;let message=payload;if(typeof message.error?.message=="string")return{errorMessage:message.error.message};if(message.result?.isError===!0){let textBlock=(Array.isArray(message.result.content)?message.result.content:[]).find(b=>b?.type==="text"&&typeof b.text=="string");return{errorMessage:textBlock?String(textBlock.text):"tool error"}}"result"in message&&(result=message.result)}return{errorMessage:null,result}}function compactToolResult(result){if(result===null||typeof result!="object")return result;let{structuredContent,content}=result;if(structuredContent!==void 0)return structuredContent;if(Array.isArray(content)){let[block]=content;if(content.length===1&&block?.type==="text")return block.text}return content}function formatForDump(value){function truncate(val){return typeof val=="string"&&val.length>100?`${val.slice(0,100)}...`:Array.isArray(val)?val.map(truncate):val!==null&&typeof val=="object"?Object.fromEntries(Object.entries(val).map(([k,v])=>[k,truncate(v)])):val}try{return JSON.stringify(truncate(value),null,2)}catch{return String(value)}}var DUMP_BODY_MAX_LENGTH=1e4;async function printTraceDump(response,requestHeaders,requestBody,readResponseBody){console.log(`
|
|
2
2
|
${cyan("=".repeat(80))}`),console.log(bold(cyan("[TRACE] Request Details"))),console.log(cyan("-".repeat(80))),Object.keys(requestHeaders).length>0&&(console.log(yellow("Request Headers:")),console.log(formatForDump(redactHeaders(requestHeaders)))),requestBody!==void 0&&(console.log(yellow("Request Body:")),console.log(typeof requestBody=="string"?requestBody:formatForDump(requestBody)));let responseHeaders={};if(response.headers.forEach((value,key)=>{responseHeaders[key]=value}),Object.keys(responseHeaders).length>0&&(console.log(yellow("Response Headers:")),console.log(formatForDump(redactHeaders(responseHeaders)))),!readResponseBody)console.log(`${yellow("Response Body:")} (streaming \u2014 not dumped)`);else if(response.body===null)console.log(`${yellow("Response Body:")} (no body)`);else try{let text2=await response.clone().text();if(text2.length===0)console.log(`${yellow("Response Body:")} (empty)`);else{console.log(yellow("Response Body:"));try{console.log(formatForDump(JSON.parse(text2)))}catch{console.log(text2.length>DUMP_BODY_MAX_LENGTH?`${text2.slice(0,DUMP_BODY_MAX_LENGTH)}
|
|
3
3
|
... (truncated, ${text2.length-DUMP_BODY_MAX_LENGTH} more characters)`:text2)}}}catch{console.log(`${yellow("Response Body:")} (unable to read)`)}console.log(`${cyan("=".repeat(80))}
|
|
4
4
|
`)}function styleStatus(status){let text2=String(status);return status>=500?magenta(text2):status>=400?red(text2):status>=300?yellow(text2):green(text2)}function isNoisyRequest(httpMethod,pathname){return httpMethod!=="GET"&&httpMethod!=="HEAD"?!1:pathname.endsWith("/favicon.ico")}function requestLogger(options={}){return options.enabled===!1?(_request,next)=>next():async(request,next)=>{let level=resolveLogLevel(options.level),startedAt=Date.now(),httpMethod=request.method,pathname=new URL(request.url).pathname;if(isNoisyRequest(httpMethod,pathname))return next();let requestHeaders={};level==="trace"&&request.headers.forEach((value,key)=>{requestHeaders[key]=value});let requestBody;if(httpMethod!=="GET"&&httpMethod!=="HEAD"){let parsedBody=getRequestBag(request).parsedBody;if(parsedBody!==void 0)requestBody=parsedBody;else try{requestBody=await request.clone().json()}catch{}}let response=await next(),durationMs=Date.now()-startedAt,timestamp=new Date().toISOString().substring(11,19),mcpRequest=isJSONRPCRequest(requestBody)?requestBody:void 0,isStreamingMethod=mcpRequest?.method==="subscriptions/listen",lines=[[dim(timestamp),bold(httpMethod),pathname,styleStatus(response.status),dim(`in ${durationMs}ms`)].join(" ")];if(mcpRequest!==void 0){let method=sanitize(mcpRequest.method),parts=[` ${methodStyle(method)(method)}`],detail=formatDetail(mcpRequest);detail.subject!==void 0&&parts.push(bold(sanitize(detail.subject)));let echoPayloads=level!=="info";echoPayloads&&detail.input!==void 0&&parts.push(inlineJson(detail.input));let outcome=isStreamingMethod?{errorMessage:null}:await extractResponseOutcome(response);if(echoPayloads&&mcpRequest.method==="tools/call"&&outcome.errorMessage===null&&outcome.result!==void 0&&parts.push(dim("->"),inlineJson(compactToolResult(outcome.result))),mcpRequest.method!=="initialize"){let client=formatClientIdentity(mcpRequest);client!==void 0&&parts.push(dim(sanitize(client)))}outcome.errorMessage!==null?parts.push(red(`ERROR ${sanitize(outcome.errorMessage)}`)):response.status>=400&&parts.push(red(`ERROR (HTTP ${response.status})`)),lines.push(parts.join(" "))}return console.log(lines.join(`
|
package/dist/internal/usage.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{flushUsage,recordUsage}from"../chunk-
|
|
1
|
+
import{flushUsage,recordRuntimeUsage,recordUsage}from"../chunk-LZNRJXOI.js";export{flushUsage,recordRuntimeUsage,recordUsage};
|
package/dist/react/index.js
CHANGED
|
@@ -93,8 +93,113 @@ function normalizeViewConfig(config) {
|
|
|
93
93
|
import {
|
|
94
94
|
createContext,
|
|
95
95
|
useContext,
|
|
96
|
+
useEffect,
|
|
96
97
|
useSyncExternalStore
|
|
97
98
|
} from "react";
|
|
99
|
+
|
|
100
|
+
// src/usage.ts
|
|
101
|
+
var EVENT = "mcp_use_sdk_event";
|
|
102
|
+
var ENDPOINT = "https://eu.i.posthog.com/i/v0/e/";
|
|
103
|
+
var TOKEN = "phc_lyTtbYwvkdSbrcMQNPiKiiRWrrM1seyKIMjycSvItEI";
|
|
104
|
+
var CONTENT = /(^|_)(arguments?|args|body|command|headers?|location|message|organization|path|query|response|secret|subject|token|uri|url|user_agent)(_|$)/i;
|
|
105
|
+
var RESERVED = new Set(
|
|
106
|
+
"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(
|
|
107
|
+
" "
|
|
108
|
+
)
|
|
109
|
+
);
|
|
110
|
+
var runtimeId = crypto.randomUUID();
|
|
111
|
+
var once = /* @__PURE__ */ new Set();
|
|
112
|
+
var pending = /* @__PURE__ */ new Set();
|
|
113
|
+
function hasControl(value) {
|
|
114
|
+
return [...value].some((character) => {
|
|
115
|
+
const code = character.charCodeAt(0);
|
|
116
|
+
return code < 32 || code === 127;
|
|
117
|
+
});
|
|
118
|
+
}
|
|
119
|
+
function env(name) {
|
|
120
|
+
return typeof process === "undefined" ? void 0 : process.env?.[name];
|
|
121
|
+
}
|
|
122
|
+
function safeEnv(name) {
|
|
123
|
+
const value = env(name);
|
|
124
|
+
return value !== void 0 && value.length > 0 && value.length <= 128 && !hasControl(value) ? value : void 0;
|
|
125
|
+
}
|
|
126
|
+
function disabled() {
|
|
127
|
+
if (env("MCP_USE_ANONYMIZED_TELEMETRY") === "false" || typeof __MCP_USE_VIEW_USAGE_DISABLED__ !== "undefined" && __MCP_USE_VIEW_USAGE_DISABLED__)
|
|
128
|
+
return true;
|
|
129
|
+
try {
|
|
130
|
+
const scope = globalThis;
|
|
131
|
+
return scope.__MCP_USE_ANONYMIZED_TELEMETRY__ === false || typeof localStorage !== "undefined" && localStorage.getItem("MCP_USE_ANONYMIZED_TELEMETRY") === "false";
|
|
132
|
+
} catch {
|
|
133
|
+
return false;
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
function clean(properties) {
|
|
137
|
+
return Object.fromEntries(
|
|
138
|
+
Object.entries(properties).filter(([key, value]) => {
|
|
139
|
+
if (key.length > 128 || hasControl(key) || key.startsWith("$") || RESERVED.has(key) || CONTENT.test(key) || value === void 0)
|
|
140
|
+
return false;
|
|
141
|
+
return typeof value === "string" ? value.length <= 128 && !hasControl(value) : typeof value === "boolean" || typeof value === "number" && Number.isFinite(value);
|
|
142
|
+
})
|
|
143
|
+
);
|
|
144
|
+
}
|
|
145
|
+
function capture(feature, action, properties, options, resolveIdentity) {
|
|
146
|
+
const validationId = safeEnv("MCP_USE_TELEMETRY_VALIDATION_ID");
|
|
147
|
+
if (disabled() || env("NODE_ENV") === "test" && validationId === void 0 || pending.size >= 16)
|
|
148
|
+
return;
|
|
149
|
+
if (options.onceKey !== void 0) {
|
|
150
|
+
if (once.has(options.onceKey)) return;
|
|
151
|
+
once.add(options.onceKey);
|
|
152
|
+
}
|
|
153
|
+
const rate = Math.max(0, Math.min(1, options.sampleRate ?? 1));
|
|
154
|
+
if (validationId === void 0 && Math.random() >= rate) return;
|
|
155
|
+
const request = (async () => {
|
|
156
|
+
try {
|
|
157
|
+
const resolvedIdentity = await resolveIdentity();
|
|
158
|
+
const body = JSON.stringify({
|
|
159
|
+
api_key: TOKEN,
|
|
160
|
+
event: EVENT,
|
|
161
|
+
properties: {
|
|
162
|
+
...clean(properties),
|
|
163
|
+
feature,
|
|
164
|
+
action,
|
|
165
|
+
sdk_generation: "v2",
|
|
166
|
+
telemetry_schema_version: 2,
|
|
167
|
+
sdk_package: "mcp-use",
|
|
168
|
+
sdk_version: false ? "development" : "2.0.0-beta.44",
|
|
169
|
+
server_id: resolvedIdentity.id,
|
|
170
|
+
runtime_id: runtimeId,
|
|
171
|
+
identity_stability: resolvedIdentity.stability,
|
|
172
|
+
distinct_id: resolvedIdentity.id,
|
|
173
|
+
sample_rate: validationId === void 0 ? rate : 1,
|
|
174
|
+
$process_person_profile: false,
|
|
175
|
+
$geoip_disable: true,
|
|
176
|
+
...validationId !== void 0 && {
|
|
177
|
+
is_validation: true,
|
|
178
|
+
validation_run_id: validationId
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
});
|
|
182
|
+
await fetch(ENDPOINT, {
|
|
183
|
+
method: "POST",
|
|
184
|
+
headers: { "content-type": "application/json" },
|
|
185
|
+
keepalive: true,
|
|
186
|
+
body
|
|
187
|
+
});
|
|
188
|
+
} catch {
|
|
189
|
+
return;
|
|
190
|
+
}
|
|
191
|
+
})();
|
|
192
|
+
pending.add(request);
|
|
193
|
+
void request.then(() => pending.delete(request));
|
|
194
|
+
}
|
|
195
|
+
function recordRuntimeUsage(feature, action, properties = {}, options = {}) {
|
|
196
|
+
capture(feature, action, properties, options, async () => ({
|
|
197
|
+
id: runtimeId,
|
|
198
|
+
stability: "process"
|
|
199
|
+
}));
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
// src/react/runtime/view-runtime-context.tsx
|
|
98
203
|
import { jsx as jsx2 } from "react/jsx-runtime";
|
|
99
204
|
var ViewRuntimeContext = createContext(null);
|
|
100
205
|
function ViewRuntimeProvider({
|
|
@@ -103,8 +208,18 @@ function ViewRuntimeProvider({
|
|
|
103
208
|
}) {
|
|
104
209
|
return /* @__PURE__ */ jsx2(ViewRuntimeContext.Provider, { value: runtime, children });
|
|
105
210
|
}
|
|
106
|
-
function useViewRuntime() {
|
|
211
|
+
function useViewRuntime(hook) {
|
|
107
212
|
const runtime = useContext(ViewRuntimeContext);
|
|
213
|
+
useEffect(() => {
|
|
214
|
+
if (hook !== void 0) {
|
|
215
|
+
recordRuntimeUsage(
|
|
216
|
+
"view",
|
|
217
|
+
"hook_used",
|
|
218
|
+
{ hook },
|
|
219
|
+
{ onceKey: `view:${hook}` }
|
|
220
|
+
);
|
|
221
|
+
}
|
|
222
|
+
}, [hook]);
|
|
108
223
|
if (!runtime) {
|
|
109
224
|
throw new Error(
|
|
110
225
|
"mcp-use/react hooks require a browser view mounted by bootstrapView"
|
|
@@ -975,7 +1090,7 @@ var Image = ({
|
|
|
975
1090
|
import {
|
|
976
1091
|
createContext as createContext2,
|
|
977
1092
|
useContext as useContext2,
|
|
978
|
-
useEffect,
|
|
1093
|
+
useEffect as useEffect2,
|
|
979
1094
|
useId
|
|
980
1095
|
} from "react";
|
|
981
1096
|
import { jsx as jsx5 } from "react/jsx-runtime";
|
|
@@ -996,7 +1111,7 @@ function ModelContext({ content, children }) {
|
|
|
996
1111
|
const id = useId();
|
|
997
1112
|
const hasContent = content.trim().length > 0;
|
|
998
1113
|
const childParentId = hasContent ? id : parentId;
|
|
999
|
-
|
|
1114
|
+
useEffect2(() => {
|
|
1000
1115
|
if (hasContent) {
|
|
1001
1116
|
store.setNode({ id, parentId, content });
|
|
1002
1117
|
}
|
|
@@ -1151,7 +1266,7 @@ import { useRef, useState as useState2 } from "react";
|
|
|
1151
1266
|
// src/react/hooks/use-display-mode.ts
|
|
1152
1267
|
import { useSyncExternalStore as useSyncExternalStore2 } from "react";
|
|
1153
1268
|
function useDisplayMode() {
|
|
1154
|
-
const runtime = useViewRuntime();
|
|
1269
|
+
const runtime = useViewRuntime("useDisplayMode");
|
|
1155
1270
|
const { displayMode, availableDisplayModes } = useSyncExternalStore2(
|
|
1156
1271
|
runtime.subscribeDisplay,
|
|
1157
1272
|
runtime.getDisplaySnapshot
|
|
@@ -1196,7 +1311,7 @@ function resolvePlatform(hostContext) {
|
|
|
1196
1311
|
return hostContext?.platform === "mobile" ? "mobile" : "web";
|
|
1197
1312
|
}
|
|
1198
1313
|
function useHostContext() {
|
|
1199
|
-
const runtime = useViewRuntime();
|
|
1314
|
+
const runtime = useViewRuntime("useHostContext");
|
|
1200
1315
|
const { hostContext, isConnected } = useSyncExternalStore3(
|
|
1201
1316
|
runtime.subscribeHost,
|
|
1202
1317
|
runtime.getHostSnapshot
|
|
@@ -1222,7 +1337,7 @@ function useHostContext() {
|
|
|
1222
1337
|
// src/react/hooks/use-tool-context.ts
|
|
1223
1338
|
import { useSyncExternalStore as useSyncExternalStore4 } from "react";
|
|
1224
1339
|
function useToolContext() {
|
|
1225
|
-
const runtime = useViewRuntime();
|
|
1340
|
+
const runtime = useViewRuntime("useToolContext");
|
|
1226
1341
|
const snap = useSyncExternalStore4(
|
|
1227
1342
|
runtime.subscribeTool,
|
|
1228
1343
|
runtime.getToolSnapshot
|
|
@@ -1418,14 +1533,14 @@ function ViewControls({
|
|
|
1418
1533
|
// src/react/hooks/use-call-tool.ts
|
|
1419
1534
|
import { useCallback, useRef as useRef2, useState as useState3 } from "react";
|
|
1420
1535
|
function useCallTool(nameOrRef) {
|
|
1421
|
-
return useToolCall(nameOrRef);
|
|
1536
|
+
return useToolCall(nameOrRef, "useCallTool");
|
|
1422
1537
|
}
|
|
1423
1538
|
function useDynamicTool(name) {
|
|
1424
|
-
return useToolCall(name);
|
|
1539
|
+
return useToolCall(name, "useDynamicTool");
|
|
1425
1540
|
}
|
|
1426
|
-
function useToolCall(nameOrRef) {
|
|
1541
|
+
function useToolCall(nameOrRef, hook) {
|
|
1427
1542
|
const toolName = typeof nameOrRef === "string" ? nameOrRef : nameOrRef.name;
|
|
1428
|
-
const runtime = useViewRuntime();
|
|
1543
|
+
const runtime = useViewRuntime(hook);
|
|
1429
1544
|
const [data, setData] = useState3(
|
|
1430
1545
|
void 0
|
|
1431
1546
|
);
|
|
@@ -1468,7 +1583,7 @@ function useToolCall(nameOrRef) {
|
|
|
1468
1583
|
// src/react/hooks/use-files.ts
|
|
1469
1584
|
import { useMemo, useSyncExternalStore as useSyncExternalStore5 } from "react";
|
|
1470
1585
|
function useFiles() {
|
|
1471
|
-
const runtime = useViewRuntime();
|
|
1586
|
+
const runtime = useViewRuntime("useFiles");
|
|
1472
1587
|
const { isSupported } = useSyncExternalStore5(
|
|
1473
1588
|
runtime.subscribeFiles,
|
|
1474
1589
|
runtime.getFilesSnapshot
|
|
@@ -1486,7 +1601,7 @@ function useFiles() {
|
|
|
1486
1601
|
// src/react/hooks/use-open-external.ts
|
|
1487
1602
|
import { useCallback as useCallback2 } from "react";
|
|
1488
1603
|
function useOpenExternal() {
|
|
1489
|
-
const runtime = useViewRuntime();
|
|
1604
|
+
const runtime = useViewRuntime("useOpenExternal");
|
|
1490
1605
|
return useCallback2(
|
|
1491
1606
|
async (args) => {
|
|
1492
1607
|
await runtime.openLink({ url: args.url });
|
|
@@ -1498,7 +1613,7 @@ function useOpenExternal() {
|
|
|
1498
1613
|
// src/react/hooks/use-send-follow-up.ts
|
|
1499
1614
|
import { useCallback as useCallback3 } from "react";
|
|
1500
1615
|
function useSendFollowUp() {
|
|
1501
|
-
const runtime = useViewRuntime();
|
|
1616
|
+
const runtime = useViewRuntime("useSendFollowUp");
|
|
1502
1617
|
return useCallback3(
|
|
1503
1618
|
async (args) => {
|
|
1504
1619
|
await runtime.sendMessage({
|
|
@@ -1512,26 +1627,26 @@ function useSendFollowUp() {
|
|
|
1512
1627
|
|
|
1513
1628
|
// src/react/hooks/use-send-size-changed.ts
|
|
1514
1629
|
function useSendSizeChanged() {
|
|
1515
|
-
const runtime = useViewRuntime();
|
|
1630
|
+
const runtime = useViewRuntime("useSendSizeChanged");
|
|
1516
1631
|
return runtime.sendSizeChanged;
|
|
1517
1632
|
}
|
|
1518
1633
|
|
|
1519
1634
|
// src/react/hooks/use-view-theme.ts
|
|
1520
1635
|
import { useSyncExternalStore as useSyncExternalStore6 } from "react";
|
|
1521
1636
|
function useViewTheme() {
|
|
1522
|
-
const runtime = useViewRuntime();
|
|
1637
|
+
const runtime = useViewRuntime("useViewTheme");
|
|
1523
1638
|
return useSyncExternalStore6(runtime.subscribeTheme, runtime.getThemeSnapshot);
|
|
1524
1639
|
}
|
|
1525
1640
|
|
|
1526
1641
|
// src/react/hooks/use-view-state.ts
|
|
1527
1642
|
import {
|
|
1528
1643
|
useCallback as useCallback4,
|
|
1529
|
-
useEffect as
|
|
1644
|
+
useEffect as useEffect3,
|
|
1530
1645
|
useRef as useRef3,
|
|
1531
1646
|
useSyncExternalStore as useSyncExternalStore7
|
|
1532
1647
|
} from "react";
|
|
1533
1648
|
function useViewState(defaultState) {
|
|
1534
|
-
const runtime = useViewRuntime();
|
|
1649
|
+
const runtime = useViewRuntime("useViewState");
|
|
1535
1650
|
const store = runtime.modelContextStore;
|
|
1536
1651
|
const defaultRef = useRef3(null);
|
|
1537
1652
|
if (defaultRef.current === null) {
|
|
@@ -1541,7 +1656,7 @@ function useViewState(defaultState) {
|
|
|
1541
1656
|
store.subscribeViewState,
|
|
1542
1657
|
store.getViewStateSnapshot
|
|
1543
1658
|
);
|
|
1544
|
-
|
|
1659
|
+
useEffect3(() => {
|
|
1545
1660
|
store.initializeViewState(defaultRef.current);
|
|
1546
1661
|
}, [store]);
|
|
1547
1662
|
const setViewState = useCallback4(
|
|
@@ -1557,7 +1672,7 @@ function useViewState(defaultState) {
|
|
|
1557
1672
|
}
|
|
1558
1673
|
|
|
1559
1674
|
// src/react/hooks/use-view-tool.ts
|
|
1560
|
-
import { useEffect as
|
|
1675
|
+
import { useEffect as useEffect4, useRef as useRef4 } from "react";
|
|
1561
1676
|
|
|
1562
1677
|
// src/tools.ts
|
|
1563
1678
|
function resolveToolInputSchema(definition) {
|
|
@@ -1566,7 +1681,7 @@ function resolveToolInputSchema(definition) {
|
|
|
1566
1681
|
|
|
1567
1682
|
// src/react/hooks/use-view-tool.ts
|
|
1568
1683
|
function useViewTool(definition, handler) {
|
|
1569
|
-
const runtime = useViewRuntime();
|
|
1684
|
+
const runtime = useViewRuntime("useViewTool");
|
|
1570
1685
|
const handlerRef = useRef4(handler);
|
|
1571
1686
|
handlerRef.current = handler;
|
|
1572
1687
|
const definitionRef = useRef4(definition);
|
|
@@ -1575,7 +1690,7 @@ function useViewTool(definition, handler) {
|
|
|
1575
1690
|
const registeredMetadataRef = useRef4(null);
|
|
1576
1691
|
const { name, title, description, enabled = true } = definition;
|
|
1577
1692
|
const annotationsJson = definition.annotations === void 0 ? void 0 : JSON.stringify(definition.annotations);
|
|
1578
|
-
|
|
1693
|
+
useEffect4(() => {
|
|
1579
1694
|
const def = definitionRef.current;
|
|
1580
1695
|
const config = {};
|
|
1581
1696
|
if (def.title !== void 0) config.title = def.title;
|
|
@@ -1622,7 +1737,7 @@ function useViewTool(definition, handler) {
|
|
|
1622
1737
|
}
|
|
1623
1738
|
};
|
|
1624
1739
|
}, [runtime, name]);
|
|
1625
|
-
|
|
1740
|
+
useEffect4(() => {
|
|
1626
1741
|
const registered = registeredRef.current;
|
|
1627
1742
|
if (!registered) return;
|
|
1628
1743
|
const applied = registeredMetadataRef.current;
|
|
@@ -1642,7 +1757,7 @@ function useViewTool(definition, handler) {
|
|
|
1642
1757
|
annotationsJson: def.annotations === void 0 ? void 0 : JSON.stringify(def.annotations)
|
|
1643
1758
|
};
|
|
1644
1759
|
}, [title, description, annotationsJson]);
|
|
1645
|
-
|
|
1760
|
+
useEffect4(() => {
|
|
1646
1761
|
const registered = registeredRef.current;
|
|
1647
1762
|
if (!registered || registered.enabled === enabled) return;
|
|
1648
1763
|
if (enabled) {
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import type { McpUiHostContext } from "@modelcontextprotocol/ext-apps";
|
|
2
2
|
import { type ReactNode } from "react";
|
|
3
3
|
import type { McpAppRuntime } from "./view-runtime.js";
|
|
4
|
+
type ViewHook = "useCallTool" | "useDisplayMode" | "useDynamicTool" | "useFiles" | "useHostContext" | "useOpenExternal" | "useSendFollowUp" | "useSendSizeChanged" | "useToolContext" | "useViewState" | "useViewTheme" | "useViewTool";
|
|
4
5
|
/**
|
|
5
6
|
* React context holding the document's {@link McpAppRuntime}.
|
|
6
7
|
*
|
|
@@ -33,7 +34,7 @@ export declare function ViewRuntimeProvider({ runtime, children, }: {
|
|
|
33
34
|
*
|
|
34
35
|
* @internal
|
|
35
36
|
*/
|
|
36
|
-
export declare function useViewRuntime(): McpAppRuntime;
|
|
37
|
+
export declare function useViewRuntime(hook?: ViewHook): McpAppRuntime;
|
|
37
38
|
/**
|
|
38
39
|
* Subscribe to host context only — re-renders when `hostContext` identity
|
|
39
40
|
* changes (connection-only updates that keep the same context object do not).
|
|
@@ -43,3 +44,4 @@ export declare function useViewRuntime(): McpAppRuntime;
|
|
|
43
44
|
* @internal
|
|
44
45
|
*/
|
|
45
46
|
export declare function useHostContextSubscription(): McpUiHostContext | undefined;
|
|
47
|
+
export {};
|
package/dist/usage.d.ts
CHANGED
|
@@ -1,11 +1,14 @@
|
|
|
1
1
|
type Value = string | number | boolean;
|
|
2
2
|
type Properties = Record<string, Value | undefined>;
|
|
3
|
-
|
|
4
|
-
export declare function recordUsage(feature: string, action: string, properties?: Properties, options?: {
|
|
3
|
+
type Options = {
|
|
5
4
|
onceKey?: string;
|
|
6
5
|
sampleRate?: number;
|
|
7
6
|
serverRoot?: string;
|
|
8
|
-
}
|
|
7
|
+
};
|
|
8
|
+
/** Capture one anonymous, flat SDK usage event. @internal */
|
|
9
|
+
export declare function recordUsage(feature: string, action: string, properties?: Properties, options?: Options): void;
|
|
10
|
+
/** Capture from a browser runtime without pulling in server persistence. @internal */
|
|
11
|
+
export declare function recordRuntimeUsage(feature: string, action: string, properties?: Properties, options?: Omit<Options, "serverRoot">): void;
|
|
9
12
|
/** Wait for in-flight usage events in validation fixtures. @internal */
|
|
10
13
|
export declare function flushUsage(): Promise<void>;
|
|
11
14
|
export {};
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "mcp-use",
|
|
3
3
|
"type": "module",
|
|
4
|
-
"version": "2.0.0-beta.
|
|
4
|
+
"version": "2.0.0-beta.44",
|
|
5
5
|
"description": "MCP framework and CLI built on the official v2 SDK",
|
|
6
6
|
"author": "mcp-use, Inc.",
|
|
7
7
|
"license": "MIT",
|
|
@@ -89,8 +89,8 @@
|
|
|
89
89
|
"@modelcontextprotocol/server": "2.0.0-beta.5",
|
|
90
90
|
"hono": "^4.12.27",
|
|
91
91
|
"jose": "^6.1.3",
|
|
92
|
-
"@mcp-use/
|
|
93
|
-
"@mcp-use/
|
|
92
|
+
"@mcp-use/cli": "4.0.0-beta.10",
|
|
93
|
+
"@mcp-use/inspector": "20.0.0-beta.36"
|
|
94
94
|
},
|
|
95
95
|
"peerDependencies": {
|
|
96
96
|
"@mcp-use/client": "^2.0.0-alpha.0",
|
|
@@ -125,7 +125,7 @@
|
|
|
125
125
|
"vitest": "^4.1.9",
|
|
126
126
|
"zod": "^4.4.3",
|
|
127
127
|
"@mcp-use/client": "2.0.0-beta.13",
|
|
128
|
-
"mcp-use": "2.0.0-beta.
|
|
128
|
+
"mcp-use": "2.0.0-beta.44"
|
|
129
129
|
},
|
|
130
130
|
"publishConfig": {
|
|
131
131
|
"access": "public"
|