@mastra/mcp 0.14.2 → 1.0.0-beta.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/CHANGELOG.md +74 -13
- package/README.md +8 -8
- package/dist/__fixtures__/tools.d.ts +1 -7
- package/dist/__fixtures__/tools.d.ts.map +1 -1
- package/dist/client/client.d.ts +4 -9
- package/dist/client/client.d.ts.map +1 -1
- package/dist/client/configuration.d.ts +10 -64
- package/dist/client/configuration.d.ts.map +1 -1
- package/dist/client/index.d.ts +0 -1
- package/dist/client/index.d.ts.map +1 -1
- package/dist/index.cjs +175 -96
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +175 -94
- package/dist/index.js.map +1 -1
- package/dist/server/server.d.ts +44 -6
- package/dist/server/server.d.ts.map +1 -1
- package/dist/server/types.d.ts +0 -54
- package/dist/server/types.d.ts.map +1 -1
- package/package.json +8 -12
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/client/elicitationActions.ts","../src/client/promptActions.ts","../src/client/resourceActions.ts","../src/client/client.ts","../src/client/configuration.ts","../../../node_modules/.pnpm/hono@4.10.1/node_modules/hono/dist/utils/stream.js","../../../node_modules/.pnpm/hono@4.10.1/node_modules/hono/dist/helper/streaming/utils.js","../../../node_modules/.pnpm/hono@4.10.1/node_modules/hono/dist/utils/html.js","../../../node_modules/.pnpm/hono@4.10.1/node_modules/hono/dist/helper/streaming/sse.js","../../../node_modules/.pnpm/hono-mcp-server-sse-transport@0.0.7_@modelcontextprotocol+sdk@1.20.1_hono@4.10.1/node_modules/hono-mcp-server-sse-transport/build/sse.js","../src/server/promptActions.ts","../src/server/resourceActions.ts","../src/server/server.ts"],"names":["ErrorCode","convertJsonSchemaToZodV3","MastraBase","DEFAULT_REQUEST_TIMEOUT_MSEC","existingInstance","MastraError","ErrorDomain","ErrorCategory","uuidv5","stream","request","z","createTool","run"],"mappings":";;;;;;;;;;;;;;;;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AAAA,OACF;AACA,MAAA,IAAA,CAAK,MAAA,CAAO,eAAe,WAAW,CAAA;AACtC,MAAA,IAAA,CAAK,OAAO,KAAA,CAAM,CAAA,wCAAA,EAA2C,MAAM,CAAA,EAAA,CAAA,EAAM,EAAE,OAAO,CAAA;AAClF,MAAA,MAAM,WAAA;AAAA,IACR;AAAA,EACF;AACF","file":"index.js","sourcesContent":["import type { IMastraLogger } from '@mastra/core/logger';\nimport type { ElicitRequest, ElicitResult } from '@modelcontextprotocol/sdk/types.js';\nimport type { InternalMastraMCPClient } from './client';\n\ninterface ElicitationClientActionsConfig {\n client: InternalMastraMCPClient;\n logger: IMastraLogger;\n}\n\n/**\n * Client-side elicitation actions for handling interactive user input requests.\n *\n * Elicitation allows MCP servers to request structured information from users during\n * tool execution. The client provides a handler that collects user input and returns\n * it to the server.\n */\nexport class ElicitationClientActions {\n private readonly client: InternalMastraMCPClient;\n private readonly logger: IMastraLogger;\n\n /**\n * @internal\n */\n constructor({ client, logger }: ElicitationClientActionsConfig) {\n this.client = client;\n this.logger = logger;\n }\n\n /**\n * Sets a handler function for processing elicitation requests from the server.\n *\n * The handler is called when the server needs to collect user input during tool execution.\n * The handler must return a response with action ('accept', 'decline', or 'cancel') and\n * optional content matching the requested schema.\n *\n * @param handler - Callback function to handle elicitation requests\n *\n * @example\n * ```typescript\n * client.elicitation.onRequest(async (request) => {\n * console.log('Server message:', request.message);\n * console.log('Requested schema:', request.requestedSchema);\n *\n * // Collect user input (e.g., via CLI prompt or UI form)\n * const userInput = await collectUserInput(request.requestedSchema);\n *\n * return {\n * action: 'accept',\n * content: userInput\n * };\n * });\n * ```\n *\n * @example\n * ```typescript\n * // Declining an elicitation request\n * client.elicitation.onRequest(async (request) => {\n * if (!shouldAcceptRequest(request)) {\n * return { action: 'decline' };\n * }\n *\n * const input = await getInput();\n * return { action: 'accept', content: input };\n * });\n * ```\n */\n public onRequest(handler: (request: ElicitRequest['params']) => Promise<ElicitResult>): void {\n this.client.setElicitationRequestHandler(handler);\n }\n}\n","import type { IMastraLogger } from '@mastra/core/logger';\nimport { ErrorCode } from '@modelcontextprotocol/sdk/types.js';\nimport type { GetPromptResult, Prompt } from '@modelcontextprotocol/sdk/types.js';\nimport type { InternalMastraMCPClient } from './client';\n\ninterface PromptClientActionsConfig {\n client: InternalMastraMCPClient;\n logger: IMastraLogger;\n}\n\n/**\n * Client-side prompt actions for interacting with MCP server prompts.\n *\n * Provides methods to list, retrieve, and subscribe to prompt templates exposed by an MCP server.\n * Prompts are reusable message templates that can be parameterized and used for AI interactions.\n */\nexport class PromptClientActions {\n private readonly client: InternalMastraMCPClient;\n private readonly logger: IMastraLogger;\n\n /**\n * @internal\n */\n constructor({ client, logger }: PromptClientActionsConfig) {\n this.client = client;\n this.logger = logger;\n }\n\n /**\n * Retrieves all available prompts from the connected MCP server.\n *\n * Returns an empty array if the server doesn't support prompts (MethodNotFound error).\n *\n * @returns Promise resolving to array of prompts with their metadata\n * @throws {Error} If fetching prompts fails (excluding MethodNotFound)\n *\n * @example\n * ```typescript\n * const prompts = await client.prompts.list();\n * prompts.forEach(prompt => {\n * console.log(`${prompt.name} (v${prompt.version}): ${prompt.description}`);\n * });\n * ```\n */\n public async list(): Promise<Prompt[]> {\n try {\n const response = await this.client.listPrompts();\n if (response && response.prompts && Array.isArray(response.prompts)) {\n return response.prompts.map(prompt => ({ ...prompt, version: prompt.version || '' }));\n } else {\n this.logger.warn(`Prompts response from server ${this.client.name} did not have expected structure.`, {\n response,\n });\n return [];\n }\n } catch (e: any) {\n // MCP Server might not support prompts, so we return an empty array\n if (e.code === ErrorCode.MethodNotFound) {\n return [];\n }\n this.logger.error(`Error getting prompts from server ${this.client.name}`, {\n error: e instanceof Error ? e.message : String(e),\n });\n throw new Error(\n `Failed to fetch prompts from server ${this.client.name}: ${e instanceof Error ? e.stack || e.message : String(e)}`,\n );\n }\n }\n\n /**\n * Retrieves a specific prompt with its messages from the MCP server.\n *\n * Prompts can accept arguments to parameterize the template. The returned messages\n * can be used directly in AI chat completions.\n *\n * @param params - Parameters for the prompt request\n * @param params.name - Name of the prompt to retrieve\n * @param params.args - Optional arguments to populate the prompt template\n * @param params.version - Optional specific version of the prompt to retrieve\n * @returns Promise resolving to the prompt result with messages\n * @throws {Error} If fetching the prompt fails or prompt not found\n *\n * @example\n * ```typescript\n * const prompt = await client.prompts.get({\n * name: 'code-review',\n * args: {\n * language: 'typescript',\n * code: 'const x = 1;'\n * },\n * version: '1.0'\n * });\n *\n * // Use prompt messages in AI completion\n * console.log(prompt.messages);\n * ```\n */\n public async get({\n name,\n args,\n version,\n }: {\n name: string;\n args?: Record<string, any>;\n version?: string;\n }): Promise<GetPromptResult> {\n return this.client.getPrompt({ name, args, version });\n }\n\n /**\n * Sets a notification handler for when the list of available prompts changes.\n *\n * The handler is called when prompts are added, removed, or modified on the server.\n *\n * @param handler - Callback function invoked when the prompt list changes\n *\n * @example\n * ```typescript\n * await client.prompts.onListChanged(async () => {\n * console.log('Prompt list changed, re-fetching...');\n * const prompts = await client.prompts.list();\n * console.log('Available prompts:', prompts.map(p => p.name));\n * });\n * ```\n */\n public async onListChanged(handler: () => void): Promise<void> {\n this.client.setPromptListChangedNotificationHandler(handler);\n }\n}\n","import type { IMastraLogger } from '@mastra/core/logger';\nimport { ErrorCode } from '@modelcontextprotocol/sdk/types.js';\nimport type { Resource, ResourceTemplate } from '@modelcontextprotocol/sdk/types.js';\nimport type { InternalMastraMCPClient } from './client';\n\ninterface ResourceClientActionsConfig {\n client: InternalMastraMCPClient;\n logger: IMastraLogger;\n}\n\n/**\n * Client-side resource actions for interacting with MCP server resources.\n *\n * Provides methods to list, read, subscribe to, and manage resources exposed by an MCP server.\n * Resources represent any kind of data that a server wants to make available (files, database\n * records, API responses, etc.).\n */\nexport class ResourceClientActions {\n private readonly client: InternalMastraMCPClient;\n private readonly logger: IMastraLogger;\n\n /**\n * @internal\n */\n constructor({ client, logger }: ResourceClientActionsConfig) {\n this.client = client;\n this.logger = logger;\n }\n\n /**\n * Retrieves all available resources from the connected MCP server.\n *\n * Returns an empty array if the server doesn't support resources (MethodNotFound error).\n *\n * @returns Promise resolving to array of resources\n * @throws {Error} If fetching resources fails (excluding MethodNotFound)\n *\n * @example\n * ```typescript\n * const resources = await client.resources.list();\n * resources.forEach(resource => {\n * console.log(`${resource.name}: ${resource.uri}`);\n * });\n * ```\n */\n public async list(): Promise<Resource[]> {\n try {\n const response = await this.client.listResources();\n if (response && response.resources && Array.isArray(response.resources)) {\n return response.resources;\n } else {\n this.logger.warn(`Resources response from server ${this.client.name} did not have expected structure.`, {\n response,\n });\n return [];\n }\n } catch (e: any) {\n // MCP Server might not support resources, so we return an empty array\n if (e.code === ErrorCode.MethodNotFound) {\n return [];\n }\n this.logger.error(`Error getting resources from server ${this.client.name}`, {\n error: e instanceof Error ? e.message : String(e),\n });\n throw new Error(\n `Failed to fetch resources from server ${this.client.name}: ${e instanceof Error ? e.stack || e.message : String(e)}`,\n );\n }\n }\n\n /**\n * Retrieves all available resource templates from the connected MCP server.\n *\n * Resource templates are URI templates (RFC 6570) that describe dynamic resources.\n * Returns an empty array if the server doesn't support resource templates.\n *\n * @returns Promise resolving to array of resource templates\n * @throws {Error} If fetching resource templates fails (excluding MethodNotFound)\n *\n * @example\n * ```typescript\n * const templates = await client.resources.templates();\n * templates.forEach(template => {\n * console.log(`${template.name}: ${template.uriTemplate}`);\n * });\n * ```\n */\n public async templates(): Promise<ResourceTemplate[]> {\n try {\n const response = await this.client.listResourceTemplates();\n if (response && response.resourceTemplates && Array.isArray(response.resourceTemplates)) {\n return response.resourceTemplates;\n } else {\n this.logger.warn(\n `Resource templates response from server ${this.client.name} did not have expected structure.`,\n { response },\n );\n return [];\n }\n } catch (e: any) {\n // MCP Server might not support resources, so we return an empty array\n if (e.code === ErrorCode.MethodNotFound) {\n return [];\n }\n this.logger.error(`Error getting resource templates from server ${this.client.name}`, {\n error: e instanceof Error ? e.message : String(e),\n });\n throw new Error(\n `Failed to fetch resource templates from server ${this.client.name}: ${e instanceof Error ? e.stack || e.message : String(e)}`,\n );\n }\n }\n\n /**\n * Reads the content of a specific resource from the MCP server.\n *\n * @param uri - URI of the resource to read (e.g., 'file://path/to/file.txt')\n * @returns Promise resolving to the resource content\n * @throws {Error} If reading the resource fails or resource not found\n *\n * @example\n * ```typescript\n * const result = await client.resources.read('file://data/config.json');\n * console.log(result.contents[0].text); // Resource text content\n * ```\n */\n public async read(uri: string) {\n return this.client.readResource(uri);\n }\n\n /**\n * Subscribes to updates for a specific resource.\n *\n * After subscribing, you'll receive notifications via the `onUpdated` handler\n * when the resource content changes.\n *\n * @param uri - URI of the resource to subscribe to\n * @returns Promise resolving when subscription is established\n * @throws {Error} If subscription fails\n *\n * @example\n * ```typescript\n * await client.resources.subscribe('file://data/config.json');\n * ```\n */\n public async subscribe(uri: string) {\n return this.client.subscribeResource(uri);\n }\n\n /**\n * Unsubscribes from updates for a specific resource.\n *\n * Stops receiving notifications for this resource URI.\n *\n * @param uri - URI of the resource to unsubscribe from\n * @returns Promise resolving when unsubscription is complete\n * @throws {Error} If unsubscription fails\n *\n * @example\n * ```typescript\n * await client.resources.unsubscribe('file://data/config.json');\n * ```\n */\n public async unsubscribe(uri: string) {\n return this.client.unsubscribeResource(uri);\n }\n\n /**\n * Sets a notification handler for when subscribed resources are updated.\n *\n * The handler is called whenever the server sends a resource update notification\n * for any resource you've subscribed to.\n *\n * @param handler - Callback function receiving the updated resource URI\n *\n * @example\n * ```typescript\n * await client.resources.onUpdated(async (params) => {\n * console.log(`Resource updated: ${params.uri}`);\n * // Re-fetch the resource\n * const content = await client.resources.read(params.uri);\n * console.log('New content:', content);\n * });\n * ```\n */\n public async onUpdated(handler: (params: { uri: string }) => void): Promise<void> {\n this.client.setResourceUpdatedNotificationHandler(handler);\n }\n\n /**\n * Sets a notification handler for when the list of available resources changes.\n *\n * The handler is called when resources are added or removed from the server.\n *\n * @param handler - Callback function invoked when the resource list changes\n *\n * @example\n * ```typescript\n * await client.resources.onListChanged(async () => {\n * console.log('Resource list changed, re-fetching...');\n * const resources = await client.resources.list();\n * console.log('Updated resource count:', resources.length);\n * });\n * ```\n */\n public async onListChanged(handler: () => void): Promise<void> {\n this.client.setResourceListChangedNotificationHandler(handler);\n }\n}\n","import $RefParser from '@apidevtools/json-schema-ref-parser';\nimport { MastraBase } from '@mastra/core/base';\nimport type { RuntimeContext } from '@mastra/core/di';\nimport { ErrorCategory, ErrorDomain, MastraError } from '@mastra/core/error';\nimport { createTool } from '@mastra/core/tools';\nimport { isZodType } from '@mastra/core/utils';\nimport { Client } from '@modelcontextprotocol/sdk/client/index.js';\nimport { SSEClientTransport } from '@modelcontextprotocol/sdk/client/sse.js';\nimport type { SSEClientTransportOptions } from '@modelcontextprotocol/sdk/client/sse.js';\nimport { getDefaultEnvironment, StdioClientTransport } from '@modelcontextprotocol/sdk/client/stdio.js';\nimport { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js';\nimport type { StreamableHTTPClientTransportOptions } from '@modelcontextprotocol/sdk/client/streamableHttp.js';\nimport { DEFAULT_REQUEST_TIMEOUT_MSEC } from '@modelcontextprotocol/sdk/shared/protocol.js';\nimport type { Transport } from '@modelcontextprotocol/sdk/shared/transport.js';\nimport type {\n ClientCapabilities,\n ElicitRequest,\n ElicitResult,\n GetPromptResult,\n ListPromptsResult,\n LoggingLevel,\n} from '@modelcontextprotocol/sdk/types.js';\nimport {\n CallToolResultSchema,\n ListResourcesResultSchema,\n ReadResourceResultSchema,\n ResourceListChangedNotificationSchema,\n ResourceUpdatedNotificationSchema,\n ListResourceTemplatesResultSchema,\n ListPromptsResultSchema,\n GetPromptResultSchema,\n PromptListChangedNotificationSchema,\n ElicitRequestSchema,\n} from '@modelcontextprotocol/sdk/types.js';\n\nimport { asyncExitHook, gracefulExit } from 'exit-hook';\nimport { z } from 'zod';\nimport { convertJsonSchemaToZod } from 'zod-from-json-schema';\nimport { convertJsonSchemaToZod as convertJsonSchemaToZodV3 } from 'zod-from-json-schema-v3';\nimport type { JSONSchema } from 'zod-from-json-schema-v3';\nimport { ElicitationClientActions } from './elicitationActions';\nimport { PromptClientActions } from './promptActions';\nimport { ResourceClientActions } from './resourceActions';\n\n// Re-export MCP SDK LoggingLevel for convenience\nexport type { LoggingLevel } from '@modelcontextprotocol/sdk/types.js';\n\n/**\n * Log message structure for MCP client logging.\n */\nexport interface LogMessage {\n /** Logging level (debug, info, warning, error, etc.) */\n level: LoggingLevel;\n /** Log message content */\n message: string;\n /** Timestamp when the log was created */\n timestamp: Date;\n /** Name of the MCP server that generated the log */\n serverName: string;\n /** Optional additional details */\n details?: Record<string, any>;\n runtimeContext?: RuntimeContext | null;\n}\n\n/**\n * Handler function for processing log messages from MCP servers.\n */\nexport type LogHandler = (logMessage: LogMessage) => void;\n\n/**\n * Handler function for processing elicitation requests from MCP servers.\n *\n * @param request - The elicitation request parameters including message and schema\n * @returns Promise resolving to the user's response (accept/decline/cancel with optional content)\n */\nexport type ElicitationHandler = (request: ElicitRequest['params']) => Promise<ElicitResult>;\n\n/**\n * Base options common to all MCP server definitions.\n */\ntype BaseServerOptions = {\n /** Optional handler for server log messages */\n logger?: LogHandler;\n /** Optional timeout in milliseconds for server operations */\n timeout?: number;\n /** Optional client capabilities to advertise to the server */\n capabilities?: ClientCapabilities;\n /** Whether to enable server log forwarding (default: true) */\n enableServerLogs?: boolean;\n};\n\n/**\n * Configuration for MCP servers using stdio (subprocess) transport.\n *\n * Used when the MCP server is spawned as a subprocess that communicates via stdin/stdout.\n */\ntype StdioServerDefinition = BaseServerOptions & {\n /** Command to execute (e.g., 'node', 'python', 'npx') */\n command: string;\n /** Optional arguments to pass to the command */\n args?: string[];\n /** Optional environment variables for the subprocess */\n env?: Record<string, string>;\n\n url?: never;\n requestInit?: never;\n eventSourceInit?: never;\n authProvider?: never;\n reconnectionOptions?: never;\n sessionId?: never;\n};\n\n/**\n * Configuration for MCP servers using HTTP-based transport (Streamable HTTP or SSE fallback).\n *\n * Used when connecting to remote MCP servers over HTTP. The client will attempt Streamable HTTP\n * transport first and fall back to SSE if that fails.\n */\ntype HttpServerDefinition = BaseServerOptions & {\n /** URL of the MCP server endpoint */\n url: URL;\n\n command?: never;\n args?: never;\n env?: never;\n\n /** Optional request configuration for HTTP requests */\n requestInit?: StreamableHTTPClientTransportOptions['requestInit'];\n /** Optional configuration for SSE fallback (required when using custom headers with SSE) */\n eventSourceInit?: SSEClientTransportOptions['eventSourceInit'];\n /** Optional authentication provider for HTTP requests */\n authProvider?: StreamableHTTPClientTransportOptions['authProvider'];\n /** Optional reconnection configuration for Streamable HTTP */\n reconnectionOptions?: StreamableHTTPClientTransportOptions['reconnectionOptions'];\n /** Optional session ID for Streamable HTTP */\n sessionId?: StreamableHTTPClientTransportOptions['sessionId'];\n};\n\n/**\n * Configuration for connecting to an MCP server.\n *\n * Either stdio-based (subprocess) or HTTP-based (remote server). The transport type is\n * automatically detected based on whether `command` or `url` is provided.\n *\n * @example\n * ```typescript\n * // Stdio server\n * const stdioServer: MastraMCPServerDefinition = {\n * command: 'npx',\n * args: ['tsx', 'server.ts'],\n * env: { API_KEY: 'secret' }\n * };\n *\n * // HTTP server\n * const httpServer: MastraMCPServerDefinition = {\n * url: new URL('http://localhost:8080/mcp'),\n * requestInit: {\n * headers: { Authorization: 'Bearer token' }\n * }\n * };\n * ```\n */\nexport type MastraMCPServerDefinition = StdioServerDefinition | HttpServerDefinition;\n\n/**\n * Convert an MCP LoggingLevel to a logger method name that exists in our logger\n */\nfunction convertLogLevelToLoggerMethod(level: LoggingLevel): 'debug' | 'info' | 'warn' | 'error' {\n switch (level) {\n case 'debug':\n return 'debug';\n case 'info':\n case 'notice':\n return 'info';\n case 'warning':\n return 'warn';\n case 'error':\n case 'critical':\n case 'alert':\n case 'emergency':\n return 'error';\n default:\n // For any other levels, default to info\n return 'info';\n }\n}\n\n/**\n * Options for creating an internal MCP client instance.\n *\n * @internal\n */\nexport type InternalMastraMCPClientOptions = {\n /** Name identifier for this client */\n name: string;\n /** Server connection configuration */\n server: MastraMCPServerDefinition;\n /** Optional client capabilities */\n capabilities?: ClientCapabilities;\n /** Optional client version */\n version?: string;\n /** Optional timeout in milliseconds */\n timeout?: number;\n};\n\n/**\n * Internal MCP client implementation for connecting to a single MCP server.\n *\n * This class handles the low-level connection, transport management, and protocol\n * communication with an MCP server. Most users should use MCPClient instead.\n *\n * @internal\n */\nexport class InternalMastraMCPClient extends MastraBase {\n name: string;\n private client: Client;\n private readonly timeout: number;\n private logHandler?: LogHandler;\n private enableServerLogs?: boolean;\n private serverConfig: MastraMCPServerDefinition;\n private transport?: Transport;\n private currentOperationContext: RuntimeContext | null = null;\n\n /** Provides access to resource operations (list, read, subscribe, etc.) */\n public readonly resources: ResourceClientActions;\n /** Provides access to prompt operations (list, get, notifications) */\n public readonly prompts: PromptClientActions;\n /** Provides access to elicitation operations (request handling) */\n public readonly elicitation: ElicitationClientActions;\n\n /**\n * @internal\n */\n constructor({\n name,\n version = '1.0.0',\n server,\n capabilities = {},\n timeout = DEFAULT_REQUEST_TIMEOUT_MSEC,\n }: InternalMastraMCPClientOptions) {\n super({ name: 'MastraMCPClient' });\n this.name = name;\n this.timeout = timeout;\n this.logHandler = server.logger;\n this.enableServerLogs = server.enableServerLogs ?? true;\n this.serverConfig = server;\n\n const clientCapabilities = { ...capabilities, elicitation: {} };\n\n this.client = new Client(\n {\n name,\n version,\n },\n {\n capabilities: clientCapabilities,\n },\n );\n\n // Set up log message capturing\n this.setupLogging();\n\n this.resources = new ResourceClientActions({ client: this, logger: this.logger });\n this.prompts = new PromptClientActions({ client: this, logger: this.logger });\n this.elicitation = new ElicitationClientActions({ client: this, logger: this.logger });\n }\n\n /**\n * Log a message at the specified level\n * @param level Log level\n * @param message Log message\n * @param details Optional additional details\n */\n private log(level: LoggingLevel, message: string, details?: Record<string, any>): void {\n // Convert MCP logging level to our logger method\n const loggerMethod = convertLogLevelToLoggerMethod(level);\n\n const msg = `[${this.name}] ${message}`;\n\n // Log to internal logger\n this.logger[loggerMethod](msg, details);\n\n // Send to registered handler if available\n if (this.logHandler) {\n this.logHandler({\n level,\n message: msg,\n timestamp: new Date(),\n serverName: this.name,\n details,\n runtimeContext: this.currentOperationContext,\n });\n }\n }\n\n private setupLogging(): void {\n if (this.enableServerLogs) {\n this.client.setNotificationHandler(\n z.object({\n method: z.literal('notifications/message'),\n params: z\n .object({\n level: z.string(),\n })\n .passthrough(),\n }),\n notification => {\n const { level, ...params } = notification.params;\n this.log(level as LoggingLevel, '[MCP SERVER LOG]', params);\n },\n );\n }\n }\n\n private async connectStdio(command: string) {\n this.log('debug', `Using Stdio transport for command: ${command}`);\n try {\n this.transport = new StdioClientTransport({\n command,\n args: this.serverConfig.args,\n env: { ...getDefaultEnvironment(), ...(this.serverConfig.env || {}) },\n });\n await this.client.connect(this.transport, { timeout: this.serverConfig.timeout ?? this.timeout });\n this.log('debug', `Successfully connected to MCP server via Stdio`);\n } catch (e) {\n this.log('error', e instanceof Error ? e.stack || e.message : JSON.stringify(e));\n throw e;\n }\n }\n\n private async connectHttp(url: URL) {\n const { requestInit, eventSourceInit, authProvider } = this.serverConfig;\n\n this.log('debug', `Attempting to connect to URL: ${url}`);\n\n // Assume /sse means sse.\n let shouldTrySSE = url.pathname.endsWith(`/sse`);\n\n if (!shouldTrySSE) {\n try {\n // Try Streamable HTTP transport first\n this.log('debug', 'Trying Streamable HTTP transport...');\n const streamableTransport = new StreamableHTTPClientTransport(url, {\n requestInit,\n reconnectionOptions: this.serverConfig.reconnectionOptions,\n authProvider: authProvider,\n });\n await this.client.connect(streamableTransport, {\n timeout:\n // this is hardcoded to 3s because the long default timeout would be extremely slow for sse backwards compat (60s)\n 3000,\n });\n this.transport = streamableTransport;\n this.log('debug', 'Successfully connected using Streamable HTTP transport.');\n } catch (error) {\n this.log('debug', `Streamable HTTP transport failed: ${error}`);\n shouldTrySSE = true;\n }\n }\n\n if (shouldTrySSE) {\n this.log('debug', 'Falling back to deprecated HTTP+SSE transport...');\n try {\n // Fallback to SSE transport\n const sseTransport = new SSEClientTransport(url, { requestInit, eventSourceInit, authProvider });\n await this.client.connect(sseTransport, { timeout: this.serverConfig.timeout ?? this.timeout });\n this.transport = sseTransport;\n this.log('debug', 'Successfully connected using deprecated HTTP+SSE transport.');\n } catch (sseError) {\n this.log(\n 'error',\n `Failed to connect with SSE transport after failing to connect to Streamable HTTP transport first. SSE error: ${sseError}`,\n );\n throw new Error('Could not connect to server with any available HTTP transport');\n }\n }\n }\n\n private isConnected: Promise<boolean> | null = null;\n\n /**\n * Connects to the MCP server using the configured transport.\n *\n * Automatically detects transport type based on configuration (stdio vs HTTP).\n * Safe to call multiple times - returns existing connection if already connected.\n *\n * @returns Promise resolving to true when connected\n * @throws {MastraError} If connection fails\n *\n * @internal\n */\n async connect() {\n // If a connection attempt is in progress, wait for it.\n if (await this.isConnected) {\n return true;\n }\n\n // Start new connection attempt.\n this.isConnected = new Promise<boolean>(async (resolve, reject) => {\n try {\n const { command, url } = this.serverConfig;\n\n if (command) {\n await this.connectStdio(command);\n } else if (url) {\n await this.connectHttp(url);\n } else {\n throw new Error('Server configuration must include either a command or a url.');\n }\n\n resolve(true);\n\n // Set up disconnect handler to reset state.\n const originalOnClose = this.client.onclose;\n this.client.onclose = () => {\n this.log('debug', `MCP server connection closed`);\n this.isConnected = null;\n if (typeof originalOnClose === 'function') {\n originalOnClose();\n }\n };\n } catch (e) {\n this.isConnected = null;\n reject(e);\n }\n });\n\n asyncExitHook(\n async () => {\n this.log('debug', `Disconnecting MCP server during exit`);\n await this.disconnect();\n },\n { wait: 5000 },\n );\n\n process.on('SIGTERM', () => gracefulExit());\n this.log('debug', `Successfully connected to MCP server`);\n return this.isConnected;\n }\n\n /**\n * Gets the current session ID if using Streamable HTTP transport.\n *\n * Returns undefined if not connected or not using Streamable HTTP transport.\n *\n * @returns Session ID string or undefined\n *\n * @internal\n */\n get sessionId(): string | undefined {\n if (this.transport instanceof StreamableHTTPClientTransport) {\n return this.transport.sessionId;\n }\n return undefined;\n }\n\n async disconnect() {\n if (!this.transport) {\n this.log('debug', 'Disconnect called but no transport was connected.');\n return;\n }\n this.log('debug', `Disconnecting from MCP server`);\n try {\n await this.transport.close();\n this.log('debug', 'Successfully disconnected from MCP server');\n } catch (e) {\n this.log('error', 'Error during MCP server disconnect', {\n error: e instanceof Error ? e.stack : JSON.stringify(e, null, 2),\n });\n throw e;\n } finally {\n this.transport = undefined;\n this.isConnected = Promise.resolve(false);\n }\n }\n\n async listResources() {\n this.log('debug', `Requesting resources from MCP server`);\n return await this.client.request({ method: 'resources/list' }, ListResourcesResultSchema, {\n timeout: this.timeout,\n });\n }\n\n async readResource(uri: string) {\n this.log('debug', `Reading resource from MCP server: ${uri}`);\n return await this.client.request({ method: 'resources/read', params: { uri } }, ReadResourceResultSchema, {\n timeout: this.timeout,\n });\n }\n\n async subscribeResource(uri: string) {\n this.log('debug', `Subscribing to resource on MCP server: ${uri}`);\n return await this.client.request({ method: 'resources/subscribe', params: { uri } }, z.object({}), {\n timeout: this.timeout,\n });\n }\n\n async unsubscribeResource(uri: string) {\n this.log('debug', `Unsubscribing from resource on MCP server: ${uri}`);\n return await this.client.request({ method: 'resources/unsubscribe', params: { uri } }, z.object({}), {\n timeout: this.timeout,\n });\n }\n\n async listResourceTemplates() {\n this.log('debug', `Requesting resource templates from MCP server`);\n return await this.client.request({ method: 'resources/templates/list' }, ListResourceTemplatesResultSchema, {\n timeout: this.timeout,\n });\n }\n\n /**\n * Fetch the list of available prompts from the MCP server.\n */\n async listPrompts(): Promise<ListPromptsResult> {\n this.log('debug', `Requesting prompts from MCP server`);\n return await this.client.request({ method: 'prompts/list' }, ListPromptsResultSchema, {\n timeout: this.timeout,\n });\n }\n\n /**\n * Get a prompt and its dynamic messages from the server.\n * @param name The prompt name\n * @param args Arguments for the prompt\n * @param version (optional) The prompt version to retrieve\n */\n async getPrompt({\n name,\n args,\n version,\n }: {\n name: string;\n args?: Record<string, any>;\n version?: string;\n }): Promise<GetPromptResult> {\n this.log('debug', `Requesting prompt from MCP server: ${name}`);\n return await this.client.request(\n { method: 'prompts/get', params: { name, arguments: args, version } },\n GetPromptResultSchema,\n { timeout: this.timeout },\n );\n }\n\n /**\n * Register a handler to be called when the prompt list changes on the server.\n * Use this to refresh cached prompt lists in the client/UI if needed.\n */\n setPromptListChangedNotificationHandler(handler: () => void): void {\n this.log('debug', 'Setting prompt list changed notification handler');\n this.client.setNotificationHandler(PromptListChangedNotificationSchema, () => {\n handler();\n });\n }\n\n setResourceUpdatedNotificationHandler(\n handler: (params: z.infer<typeof ResourceUpdatedNotificationSchema>['params']) => void,\n ): void {\n this.log('debug', 'Setting resource updated notification handler');\n this.client.setNotificationHandler(ResourceUpdatedNotificationSchema, notification => {\n handler(notification.params);\n });\n }\n\n setResourceListChangedNotificationHandler(handler: () => void): void {\n this.log('debug', 'Setting resource list changed notification handler');\n this.client.setNotificationHandler(ResourceListChangedNotificationSchema, () => {\n handler();\n });\n }\n\n setElicitationRequestHandler(handler: ElicitationHandler): void {\n this.log('debug', 'Setting elicitation request handler');\n this.client.setRequestHandler(ElicitRequestSchema, async request => {\n this.log('debug', `Received elicitation request: ${request.params.message}`);\n return handler(request.params);\n });\n }\n\n private async convertInputSchema(\n inputSchema: Awaited<ReturnType<Client['listTools']>>['tools'][0]['inputSchema'] | JSONSchema,\n ): Promise<z.ZodType> {\n if (isZodType(inputSchema)) {\n return inputSchema;\n }\n\n try {\n await $RefParser.dereference(inputSchema);\n const jsonSchemaToConvert = ('jsonSchema' in inputSchema ? inputSchema.jsonSchema : inputSchema) as JSONSchema;\n if ('toJSONSchema' in z) {\n //@ts-expect-error - zod type issue\n return convertJsonSchemaToZod(jsonSchemaToConvert);\n } else {\n return convertJsonSchemaToZodV3(jsonSchemaToConvert);\n }\n } catch (error: unknown) {\n let errorDetails: string | undefined;\n if (error instanceof Error) {\n errorDetails = error.stack;\n } else {\n // Attempt to stringify, fallback to String()\n try {\n errorDetails = JSON.stringify(error);\n } catch {\n errorDetails = String(error);\n }\n }\n this.log('error', 'Failed to convert JSON schema to Zod schema using zodFromJsonSchema', {\n error: errorDetails,\n originalJsonSchema: inputSchema,\n });\n\n throw new MastraError({\n id: 'MCP_TOOL_INPUT_SCHEMA_CONVERSION_FAILED',\n domain: ErrorDomain.MCP,\n category: ErrorCategory.USER,\n details: { error: errorDetails ?? 'Unknown error' },\n });\n }\n }\n\n private async convertOutputSchema(\n outputSchema: Awaited<ReturnType<Client['listTools']>>['tools'][0]['outputSchema'] | JSONSchema,\n ): Promise<z.ZodType | undefined> {\n if (!outputSchema) return;\n if (isZodType(outputSchema)) {\n return outputSchema;\n }\n\n try {\n await $RefParser.dereference(outputSchema);\n const jsonSchemaToConvert = ('jsonSchema' in outputSchema ? outputSchema.jsonSchema : outputSchema) as JSONSchema;\n if ('toJSONSchema' in z) {\n //@ts-expect-error - zod type issue\n return convertJsonSchemaToZod(jsonSchemaToConvert);\n } else {\n return convertJsonSchemaToZodV3(jsonSchemaToConvert);\n }\n } catch (error: unknown) {\n let errorDetails: string | undefined;\n if (error instanceof Error) {\n errorDetails = error.stack;\n } else {\n // Attempt to stringify, fallback to String()\n try {\n errorDetails = JSON.stringify(error);\n } catch {\n errorDetails = String(error);\n }\n }\n this.log('error', 'Failed to convert JSON schema to Zod schema using zodFromJsonSchema', {\n error: errorDetails,\n originalJsonSchema: outputSchema,\n });\n\n throw new MastraError({\n id: 'MCP_TOOL_OUTPUT_SCHEMA_CONVERSION_FAILED',\n domain: ErrorDomain.MCP,\n category: ErrorCategory.USER,\n details: { error: errorDetails ?? 'Unknown error' },\n });\n }\n }\n\n async tools() {\n this.log('debug', `Requesting tools from MCP server`);\n const { tools } = await this.client.listTools({ timeout: this.timeout });\n const toolsRes: Record<string, any> = {};\n for (const tool of tools) {\n this.log('debug', `Processing tool: ${tool.name}`);\n try {\n const mastraTool = createTool({\n id: `${this.name}_${tool.name}`,\n description: tool.description || '',\n inputSchema: await this.convertInputSchema(tool.inputSchema),\n outputSchema: await this.convertOutputSchema(tool.outputSchema),\n execute: async ({ context, runtimeContext }: { context: any; runtimeContext?: RuntimeContext | null }) => {\n const previousContext = this.currentOperationContext;\n this.currentOperationContext = runtimeContext || null; // Set current context\n try {\n this.log('debug', `Executing tool: ${tool.name}`, { toolArgs: context });\n const res = await this.client.callTool(\n {\n name: tool.name,\n arguments: context,\n },\n CallToolResultSchema,\n {\n timeout: this.timeout,\n },\n );\n\n this.log('debug', `Tool executed successfully: ${tool.name}`);\n return res;\n } catch (e) {\n this.log('error', `Error calling tool: ${tool.name}`, {\n error: e instanceof Error ? e.stack : JSON.stringify(e, null, 2),\n toolArgs: context,\n });\n throw e;\n } finally {\n this.currentOperationContext = previousContext; // Restore previous context\n }\n },\n });\n\n if (tool.name) {\n toolsRes[tool.name] = mastraTool;\n }\n } catch (toolCreationError: unknown) {\n // Catch errors during tool creation itself (e.g., if createTool has issues)\n this.log('error', `Failed to create Mastra tool wrapper for MCP tool: ${tool.name}`, {\n error: toolCreationError instanceof Error ? toolCreationError.stack : String(toolCreationError),\n mcpToolDefinition: tool,\n });\n }\n }\n\n return toolsRes;\n }\n}\n\n/**\n * @deprecated MastraMCPClient is deprecated and will be removed in a future release. Please use MCPClient instead.\n */\n\nexport class MastraMCPClient extends InternalMastraMCPClient {\n constructor(args: InternalMastraMCPClientOptions) {\n super(args);\n throw new MastraError(\n {\n id: 'MASTRA_MCP_CLIENT_DEPRECATED',\n domain: ErrorDomain.MCP,\n category: ErrorCategory.USER,\n text: '[DEPRECATION] MastraMCPClient is deprecated and will be removed in a future release. Please use MCPClient instead.',\n },\n );\n }\n}","import { MastraBase } from '@mastra/core/base';\nimport { ErrorCategory, ErrorDomain, MastraError } from '@mastra/core/error';\nimport { DEFAULT_REQUEST_TIMEOUT_MSEC } from '@modelcontextprotocol/sdk/shared/protocol.js';\nimport type {\n ElicitRequest,\n ElicitResult,\n Prompt,\n Resource,\n ResourceTemplate,\n} from '@modelcontextprotocol/sdk/types.js';\nimport equal from 'fast-deep-equal';\nimport { v5 as uuidv5 } from 'uuid';\nimport { InternalMastraMCPClient } from './client';\nimport type { MastraMCPServerDefinition } from './client';\n\nconst mcpClientInstances = new Map<string, InstanceType<typeof MCPClient>>();\n\n/**\n * Configuration options for creating an MCPClient instance.\n */\nexport interface MCPClientOptions {\n /** Optional unique identifier to prevent memory leaks when creating multiple instances with identical configurations */\n id?: string;\n /** Map of server names to their connection configurations (stdio or HTTP-based) */\n servers: Record<string, MastraMCPServerDefinition>;\n /** Optional global timeout in milliseconds for all servers (default: 60000ms) */\n timeout?: number;\n}\n\n/**\n * MCPClient manages multiple MCP server connections and their tools in a Mastra application.\n *\n * This class handles connection lifecycle, tool namespacing, and provides access to tools,\n * resources, prompts, and elicitation across all configured servers.\n *\n * @example\n * ```typescript\n * import { MCPClient } from '@mastra/mcp';\n * import { Agent } from '@mastra/core/agent';\n *\n * const mcp = new MCPClient({\n * servers: {\n * weather: {\n * url: new URL('http://localhost:8080/sse'),\n * },\n * stockPrice: {\n * command: 'npx',\n * args: ['tsx', 'stock-price.ts'],\n * env: { API_KEY: 'your-api-key' },\n * },\n * },\n * timeout: 30000,\n * });\n *\n * const agent = new Agent({\n * name: 'Multi-tool Agent',\n * instructions: 'You have access to multiple tools.',\n * model: 'openai/gpt-4o',\n * tools: await mcp.getTools(),\n * });\n * ```\n */\nexport class MCPClient extends MastraBase {\n private serverConfigs: Record<string, MastraMCPServerDefinition> = {};\n private id: string;\n private defaultTimeout: number;\n private mcpClientsById = new Map<string, InternalMastraMCPClient>();\n private disconnectPromise: Promise<void> | null = null;\n\n /**\n * Creates a new MCPClient instance for managing MCP server connections.\n *\n * The client automatically manages connection lifecycle and prevents memory leaks by\n * caching instances with identical configurations.\n *\n * @param args - Configuration options\n * @param args.id - Optional unique identifier to allow multiple instances with same config\n * @param args.servers - Map of server names to server configurations\n * @param args.timeout - Optional global timeout in milliseconds (default: 60000)\n *\n * @throws {Error} If multiple instances with identical config are created without an ID\n *\n * @example\n * ```typescript\n * const mcp = new MCPClient({\n * servers: {\n * weatherServer: {\n * url: new URL('http://localhost:8080/sse'),\n * requestInit: {\n * headers: { Authorization: 'Bearer token' }\n * }\n * }\n * },\n * timeout: 30000\n * });\n * ```\n */\n constructor(args: MCPClientOptions) {\n super({ name: 'MCPClient' });\n this.defaultTimeout = args.timeout ?? DEFAULT_REQUEST_TIMEOUT_MSEC;\n this.serverConfigs = args.servers;\n this.id = args.id ?? this.makeId();\n\n if (args.id) {\n this.id = args.id;\n const cached = mcpClientInstances.get(this.id);\n\n if (cached && !equal(cached.serverConfigs, args.servers)) {\n const existingInstance = mcpClientInstances.get(this.id);\n if (existingInstance) {\n void existingInstance.disconnect();\n mcpClientInstances.delete(this.id);\n }\n }\n } else {\n this.id = this.makeId();\n }\n\n // to prevent memory leaks return the same MCP server instance when configured the same way multiple times\n const existingInstance = mcpClientInstances.get(this.id);\n if (existingInstance) {\n if (!args.id) {\n throw new Error(`MCPClient was initialized multiple times with the same configuration options.\n\nThis error is intended to prevent memory leaks.\n\nTo fix this you have three different options:\n1. If you need multiple MCPClient class instances with identical server configurations, set an id when configuring: new MCPClient({ id: \"my-unique-id\" })\n2. Call \"await client.disconnect()\" after you're done using the client and before you recreate another instance with the same options. If the identical MCPClient instance is already closed at the time of re-creating it, you will not see this error.\n3. If you only need one instance of MCPClient in your app, refactor your code so it's only created one time (ex. move it out of a loop into a higher scope code block)\n`);\n }\n return existingInstance;\n }\n\n mcpClientInstances.set(this.id, this);\n this.addToInstanceCache();\n return this;\n }\n /**\n * Provides access to elicitation-related operations for interactive user input collection.\n *\n * Elicitation allows MCP servers to request structured information from users during tool execution.\n *\n * @example\n * ```typescript\n * // Set up handler for elicitation requests from a server\n * await mcp.elicitation.onRequest('serverName', async (request) => {\n * console.log(`Server requests: ${request.message}`);\n * console.log('Schema:', request.requestedSchema);\n *\n * // Collect user input and return response\n * return {\n * action: 'accept',\n * content: { name: 'John Doe', email: 'john@example.com' }\n * };\n * });\n * ```\n */\n public get elicitation() {\n this.addToInstanceCache();\n return {\n /**\n * Sets up a handler function for elicitation requests from a specific server.\n *\n * The handler receives requests for user input and must return a response with\n * action ('accept', 'decline', or 'cancel') and optional content.\n *\n * @param serverName - Name of the server to handle elicitation requests for\n * @param handler - Function to handle elicitation requests\n * @throws {MastraError} If setting up the handler fails\n *\n * @example\n * ```typescript\n * await mcp.elicitation.onRequest('weatherServer', async (request) => {\n * // Prompt user for input\n * const userInput = await promptUser(request.requestedSchema);\n * return { action: 'accept', content: userInput };\n * });\n * ```\n */\n onRequest: async (serverName: string, handler: (request: ElicitRequest['params']) => Promise<ElicitResult>) => {\n try {\n const internalClient = await this.getConnectedClientForServer(serverName);\n return internalClient.elicitation.onRequest(handler);\n } catch (err) {\n throw new MastraError(\n {\n id: 'MCP_CLIENT_ON_REQUEST_ELICITATION_FAILED',\n domain: ErrorDomain.MCP,\n category: ErrorCategory.THIRD_PARTY,\n details: {\n serverName,\n },\n },\n err,\n );\n }\n },\n };\n }\n\n /**\n * Provides access to resource-related operations across all configured servers.\n *\n * Resources represent data exposed by MCP servers (files, database records, API responses, etc.).\n *\n * @example\n * ```typescript\n * // List all resources from all servers\n * const allResources = await mcp.resources.list();\n * Object.entries(allResources).forEach(([serverName, resources]) => {\n * console.log(`${serverName}: ${resources.length} resources`);\n * });\n *\n * // Read a specific resource\n * const content = await mcp.resources.read('weatherServer', 'file://data.json');\n *\n * // Subscribe to resource updates\n * await mcp.resources.subscribe('weatherServer', 'file://data.json');\n * await mcp.resources.onUpdated('weatherServer', async (params) => {\n * console.log(`Resource updated: ${params.uri}`);\n * });\n * ```\n */\n public get resources() {\n this.addToInstanceCache();\n return {\n /**\n * Lists all available resources from all configured servers.\n *\n * Returns a map of server names to their resource arrays. Errors for individual\n * servers are logged but don't throw - failed servers return empty arrays.\n *\n * @returns Promise resolving to object mapping server names to resource arrays\n *\n * @example\n * ```typescript\n * const resources = await mcp.resources.list();\n * console.log(resources.weatherServer); // Array of resources\n * ```\n */\n list: async (): Promise<Record<string, Resource[]>> => {\n const allResources: Record<string, Resource[]> = {};\n for (const serverName of Object.keys(this.serverConfigs)) {\n try {\n const internalClient = await this.getConnectedClientForServer(serverName);\n allResources[serverName] = await internalClient.resources.list();\n } catch (error) {\n const mastraError = new MastraError(\n {\n id: 'MCP_CLIENT_LIST_RESOURCES_FAILED',\n domain: ErrorDomain.MCP,\n category: ErrorCategory.THIRD_PARTY,\n details: {\n serverName,\n },\n },\n error,\n );\n this.logger.trackException(mastraError);\n this.logger.error('Failed to list resources from server:', { error: mastraError.toString() });\n }\n }\n return allResources;\n },\n /**\n * Lists all available resource templates from all configured servers.\n *\n * Resource templates are URI templates (RFC 6570) describing dynamic resources.\n * Errors for individual servers are logged but don't throw.\n *\n * @returns Promise resolving to object mapping server names to template arrays\n *\n * @example\n * ```typescript\n * const templates = await mcp.resources.templates();\n * console.log(templates.weatherServer); // Array of resource templates\n * ```\n */\n templates: async (): Promise<Record<string, ResourceTemplate[]>> => {\n const allTemplates: Record<string, ResourceTemplate[]> = {};\n for (const serverName of Object.keys(this.serverConfigs)) {\n try {\n const internalClient = await this.getConnectedClientForServer(serverName);\n allTemplates[serverName] = await internalClient.resources.templates();\n } catch (error) {\n const mastraError = new MastraError(\n {\n id: 'MCP_CLIENT_LIST_RESOURCE_TEMPLATES_FAILED',\n domain: ErrorDomain.MCP,\n category: ErrorCategory.THIRD_PARTY,\n details: {\n serverName,\n },\n },\n error,\n );\n this.logger.trackException(mastraError);\n this.logger.error('Failed to list resource templates from server:', { error: mastraError.toString() });\n }\n }\n return allTemplates;\n },\n /**\n * Reads the content of a specific resource from a server.\n *\n * @param serverName - Name of the server to read from\n * @param uri - URI of the resource to read\n * @returns Promise resolving to the resource content\n * @throws {MastraError} If reading the resource fails\n *\n * @example\n * ```typescript\n * const content = await mcp.resources.read('weatherServer', 'file://config.json');\n * console.log(content.contents[0].text);\n * ```\n */\n read: async (serverName: string, uri: string) => {\n try {\n const internalClient = await this.getConnectedClientForServer(serverName);\n return internalClient.resources.read(uri);\n } catch (error) {\n throw new MastraError(\n {\n id: 'MCP_CLIENT_READ_RESOURCE_FAILED',\n domain: ErrorDomain.MCP,\n category: ErrorCategory.THIRD_PARTY,\n details: {\n serverName,\n uri,\n },\n },\n error,\n );\n }\n },\n /**\n * Subscribes to updates for a specific resource on a server.\n *\n * @param serverName - Name of the server\n * @param uri - URI of the resource to subscribe to\n * @returns Promise resolving when subscription is established\n * @throws {MastraError} If subscription fails\n *\n * @example\n * ```typescript\n * await mcp.resources.subscribe('weatherServer', 'file://config.json');\n * ```\n */\n subscribe: async (serverName: string, uri: string) => {\n try {\n const internalClient = await this.getConnectedClientForServer(serverName);\n return internalClient.resources.subscribe(uri);\n } catch (error) {\n throw new MastraError(\n {\n id: 'MCP_CLIENT_SUBSCRIBE_RESOURCE_FAILED',\n domain: ErrorDomain.MCP,\n category: ErrorCategory.THIRD_PARTY,\n details: {\n serverName,\n uri,\n },\n },\n error,\n );\n }\n },\n /**\n * Unsubscribes from updates for a specific resource on a server.\n *\n * @param serverName - Name of the server\n * @param uri - URI of the resource to unsubscribe from\n * @returns Promise resolving when unsubscription is complete\n * @throws {MastraError} If unsubscription fails\n *\n * @example\n * ```typescript\n * await mcp.resources.unsubscribe('weatherServer', 'file://config.json');\n * ```\n */\n unsubscribe: async (serverName: string, uri: string) => {\n try {\n const internalClient = await this.getConnectedClientForServer(serverName);\n return internalClient.resources.unsubscribe(uri);\n } catch (err) {\n throw new MastraError(\n {\n id: 'MCP_CLIENT_UNSUBSCRIBE_RESOURCE_FAILED',\n domain: ErrorDomain.MCP,\n category: ErrorCategory.THIRD_PARTY,\n details: {\n serverName,\n uri,\n },\n },\n err,\n );\n }\n },\n /**\n * Sets a notification handler for when subscribed resources are updated on a server.\n *\n * @param serverName - Name of the server to monitor\n * @param handler - Callback function receiving the updated resource URI\n * @returns Promise resolving when handler is registered\n * @throws {MastraError} If setting up the handler fails\n *\n * @example\n * ```typescript\n * await mcp.resources.onUpdated('weatherServer', async (params) => {\n * console.log(`Resource updated: ${params.uri}`);\n * const content = await mcp.resources.read('weatherServer', params.uri);\n * });\n * ```\n */\n onUpdated: async (serverName: string, handler: (params: { uri: string }) => void) => {\n try {\n const internalClient = await this.getConnectedClientForServer(serverName);\n return internalClient.resources.onUpdated(handler);\n } catch (err) {\n throw new MastraError(\n {\n id: 'MCP_CLIENT_ON_UPDATED_RESOURCE_FAILED',\n domain: ErrorDomain.MCP,\n category: ErrorCategory.THIRD_PARTY,\n details: {\n serverName,\n },\n },\n err,\n );\n }\n },\n /**\n * Sets a notification handler for when the resource list changes on a server.\n *\n * @param serverName - Name of the server to monitor\n * @param handler - Callback function invoked when resources are added/removed\n * @returns Promise resolving when handler is registered\n * @throws {MastraError} If setting up the handler fails\n *\n * @example\n * ```typescript\n * await mcp.resources.onListChanged('weatherServer', async () => {\n * console.log('Resource list changed, re-fetching...');\n * const resources = await mcp.resources.list();\n * });\n * ```\n */\n onListChanged: async (serverName: string, handler: () => void) => {\n try {\n const internalClient = await this.getConnectedClientForServer(serverName);\n return internalClient.resources.onListChanged(handler);\n } catch (err) {\n throw new MastraError(\n {\n id: 'MCP_CLIENT_ON_LIST_CHANGED_RESOURCE_FAILED',\n domain: ErrorDomain.MCP,\n category: ErrorCategory.THIRD_PARTY,\n details: {\n serverName,\n },\n },\n err,\n );\n }\n },\n };\n }\n\n /**\n * Provides access to prompt-related operations across all configured servers.\n *\n * Prompts are reusable message templates exposed by MCP servers that can be parameterized\n * and used for AI interactions.\n *\n * @example\n * ```typescript\n * // List all prompts from all servers\n * const allPrompts = await mcp.prompts.list();\n * Object.entries(allPrompts).forEach(([serverName, prompts]) => {\n * console.log(`${serverName}: ${prompts.map(p => p.name).join(', ')}`);\n * });\n *\n * // Get a specific prompt with arguments\n * const prompt = await mcp.prompts.get({\n * serverName: 'weatherServer',\n * name: 'forecast-template',\n * args: { city: 'London', days: 7 }\n * });\n * ```\n */\n public get prompts() {\n this.addToInstanceCache();\n return {\n /**\n * Lists all available prompts from all configured servers.\n *\n * Returns a map of server names to their prompt arrays. Errors for individual\n * servers are logged but don't throw - failed servers return empty arrays.\n *\n * @returns Promise resolving to object mapping server names to prompt arrays\n *\n * @example\n * ```typescript\n * const prompts = await mcp.prompts.list();\n * console.log(prompts.weatherServer); // Array of prompts\n * ```\n */\n list: async (): Promise<Record<string, Prompt[]>> => {\n const allPrompts: Record<string, Prompt[]> = {};\n for (const serverName of Object.keys(this.serverConfigs)) {\n try {\n const internalClient = await this.getConnectedClientForServer(serverName);\n allPrompts[serverName] = await internalClient.prompts.list();\n } catch (error) {\n const mastraError = new MastraError(\n {\n id: 'MCP_CLIENT_LIST_PROMPTS_FAILED',\n domain: ErrorDomain.MCP,\n category: ErrorCategory.THIRD_PARTY,\n details: {\n serverName,\n },\n },\n error,\n );\n this.logger.trackException(mastraError);\n this.logger.error('Failed to list prompts from server:', { error: mastraError.toString() });\n }\n }\n return allPrompts;\n },\n /**\n * Retrieves a specific prompt with its messages from a server.\n *\n * @param params - Parameters for the prompt request\n * @param params.serverName - Name of the server to retrieve from\n * @param params.name - Name of the prompt to retrieve\n * @param params.args - Optional arguments to populate the prompt template\n * @param params.version - Optional specific version of the prompt\n * @returns Promise resolving to the prompt result with messages\n * @throws {MastraError} If fetching the prompt fails\n *\n * @example\n * ```typescript\n * const prompt = await mcp.prompts.get({\n * serverName: 'weatherServer',\n * name: 'forecast',\n * args: { city: 'London' },\n * version: '1.0'\n * });\n * console.log(prompt.messages);\n * ```\n */\n get: async ({\n serverName,\n name,\n args,\n version,\n }: {\n serverName: string;\n name: string;\n args?: Record<string, any>;\n version?: string;\n }) => {\n try {\n const internalClient = await this.getConnectedClientForServer(serverName);\n return internalClient.prompts.get({ name, args, version });\n } catch (error) {\n throw new MastraError(\n {\n id: 'MCP_CLIENT_GET_PROMPT_FAILED',\n domain: ErrorDomain.MCP,\n category: ErrorCategory.THIRD_PARTY,\n details: {\n serverName,\n name,\n },\n },\n error,\n );\n }\n },\n /**\n * Sets a notification handler for when the prompt list changes on a server.\n *\n * @param serverName - Name of the server to monitor\n * @param handler - Callback function invoked when prompts are added/removed/modified\n * @returns Promise resolving when handler is registered\n * @throws {MastraError} If setting up the handler fails\n *\n * @example\n * ```typescript\n * await mcp.prompts.onListChanged('weatherServer', async () => {\n * console.log('Prompt list changed, re-fetching...');\n * const prompts = await mcp.prompts.list();\n * });\n * ```\n */\n onListChanged: async (serverName: string, handler: () => void) => {\n try {\n const internalClient = await this.getConnectedClientForServer(serverName);\n return internalClient.prompts.onListChanged(handler);\n } catch (error) {\n throw new MastraError(\n {\n id: 'MCP_CLIENT_ON_LIST_CHANGED_PROMPT_FAILED',\n domain: ErrorDomain.MCP,\n category: ErrorCategory.THIRD_PARTY,\n details: {\n serverName,\n },\n },\n error,\n );\n }\n },\n };\n }\n\n private addToInstanceCache() {\n if (!mcpClientInstances.has(this.id)) {\n mcpClientInstances.set(this.id, this);\n }\n }\n\n private makeId() {\n const text = JSON.stringify(this.serverConfigs).normalize('NFKC');\n const idNamespace = uuidv5(`MCPClient`, uuidv5.DNS);\n\n return uuidv5(text, idNamespace);\n }\n\n /**\n * Disconnects from all MCP servers and cleans up resources.\n *\n * This method gracefully closes all server connections and clears internal caches.\n * Safe to call multiple times - subsequent calls will wait for the first disconnect to complete.\n *\n * @example\n * ```typescript\n * // Cleanup on application shutdown\n * process.on('SIGTERM', async () => {\n * await mcp.disconnect();\n * process.exit(0);\n * });\n * ```\n */\n public async disconnect() {\n // Helps to prevent race condition\n // If there is already a disconnect ongoing, return the existing promise.\n if (this.disconnectPromise) {\n return this.disconnectPromise;\n }\n\n this.disconnectPromise = (async () => {\n try {\n mcpClientInstances.delete(this.id);\n\n // Disconnect all clients in the cache\n await Promise.all(Array.from(this.mcpClientsById.values()).map(client => client.disconnect()));\n this.mcpClientsById.clear();\n } finally {\n this.disconnectPromise = null;\n }\n })();\n\n return this.disconnectPromise;\n }\n\n /**\n * Retrieves all tools from all configured servers with namespaced names.\n *\n * Tool names are namespaced as `serverName_toolName` to prevent conflicts between servers.\n * This method is intended to be passed directly to an Agent definition.\n *\n * @returns Object mapping namespaced tool names to tool implementations\n * @throws {MastraError} If retrieving tools fails\n *\n * @example\n * ```typescript\n * const agent = new Agent({\n * name: 'Multi-tool Agent',\n * instructions: 'You have access to weather and stock tools.',\n * model: 'openai/gpt-4',\n * tools: await mcp.getTools(), // weather_getWeather, stockPrice_getPrice\n * });\n * ```\n */\n public async getTools() {\n this.addToInstanceCache();\n const connectedTools: Record<string, any> = {}; // <- any because we don't have proper tool schemas\n\n try {\n await this.eachClientTools(async ({ serverName, tools }) => {\n for (const [toolName, toolConfig] of Object.entries(tools)) {\n connectedTools[`${serverName}_${toolName}`] = toolConfig; // namespace tool to prevent tool name conflicts between servers\n }\n });\n } catch (error) {\n throw new MastraError(\n {\n id: 'MCP_CLIENT_GET_TOOLS_FAILED',\n domain: ErrorDomain.MCP,\n category: ErrorCategory.THIRD_PARTY,\n },\n error,\n );\n }\n\n return connectedTools;\n }\n\n /**\n * Returns toolsets organized by server name for dynamic tool injection.\n *\n * Unlike getTools(), this returns tools grouped by server without namespacing.\n * This is intended to be passed dynamically to the generate() or stream() method.\n *\n * @returns Object mapping server names to their tool collections\n * @throws {MastraError} If retrieving toolsets fails\n *\n * @example\n * ```typescript\n * const agent = new Agent({\n * name: 'Dynamic Agent',\n * instructions: 'You can use tools dynamically.',\n * model: 'openai/gpt-4',\n * });\n *\n * const response = await agent.stream(prompt, {\n * toolsets: await mcp.getToolsets(), // { weather: {...}, stockPrice: {...} }\n * });\n * ```\n */\n public async getToolsets() {\n this.addToInstanceCache();\n const connectedToolsets: Record<string, Record<string, any>> = {}; // <- any because we don't have proper tool schemas\n\n try {\n await this.eachClientTools(async ({ serverName, tools }) => {\n if (tools) {\n connectedToolsets[serverName] = tools;\n }\n });\n } catch (error) {\n throw new MastraError(\n {\n id: 'MCP_CLIENT_GET_TOOLSETS_FAILED',\n domain: ErrorDomain.MCP,\n category: ErrorCategory.THIRD_PARTY,\n },\n error,\n );\n }\n\n return connectedToolsets;\n }\n\n /**\n * @deprecated all resource actions have been moved to the this.resources object. Use this.resources.list() instead.\n */\n public async getResources() {\n return this.resources.list();\n }\n\n /**\n * Gets current session IDs for all connected MCP clients using Streamable HTTP transport.\n *\n * Returns an object mapping server names to their session IDs. Only includes servers\n * that are currently connected via Streamable HTTP transport.\n *\n * @returns Object mapping server names to session IDs\n *\n * @example\n * ```typescript\n * const sessions = mcp.sessionIds;\n * console.log(sessions);\n * // { weatherServer: 'abc-123', stockServer: 'def-456' }\n * ```\n */\n get sessionIds(): Record<string, string> {\n const sessionIds: Record<string, string> = {};\n for (const [serverName, client] of this.mcpClientsById.entries()) {\n if (client.sessionId) {\n sessionIds[serverName] = client.sessionId;\n }\n }\n return sessionIds;\n }\n\n private async getConnectedClient(name: string, config: MastraMCPServerDefinition): Promise<InternalMastraMCPClient> {\n if (this.disconnectPromise) {\n await this.disconnectPromise;\n }\n\n const exists = this.mcpClientsById.has(name);\n const existingClient = this.mcpClientsById.get(name);\n\n this.logger.debug(`getConnectedClient ${name} exists: ${exists}`);\n\n if (exists) {\n // This is just to satisfy Typescript since technically you could have this.mcpClientsById.set('someKey', undefined);\n // Should never reach this point basically we always create a new MastraMCPClient instance when we add to the Map.\n if (!existingClient) {\n throw new Error(`Client ${name} exists but is undefined`);\n }\n await existingClient.connect();\n return existingClient;\n }\n\n this.logger.debug(`Connecting to ${name} MCP server`);\n\n // Create client with server configuration including log handler\n const mcpClient = new InternalMastraMCPClient({\n name,\n server: config,\n timeout: config.timeout ?? this.defaultTimeout,\n });\n\n mcpClient.__setLogger(this.logger);\n\n this.mcpClientsById.set(name, mcpClient);\n\n try {\n await mcpClient.connect();\n } catch (e) {\n const mastraError = new MastraError(\n {\n id: 'MCP_CLIENT_CONNECT_FAILED',\n domain: ErrorDomain.MCP,\n category: ErrorCategory.THIRD_PARTY,\n text: `Failed to connect to MCP server ${name}: ${e instanceof Error ? e.stack || e.message : String(e)}`,\n details: {\n name,\n },\n },\n e,\n );\n this.logger.trackException(mastraError);\n this.logger.error('MCPClient errored connecting to MCP server:', { error: mastraError.toString() });\n this.mcpClientsById.delete(name);\n throw mastraError;\n }\n this.logger.debug(`Connected to ${name} MCP server`);\n return mcpClient;\n }\n\n private async getConnectedClientForServer(serverName: string): Promise<InternalMastraMCPClient> {\n const serverConfig = this.serverConfigs[serverName];\n if (!serverConfig) {\n throw new Error(`Server configuration not found for name: ${serverName}`);\n }\n return this.getConnectedClient(serverName, serverConfig);\n }\n\n private async eachClientTools(\n cb: (args: {\n serverName: string;\n tools: Record<string, any>; // <- any because we don't have proper tool schemas\n client: InstanceType<typeof InternalMastraMCPClient>;\n }) => Promise<void>,\n ) {\n await Promise.all(\n Object.entries(this.serverConfigs).map(async ([serverName, serverConfig]) => {\n const client = await this.getConnectedClient(serverName, serverConfig);\n const tools = await client.tools();\n await cb({ serverName, tools, client });\n }),\n );\n }\n}\n\n/**\n * @deprecated MCPConfigurationOptions is deprecated and will be removed in a future release. Use {@link MCPClientOptions} instead.\n *\n * This interface has been renamed to MCPClientOptions. The API is identical.\n */\nexport interface MCPConfigurationOptions {\n /** @deprecated Use MCPClientOptions.id instead */\n id?: string;\n /** @deprecated Use MCPClientOptions.servers instead */\n servers: Record<string, MastraMCPServerDefinition>;\n /** @deprecated Use MCPClientOptions.timeout instead */\n timeout?: number;\n}\n\n/**\n * @deprecated MCPConfiguration is deprecated and will be removed in a future release. Use {@link MCPClient} instead.\n *\n * This class has been renamed to MCPClient. The API is identical but the class name changed\n * for clarity and consistency.\n *\n * @example\n * ```typescript\n * // Old way (deprecated)\n * const config = new MCPConfiguration({\n * servers: { myServer: { command: 'npx', args: ['tsx', 'server.ts'] } }\n * });\n *\n * // New way (recommended)\n * const client = new MCPClient({\n * servers: { myServer: { command: 'npx', args: ['tsx', 'server.ts'] } }\n * });\n * ```\n */\nexport class MCPConfiguration extends MCPClient {\n /**\n * @deprecated Use MCPClient constructor instead\n */\n constructor(args: MCPClientOptions) {\n super(args);\n throw new MastraError(\n {\n id: 'MCP_CLIENT_CONFIGURATION_DEPRECATED',\n domain: ErrorDomain.MCP,\n category: ErrorCategory.USER,\n text: '[DEPRECATION] MCPConfiguration has been renamed to MCPClient and MCPConfiguration is deprecated. The API is identical but the MCPConfiguration export will be removed in the future. Update your imports now to prevent future errors.',\n },\n );\n }\n}","// src/utils/stream.ts\nvar StreamingApi = class {\n writer;\n encoder;\n writable;\n abortSubscribers = [];\n responseReadable;\n aborted = false;\n closed = false;\n constructor(writable, _readable) {\n this.writable = writable;\n this.writer = writable.getWriter();\n this.encoder = new TextEncoder();\n const reader = _readable.getReader();\n this.abortSubscribers.push(async () => {\n await reader.cancel();\n });\n this.responseReadable = new ReadableStream({\n async pull(controller) {\n const { done, value } = await reader.read();\n done ? controller.close() : controller.enqueue(value);\n },\n cancel: () => {\n this.abort();\n }\n });\n }\n async write(input) {\n try {\n if (typeof input === \"string\") {\n input = this.encoder.encode(input);\n }\n await this.writer.write(input);\n } catch {\n }\n return this;\n }\n async writeln(input) {\n await this.write(input + \"\\n\");\n return this;\n }\n sleep(ms) {\n return new Promise((res) => setTimeout(res, ms));\n }\n async close() {\n try {\n await this.writer.close();\n } catch {\n }\n this.closed = true;\n }\n async pipe(body) {\n this.writer.releaseLock();\n await body.pipeTo(this.writable, { preventClose: true });\n this.writer = this.writable.getWriter();\n }\n onAbort(listener) {\n this.abortSubscribers.push(listener);\n }\n abort() {\n if (!this.aborted) {\n this.aborted = true;\n this.abortSubscribers.forEach((subscriber) => subscriber());\n }\n }\n};\nexport {\n StreamingApi\n};\n","// src/helper/streaming/utils.ts\nvar isOldBunVersion = () => {\n const version = typeof Bun !== \"undefined\" ? Bun.version : void 0;\n if (version === void 0) {\n return false;\n }\n const result = version.startsWith(\"1.1\") || version.startsWith(\"1.0\") || version.startsWith(\"0.\");\n isOldBunVersion = () => result;\n return result;\n};\nexport {\n isOldBunVersion\n};\n","// src/utils/html.ts\nvar HtmlEscapedCallbackPhase = {\n Stringify: 1,\n BeforeStream: 2,\n Stream: 3\n};\nvar raw = (value, callbacks) => {\n const escapedString = new String(value);\n escapedString.isEscaped = true;\n escapedString.callbacks = callbacks;\n return escapedString;\n};\nvar escapeRe = /[&<>'\"]/;\nvar stringBufferToString = async (buffer, callbacks) => {\n let str = \"\";\n callbacks ||= [];\n const resolvedBuffer = await Promise.all(buffer);\n for (let i = resolvedBuffer.length - 1; ; i--) {\n str += resolvedBuffer[i];\n i--;\n if (i < 0) {\n break;\n }\n let r = resolvedBuffer[i];\n if (typeof r === \"object\") {\n callbacks.push(...r.callbacks || []);\n }\n const isEscaped = r.isEscaped;\n r = await (typeof r === \"object\" ? r.toString() : r);\n if (typeof r === \"object\") {\n callbacks.push(...r.callbacks || []);\n }\n if (r.isEscaped ?? isEscaped) {\n str += r;\n } else {\n const buf = [str];\n escapeToBuffer(r, buf);\n str = buf[0];\n }\n }\n return raw(str, callbacks);\n};\nvar escapeToBuffer = (str, buffer) => {\n const match = str.search(escapeRe);\n if (match === -1) {\n buffer[0] += str;\n return;\n }\n let escape;\n let index;\n let lastIndex = 0;\n for (index = match; index < str.length; index++) {\n switch (str.charCodeAt(index)) {\n case 34:\n escape = \""\";\n break;\n case 39:\n escape = \"'\";\n break;\n case 38:\n escape = \"&\";\n break;\n case 60:\n escape = \"<\";\n break;\n case 62:\n escape = \">\";\n break;\n default:\n continue;\n }\n buffer[0] += str.substring(lastIndex, index) + escape;\n lastIndex = index + 1;\n }\n buffer[0] += str.substring(lastIndex, index);\n};\nvar resolveCallbackSync = (str) => {\n const callbacks = str.callbacks;\n if (!callbacks?.length) {\n return str;\n }\n const buffer = [str];\n const context = {};\n callbacks.forEach((c) => c({ phase: HtmlEscapedCallbackPhase.Stringify, buffer, context }));\n return buffer[0];\n};\nvar resolveCallback = async (str, phase, preserveCallbacks, context, buffer) => {\n if (typeof str === \"object\" && !(str instanceof String)) {\n if (!(str instanceof Promise)) {\n str = str.toString();\n }\n if (str instanceof Promise) {\n str = await str;\n }\n }\n const callbacks = str.callbacks;\n if (!callbacks?.length) {\n return Promise.resolve(str);\n }\n if (buffer) {\n buffer[0] += str;\n } else {\n buffer = [str];\n }\n const resStr = Promise.all(callbacks.map((c) => c({ phase, buffer, context }))).then(\n (res) => Promise.all(\n res.filter(Boolean).map((str2) => resolveCallback(str2, phase, false, context, buffer))\n ).then(() => buffer[0])\n );\n if (preserveCallbacks) {\n return raw(await resStr, callbacks);\n } else {\n return resStr;\n }\n};\nexport {\n HtmlEscapedCallbackPhase,\n escapeToBuffer,\n raw,\n resolveCallback,\n resolveCallbackSync,\n stringBufferToString\n};\n","// src/helper/streaming/sse.ts\nimport { HtmlEscapedCallbackPhase, resolveCallback } from \"../../utils/html.js\";\nimport { StreamingApi } from \"../../utils/stream.js\";\nimport { isOldBunVersion } from \"./utils.js\";\nvar SSEStreamingApi = class extends StreamingApi {\n constructor(writable, readable) {\n super(writable, readable);\n }\n async writeSSE(message) {\n const data = await resolveCallback(message.data, HtmlEscapedCallbackPhase.Stringify, false, {});\n const dataLines = data.split(\"\\n\").map((line) => {\n return `data: ${line}`;\n }).join(\"\\n\");\n const sseData = [\n message.event && `event: ${message.event}`,\n dataLines,\n message.id && `id: ${message.id}`,\n message.retry && `retry: ${message.retry}`\n ].filter(Boolean).join(\"\\n\") + \"\\n\\n\";\n await this.write(sseData);\n }\n};\nvar run = async (stream, cb, onError) => {\n try {\n await cb(stream);\n } catch (e) {\n if (e instanceof Error && onError) {\n await onError(e, stream);\n await stream.writeSSE({\n event: \"error\",\n data: e.message\n });\n } else {\n console.error(e);\n }\n } finally {\n stream.close();\n }\n};\nvar contextStash = /* @__PURE__ */ new WeakMap();\nvar streamSSE = (c, cb, onError) => {\n const { readable, writable } = new TransformStream();\n const stream = new SSEStreamingApi(writable, readable);\n if (isOldBunVersion()) {\n c.req.raw.signal.addEventListener(\"abort\", () => {\n if (!stream.closed) {\n stream.abort();\n }\n });\n }\n contextStash.set(stream.responseReadable, c);\n c.header(\"Transfer-Encoding\", \"chunked\");\n c.header(\"Content-Type\", \"text/event-stream\");\n c.header(\"Cache-Control\", \"no-cache\");\n c.header(\"Connection\", \"keep-alive\");\n run(stream, cb, onError);\n return c.newResponse(stream.responseReadable);\n};\nexport {\n SSEStreamingApi,\n streamSSE\n};\n","import { JSONRPCMessageSchema, } from '@modelcontextprotocol/sdk/types.js';\nconst MAXIMUM_MESSAGE_SIZE = 4 * 1024 * 1024; // 4MB\nexport class SSETransport {\n messageUrl;\n stream;\n _sessionId;\n onclose;\n onerror;\n onmessage;\n /**\n * Creates a new SSETransport, which will direct the MPC client to POST messages to messageUrl\n */\n constructor(messageUrl, stream) {\n this.messageUrl = messageUrl;\n this.stream = stream;\n this._sessionId = crypto.randomUUID();\n this.stream.onAbort(() => {\n void this.close();\n });\n }\n get sessionId() {\n return this._sessionId;\n }\n // start() is automatically called after MCP Server connects to the transport\n async start() {\n if (this.stream == null) {\n throw new Error('Stream not initialized');\n }\n if (this.stream.closed) {\n throw new Error('SSE transport already closed!');\n }\n await this.stream.writeSSE({\n event: 'ping',\n data: '',\n });\n await this.stream.writeSSE({\n event: 'endpoint',\n data: `${this.messageUrl}?sessionId=${this.sessionId}`,\n });\n }\n async handlePostMessage(context) {\n if (this.stream?.closed == null) {\n return context.text('SSE connection not established', 500);\n }\n try {\n const contentType = context.req.header('content-type') || '';\n if (!contentType.includes('application/json')) {\n throw new Error(`Unsupported content-type: ${contentType}`);\n }\n // Check if the request body is too large\n const contentLength = Number.parseInt(context.req.header('content-length') || '0', 10);\n if (contentLength > MAXIMUM_MESSAGE_SIZE) {\n throw new Error(`Request body too large: ${contentLength} bytes`);\n }\n // Clone the request before reading the body to avoid stream issues\n const body = (await context.req.json());\n await this.handleMessage(body);\n return context.text('Accepted', 202);\n }\n catch (error) {\n this.onerror?.(error);\n return context.text('Error', 400);\n }\n }\n /**\n * Handle a client message, regardless of how it arrived. This can be used to inform the server of messages that arrive via a means different than HTTP POST.\n */\n async handleMessage(message) {\n let parsedMessage;\n try {\n parsedMessage = JSONRPCMessageSchema.parse(message);\n }\n catch (error) {\n this.onerror?.(error);\n throw error;\n }\n this.onmessage?.(parsedMessage);\n }\n async close() {\n if (this.stream?.closed) {\n this.stream.abort();\n }\n }\n async send(message) {\n if (this.stream?.closed) {\n throw new Error('Not connected');\n }\n await this.stream.writeSSE({\n event: 'message',\n data: JSON.stringify(message),\n });\n }\n}\n","import { ErrorCategory, ErrorDomain, MastraError } from '@mastra/core/error';\nimport type { IMastraLogger } from '@mastra/core/logger';\nimport type { Server } from '@modelcontextprotocol/sdk/server/index.js';\n\ninterface ServerPromptActionsDependencies {\n getLogger: () => IMastraLogger;\n getSdkServer: () => Server;\n clearDefinedPrompts: () => void;\n}\n\n/**\n * Server-side prompt actions for notifying clients about prompt changes.\n *\n * This class provides methods for MCP servers to notify connected clients when\n * the list of available prompts changes.\n */\nexport class ServerPromptActions {\n private readonly getLogger: () => IMastraLogger;\n private readonly getSdkServer: () => Server;\n private readonly clearDefinedPrompts: () => void;\n\n /**\n * @internal\n */\n constructor(dependencies: ServerPromptActionsDependencies) {\n this.getLogger = dependencies.getLogger;\n this.getSdkServer = dependencies.getSdkServer;\n this.clearDefinedPrompts = dependencies.clearDefinedPrompts;\n }\n\n /**\n * Notifies clients that the overall list of available prompts has changed.\n *\n * This clears the internal prompt cache and sends a `notifications/prompts/list_changed`\n * message to all clients, prompting them to re-fetch the prompt list.\n *\n * @throws {MastraError} If sending the notification fails\n *\n * @example\n * ```typescript\n * // After adding or modifying prompts\n * await server.prompts.notifyListChanged();\n * ```\n */\n public async notifyListChanged(): Promise<void> {\n this.getLogger().info('Prompt list change externally notified. Clearing definedPrompts and sending notification.');\n this.clearDefinedPrompts();\n try {\n await this.getSdkServer().sendPromptListChanged();\n } catch (error) {\n const mastraError = new MastraError(\n {\n id: 'MCP_SERVER_PROMPT_LIST_CHANGED_NOTIFICATION_FAILED',\n domain: ErrorDomain.MCP,\n category: ErrorCategory.THIRD_PARTY,\n text: 'Failed to send prompt list changed notification',\n },\n error,\n );\n this.getLogger().error('Failed to send prompt list changed notification:', {\n error: mastraError.toString(),\n });\n this.getLogger().trackException(mastraError);\n throw mastraError;\n }\n }\n}\n","import { ErrorCategory, ErrorDomain, MastraError } from '@mastra/core/error';\nimport type { IMastraLogger } from '@mastra/core/logger';\nimport type { Server } from '@modelcontextprotocol/sdk/server/index.js';\n\ninterface ServerResourceActionsDependencies {\n getSubscriptions: () => Set<string>;\n getLogger: () => IMastraLogger;\n getSdkServer: () => Server;\n clearDefinedResources: () => void;\n clearDefinedResourceTemplates: () => void;\n}\n\n/**\n * Server-side resource actions for notifying clients about resource changes.\n *\n * This class provides methods for MCP servers to notify connected clients when\n * resources are updated or when the resource list changes.\n */\nexport class ServerResourceActions {\n private readonly getSubscriptions: () => Set<string>;\n private readonly getLogger: () => IMastraLogger;\n private readonly getSdkServer: () => Server;\n private readonly clearDefinedResources: () => void;\n private readonly clearDefinedResourceTemplates: () => void;\n\n /**\n * @internal\n */\n constructor(dependencies: ServerResourceActionsDependencies) {\n this.getSubscriptions = dependencies.getSubscriptions;\n this.getLogger = dependencies.getLogger;\n this.getSdkServer = dependencies.getSdkServer;\n this.clearDefinedResources = dependencies.clearDefinedResources;\n this.clearDefinedResourceTemplates = dependencies.clearDefinedResourceTemplates;\n }\n\n /**\n * Notifies subscribed clients that a specific resource has been updated.\n *\n * If clients are subscribed to the resource URI, they will receive a\n * `notifications/resources/updated` message to re-fetch the resource content.\n *\n * @param params - Notification parameters\n * @param params.uri - URI of the resource that was updated\n * @throws {MastraError} If sending the notification fails\n *\n * @example\n * ```typescript\n * // After updating a file resource\n * await server.resources.notifyUpdated({ uri: 'file://data.txt' });\n * ```\n */\n public async notifyUpdated({ uri }: { uri: string }): Promise<void> {\n if (this.getSubscriptions().has(uri)) {\n this.getLogger().info(`Sending notifications/resources/updated for externally notified resource: ${uri}`);\n try {\n await this.getSdkServer().sendResourceUpdated({ uri });\n } catch (error) {\n const mastraError = new MastraError(\n {\n id: 'MCP_SERVER_RESOURCE_UPDATED_NOTIFICATION_FAILED',\n domain: ErrorDomain.MCP,\n category: ErrorCategory.THIRD_PARTY,\n text: 'Failed to send resource updated notification',\n details: {\n uri,\n },\n },\n error,\n );\n this.getLogger().trackException(mastraError);\n this.getLogger().error('Failed to send resource updated notification:', {\n error: mastraError.toString(),\n });\n throw mastraError;\n }\n } else {\n this.getLogger().debug(`Resource ${uri} was updated, but no active subscriptions for it.`);\n }\n }\n\n /**\n * Notifies clients that the overall list of available resources has changed.\n *\n * This clears the internal resource cache and sends a `notifications/resources/list_changed`\n * message to all clients, prompting them to re-fetch the resource list.\n *\n * @throws {MastraError} If sending the notification fails\n *\n * @example\n * ```typescript\n * // After adding a new resource to your resource handler\n * await server.resources.notifyListChanged();\n * ```\n */\n public async notifyListChanged(): Promise<void> {\n this.getLogger().info(\n 'Resource list change externally notified. Clearing definedResources and sending notification.',\n );\n this.clearDefinedResources(); // Clear cached resources\n this.clearDefinedResourceTemplates(); // Clear cached resource templates\n try {\n await this.getSdkServer().sendResourceListChanged();\n } catch (error) {\n const mastraError = new MastraError(\n {\n id: 'MCP_SERVER_RESOURCE_LIST_CHANGED_NOTIFICATION_FAILED',\n domain: ErrorDomain.MCP,\n category: ErrorCategory.THIRD_PARTY,\n text: 'Failed to send resource list changed notification',\n },\n error,\n );\n this.getLogger().trackException(mastraError);\n this.getLogger().error('Failed to send resource list changed notification:', {\n error: mastraError.toString(),\n });\n throw mastraError;\n }\n }\n}\n","import { randomUUID } from 'node:crypto';\nimport type * as http from 'node:http';\nimport type { ToolsInput, Agent } from '@mastra/core/agent';\nimport { ErrorCategory, ErrorDomain, MastraError } from '@mastra/core/error';\nimport { MCPServerBase } from '@mastra/core/mcp';\nimport type {\n MCPServerConfig,\n ServerInfo,\n ServerDetailInfo,\n ConvertedTool,\n MCPServerHonoSSEOptions,\n MCPServerSSEOptions,\n MCPToolType,\n} from '@mastra/core/mcp';\nimport { RuntimeContext } from '@mastra/core/runtime-context';\nimport { createTool } from '@mastra/core/tools';\nimport type { InternalCoreTool } from '@mastra/core/tools';\nimport { makeCoreTool } from '@mastra/core/utils';\nimport type { Workflow } from '@mastra/core/workflows';\nimport { Server } from '@modelcontextprotocol/sdk/server/index.js';\nimport { SSEServerTransport } from '@modelcontextprotocol/sdk/server/sse.js';\nimport { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';\nimport { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js';\nimport type { StreamableHTTPServerTransportOptions } from '@modelcontextprotocol/sdk/server/streamableHttp.js';\nimport {\n CallToolRequestSchema,\n ListToolsRequestSchema,\n ListResourcesRequestSchema,\n ReadResourceRequestSchema,\n ListResourceTemplatesRequestSchema,\n SubscribeRequestSchema,\n UnsubscribeRequestSchema,\n ListPromptsRequestSchema,\n GetPromptRequestSchema,\n SetLevelRequestSchema,\n PromptSchema,\n} from '@modelcontextprotocol/sdk/types.js';\nimport type {\n ResourceContents,\n Resource,\n ResourceTemplate,\n ServerCapabilities,\n Prompt,\n CallToolResult,\n ElicitResult,\n ElicitRequest,\n LoggingLevel,\n} from '@modelcontextprotocol/sdk/types.js';\nimport type { SSEStreamingApi } from 'hono/streaming';\nimport { streamSSE } from 'hono/streaming';\nimport { SSETransport } from 'hono-mcp-server-sse-transport';\nimport { z } from 'zod';\nimport { ServerPromptActions } from './promptActions';\nimport { ServerResourceActions } from './resourceActions';\nimport type { MCPServerPrompts, MCPServerResources, ElicitationActions, MCPTool } from './types';\n/**\n * MCPServer exposes Mastra tools, agents, and workflows as a Model Context Protocol (MCP) server.\n *\n * This class allows any MCP client (like Cursor, Windsurf, or Claude Desktop) to connect and use your\n * Mastra capabilities. It supports both stdio (subprocess) and SSE (HTTP) MCP transports.\n *\n * @example\n * ```typescript\n * import { MCPServer } from '@mastra/mcp';\n * import { createTool } from '@mastra/core/tools';\n * import { z } from 'zod';\n *\n * const weatherTool = createTool({\n * id: 'getWeather',\n * description: 'Gets the current weather for a location.',\n * inputSchema: z.object({ location: z.string() }),\n * execute: async ({ context }) => `Weather in ${context.location} is sunny.`,\n * });\n *\n * const server = new MCPServer({\n * name: 'My Weather Server',\n * version: '1.0.0',\n * tools: { weatherTool },\n * });\n *\n * await server.startStdio();\n * ```\n */\nexport class MCPServer extends MCPServerBase {\n private server: Server;\n private stdioTransport?: StdioServerTransport;\n private sseTransport?: SSEServerTransport;\n private sseHonoTransports: Map<string, SSETransport>;\n private streamableHTTPTransports: Map<string, StreamableHTTPServerTransport> = new Map();\n // Track server instances for each HTTP session\n private httpServerInstances: Map<string, Server> = new Map();\n\n private definedResources?: Resource[];\n private definedResourceTemplates?: ResourceTemplate[];\n private resourceOptions?: MCPServerResources;\n private definedPrompts?: Prompt[];\n private promptOptions?: MCPServerPrompts;\n private subscriptions: Set<string> = new Set();\n private currentLoggingLevel: LoggingLevel | undefined;\n\n /**\n * Provides methods to notify clients about resource changes.\n *\n * @example\n * ```typescript\n * // Notify that a specific resource was updated\n * await server.resources.notifyUpdated({ uri: 'file://data.txt' });\n *\n * // Notify that the resource list changed\n * await server.resources.notifyListChanged();\n * ```\n */\n public readonly resources: ServerResourceActions;\n\n /**\n * Provides methods to notify clients about prompt changes.\n *\n * @example\n * ```typescript\n * // Notify that the prompt list changed\n * await server.prompts.notifyListChanged();\n * ```\n */\n public readonly prompts: ServerPromptActions;\n\n /**\n * Provides methods for interactive user input collection during tool execution.\n *\n * @example\n * ```typescript\n * // Within a tool's execute function\n * const result = await options.elicitation.sendRequest({\n * message: 'Please provide your email address',\n * requestedSchema: {\n * type: 'object',\n * properties: {\n * email: { type: 'string', format: 'email' }\n * },\n * required: ['email']\n * }\n * });\n * ```\n */\n public readonly elicitation: ElicitationActions;\n\n /**\n * Gets the stdio transport instance if the server was started using stdio.\n *\n * This is primarily for internal checks or testing purposes.\n *\n * @returns The stdio transport instance, or undefined if not using stdio transport\n */\n public getStdioTransport(): StdioServerTransport | undefined {\n return this.stdioTransport;\n }\n\n /**\n * Gets the SSE transport instance if the server was started using SSE.\n *\n * This is primarily for internal checks or testing purposes.\n *\n * @returns The SSE transport instance, or undefined if not using SSE transport\n */\n public getSseTransport(): SSEServerTransport | undefined {\n return this.sseTransport;\n }\n\n /**\n * Gets the Hono SSE transport instance for a specific session.\n *\n * This is primarily for internal checks or testing purposes.\n *\n * @param sessionId - The session identifier\n * @returns The Hono SSE transport instance, or undefined if session not found\n */\n public getSseHonoTransport(sessionId: string): SSETransport | undefined {\n return this.sseHonoTransports.get(sessionId);\n }\n\n /**\n * Gets the underlying MCP SDK Server instance.\n *\n * This provides access to the low-level server instance for advanced use cases.\n *\n * @returns The Server instance from @modelcontextprotocol/sdk\n */\n public getServer(): Server {\n return this.server;\n }\n\n /**\n * Creates a new MCPServer instance.\n *\n * The server exposes tools, agents, and workflows to MCP clients. Agents are automatically\n * converted to tools named `ask_<agentKey>`, and workflows become tools named `run_<workflowKey>`.\n *\n * @param opts - Configuration options for the server\n * @param opts.name - Descriptive name for the server (e.g., 'My Weather Server')\n * @param opts.version - Semantic version of the server (e.g., '1.0.0')\n * @param opts.tools - Object mapping tool names to tool definitions\n * @param opts.agents - Optional object mapping agent identifiers to Agent instances\n * @param opts.workflows - Optional object mapping workflow identifiers to Workflow instances\n * @param opts.resources - Optional resource configuration for exposing data and content\n * @param opts.prompts - Optional prompt configuration for exposing reusable templates\n * @param opts.id - Optional unique identifier (generated if not provided)\n * @param opts.description - Optional description of what the server does\n *\n * @example\n * ```typescript\n * import { MCPServer } from '@mastra/mcp';\n * import { Agent } from '@mastra/core/agent';\n * import { createTool } from '@mastra/core/tools';\n * import { z } from 'zod';\n *\n * const myAgent = new Agent({\n * name: 'Helper',\n * description: 'A helpful assistant',\n * instructions: 'You are helpful.',\n * model: 'openai/gpt-4o-mini',\n * });\n *\n * const server = new MCPServer({\n * name: 'My Server',\n * version: '1.0.0',\n * tools: {\n * weatherTool: createTool({\n * id: 'getWeather',\n * description: 'Gets weather',\n * inputSchema: z.object({ location: z.string() }),\n * execute: async ({ context }) => `Sunny in ${context.location}`,\n * })\n * },\n * agents: { myAgent },\n * });\n * ```\n */\n constructor(opts: MCPServerConfig & { resources?: MCPServerResources; prompts?: MCPServerPrompts }) {\n super(opts);\n this.resourceOptions = opts.resources;\n this.promptOptions = opts.prompts;\n\n const capabilities: ServerCapabilities = {\n tools: {},\n logging: { enabled: true },\n elicitation: {},\n };\n\n if (opts.resources) {\n capabilities.resources = { subscribe: true, listChanged: true };\n }\n\n if (opts.prompts) {\n capabilities.prompts = { listChanged: true };\n }\n\n this.server = new Server({ name: this.name, version: this.version }, { capabilities });\n\n this.logger.info(\n `Initialized MCPServer '${this.name}' v${this.version} (ID: ${this.id}) with tools: ${Object.keys(this.convertedTools).join(', ')} and resources. Capabilities: ${JSON.stringify(capabilities)}`,\n );\n\n this.sseHonoTransports = new Map();\n\n // Register all handlers on the main server instance\n this.registerHandlersOnServer(this.server);\n\n this.resources = new ServerResourceActions({\n getSubscriptions: () => this.subscriptions,\n getLogger: () => this.logger,\n getSdkServer: () => this.server,\n clearDefinedResources: () => {\n this.definedResources = undefined;\n },\n clearDefinedResourceTemplates: () => {\n this.definedResourceTemplates = undefined;\n },\n });\n\n this.prompts = new ServerPromptActions({\n getLogger: () => this.logger,\n getSdkServer: () => this.server,\n clearDefinedPrompts: () => {\n this.definedPrompts = undefined;\n },\n });\n\n this.elicitation = {\n sendRequest: async request => {\n return this.handleElicitationRequest(request);\n },\n };\n }\n\n /**\n * Handle an elicitation request by sending it to the connected client.\n * This method sends an elicitation/create request to the client and waits for the response.\n *\n * @param request - The elicitation request containing message and schema\n * @param serverInstance - Optional server instance to use; defaults to main server for backward compatibility\n * @returns Promise that resolves to the client's response\n */\n private async handleElicitationRequest(\n request: ElicitRequest['params'],\n serverInstance?: Server,\n ): Promise<ElicitResult> {\n this.logger.debug(`Sending elicitation request: ${request.message}`);\n\n const server = serverInstance || this.server;\n const response = await server.elicitInput(request);\n\n this.logger.debug(`Received elicitation response: ${JSON.stringify(response)}`);\n\n return response;\n }\n\n /**\n * Creates a new Server instance configured with all handlers for HTTP sessions.\n * Each HTTP client connection gets its own Server instance to avoid routing conflicts.\n */\n private createServerInstance(): Server {\n const capabilities: ServerCapabilities = {\n tools: {},\n logging: { enabled: true },\n elicitation: {},\n };\n\n if (this.resourceOptions) {\n capabilities.resources = { subscribe: true, listChanged: true };\n }\n\n if (this.promptOptions) {\n capabilities.prompts = { listChanged: true };\n }\n\n const serverInstance = new Server({ name: this.name, version: this.version }, { capabilities });\n\n // Register all handlers on the new server instance\n this.registerHandlersOnServer(serverInstance);\n\n return serverInstance;\n }\n\n /**\n * Registers all MCP handlers on a given server instance.\n * This allows us to create multiple server instances with identical functionality.\n */\n private registerHandlersOnServer(serverInstance: Server) {\n // List tools handler\n serverInstance.setRequestHandler(ListToolsRequestSchema, async () => {\n this.logger.debug('Handling ListTools request');\n return {\n tools: Object.values(this.convertedTools).map(tool => {\n const toolSpec: any = {\n name: tool.name,\n description: tool.description,\n inputSchema: tool.parameters.jsonSchema,\n };\n if (tool.outputSchema) {\n toolSpec.outputSchema = tool.outputSchema.jsonSchema;\n }\n return toolSpec;\n }),\n };\n });\n\n // Call tool handler\n serverInstance.setRequestHandler(CallToolRequestSchema, async (request, extra) => {\n const startTime = Date.now();\n try {\n const tool = this.convertedTools[request.params.name] as MCPTool;\n if (!tool) {\n this.logger.warn(`CallTool: Unknown tool '${request.params.name}' requested.`);\n return {\n content: [{ type: 'text', text: `Unknown tool: ${request.params.name}` }],\n isError: true,\n };\n }\n\n const validation = tool.parameters.validate?.(request.params.arguments ?? {});\n if (validation && !validation.success) {\n this.logger.warn(`CallTool: Invalid tool arguments for '${request.params.name}'`, {\n errors: validation.error,\n });\n\n // Format validation errors for agent understanding\n let errorMessages = 'Validation failed';\n if ('errors' in validation.error && Array.isArray(validation.error.errors)) {\n errorMessages = validation.error.errors\n .map((e: any) => `- ${e.path?.join('.') || 'root'}: ${e.message}`)\n .join('\\n');\n } else if (validation.error instanceof Error) {\n errorMessages = validation.error.message;\n }\n\n return {\n content: [\n {\n type: 'text',\n text: `Tool validation failed. Please fix the following errors and try again:\\n${errorMessages}\\n\\nProvided arguments: ${JSON.stringify(request.params.arguments, null, 2)}`,\n },\n ],\n isError: true, // Set to true so the LLM sees the error and can self-correct\n };\n }\n if (!tool.execute) {\n this.logger.warn(`CallTool: Tool '${request.params.name}' does not have an execute function.`);\n return {\n content: [{ type: 'text', text: `Tool '${request.params.name}' does not have an execute function.` }],\n isError: true,\n };\n }\n\n // Create session-aware elicitation for this tool execution\n const sessionElicitation = {\n sendRequest: async (request: ElicitRequest['params']) => {\n return this.handleElicitationRequest(request, serverInstance);\n },\n };\n\n const result = await tool.execute(validation?.value ?? request.params.arguments ?? {}, {\n messages: [],\n toolCallId: '',\n elicitation: sessionElicitation,\n extra,\n });\n\n this.logger.debug(`CallTool: Tool '${request.params.name}' executed successfully with result:`, result);\n const duration = Date.now() - startTime;\n this.logger.info(`Tool '${request.params.name}' executed successfully in ${duration}ms.`);\n\n const response: CallToolResult = { isError: false, content: [] };\n\n if (tool.outputSchema) {\n // Handle both cases: tools that return { structuredContent: ... } and tools that return the plain object\n let structuredContent;\n if (result && typeof result === 'object' && 'structuredContent' in result) {\n // Tool returned { structuredContent: ... } format (MCP-aware tool)\n structuredContent = result.structuredContent;\n } else {\n // Tool returned plain object, wrap it automatically for backward compatibility\n structuredContent = result;\n }\n\n const outputValidation = tool.outputSchema.validate?.(structuredContent ?? {});\n if (outputValidation && !outputValidation.success) {\n this.logger.warn(`CallTool: Invalid structured content for '${request.params.name}'`, {\n errors: outputValidation.error,\n });\n throw new Error(\n `Invalid structured content for tool ${request.params.name}: ${JSON.stringify(outputValidation.error)}`,\n );\n }\n response.structuredContent = structuredContent;\n }\n\n if (response.structuredContent) {\n response.content = [{ type: 'text', text: JSON.stringify(response.structuredContent) }];\n } else {\n response.content = [\n {\n type: 'text',\n text: typeof result === 'string' ? result : JSON.stringify(result),\n },\n ];\n }\n\n return response;\n } catch (error) {\n const duration = Date.now() - startTime;\n if (error instanceof z.ZodError) {\n this.logger.warn('Invalid tool arguments', {\n tool: request.params.name,\n errors: error.errors,\n duration: `${duration}ms`,\n });\n return {\n content: [\n {\n type: 'text',\n text: `Invalid arguments: ${error.errors.map(e => `${e.path.join('.')}: ${e.message}`).join(', ')}`,\n },\n ],\n isError: true,\n };\n }\n this.logger.error(`Tool execution failed: ${request.params.name}`, { error });\n return {\n content: [{ type: 'text', text: `Error: ${error instanceof Error ? error.message : String(error)}` }],\n isError: true,\n };\n }\n });\n\n // Set logging level handler\n serverInstance.setRequestHandler(SetLevelRequestSchema, async request => {\n this.currentLoggingLevel = request.params.level;\n this.logger.debug(`Logging level set to: ${request.params.level}`);\n return {};\n });\n\n // Register resource handlers if resources are configured\n if (this.resourceOptions) {\n this.registerResourceHandlersOnServer(serverInstance);\n }\n\n // Register prompt handlers if prompts are configured\n if (this.promptOptions) {\n this.registerPromptHandlersOnServer(serverInstance);\n }\n }\n\n /**\n * Registers resource-related handlers on a server instance.\n */\n private registerResourceHandlersOnServer(serverInstance: Server) {\n const capturedResourceOptions = this.resourceOptions;\n if (!capturedResourceOptions) return;\n\n // List resources handler\n if (capturedResourceOptions.listResources) {\n serverInstance.setRequestHandler(ListResourcesRequestSchema, async (_request, extra) => {\n this.logger.debug('Handling ListResources request');\n if (this.definedResources) {\n return { resources: this.definedResources };\n } else {\n try {\n const resources = await capturedResourceOptions.listResources!({ extra });\n this.definedResources = resources;\n this.logger.debug(`Fetched and cached ${this.definedResources.length} resources.`);\n return { resources: this.definedResources };\n } catch (error) {\n this.logger.error('Error fetching resources via listResources():', { error });\n throw error;\n }\n }\n });\n }\n\n // Read resource handler\n if (capturedResourceOptions.getResourceContent) {\n serverInstance.setRequestHandler(ReadResourceRequestSchema, async (request, extra) => {\n const startTime = Date.now();\n const uri = request.params.uri;\n this.logger.debug(`Handling ReadResource request for URI: ${uri}`);\n\n if (!this.definedResources) {\n const resources = await this.resourceOptions?.listResources?.({ extra });\n if (!resources) throw new Error('Failed to load resources');\n this.definedResources = resources;\n }\n\n const resource = this.definedResources?.find(r => r.uri === uri);\n\n if (!resource) {\n this.logger.warn(`ReadResource: Unknown resource URI '${uri}' requested.`);\n throw new Error(`Resource not found: ${uri}`);\n }\n\n try {\n const resourcesOrResourceContent = await capturedResourceOptions.getResourceContent({ uri, extra });\n const resourcesContent = Array.isArray(resourcesOrResourceContent)\n ? resourcesOrResourceContent\n : [resourcesOrResourceContent];\n const contents: ResourceContents[] = resourcesContent.map(resourceContent => {\n const contentItem: ResourceContents = {\n uri: resource.uri,\n mimeType: resource.mimeType,\n };\n if ('text' in resourceContent) {\n contentItem.text = resourceContent.text;\n }\n\n if ('blob' in resourceContent) {\n contentItem.blob = resourceContent.blob;\n }\n\n return contentItem;\n });\n const duration = Date.now() - startTime;\n this.logger.info(`Resource '${uri}' read successfully in ${duration}ms.`);\n return {\n contents,\n };\n } catch (error) {\n const duration = Date.now() - startTime;\n this.logger.error(`Failed to get content for resource URI '${uri}' in ${duration}ms`, { error });\n throw error;\n }\n });\n }\n\n // Resource templates handler\n if (capturedResourceOptions.resourceTemplates) {\n serverInstance.setRequestHandler(ListResourceTemplatesRequestSchema, async (_request, extra) => {\n this.logger.debug('Handling ListResourceTemplates request');\n if (this.definedResourceTemplates) {\n return { resourceTemplates: this.definedResourceTemplates };\n } else {\n try {\n const templates = await capturedResourceOptions.resourceTemplates!({ extra });\n this.definedResourceTemplates = templates;\n this.logger.debug(`Fetched and cached ${this.definedResourceTemplates.length} resource templates.`);\n return { resourceTemplates: this.definedResourceTemplates };\n } catch (error) {\n this.logger.error('Error fetching resource templates via resourceTemplates():', { error });\n throw error;\n }\n }\n });\n }\n\n // Subscribe/unsubscribe handlers\n serverInstance.setRequestHandler(SubscribeRequestSchema, async (request: { params: { uri: string } }) => {\n const uri = request.params.uri;\n this.logger.info(`Received resources/subscribe request for URI: ${uri}`);\n this.subscriptions.add(uri);\n return {};\n });\n\n serverInstance.setRequestHandler(UnsubscribeRequestSchema, async (request: { params: { uri: string } }) => {\n const uri = request.params.uri;\n this.logger.info(`Received resources/unsubscribe request for URI: ${uri}`);\n this.subscriptions.delete(uri);\n return {};\n });\n }\n\n /**\n * Registers prompt-related handlers on a server instance.\n */\n private registerPromptHandlersOnServer(serverInstance: Server) {\n const capturedPromptOptions = this.promptOptions;\n if (!capturedPromptOptions) return;\n\n // List prompts handler\n if (capturedPromptOptions.listPrompts) {\n serverInstance.setRequestHandler(ListPromptsRequestSchema, async (_request, extra) => {\n this.logger.debug('Handling ListPrompts request');\n if (this.definedPrompts) {\n return {\n prompts: this.definedPrompts?.map(p => ({ ...p, version: p.version ?? undefined })),\n };\n } else {\n try {\n const prompts = await capturedPromptOptions.listPrompts({ extra });\n for (const prompt of prompts) {\n PromptSchema.parse(prompt);\n }\n this.definedPrompts = prompts;\n this.logger.debug(`Fetched and cached ${this.definedPrompts.length} prompts.`);\n return {\n prompts: this.definedPrompts?.map(p => ({ ...p, version: p.version ?? undefined })),\n };\n } catch (error) {\n this.logger.error('Error fetching prompts via listPrompts():', {\n error: error instanceof Error ? error.message : String(error),\n });\n throw error;\n }\n }\n });\n }\n\n // Get prompt handler\n if (capturedPromptOptions.getPromptMessages) {\n serverInstance.setRequestHandler(\n GetPromptRequestSchema,\n async (request: { params: { name: string; version?: string; arguments?: any } }, extra) => {\n const startTime = Date.now();\n const { name, version, arguments: args } = request.params;\n if (!this.definedPrompts) {\n const prompts = await this.promptOptions?.listPrompts?.({ extra });\n if (!prompts) throw new Error('Failed to load prompts');\n this.definedPrompts = prompts;\n }\n // Select prompt by name and version (if provided)\n let prompt;\n if (version) {\n prompt = this.definedPrompts?.find(p => p.name === name && p.version === version);\n } else {\n // Select the first matching name if no version is provided.\n prompt = this.definedPrompts?.find(p => p.name === name);\n }\n if (!prompt) throw new Error(`Prompt \"${name}\"${version ? ` (version ${version})` : ''} not found`);\n // Validate required arguments\n if (prompt.arguments) {\n for (const arg of prompt.arguments) {\n if (arg.required && (args?.[arg.name] === undefined || args?.[arg.name] === null)) {\n throw new Error(`Missing required argument: ${arg.name}`);\n }\n }\n }\n try {\n let messages: any[] = [];\n if (capturedPromptOptions.getPromptMessages) {\n messages = await capturedPromptOptions.getPromptMessages({ name, version, args, extra });\n }\n const duration = Date.now() - startTime;\n this.logger.info(\n `Prompt '${name}'${version ? ` (version ${version})` : ''} retrieved successfully in ${duration}ms.`,\n );\n return { prompt, messages };\n } catch (error) {\n const duration = Date.now() - startTime;\n this.logger.error(`Failed to get content for prompt '${name}' in ${duration}ms`, { error });\n throw error;\n }\n },\n );\n }\n }\n\n private convertAgentsToTools(\n agentsConfig?: Record<string, Agent>,\n definedConvertedTools?: Record<string, ConvertedTool>,\n ): Record<string, ConvertedTool> {\n const agentTools: Record<string, ConvertedTool> = {};\n if (!agentsConfig) {\n return agentTools;\n }\n\n for (const agentKey in agentsConfig) {\n const agent = agentsConfig[agentKey];\n if (!agent || !('generate' in agent)) {\n this.logger.warn(`Agent instance for '${agentKey}' is invalid or missing a generate function. Skipping.`);\n continue;\n }\n\n const agentDescription = agent.getDescription();\n\n if (!agentDescription) {\n throw new Error(\n `Agent '${agent.name}' (key: '${agentKey}') must have a non-empty description to be used in an MCPServer.`,\n );\n }\n\n const agentToolName = `ask_${agentKey}`;\n if (definedConvertedTools?.[agentToolName] || agentTools[agentToolName]) {\n this.logger.warn(\n `Tool with name '${agentToolName}' already exists. Agent '${agentKey}' will not be added as a duplicate tool.`,\n );\n continue;\n }\n\n const agentToolDefinition = createTool({\n id: agentToolName,\n description: `Ask agent '${agent.name}' a question. Agent description: ${agentDescription}`,\n inputSchema: z.object({\n message: z.string().describe('The question or input for the agent.'),\n }),\n execute: async ({ context, runtimeContext, tracingContext }) => {\n this.logger.debug(\n `Executing agent tool '${agentToolName}' for agent '${agent.name}' with message: \"${context.message}\"`,\n );\n try {\n const response = await agent.generate(context.message, { runtimeContext, tracingContext });\n return response;\n } catch (error) {\n this.logger.error(`Error executing agent tool '${agentToolName}' for agent '${agent.name}':`, error);\n throw error;\n }\n },\n });\n\n const options = {\n name: agentToolName,\n logger: this.logger,\n mastra: this.mastra,\n runtimeContext: new RuntimeContext(),\n tracingContext: {},\n description: agentToolDefinition.description,\n };\n const coreTool = makeCoreTool(agentToolDefinition, options) as InternalCoreTool;\n\n agentTools[agentToolName] = {\n name: agentToolName,\n description: coreTool.description,\n parameters: coreTool.parameters,\n execute: coreTool.execute!,\n toolType: 'agent',\n };\n this.logger.info(`Registered agent '${agent.name}' (key: '${agentKey}') as tool: '${agentToolName}'`);\n }\n return agentTools;\n }\n\n private convertWorkflowsToTools(\n workflowsConfig?: Record<string, Workflow>,\n definedConvertedTools?: Record<string, ConvertedTool>,\n ): Record<string, ConvertedTool> {\n const workflowTools: Record<string, ConvertedTool> = {};\n if (!workflowsConfig) {\n return workflowTools;\n }\n\n for (const workflowKey in workflowsConfig) {\n const workflow = workflowsConfig[workflowKey];\n if (!workflow || typeof workflow.createRun !== 'function') {\n this.logger.warn(\n `Workflow instance for '${workflowKey}' is invalid or missing a createRun function. Skipping.`,\n );\n continue;\n }\n\n const workflowDescription = workflow.description;\n if (!workflowDescription) {\n throw new Error(\n `Workflow '${workflow.id}' (key: '${workflowKey}') must have a non-empty description to be used in an MCPServer.`,\n );\n }\n\n const workflowToolName = `run_${workflowKey}`;\n if (definedConvertedTools?.[workflowToolName] || workflowTools[workflowToolName]) {\n this.logger.warn(\n `Tool with name '${workflowToolName}' already exists. Workflow '${workflowKey}' will not be added as a duplicate tool.`,\n );\n continue;\n }\n\n const workflowToolDefinition = createTool({\n id: workflowToolName,\n description: `Run workflow '${workflowKey}'. Workflow description: ${workflowDescription}`,\n inputSchema: workflow.inputSchema,\n execute: async ({ context, runtimeContext, tracingContext }) => {\n this.logger.debug(\n `Executing workflow tool '${workflowToolName}' for workflow '${workflow.id}' with input:`,\n context,\n );\n try {\n const run = await workflow.createRunAsync({ runId: runtimeContext?.get('runId') });\n\n const response = await run.start({ inputData: context, runtimeContext, tracingContext });\n\n return response;\n } catch (error) {\n this.logger.error(\n `Error executing workflow tool '${workflowToolName}' for workflow '${workflow.id}':`,\n error,\n );\n throw error;\n }\n },\n });\n\n const options = {\n name: workflowToolName,\n logger: this.logger,\n mastra: this.mastra,\n runtimeContext: new RuntimeContext(),\n tracingContext: {},\n description: workflowToolDefinition.description,\n };\n\n const coreTool = makeCoreTool(workflowToolDefinition, options) as InternalCoreTool;\n\n workflowTools[workflowToolName] = {\n name: workflowToolName,\n description: coreTool.description,\n parameters: coreTool.parameters,\n outputSchema: coreTool.outputSchema,\n execute: coreTool.execute!,\n toolType: 'workflow',\n };\n this.logger.info(`Registered workflow '${workflow.id}' (key: '${workflowKey}') as tool: '${workflowToolName}'`);\n }\n return workflowTools;\n }\n\n /**\n * Convert and validate all provided tools, logging registration status.\n * Also converts agents and workflows into tools.\n * @param tools Tool definitions\n * @param agentsConfig Agent definitions to be converted to tools, expected from MCPServerConfig\n * @param workflowsConfig Workflow definitions to be converted to tools, expected from MCPServerConfig\n * @returns Converted tools registry\n */\n convertTools(\n tools: ToolsInput,\n agentsConfig?: Record<string, Agent>,\n workflowsConfig?: Record<string, Workflow>,\n ): Record<string, ConvertedTool> {\n const definedConvertedTools: Record<string, ConvertedTool> = {};\n\n for (const toolName of Object.keys(tools)) {\n const toolInstance = tools[toolName];\n if (!toolInstance) {\n this.logger.warn(`Tool instance for '${toolName}' is undefined. Skipping.`);\n continue;\n }\n\n if (typeof toolInstance.execute !== 'function') {\n this.logger.warn(`Tool '${toolName}' does not have a valid execute function. Skipping.`);\n continue;\n }\n\n const options = {\n name: toolName,\n runtimeContext: new RuntimeContext(),\n tracingContext: {},\n mastra: this.mastra,\n logger: this.logger,\n description: toolInstance?.description,\n };\n\n const coreTool = makeCoreTool(toolInstance, options) as InternalCoreTool;\n\n definedConvertedTools[toolName] = {\n name: toolName,\n description: coreTool.description,\n parameters: coreTool.parameters,\n outputSchema: coreTool.outputSchema,\n execute: coreTool.execute!,\n };\n this.logger.info(`Registered explicit tool: '${toolName}'`);\n }\n this.logger.info(`Total defined tools registered: ${Object.keys(definedConvertedTools).length}`);\n\n let agentDerivedTools: Record<string, ConvertedTool> = {};\n let workflowDerivedTools: Record<string, ConvertedTool> = {};\n try {\n agentDerivedTools = this.convertAgentsToTools(agentsConfig, definedConvertedTools);\n workflowDerivedTools = this.convertWorkflowsToTools(workflowsConfig, definedConvertedTools);\n } catch (e) {\n const mastraError = new MastraError(\n {\n id: 'MCP_SERVER_AGENT_OR_WORKFLOW_TOOL_CONVERSION_FAILED',\n domain: ErrorDomain.MCP,\n category: ErrorCategory.USER,\n },\n e,\n );\n this.logger.trackException(mastraError);\n this.logger.error('Failed to convert tools:', {\n error: mastraError.toString(),\n });\n throw mastraError;\n }\n\n const allConvertedTools = { ...definedConvertedTools, ...agentDerivedTools, ...workflowDerivedTools };\n\n const finalToolCount = Object.keys(allConvertedTools).length;\n const definedCount = Object.keys(definedConvertedTools).length;\n const fromAgentsCount = Object.keys(agentDerivedTools).length;\n const fromWorkflowsCount = Object.keys(workflowDerivedTools).length;\n this.logger.info(\n `${finalToolCount} total tools registered (${definedCount} defined + ${fromAgentsCount} agents + ${fromWorkflowsCount} workflows)`,\n );\n\n return allConvertedTools;\n }\n\n /**\n * Starts the MCP server using standard input/output (stdio) transport.\n *\n * This is typically used when running the server as a command-line program that MCP clients\n * spawn as a subprocess (e.g., integration with Windsurf, Cursor, or Claude Desktop).\n *\n * @throws {MastraError} If the stdio connection fails\n *\n * @example\n * ```typescript\n * const server = new MCPServer({\n * name: 'My Server',\n * version: '1.0.0',\n * tools: { weatherTool },\n * });\n *\n * await server.startStdio();\n * ```\n */\n public async startStdio(): Promise<void> {\n this.stdioTransport = new StdioServerTransport();\n try {\n await this.server.connect(this.stdioTransport);\n } catch (error) {\n const mastraError = new MastraError(\n {\n id: 'MCP_SERVER_STDIO_CONNECTION_FAILED',\n domain: ErrorDomain.MCP,\n category: ErrorCategory.THIRD_PARTY,\n },\n error,\n );\n this.logger.trackException(mastraError);\n this.logger.error('Failed to connect MCP server using stdio transport:', {\n error: mastraError.toString(),\n });\n throw mastraError;\n }\n this.logger.info('Started MCP Server (stdio)');\n }\n\n /**\n * Integrates the MCP server with an existing HTTP server using Server-Sent Events (SSE).\n *\n * Call this method from your web server's request handler for both the SSE and message paths.\n * This enables web-based MCP clients to connect to your server.\n *\n * @param options - Configuration for SSE integration\n * @param options.url - Parsed URL of the incoming request\n * @param options.ssePath - Path for establishing SSE connection (e.g., '/sse')\n * @param options.messagePath - Path for POSTing client messages (e.g., '/message')\n * @param options.req - Incoming HTTP request object\n * @param options.res - HTTP response object (must support .write/.end)\n *\n * @throws {MastraError} If SSE connection setup fails\n *\n * @example\n * ```typescript\n * import http from 'http';\n *\n * const httpServer = http.createServer(async (req, res) => {\n * await server.startSSE({\n * url: new URL(req.url || '', `http://localhost:1234`),\n * ssePath: '/sse',\n * messagePath: '/message',\n * req,\n * res,\n * });\n * });\n *\n * httpServer.listen(1234, () => {\n * console.log('MCP server listening on http://localhost:1234/sse');\n * });\n * ```\n */\n public async startSSE({ url, ssePath, messagePath, req, res }: MCPServerSSEOptions): Promise<void> {\n try {\n if (url.pathname === ssePath) {\n await this.connectSSE({\n messagePath,\n res,\n });\n } else if (url.pathname === messagePath) {\n this.logger.debug('Received message');\n if (!this.sseTransport) {\n res.writeHead(503);\n res.end('SSE connection not established');\n return;\n }\n await this.sseTransport.handlePostMessage(req, res);\n } else {\n this.logger.debug('Unknown path:', { path: url.pathname });\n res.writeHead(404);\n res.end();\n }\n } catch (e) {\n const mastraError = new MastraError(\n {\n id: 'MCP_SERVER_SSE_START_FAILED',\n domain: ErrorDomain.MCP,\n category: ErrorCategory.USER,\n details: {\n url: url.toString(),\n ssePath,\n messagePath,\n },\n },\n e,\n );\n this.logger.trackException(mastraError);\n this.logger.error('Failed to start MCP Server (SSE):', { error: mastraError.toString() });\n throw mastraError;\n }\n }\n\n /**\n * Integrates the MCP server with a Hono web framework using Server-Sent Events (SSE).\n *\n * Call this method from your Hono server's request handler for both the SSE and message paths.\n * This enables Hono-based web applications to expose MCP servers.\n *\n * @param options - Configuration for Hono SSE integration\n * @param options.url - Parsed URL of the incoming request\n * @param options.ssePath - Path for establishing SSE connection (e.g., '/hono-sse')\n * @param options.messagePath - Path for POSTing client messages (e.g., '/message')\n * @param options.context - Hono context object\n *\n * @throws {MastraError} If Hono SSE connection setup fails\n *\n * @example\n * ```typescript\n * import { Hono } from 'hono';\n *\n * const app = new Hono();\n *\n * app.all('*', async (c) => {\n * const url = new URL(c.req.url);\n * return await server.startHonoSSE({\n * url,\n * ssePath: '/hono-sse',\n * messagePath: '/message',\n * context: c,\n * });\n * });\n *\n * export default app;\n * ```\n */\n public async startHonoSSE({ url, ssePath, messagePath, context }: MCPServerHonoSSEOptions) {\n try {\n if (url.pathname === ssePath) {\n return streamSSE(context, async stream => {\n await this.connectHonoSSE({\n messagePath,\n stream,\n });\n });\n } else if (url.pathname === messagePath) {\n this.logger.debug('Received message');\n const sessionId = context.req.query('sessionId');\n this.logger.debug('Received message for sessionId', { sessionId });\n if (!sessionId) {\n return context.text('No sessionId provided', 400);\n }\n if (!this.sseHonoTransports.has(sessionId)) {\n return context.text(`No transport found for sessionId ${sessionId}`, 400);\n }\n const message = await this.sseHonoTransports.get(sessionId)?.handlePostMessage(context);\n if (!message) {\n return context.text('Transport not found', 400);\n }\n return message;\n } else {\n this.logger.debug('Unknown path:', { path: url.pathname });\n return context.text('Unknown path', 404);\n }\n } catch (e) {\n const mastraError = new MastraError(\n {\n id: 'MCP_SERVER_HONO_SSE_START_FAILED',\n domain: ErrorDomain.MCP,\n category: ErrorCategory.USER,\n details: {\n url: url.toString(),\n ssePath,\n messagePath,\n },\n },\n e,\n );\n this.logger.trackException(mastraError);\n this.logger.error('Failed to start MCP Server (Hono SSE):', { error: mastraError.toString() });\n throw mastraError;\n }\n }\n\n /**\n * Integrates the MCP server with an existing HTTP server using streamable HTTP transport.\n *\n * This is the recommended modern transport method, providing better session management and\n * reliability compared to SSE. Call this from your HTTP server's request handler.\n *\n * @param options - Configuration for HTTP integration\n * @param options.url - Parsed URL of the incoming request\n * @param options.httpPath - Path for the MCP endpoint (e.g., '/mcp')\n * @param options.req - Incoming HTTP request (http.IncomingMessage)\n * @param options.res - HTTP response object (http.ServerResponse)\n * @param options.options - Optional transport options\n * @param options.options.sessionIdGenerator - Function to generate unique session IDs (defaults to randomUUID)\n * @param options.options.onsessioninitialized - Callback when a new session is initialized\n * @param options.options.enableJsonResponse - If true, return JSON instead of SSE streaming\n * @param options.options.eventStore - Event store for message resumability\n *\n * @throws {MastraError} If HTTP connection setup fails\n *\n * @example\n * ```typescript\n * import http from 'http';\n * import { randomUUID } from 'crypto';\n *\n * const httpServer = http.createServer(async (req, res) => {\n * await server.startHTTP({\n * url: new URL(req.url || '', 'http://localhost:1234'),\n * httpPath: '/mcp',\n * req,\n * res,\n * options: {\n * sessionIdGenerator: () => randomUUID(),\n * onsessioninitialized: (sessionId) => {\n * console.log(`New MCP session: ${sessionId}`);\n * },\n * },\n * });\n * });\n *\n * httpServer.listen(1234);\n * ```\n */\n public async startHTTP({\n url,\n httpPath,\n req,\n res,\n options = { sessionIdGenerator: () => randomUUID() },\n }: {\n url: URL;\n httpPath: string;\n req: http.IncomingMessage;\n res: http.ServerResponse<http.IncomingMessage>;\n options?: StreamableHTTPServerTransportOptions;\n }) {\n this.logger.debug(`startHTTP: Received ${req.method} request to ${url.pathname}`);\n\n if (url.pathname !== httpPath) {\n this.logger.debug(`startHTTP: Pathname ${url.pathname} does not match httpPath ${httpPath}. Returning 404.`);\n res.writeHead(404);\n res.end();\n return;\n }\n\n const sessionId = req.headers['mcp-session-id'] as string | undefined;\n let transport: StreamableHTTPServerTransport | undefined;\n\n this.logger.debug(\n `startHTTP: Session ID from headers: ${sessionId}. Active transports: ${Array.from(this.streamableHTTPTransports.keys()).join(', ')}`,\n );\n\n try {\n if (sessionId && this.streamableHTTPTransports.has(sessionId)) {\n // Found existing session\n transport = this.streamableHTTPTransports.get(sessionId)!;\n this.logger.debug(`startHTTP: Using existing Streamable HTTP transport for session ID: ${sessionId}`);\n\n if (req.method === 'GET') {\n this.logger.debug(\n `startHTTP: Handling GET request for existing session ${sessionId}. Calling transport.handleRequest.`,\n );\n }\n\n // Handle the request using the existing transport\n // Need to parse body for POST requests before passing to handleRequest\n const body =\n req.method === 'POST'\n ? await new Promise((resolve, reject) => {\n let data = '';\n req.on('data', chunk => (data += chunk));\n req.on('end', () => {\n try {\n resolve(JSON.parse(data));\n } catch (e) {\n reject(e);\n }\n });\n req.on('error', reject);\n })\n : undefined;\n\n await transport.handleRequest(req, res, body);\n } else {\n // No session ID or session ID not found\n this.logger.debug(`startHTTP: No existing Streamable HTTP session ID found. ${req.method}`);\n\n // Only allow new sessions via POST initialize request\n if (req.method === 'POST') {\n const body = await new Promise((resolve, reject) => {\n let data = '';\n req.on('data', chunk => (data += chunk));\n req.on('end', () => {\n try {\n resolve(JSON.parse(data));\n } catch (e) {\n reject(e);\n }\n });\n req.on('error', reject);\n });\n\n // Import isInitializeRequest from the correct path\n const { isInitializeRequest } = await import('@modelcontextprotocol/sdk/types.js');\n\n if (isInitializeRequest(body)) {\n this.logger.debug('startHTTP: Received Streamable HTTP initialize request, creating new transport.');\n\n // Create a new transport for the new session\n transport = new StreamableHTTPServerTransport({\n ...options,\n sessionIdGenerator: () => randomUUID(),\n onsessioninitialized: id => {\n this.streamableHTTPTransports.set(id, transport!);\n },\n });\n\n // Set up onclose handler to clean up transport when closed\n transport.onclose = () => {\n const closedSessionId = transport?.sessionId;\n if (closedSessionId && this.streamableHTTPTransports.has(closedSessionId)) {\n this.logger.debug(\n `startHTTP: Streamable HTTP transport closed for session ${closedSessionId}, removing from map.`,\n );\n this.streamableHTTPTransports.delete(closedSessionId);\n // Also clean up the server instance for this session\n if (this.httpServerInstances.has(closedSessionId)) {\n this.httpServerInstances.delete(closedSessionId);\n this.logger.debug(`startHTTP: Cleaned up server instance for closed session ${closedSessionId}`);\n }\n }\n };\n\n // Create a new server instance for this HTTP session\n const sessionServerInstance = this.createServerInstance();\n\n // Connect the new server instance to the new transport\n await sessionServerInstance.connect(transport);\n\n // Store both the transport and server instance when the session is initialized\n if (transport.sessionId) {\n this.streamableHTTPTransports.set(transport.sessionId, transport);\n this.httpServerInstances.set(transport.sessionId, sessionServerInstance);\n this.logger.debug(\n `startHTTP: Streamable HTTP session initialized and stored with ID: ${transport.sessionId}`,\n );\n } else {\n this.logger.warn('startHTTP: Streamable HTTP transport initialized without a session ID.');\n }\n\n // Handle the initialize request\n return await transport.handleRequest(req, res, body);\n } else {\n // POST request but not initialize, and no session ID\n this.logger.warn('startHTTP: Received non-initialize POST request without a session ID.');\n res.writeHead(400, { 'Content-Type': 'application/json' });\n res.end(\n JSON.stringify({\n jsonrpc: '2.0',\n error: {\n code: -32000,\n message: 'Bad Request: No valid session ID provided for non-initialize request',\n },\n id: (body as any)?.id ?? null, // Include original request ID if available\n }),\n );\n }\n } else {\n // Non-POST request (GET/DELETE) without a session ID\n this.logger.warn(`startHTTP: Received ${req.method} request without a session ID.`);\n res.writeHead(400, { 'Content-Type': 'application/json' });\n res.end(\n JSON.stringify({\n jsonrpc: '2.0',\n error: {\n code: -32000,\n message: `Bad Request: ${req.method} request requires a valid session ID`,\n },\n id: null,\n }),\n );\n }\n }\n } catch (error) {\n const mastraError = new MastraError(\n {\n id: 'MCP_SERVER_HTTP_CONNECTION_FAILED',\n domain: ErrorDomain.MCP,\n category: ErrorCategory.USER,\n text: 'Failed to connect MCP server using HTTP transport',\n },\n error,\n );\n this.logger.trackException(mastraError);\n this.logger.error('startHTTP: Error handling Streamable HTTP request:', { error: mastraError });\n // If headers haven't been sent, send an error response\n if (!res.headersSent) {\n res.writeHead(500, { 'Content-Type': 'application/json' });\n res.end(\n JSON.stringify({\n jsonrpc: '2.0',\n error: {\n code: -32603,\n message: 'Internal server error',\n },\n id: null, // Cannot determine original request ID in catch\n }),\n );\n }\n }\n }\n\n /**\n * Establishes the SSE connection for the MCP server.\n *\n * This is a lower-level method called internally by `startSSE()`. In most cases,\n * you should use `startSSE()` instead which handles both connection establishment\n * and message routing.\n *\n * @param params - Connection parameters\n * @param params.messagePath - Path for POST requests from the client\n * @param params.res - HTTP response object for the SSE stream\n * @throws {MastraError} If SSE connection establishment fails\n *\n * @example\n * ```typescript\n * // Usually called internally by startSSE()\n * await server.connectSSE({\n * messagePath: '/message',\n * res: response\n * });\n * ```\n */\n public async connectSSE({\n messagePath,\n res,\n }: {\n messagePath: string;\n res: http.ServerResponse<http.IncomingMessage>;\n }) {\n try {\n this.logger.debug('Received SSE connection');\n this.sseTransport = new SSEServerTransport(messagePath, res);\n await this.server.connect(this.sseTransport);\n\n this.server.onclose = async () => {\n this.sseTransport = undefined;\n await this.server.close();\n };\n\n res.on('close', () => {\n this.sseTransport = undefined;\n });\n } catch (e) {\n const mastraError = new MastraError(\n {\n id: 'MCP_SERVER_SSE_CONNECT_FAILED',\n domain: ErrorDomain.MCP,\n category: ErrorCategory.USER,\n details: {\n messagePath,\n },\n },\n e,\n );\n this.logger.trackException(mastraError);\n this.logger.error('Failed to connect to MCP Server (SSE):', { error: mastraError });\n throw mastraError;\n }\n }\n\n /**\n * Establishes the Hono SSE connection for the MCP server.\n *\n * This is a lower-level method called internally by `startHonoSSE()`. In most cases,\n * you should use `startHonoSSE()` instead which handles both connection establishment\n * and message routing.\n *\n * @param params - Connection parameters\n * @param params.messagePath - Path for POST requests from the client\n * @param params.stream - Hono SSE streaming API object\n * @throws {MastraError} If Hono SSE connection establishment fails\n *\n * @example\n * ```typescript\n * // Usually called internally by startHonoSSE()\n * await server.connectHonoSSE({\n * messagePath: '/message',\n * stream: sseStream\n * });\n * ```\n */\n public async connectHonoSSE({ messagePath, stream }: { messagePath: string; stream: SSEStreamingApi }) {\n this.logger.debug('Received SSE connection');\n const sseTransport = new SSETransport(messagePath, stream);\n const sessionId = sseTransport.sessionId;\n this.logger.debug('SSE Transport created with sessionId:', { sessionId });\n this.sseHonoTransports.set(sessionId, sseTransport);\n\n stream.onAbort(() => {\n this.logger.debug('SSE Transport aborted with sessionId:', { sessionId });\n this.sseHonoTransports.delete(sessionId);\n });\n try {\n await this.server.connect(sseTransport);\n this.server.onclose = async () => {\n this.logger.debug('SSE Transport closed with sessionId:', { sessionId });\n this.sseHonoTransports.delete(sessionId);\n await this.server.close();\n };\n\n while (true) {\n // This will keep the connection alive\n // You can also await for a promise that never resolves\n await stream.sleep(60_000);\n const sessionIds = Array.from(this.sseHonoTransports.keys() || []);\n this.logger.debug('Active Hono SSE sessions:', { sessionIds });\n await stream.write(':keep-alive\\n\\n');\n }\n } catch (e) {\n const mastraError = new MastraError(\n {\n id: 'MCP_SERVER_HONO_SSE_CONNECT_FAILED',\n domain: ErrorDomain.MCP,\n category: ErrorCategory.USER,\n details: {\n messagePath,\n },\n },\n e,\n );\n this.logger.trackException(mastraError);\n this.logger.error('Failed to connect to MCP Server (Hono SSE):', { error: mastraError });\n throw mastraError;\n }\n }\n\n /**\n * Closes the MCP server and releases all resources.\n *\n * This method cleanly shuts down all active transports (stdio, SSE, HTTP) and their\n * associated connections. Call this when your application is shutting down.\n *\n * @throws {MastraError} If closing the server fails\n *\n * @example\n * ```typescript\n * // Graceful shutdown\n * process.on('SIGTERM', async () => {\n * await server.close();\n * process.exit(0);\n * });\n * ```\n */\n async close() {\n try {\n if (this.stdioTransport) {\n await this.stdioTransport.close?.();\n this.stdioTransport = undefined;\n }\n if (this.sseTransport) {\n await this.sseTransport.close?.();\n this.sseTransport = undefined;\n }\n if (this.sseHonoTransports) {\n for (const transport of this.sseHonoTransports.values()) {\n await transport.close?.();\n }\n this.sseHonoTransports.clear();\n }\n // Close all active Streamable HTTP transports and their server instances\n if (this.streamableHTTPTransports) {\n for (const transport of this.streamableHTTPTransports.values()) {\n await transport.close?.();\n }\n this.streamableHTTPTransports.clear();\n }\n // Close all HTTP server instances\n if (this.httpServerInstances) {\n for (const serverInstance of this.httpServerInstances.values()) {\n await serverInstance.close?.();\n }\n this.httpServerInstances.clear();\n }\n await this.server.close();\n this.logger.info('MCP server closed.');\n } catch (error) {\n const mastraError = new MastraError(\n {\n id: 'MCP_SERVER_CLOSE_FAILED',\n domain: ErrorDomain.MCP,\n category: ErrorCategory.THIRD_PARTY,\n },\n error,\n );\n this.logger.trackException(mastraError);\n this.logger.error('Error closing MCP server:', { error: mastraError });\n throw mastraError;\n }\n }\n\n /**\n * Gets basic information about the server.\n *\n * Returns metadata including server ID, name, description, repository, and version details.\n * This information conforms to the MCP Server schema.\n *\n * @returns Server information object\n *\n * @example\n * ```typescript\n * const info = server.getServerInfo();\n * console.log(`${info.name} v${info.version_detail.version}`);\n * // Output: My Weather Server v1.0.0\n * ```\n */\n public getServerInfo(): ServerInfo {\n return {\n id: this.id,\n name: this.name,\n description: this.description,\n repository: this.repository,\n version_detail: {\n version: this.version,\n release_date: this.releaseDate,\n is_latest: this.isLatest,\n },\n };\n }\n\n /**\n * Gets detailed information about the server including packaging and deployment metadata.\n *\n * Returns extended server information with package details, remotes, and deployment configurations.\n * This information conforms to the MCP ServerDetail schema.\n *\n * @returns Detailed server information object\n *\n * @example\n * ```typescript\n * const detail = server.getServerDetail();\n * console.log(detail.package_canonical); // 'npm'\n * console.log(detail.packages); // Package installation info\n * ```\n */\n public getServerDetail(): ServerDetailInfo {\n return {\n ...this.getServerInfo(),\n package_canonical: this.packageCanonical,\n packages: this.packages,\n remotes: this.remotes,\n };\n }\n\n /**\n * Gets a list of all tools provided by this MCP server with their schemas.\n *\n * Returns information about all registered tools including explicit tools, agent-derived tools,\n * and workflow-derived tools. Includes input/output schemas and tool types.\n *\n * @returns Object containing array of tool information\n *\n * @example\n * ```typescript\n * const toolList = server.getToolListInfo();\n * toolList.tools.forEach(tool => {\n * console.log(`${tool.name}: ${tool.description}`);\n * console.log(`Type: ${tool.toolType || 'tool'}`);\n * });\n * ```\n */\n public getToolListInfo(): {\n tools: Array<{ name: string; description?: string; inputSchema: any; outputSchema?: any; toolType?: MCPToolType }>;\n } {\n this.logger.debug(`Getting tool list information for MCPServer '${this.name}'`);\n return {\n tools: Object.entries(this.convertedTools).map(([toolId, tool]) => ({\n id: toolId,\n name: tool.name,\n description: tool.description,\n inputSchema: tool.parameters?.jsonSchema || tool.parameters,\n outputSchema: tool.outputSchema?.jsonSchema || tool.outputSchema,\n toolType: tool.toolType,\n })),\n };\n }\n\n /**\n * Gets information for a specific tool provided by this MCP server.\n *\n * Returns detailed information about a single tool including its name, description, schemas, and type.\n * Returns undefined if the tool is not found.\n *\n * @param toolId - The ID/name of the tool to retrieve\n * @returns Tool information object or undefined if not found\n *\n * @example\n * ```typescript\n * const toolInfo = server.getToolInfo('getWeather');\n * if (toolInfo) {\n * console.log(toolInfo.description);\n * console.log(toolInfo.inputSchema);\n * }\n * ```\n */\n public getToolInfo(\n toolId: string,\n ): { name: string; description?: string; inputSchema: any; outputSchema?: any; toolType?: MCPToolType } | undefined {\n const tool = this.convertedTools[toolId];\n if (!tool) {\n this.logger.debug(`Tool '${toolId}' not found on MCPServer '${this.name}'`);\n return undefined;\n }\n this.logger.debug(`Getting info for tool '${toolId}' on MCPServer '${this.name}'`);\n return {\n name: tool.name,\n description: tool.description,\n inputSchema: tool.parameters?.jsonSchema || tool.parameters,\n outputSchema: tool.outputSchema?.jsonSchema || tool.outputSchema,\n toolType: tool.toolType,\n };\n }\n\n /**\n * Executes a specific tool provided by this MCP server.\n *\n * This method validates the tool arguments against the input schema and executes the tool.\n * If validation fails, returns an error object instead of throwing.\n *\n * @param toolId - The ID/name of the tool to execute\n * @param args - The arguments to pass to the tool's execute function\n * @param executionContext - Optional context including messages and toolCallId\n * @returns Promise resolving to the tool execution result\n * @throws {MastraError} If the tool is not found or execution fails\n *\n * @example\n * ```typescript\n * const result = await server.executeTool(\n * 'getWeather',\n * { location: 'London' },\n * { toolCallId: 'call_123' }\n * );\n * console.log(result);\n * ```\n */\n public async executeTool(\n toolId: string,\n args: any,\n executionContext?: { messages?: any[]; toolCallId?: string },\n ): Promise<any> {\n const tool = this.convertedTools[toolId];\n let validatedArgs = args;\n try {\n if (!tool) {\n this.logger.warn(`ExecuteTool: Unknown tool '${toolId}' requested on MCPServer '${this.name}'.`);\n throw new Error(`Unknown tool: ${toolId}`);\n }\n\n this.logger.debug(`ExecuteTool: Invoking '${toolId}' with arguments:`, args);\n\n if (tool.parameters instanceof z.ZodType && typeof tool.parameters.safeParse === 'function') {\n const validation = tool.parameters.safeParse(args ?? {});\n if (!validation.success) {\n const errorMessages = validation.error.errors\n .map((e: z.ZodIssue) => `- ${e.path?.join('.') || 'root'}: ${e.message}`)\n .join('\\n');\n this.logger.warn(`ExecuteTool: Invalid tool arguments for '${toolId}': ${errorMessages}`, {\n errors: validation.error.format(),\n });\n // Return validation error as a result instead of throwing\n return {\n error: true,\n message: `Tool validation failed. Please fix the following errors and try again:\\n${errorMessages}\\n\\nProvided arguments: ${JSON.stringify(args, null, 2)}`,\n validationErrors: validation.error.format(),\n };\n }\n validatedArgs = validation.data;\n } else {\n this.logger.debug(\n `ExecuteTool: Tool '${toolId}' parameters is not a Zod schema with safeParse or is undefined. Skipping validation.`,\n );\n }\n\n if (!tool.execute) {\n this.logger.error(`ExecuteTool: Tool '${toolId}' does not have an execute function.`);\n throw new Error(`Tool '${toolId}' cannot be executed.`);\n }\n } catch (error) {\n const mastraError = new MastraError(\n {\n id: 'MCP_SERVER_TOOL_EXECUTE_PREPARATION_FAILED',\n domain: ErrorDomain.MCP,\n category: ErrorCategory.USER,\n details: {\n toolId,\n args,\n },\n },\n error,\n );\n this.logger.trackException(mastraError);\n throw mastraError;\n }\n\n try {\n const finalExecutionContext = {\n messages: executionContext?.messages || [],\n toolCallId: executionContext?.toolCallId || randomUUID(),\n };\n const result = await tool.execute(validatedArgs, finalExecutionContext);\n this.logger.info(`ExecuteTool: Tool '${toolId}' executed successfully.`);\n return result;\n } catch (error) {\n const mastraError = new MastraError(\n {\n id: 'MCP_SERVER_TOOL_EXECUTE_FAILED',\n domain: ErrorDomain.MCP,\n category: ErrorCategory.USER,\n details: {\n toolId,\n validatedArgs: validatedArgs,\n },\n },\n error,\n );\n this.logger.trackException(mastraError);\n this.logger.error(`ExecuteTool: Tool execution failed for '${toolId}':`, { error });\n throw mastraError;\n }\n }\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/client/elicitationActions.ts","../src/client/promptActions.ts","../src/client/resourceActions.ts","../src/client/client.ts","../src/client/configuration.ts","../../../node_modules/.pnpm/hono@4.10.3/node_modules/hono/dist/utils/stream.js","../../../node_modules/.pnpm/hono@4.10.3/node_modules/hono/dist/helper/streaming/utils.js","../../../node_modules/.pnpm/hono@4.10.3/node_modules/hono/dist/utils/html.js","../../../node_modules/.pnpm/hono@4.10.3/node_modules/hono/dist/helper/streaming/sse.js","../../../node_modules/.pnpm/hono-mcp-server-sse-transport@0.0.7_@modelcontextprotocol+sdk@1.20.1_hono@4.10.3/node_modules/hono-mcp-server-sse-transport/build/sse.js","../src/server/promptActions.ts","../src/server/resourceActions.ts","../src/server/server.ts"],"names":["ErrorCode","convertJsonSchemaToZodV3","MastraBase","DEFAULT_REQUEST_TIMEOUT_MSEC","existingInstance","MastraError","ErrorDomain","ErrorCategory","uuidv5","stream","request","z","createTool","run"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgBO,IAAM,2BAAN,MAA+B;AAAA,EACnB,MAAA;AAAA,EACA,MAAA;AAAA;AAAA;AAAA;AAAA,EAKjB,WAAA,CAAY,EAAE,MAAA,EAAQ,MAAA,EAAO,EAAmC;AAC9D,IAAA,IAAA,CAAK,MAAA,GAAS,MAAA;AACd,IAAA,IAAA,CAAK,MAAA,GAAS,MAAA;AAAA,EAChB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAA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ACtC,MAAA,MAAM,WAAA;AAAA,IACR;AAEA,IAAA,IAAI;AACF,MAAA,MAAM,qBAAA,GAAwB;AAAA,QAC5B,QAAA,EAAU,gBAAA,EAAkB,QAAA,IAAY,EAAC;AAAA,QACzC,UAAA,EAAY,gBAAA,EAAkB,UAAA,IAAc,UAAA;AAAW,OACzD;AACA,MAAA,MAAM,MAAA,GAAS,MAAM,IAAA,CAAK,OAAA,CAAQ,eAAe,qBAAqB,CAAA;AACtE,MAAA,IAAA,CAAK,MAAA,CAAO,IAAA,CAAK,CAAA,mBAAA,EAAsB,MAAM,CAAA,wBAAA,CAA0B,CAAA;AACvE,MAAA,OAAO,MAAA;AAAA,IACT,SAAS,KAAA,EAAO;AACd,MAAA,MAAM,cAAc,IAAIF,WAAAA;AAAA,QACtB;AAAA,UACE,EAAA,EAAI,gCAAA;AAAA,UACJ,QAAQC,WAAAA,CAAY,GAAA;AAAA,UACpB,UAAUC,aAAAA,CAAc,IAAA;AAAA,UACxB,OAAA,EAAS;AAAA,YACP,MAAA;AAAA,YACA;AAAA;AACF,SACF;AAAA,QACA;AAAA,OACF;AACA,MAAA,IAAA,CAAK,MAAA,CAAO,eAAe,WAAW,CAAA;AACtC,MAAA,IAAA,CAAK,OAAO,KAAA,CAAM,CAAA,wCAAA,EAA2C,MAAM,CAAA,EAAA,CAAA,EAAM,EAAE,OAAO,CAAA;AAClF,MAAA,MAAM,WAAA;AAAA,IACR;AAAA,EACF;AACF","file":"index.js","sourcesContent":["import type { IMastraLogger } from '@mastra/core/logger';\nimport type { ElicitRequest, ElicitResult } from '@modelcontextprotocol/sdk/types.js';\nimport type { InternalMastraMCPClient } from './client';\n\ninterface ElicitationClientActionsConfig {\n client: InternalMastraMCPClient;\n logger: IMastraLogger;\n}\n\n/**\n * Client-side elicitation actions for handling interactive user input requests.\n *\n * Elicitation allows MCP servers to request structured information from users during\n * tool execution. The client provides a handler that collects user input and returns\n * it to the server.\n */\nexport class ElicitationClientActions {\n private readonly client: InternalMastraMCPClient;\n private readonly logger: IMastraLogger;\n\n /**\n * @internal\n */\n constructor({ client, logger }: ElicitationClientActionsConfig) {\n this.client = client;\n this.logger = logger;\n }\n\n /**\n * Sets a handler function for processing elicitation requests from the server.\n *\n * The handler is called when the server needs to collect user input during tool execution.\n * The handler must return a response with action ('accept', 'decline', or 'cancel') and\n * optional content matching the requested schema.\n *\n * @param handler - Callback function to handle elicitation requests\n *\n * @example\n * ```typescript\n * client.elicitation.onRequest(async (request) => {\n * console.log('Server message:', request.message);\n * console.log('Requested schema:', request.requestedSchema);\n *\n * // Collect user input (e.g., via CLI prompt or UI form)\n * const userInput = await collectUserInput(request.requestedSchema);\n *\n * return {\n * action: 'accept',\n * content: userInput\n * };\n * });\n * ```\n *\n * @example\n * ```typescript\n * // Declining an elicitation request\n * client.elicitation.onRequest(async (request) => {\n * if (!shouldAcceptRequest(request)) {\n * return { action: 'decline' };\n * }\n *\n * const input = await getInput();\n * return { action: 'accept', content: input };\n * });\n * ```\n */\n public onRequest(handler: (request: ElicitRequest['params']) => Promise<ElicitResult>): void {\n this.client.setElicitationRequestHandler(handler);\n }\n}\n","import type { IMastraLogger } from '@mastra/core/logger';\nimport { ErrorCode } from '@modelcontextprotocol/sdk/types.js';\nimport type { GetPromptResult, Prompt } from '@modelcontextprotocol/sdk/types.js';\nimport type { InternalMastraMCPClient } from './client';\n\ninterface PromptClientActionsConfig {\n client: InternalMastraMCPClient;\n logger: IMastraLogger;\n}\n\n/**\n * Client-side prompt actions for interacting with MCP server prompts.\n *\n * Provides methods to list, retrieve, and subscribe to prompt templates exposed by an MCP server.\n * Prompts are reusable message templates that can be parameterized and used for AI interactions.\n */\nexport class PromptClientActions {\n private readonly client: InternalMastraMCPClient;\n private readonly logger: IMastraLogger;\n\n /**\n * @internal\n */\n constructor({ client, logger }: PromptClientActionsConfig) {\n this.client = client;\n this.logger = logger;\n }\n\n /**\n * Retrieves all available prompts from the connected MCP server.\n *\n * Returns an empty array if the server doesn't support prompts (MethodNotFound error).\n *\n * @returns Promise resolving to array of prompts with their metadata\n * @throws {Error} If fetching prompts fails (excluding MethodNotFound)\n *\n * @example\n * ```typescript\n * const prompts = await client.prompts.list();\n * prompts.forEach(prompt => {\n * console.log(`${prompt.name} (v${prompt.version}): ${prompt.description}`);\n * });\n * ```\n */\n public async list(): Promise<Prompt[]> {\n try {\n const response = await this.client.listPrompts();\n if (response && response.prompts && Array.isArray(response.prompts)) {\n return response.prompts.map(prompt => ({ ...prompt, version: prompt.version || '' }));\n } else {\n this.logger.warn(`Prompts response from server ${this.client.name} did not have expected structure.`, {\n response,\n });\n return [];\n }\n } catch (e: any) {\n // MCP Server might not support prompts, so we return an empty array\n if (e.code === ErrorCode.MethodNotFound) {\n return [];\n }\n this.logger.error(`Error getting prompts from server ${this.client.name}`, {\n error: e instanceof Error ? e.message : String(e),\n });\n throw new Error(\n `Failed to fetch prompts from server ${this.client.name}: ${e instanceof Error ? e.stack || e.message : String(e)}`,\n );\n }\n }\n\n /**\n * Retrieves a specific prompt with its messages from the MCP server.\n *\n * Prompts can accept arguments to parameterize the template. The returned messages\n * can be used directly in AI chat completions.\n *\n * @param params - Parameters for the prompt request\n * @param params.name - Name of the prompt to retrieve\n * @param params.args - Optional arguments to populate the prompt template\n * @param params.version - Optional specific version of the prompt to retrieve\n * @returns Promise resolving to the prompt result with messages\n * @throws {Error} If fetching the prompt fails or prompt not found\n *\n * @example\n * ```typescript\n * const prompt = await client.prompts.get({\n * name: 'code-review',\n * args: {\n * language: 'typescript',\n * code: 'const x = 1;'\n * },\n * version: '1.0'\n * });\n *\n * // Use prompt messages in AI completion\n * console.log(prompt.messages);\n * ```\n */\n public async get({\n name,\n args,\n version,\n }: {\n name: string;\n args?: Record<string, any>;\n version?: string;\n }): Promise<GetPromptResult> {\n return this.client.getPrompt({ name, args, version });\n }\n\n /**\n * Sets a notification handler for when the list of available prompts changes.\n *\n * The handler is called when prompts are added, removed, or modified on the server.\n *\n * @param handler - Callback function invoked when the prompt list changes\n *\n * @example\n * ```typescript\n * await client.prompts.onListChanged(async () => {\n * console.log('Prompt list changed, re-fetching...');\n * const prompts = await client.prompts.list();\n * console.log('Available prompts:', prompts.map(p => p.name));\n * });\n * ```\n */\n public async onListChanged(handler: () => void): Promise<void> {\n this.client.setPromptListChangedNotificationHandler(handler);\n }\n}\n","import type { IMastraLogger } from '@mastra/core/logger';\nimport { ErrorCode } from '@modelcontextprotocol/sdk/types.js';\nimport type { Resource, ResourceTemplate } from '@modelcontextprotocol/sdk/types.js';\nimport type { InternalMastraMCPClient } from './client';\n\ninterface ResourceClientActionsConfig {\n client: InternalMastraMCPClient;\n logger: IMastraLogger;\n}\n\n/**\n * Client-side resource actions for interacting with MCP server resources.\n *\n * Provides methods to list, read, subscribe to, and manage resources exposed by an MCP server.\n * Resources represent any kind of data that a server wants to make available (files, database\n * records, API responses, etc.).\n */\nexport class ResourceClientActions {\n private readonly client: InternalMastraMCPClient;\n private readonly logger: IMastraLogger;\n\n /**\n * @internal\n */\n constructor({ client, logger }: ResourceClientActionsConfig) {\n this.client = client;\n this.logger = logger;\n }\n\n /**\n * Retrieves all available resources from the connected MCP server.\n *\n * Returns an empty array if the server doesn't support resources (MethodNotFound error).\n *\n * @returns Promise resolving to array of resources\n * @throws {Error} If fetching resources fails (excluding MethodNotFound)\n *\n * @example\n * ```typescript\n * const resources = await client.resources.list();\n * resources.forEach(resource => {\n * console.log(`${resource.name}: ${resource.uri}`);\n * });\n * ```\n */\n public async list(): Promise<Resource[]> {\n try {\n const response = await this.client.listResources();\n if (response && response.resources && Array.isArray(response.resources)) {\n return response.resources;\n } else {\n this.logger.warn(`Resources response from server ${this.client.name} did not have expected structure.`, {\n response,\n });\n return [];\n }\n } catch (e: any) {\n // MCP Server might not support resources, so we return an empty array\n if (e.code === ErrorCode.MethodNotFound) {\n return [];\n }\n this.logger.error(`Error getting resources from server ${this.client.name}`, {\n error: e instanceof Error ? e.message : String(e),\n });\n throw new Error(\n `Failed to fetch resources from server ${this.client.name}: ${e instanceof Error ? e.stack || e.message : String(e)}`,\n );\n }\n }\n\n /**\n * Retrieves all available resource templates from the connected MCP server.\n *\n * Resource templates are URI templates (RFC 6570) that describe dynamic resources.\n * Returns an empty array if the server doesn't support resource templates.\n *\n * @returns Promise resolving to array of resource templates\n * @throws {Error} If fetching resource templates fails (excluding MethodNotFound)\n *\n * @example\n * ```typescript\n * const templates = await client.resources.templates();\n * templates.forEach(template => {\n * console.log(`${template.name}: ${template.uriTemplate}`);\n * });\n * ```\n */\n public async templates(): Promise<ResourceTemplate[]> {\n try {\n const response = await this.client.listResourceTemplates();\n if (response && response.resourceTemplates && Array.isArray(response.resourceTemplates)) {\n return response.resourceTemplates;\n } else {\n this.logger.warn(\n `Resource templates response from server ${this.client.name} did not have expected structure.`,\n { response },\n );\n return [];\n }\n } catch (e: any) {\n // MCP Server might not support resources, so we return an empty array\n if (e.code === ErrorCode.MethodNotFound) {\n return [];\n }\n this.logger.error(`Error getting resource templates from server ${this.client.name}`, {\n error: e instanceof Error ? e.message : String(e),\n });\n throw new Error(\n `Failed to fetch resource templates from server ${this.client.name}: ${e instanceof Error ? e.stack || e.message : String(e)}`,\n );\n }\n }\n\n /**\n * Reads the content of a specific resource from the MCP server.\n *\n * @param uri - URI of the resource to read (e.g., 'file://path/to/file.txt')\n * @returns Promise resolving to the resource content\n * @throws {Error} If reading the resource fails or resource not found\n *\n * @example\n * ```typescript\n * const result = await client.resources.read('file://data/config.json');\n * console.log(result.contents[0].text); // Resource text content\n * ```\n */\n public async read(uri: string) {\n return this.client.readResource(uri);\n }\n\n /**\n * Subscribes to updates for a specific resource.\n *\n * After subscribing, you'll receive notifications via the `onUpdated` handler\n * when the resource content changes.\n *\n * @param uri - URI of the resource to subscribe to\n * @returns Promise resolving when subscription is established\n * @throws {Error} If subscription fails\n *\n * @example\n * ```typescript\n * await client.resources.subscribe('file://data/config.json');\n * ```\n */\n public async subscribe(uri: string) {\n return this.client.subscribeResource(uri);\n }\n\n /**\n * Unsubscribes from updates for a specific resource.\n *\n * Stops receiving notifications for this resource URI.\n *\n * @param uri - URI of the resource to unsubscribe from\n * @returns Promise resolving when unsubscription is complete\n * @throws {Error} If unsubscription fails\n *\n * @example\n * ```typescript\n * await client.resources.unsubscribe('file://data/config.json');\n * ```\n */\n public async unsubscribe(uri: string) {\n return this.client.unsubscribeResource(uri);\n }\n\n /**\n * Sets a notification handler for when subscribed resources are updated.\n *\n * The handler is called whenever the server sends a resource update notification\n * for any resource you've subscribed to.\n *\n * @param handler - Callback function receiving the updated resource URI\n *\n * @example\n * ```typescript\n * await client.resources.onUpdated(async (params) => {\n * console.log(`Resource updated: ${params.uri}`);\n * // Re-fetch the resource\n * const content = await client.resources.read(params.uri);\n * console.log('New content:', content);\n * });\n * ```\n */\n public async onUpdated(handler: (params: { uri: string }) => void): Promise<void> {\n this.client.setResourceUpdatedNotificationHandler(handler);\n }\n\n /**\n * Sets a notification handler for when the list of available resources changes.\n *\n * The handler is called when resources are added or removed from the server.\n *\n * @param handler - Callback function invoked when the resource list changes\n *\n * @example\n * ```typescript\n * await client.resources.onListChanged(async () => {\n * console.log('Resource list changed, re-fetching...');\n * const resources = await client.resources.list();\n * console.log('Updated resource count:', resources.length);\n * });\n * ```\n */\n public async onListChanged(handler: () => void): Promise<void> {\n this.client.setResourceListChangedNotificationHandler(handler);\n }\n}\n","import $RefParser from '@apidevtools/json-schema-ref-parser';\nimport { MastraBase } from '@mastra/core/base';\nimport type { RequestContext } from '@mastra/core/di';\nimport { ErrorCategory, ErrorDomain, MastraError } from '@mastra/core/error';\nimport { createTool } from '@mastra/core/tools';\nimport type { Tool } from '@mastra/core/tools';\nimport { isZodType } from '@mastra/core/utils';\nimport { Client } from '@modelcontextprotocol/sdk/client/index.js';\nimport { SSEClientTransport } from '@modelcontextprotocol/sdk/client/sse.js';\nimport type { SSEClientTransportOptions } from '@modelcontextprotocol/sdk/client/sse.js';\nimport { getDefaultEnvironment, StdioClientTransport } from '@modelcontextprotocol/sdk/client/stdio.js';\nimport { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js';\nimport type { StreamableHTTPClientTransportOptions } from '@modelcontextprotocol/sdk/client/streamableHttp.js';\nimport { DEFAULT_REQUEST_TIMEOUT_MSEC } from '@modelcontextprotocol/sdk/shared/protocol.js';\nimport type { Transport } from '@modelcontextprotocol/sdk/shared/transport.js';\nimport type {\n ClientCapabilities,\n ElicitRequest,\n ElicitResult,\n GetPromptResult,\n ListPromptsResult,\n LoggingLevel,\n} from '@modelcontextprotocol/sdk/types.js';\nimport {\n CallToolResultSchema,\n ListResourcesResultSchema,\n ReadResourceResultSchema,\n ResourceListChangedNotificationSchema,\n ResourceUpdatedNotificationSchema,\n ListResourceTemplatesResultSchema,\n ListPromptsResultSchema,\n GetPromptResultSchema,\n PromptListChangedNotificationSchema,\n ElicitRequestSchema,\n} from '@modelcontextprotocol/sdk/types.js';\n\nimport { asyncExitHook, gracefulExit } from 'exit-hook';\nimport { z } from 'zod';\nimport { convertJsonSchemaToZod } from 'zod-from-json-schema';\nimport { convertJsonSchemaToZod as convertJsonSchemaToZodV3 } from 'zod-from-json-schema-v3';\nimport type { JSONSchema } from 'zod-from-json-schema-v3';\nimport { ElicitationClientActions } from './elicitationActions';\nimport { PromptClientActions } from './promptActions';\nimport { ResourceClientActions } from './resourceActions';\n\n// Re-export MCP SDK LoggingLevel for convenience\nexport type { LoggingLevel } from '@modelcontextprotocol/sdk/types.js';\n\n/**\n * Log message structure for MCP client logging.\n */\nexport interface LogMessage {\n /** Logging level (debug, info, warning, error, etc.) */\n level: LoggingLevel;\n /** Log message content */\n message: string;\n /** Timestamp when the log was created */\n timestamp: Date;\n /** Name of the MCP server that generated the log */\n serverName: string;\n /** Optional additional details */\n details?: Record<string, any>;\n requestContext?: RequestContext | null;\n}\n\n/**\n * Handler function for processing log messages from MCP servers.\n */\nexport type LogHandler = (logMessage: LogMessage) => void;\n\n/**\n * Handler function for processing elicitation requests from MCP servers.\n *\n * @param request - The elicitation request parameters including message and schema\n * @returns Promise resolving to the user's response (accept/decline/cancel with optional content)\n */\nexport type ElicitationHandler = (request: ElicitRequest['params']) => Promise<ElicitResult>;\n\n/**\n * Base options common to all MCP server definitions.\n */\ntype BaseServerOptions = {\n /** Optional handler for server log messages */\n logger?: LogHandler;\n /** Optional timeout in milliseconds for server operations */\n timeout?: number;\n /** Optional client capabilities to advertise to the server */\n capabilities?: ClientCapabilities;\n /** Whether to enable server log forwarding (default: true) */\n enableServerLogs?: boolean;\n};\n\n/**\n * Configuration for MCP servers using stdio (subprocess) transport.\n *\n * Used when the MCP server is spawned as a subprocess that communicates via stdin/stdout.\n */\ntype StdioServerDefinition = BaseServerOptions & {\n /** Command to execute (e.g., 'node', 'python', 'npx') */\n command: string;\n /** Optional arguments to pass to the command */\n args?: string[];\n /** Optional environment variables for the subprocess */\n env?: Record<string, string>;\n\n url?: never;\n requestInit?: never;\n eventSourceInit?: never;\n authProvider?: never;\n reconnectionOptions?: never;\n sessionId?: never;\n};\n\n/**\n * Configuration for MCP servers using HTTP-based transport (Streamable HTTP or SSE fallback).\n *\n * Used when connecting to remote MCP servers over HTTP. The client will attempt Streamable HTTP\n * transport first and fall back to SSE if that fails.\n */\ntype HttpServerDefinition = BaseServerOptions & {\n /** URL of the MCP server endpoint */\n url: URL;\n\n command?: never;\n args?: never;\n env?: never;\n\n /** Optional request configuration for HTTP requests */\n requestInit?: StreamableHTTPClientTransportOptions['requestInit'];\n /** Optional configuration for SSE fallback (required when using custom headers with SSE) */\n eventSourceInit?: SSEClientTransportOptions['eventSourceInit'];\n /** Optional authentication provider for HTTP requests */\n authProvider?: StreamableHTTPClientTransportOptions['authProvider'];\n /** Optional reconnection configuration for Streamable HTTP */\n reconnectionOptions?: StreamableHTTPClientTransportOptions['reconnectionOptions'];\n /** Optional session ID for Streamable HTTP */\n sessionId?: StreamableHTTPClientTransportOptions['sessionId'];\n};\n\n/**\n * Configuration for connecting to an MCP server.\n *\n * Either stdio-based (subprocess) or HTTP-based (remote server). The transport type is\n * automatically detected based on whether `command` or `url` is provided.\n *\n * @example\n * ```typescript\n * // Stdio server\n * const stdioServer: MastraMCPServerDefinition = {\n * command: 'npx',\n * args: ['tsx', 'server.ts'],\n * env: { API_KEY: 'secret' }\n * };\n *\n * // HTTP server\n * const httpServer: MastraMCPServerDefinition = {\n * url: new URL('http://localhost:8080/mcp'),\n * requestInit: {\n * headers: { Authorization: 'Bearer token' }\n * }\n * };\n * ```\n */\nexport type MastraMCPServerDefinition = StdioServerDefinition | HttpServerDefinition;\n\n/**\n * Convert an MCP LoggingLevel to a logger method name that exists in our logger\n */\nfunction convertLogLevelToLoggerMethod(level: LoggingLevel): 'debug' | 'info' | 'warn' | 'error' {\n switch (level) {\n case 'debug':\n return 'debug';\n case 'info':\n case 'notice':\n return 'info';\n case 'warning':\n return 'warn';\n case 'error':\n case 'critical':\n case 'alert':\n case 'emergency':\n return 'error';\n default:\n // For any other levels, default to info\n return 'info';\n }\n}\n\n/**\n * Options for creating an internal MCP client instance.\n *\n * @internal\n */\nexport type InternalMastraMCPClientOptions = {\n /** Name identifier for this client */\n name: string;\n /** Server connection configuration */\n server: MastraMCPServerDefinition;\n /** Optional client capabilities */\n capabilities?: ClientCapabilities;\n /** Optional client version */\n version?: string;\n /** Optional timeout in milliseconds */\n timeout?: number;\n};\n\n/**\n * Internal MCP client implementation for connecting to a single MCP server.\n *\n * This class handles the low-level connection, transport management, and protocol\n * communication with an MCP server. Most users should use MCPClient instead.\n *\n * @internal\n */\nexport class InternalMastraMCPClient extends MastraBase {\n name: string;\n private client: Client;\n private readonly timeout: number;\n private logHandler?: LogHandler;\n private enableServerLogs?: boolean;\n private serverConfig: MastraMCPServerDefinition;\n private transport?: Transport;\n private currentOperationContext: RequestContext | null = null;\n\n /** Provides access to resource operations (list, read, subscribe, etc.) */\n public readonly resources: ResourceClientActions;\n /** Provides access to prompt operations (list, get, notifications) */\n public readonly prompts: PromptClientActions;\n /** Provides access to elicitation operations (request handling) */\n public readonly elicitation: ElicitationClientActions;\n\n /**\n * @internal\n */\n constructor({\n name,\n version = '1.0.0',\n server,\n capabilities = {},\n timeout = DEFAULT_REQUEST_TIMEOUT_MSEC,\n }: InternalMastraMCPClientOptions) {\n super({ name: 'MastraMCPClient' });\n this.name = name;\n this.timeout = timeout;\n this.logHandler = server.logger;\n this.enableServerLogs = server.enableServerLogs ?? true;\n this.serverConfig = server;\n\n const clientCapabilities = { ...capabilities, elicitation: {} };\n\n this.client = new Client(\n {\n name,\n version,\n },\n {\n capabilities: clientCapabilities,\n },\n );\n\n // Set up log message capturing\n this.setupLogging();\n\n this.resources = new ResourceClientActions({ client: this, logger: this.logger });\n this.prompts = new PromptClientActions({ client: this, logger: this.logger });\n this.elicitation = new ElicitationClientActions({ client: this, logger: this.logger });\n }\n\n /**\n * Log a message at the specified level\n * @param level Log level\n * @param message Log message\n * @param details Optional additional details\n */\n private log(level: LoggingLevel, message: string, details?: Record<string, any>): void {\n // Convert MCP logging level to our logger method\n const loggerMethod = convertLogLevelToLoggerMethod(level);\n\n const msg = `[${this.name}] ${message}`;\n\n // Log to internal logger\n this.logger[loggerMethod](msg, details);\n\n // Send to registered handler if available\n if (this.logHandler) {\n this.logHandler({\n level,\n message: msg,\n timestamp: new Date(),\n serverName: this.name,\n details,\n requestContext: this.currentOperationContext,\n });\n }\n }\n\n private setupLogging(): void {\n if (this.enableServerLogs) {\n this.client.setNotificationHandler(\n z.object({\n method: z.literal('notifications/message'),\n params: z\n .object({\n level: z.string(),\n })\n .passthrough(),\n }),\n notification => {\n const { level, ...params } = notification.params;\n this.log(level as LoggingLevel, '[MCP SERVER LOG]', params);\n },\n );\n }\n }\n\n private async connectStdio(command: string) {\n this.log('debug', `Using Stdio transport for command: ${command}`);\n try {\n this.transport = new StdioClientTransport({\n command,\n args: this.serverConfig.args,\n env: { ...getDefaultEnvironment(), ...(this.serverConfig.env || {}) },\n });\n await this.client.connect(this.transport, { timeout: this.serverConfig.timeout ?? this.timeout });\n this.log('debug', `Successfully connected to MCP server via Stdio`);\n } catch (e) {\n this.log('error', e instanceof Error ? e.stack || e.message : JSON.stringify(e));\n throw e;\n }\n }\n\n private async connectHttp(url: URL) {\n const { requestInit, eventSourceInit, authProvider } = this.serverConfig;\n\n this.log('debug', `Attempting to connect to URL: ${url}`);\n\n // Assume /sse means sse.\n let shouldTrySSE = url.pathname.endsWith(`/sse`);\n\n if (!shouldTrySSE) {\n try {\n // Try Streamable HTTP transport first\n this.log('debug', 'Trying Streamable HTTP transport...');\n const streamableTransport = new StreamableHTTPClientTransport(url, {\n requestInit,\n reconnectionOptions: this.serverConfig.reconnectionOptions,\n authProvider: authProvider,\n });\n await this.client.connect(streamableTransport, {\n timeout:\n // this is hardcoded to 3s because the long default timeout would be extremely slow for sse backwards compat (60s)\n 3000,\n });\n this.transport = streamableTransport;\n this.log('debug', 'Successfully connected using Streamable HTTP transport.');\n } catch (error) {\n this.log('debug', `Streamable HTTP transport failed: ${error}`);\n shouldTrySSE = true;\n }\n }\n\n if (shouldTrySSE) {\n this.log('debug', 'Falling back to deprecated HTTP+SSE transport...');\n try {\n // Fallback to SSE transport\n const sseTransport = new SSEClientTransport(url, { requestInit, eventSourceInit, authProvider });\n await this.client.connect(sseTransport, { timeout: this.serverConfig.timeout ?? this.timeout });\n this.transport = sseTransport;\n this.log('debug', 'Successfully connected using deprecated HTTP+SSE transport.');\n } catch (sseError) {\n this.log(\n 'error',\n `Failed to connect with SSE transport after failing to connect to Streamable HTTP transport first. SSE error: ${sseError}`,\n );\n throw new Error('Could not connect to server with any available HTTP transport');\n }\n }\n }\n\n private isConnected: Promise<boolean> | null = null;\n\n /**\n * Connects to the MCP server using the configured transport.\n *\n * Automatically detects transport type based on configuration (stdio vs HTTP).\n * Safe to call multiple times - returns existing connection if already connected.\n *\n * @returns Promise resolving to true when connected\n * @throws {MastraError} If connection fails\n *\n * @internal\n */\n async connect() {\n // If a connection attempt is in progress, wait for it.\n if (await this.isConnected) {\n return true;\n }\n\n // Start new connection attempt.\n this.isConnected = new Promise<boolean>(async (resolve, reject) => {\n try {\n const { command, url } = this.serverConfig;\n\n if (command) {\n await this.connectStdio(command);\n } else if (url) {\n await this.connectHttp(url);\n } else {\n throw new Error('Server configuration must include either a command or a url.');\n }\n\n resolve(true);\n\n // Set up disconnect handler to reset state.\n const originalOnClose = this.client.onclose;\n this.client.onclose = () => {\n this.log('debug', `MCP server connection closed`);\n this.isConnected = null;\n if (typeof originalOnClose === 'function') {\n originalOnClose();\n }\n };\n } catch (e) {\n this.isConnected = null;\n reject(e);\n }\n });\n\n asyncExitHook(\n async () => {\n this.log('debug', `Disconnecting MCP server during exit`);\n await this.disconnect();\n },\n { wait: 5000 },\n );\n\n process.on('SIGTERM', () => gracefulExit());\n this.log('debug', `Successfully connected to MCP server`);\n return this.isConnected;\n }\n\n /**\n * Gets the current session ID if using Streamable HTTP transport.\n *\n * Returns undefined if not connected or not using Streamable HTTP transport.\n *\n * @returns Session ID string or undefined\n *\n * @internal\n */\n get sessionId(): string | undefined {\n if (this.transport instanceof StreamableHTTPClientTransport) {\n return this.transport.sessionId;\n }\n return undefined;\n }\n\n async disconnect() {\n if (!this.transport) {\n this.log('debug', 'Disconnect called but no transport was connected.');\n return;\n }\n this.log('debug', `Disconnecting from MCP server`);\n try {\n await this.transport.close();\n this.log('debug', 'Successfully disconnected from MCP server');\n } catch (e) {\n this.log('error', 'Error during MCP server disconnect', {\n error: e instanceof Error ? e.stack : JSON.stringify(e, null, 2),\n });\n throw e;\n } finally {\n this.transport = undefined;\n this.isConnected = Promise.resolve(false);\n }\n }\n\n async listResources() {\n this.log('debug', `Requesting resources from MCP server`);\n return await this.client.request({ method: 'resources/list' }, ListResourcesResultSchema, {\n timeout: this.timeout,\n });\n }\n\n async readResource(uri: string) {\n this.log('debug', `Reading resource from MCP server: ${uri}`);\n return await this.client.request({ method: 'resources/read', params: { uri } }, ReadResourceResultSchema, {\n timeout: this.timeout,\n });\n }\n\n async subscribeResource(uri: string) {\n this.log('debug', `Subscribing to resource on MCP server: ${uri}`);\n return await this.client.request({ method: 'resources/subscribe', params: { uri } }, z.object({}), {\n timeout: this.timeout,\n });\n }\n\n async unsubscribeResource(uri: string) {\n this.log('debug', `Unsubscribing from resource on MCP server: ${uri}`);\n return await this.client.request({ method: 'resources/unsubscribe', params: { uri } }, z.object({}), {\n timeout: this.timeout,\n });\n }\n\n async listResourceTemplates() {\n this.log('debug', `Requesting resource templates from MCP server`);\n return await this.client.request({ method: 'resources/templates/list' }, ListResourceTemplatesResultSchema, {\n timeout: this.timeout,\n });\n }\n\n /**\n * Fetch the list of available prompts from the MCP server.\n */\n async listPrompts(): Promise<ListPromptsResult> {\n this.log('debug', `Requesting prompts from MCP server`);\n return await this.client.request({ method: 'prompts/list' }, ListPromptsResultSchema, {\n timeout: this.timeout,\n });\n }\n\n /**\n * Get a prompt and its dynamic messages from the server.\n * @param name The prompt name\n * @param args Arguments for the prompt\n * @param version (optional) The prompt version to retrieve\n */\n async getPrompt({\n name,\n args,\n version,\n }: {\n name: string;\n args?: Record<string, any>;\n version?: string;\n }): Promise<GetPromptResult> {\n this.log('debug', `Requesting prompt from MCP server: ${name}`);\n return await this.client.request(\n { method: 'prompts/get', params: { name, arguments: args, version } },\n GetPromptResultSchema,\n { timeout: this.timeout },\n );\n }\n\n /**\n * Register a handler to be called when the prompt list changes on the server.\n * Use this to refresh cached prompt lists in the client/UI if needed.\n */\n setPromptListChangedNotificationHandler(handler: () => void): void {\n this.log('debug', 'Setting prompt list changed notification handler');\n this.client.setNotificationHandler(PromptListChangedNotificationSchema, () => {\n handler();\n });\n }\n\n setResourceUpdatedNotificationHandler(\n handler: (params: z.infer<typeof ResourceUpdatedNotificationSchema>['params']) => void,\n ): void {\n this.log('debug', 'Setting resource updated notification handler');\n this.client.setNotificationHandler(ResourceUpdatedNotificationSchema, notification => {\n handler(notification.params);\n });\n }\n\n setResourceListChangedNotificationHandler(handler: () => void): void {\n this.log('debug', 'Setting resource list changed notification handler');\n this.client.setNotificationHandler(ResourceListChangedNotificationSchema, () => {\n handler();\n });\n }\n\n setElicitationRequestHandler(handler: ElicitationHandler): void {\n this.log('debug', 'Setting elicitation request handler');\n this.client.setRequestHandler(ElicitRequestSchema, async request => {\n this.log('debug', `Received elicitation request: ${request.params.message}`);\n return handler(request.params);\n });\n }\n\n private async convertInputSchema(\n inputSchema: Awaited<ReturnType<Client['listTools']>>['tools'][0]['inputSchema'] | JSONSchema,\n ): Promise<z.ZodType> {\n if (isZodType(inputSchema)) {\n return inputSchema;\n }\n\n try {\n await $RefParser.dereference(inputSchema);\n const jsonSchemaToConvert = ('jsonSchema' in inputSchema ? inputSchema.jsonSchema : inputSchema) as JSONSchema;\n if ('toJSONSchema' in z) {\n //@ts-expect-error - zod type issue\n return convertJsonSchemaToZod(jsonSchemaToConvert);\n } else {\n return convertJsonSchemaToZodV3(jsonSchemaToConvert);\n }\n } catch (error: unknown) {\n let errorDetails: string | undefined;\n if (error instanceof Error) {\n errorDetails = error.stack;\n } else {\n // Attempt to stringify, fallback to String()\n try {\n errorDetails = JSON.stringify(error);\n } catch {\n errorDetails = String(error);\n }\n }\n this.log('error', 'Failed to convert JSON schema to Zod schema using zodFromJsonSchema', {\n error: errorDetails,\n originalJsonSchema: inputSchema,\n });\n\n throw new MastraError({\n id: 'MCP_TOOL_INPUT_SCHEMA_CONVERSION_FAILED',\n domain: ErrorDomain.MCP,\n category: ErrorCategory.USER,\n details: { error: errorDetails ?? 'Unknown error' },\n });\n }\n }\n\n private async convertOutputSchema(\n outputSchema: Awaited<ReturnType<Client['listTools']>>['tools'][0]['outputSchema'] | JSONSchema,\n ): Promise<z.ZodType | undefined> {\n if (!outputSchema) return;\n if (isZodType(outputSchema)) {\n return outputSchema;\n }\n\n try {\n await $RefParser.dereference(outputSchema);\n const jsonSchemaToConvert = ('jsonSchema' in outputSchema ? outputSchema.jsonSchema : outputSchema) as JSONSchema;\n if ('toJSONSchema' in z) {\n //@ts-expect-error - zod type issue\n return convertJsonSchemaToZod(jsonSchemaToConvert);\n } else {\n return convertJsonSchemaToZodV3(jsonSchemaToConvert);\n }\n } catch (error: unknown) {\n let errorDetails: string | undefined;\n if (error instanceof Error) {\n errorDetails = error.stack;\n } else {\n // Attempt to stringify, fallback to String()\n try {\n errorDetails = JSON.stringify(error);\n } catch {\n errorDetails = String(error);\n }\n }\n this.log('error', 'Failed to convert JSON schema to Zod schema using zodFromJsonSchema', {\n error: errorDetails,\n originalJsonSchema: outputSchema,\n });\n\n throw new MastraError({\n id: 'MCP_TOOL_OUTPUT_SCHEMA_CONVERSION_FAILED',\n domain: ErrorDomain.MCP,\n category: ErrorCategory.USER,\n details: { error: errorDetails ?? 'Unknown error' },\n });\n }\n }\n\n async tools(): Promise<Record<string, Tool<any, any, any, any>>> {\n this.log('debug', `Requesting tools from MCP server`);\n const { tools } = await this.client.listTools({ timeout: this.timeout });\n const toolsRes: Record<string, Tool<any, any, any, any>> = {};\n for (const tool of tools) {\n this.log('debug', `Processing tool: ${tool.name}`);\n try {\n const mastraTool = createTool({\n id: `${this.name}_${tool.name}`,\n description: tool.description || '',\n inputSchema: await this.convertInputSchema(tool.inputSchema),\n outputSchema: await this.convertOutputSchema(tool.outputSchema),\n execute: async (input: any, context?: { requestContext?: RequestContext | null }) => {\n const previousContext = this.currentOperationContext;\n this.currentOperationContext = context?.requestContext || null; // Set current context\n try {\n this.log('debug', `Executing tool: ${tool.name}`, { toolArgs: input });\n const res = await this.client.callTool(\n {\n name: tool.name,\n arguments: input,\n },\n CallToolResultSchema,\n {\n timeout: this.timeout,\n },\n );\n\n this.log('debug', `Tool executed successfully: ${tool.name}`);\n return res;\n } catch (e) {\n this.log('error', `Error calling tool: ${tool.name}`, {\n error: e instanceof Error ? e.stack : JSON.stringify(e, null, 2),\n toolArgs: input,\n });\n throw e;\n } finally {\n this.currentOperationContext = previousContext; // Restore previous context\n }\n },\n });\n\n if (tool.name) {\n toolsRes[tool.name] = mastraTool;\n }\n } catch (toolCreationError: unknown) {\n // Catch errors during tool creation itself (e.g., if createTool has issues)\n this.log('error', `Failed to create Mastra tool wrapper for MCP tool: ${tool.name}`, {\n error: toolCreationError instanceof Error ? toolCreationError.stack : String(toolCreationError),\n mcpToolDefinition: tool,\n });\n }\n }\n\n return toolsRes;\n }\n}\n","import { MastraBase } from '@mastra/core/base';\nimport { ErrorCategory, ErrorDomain, MastraError } from '@mastra/core/error';\nimport type { Tool } from '@mastra/core/tools';\nimport { DEFAULT_REQUEST_TIMEOUT_MSEC } from '@modelcontextprotocol/sdk/shared/protocol.js';\nimport type {\n ElicitRequest,\n ElicitResult,\n Prompt,\n Resource,\n ResourceTemplate,\n} from '@modelcontextprotocol/sdk/types.js';\nimport equal from 'fast-deep-equal';\nimport { v5 as uuidv5 } from 'uuid';\nimport { InternalMastraMCPClient } from './client';\nimport type { MastraMCPServerDefinition } from './client';\n\nconst mcpClientInstances = new Map<string, InstanceType<typeof MCPClient>>();\n\n/**\n * Configuration options for creating an MCPClient instance.\n */\nexport interface MCPClientOptions {\n /** Optional unique identifier to prevent memory leaks when creating multiple instances with identical configurations */\n id?: string;\n /** Map of server names to their connection configurations (stdio or HTTP-based) */\n servers: Record<string, MastraMCPServerDefinition>;\n /** Optional global timeout in milliseconds for all servers (default: 60000ms) */\n timeout?: number;\n}\n\n/**\n * MCPClient manages multiple MCP server connections and their tools in a Mastra application.\n *\n * This class handles connection lifecycle, tool namespacing, and provides access to tools,\n * resources, prompts, and elicitation across all configured servers.\n *\n * @example\n * ```typescript\n * import { MCPClient } from '@mastra/mcp';\n * import { Agent } from '@mastra/core/agent';\n *\n * const mcp = new MCPClient({\n * servers: {\n * weather: {\n * url: new URL('http://localhost:8080/sse'),\n * },\n * stockPrice: {\n * command: 'npx',\n * args: ['tsx', 'stock-price.ts'],\n * env: { API_KEY: 'your-api-key' },\n * },\n * },\n * timeout: 30000,\n * });\n *\n * const agent = new Agent({\n * id: 'multi-tool-agent',\n * name: 'Multi-tool Agent',\n * instructions: 'You have access to multiple tools.',\n * model: 'openai/gpt-4o',\n * tools: await mcp.listTools(),\n * });\n * ```\n */\nexport class MCPClient extends MastraBase {\n private serverConfigs: Record<string, MastraMCPServerDefinition> = {};\n private id: string;\n private defaultTimeout: number;\n private mcpClientsById = new Map<string, InternalMastraMCPClient>();\n private disconnectPromise: Promise<void> | null = null;\n\n /**\n * Creates a new MCPClient instance for managing MCP server connections.\n *\n * The client automatically manages connection lifecycle and prevents memory leaks by\n * caching instances with identical configurations.\n *\n * @param args - Configuration options\n * @param args.id - Optional unique identifier to allow multiple instances with same config\n * @param args.servers - Map of server names to server configurations\n * @param args.timeout - Optional global timeout in milliseconds (default: 60000)\n *\n * @throws {Error} If multiple instances with identical config are created without an ID\n *\n * @example\n * ```typescript\n * const mcp = new MCPClient({\n * servers: {\n * weatherServer: {\n * url: new URL('http://localhost:8080/sse'),\n * requestInit: {\n * headers: { Authorization: 'Bearer token' }\n * }\n * }\n * },\n * timeout: 30000\n * });\n * ```\n */\n constructor(args: MCPClientOptions) {\n super({ name: 'MCPClient' });\n this.defaultTimeout = args.timeout ?? DEFAULT_REQUEST_TIMEOUT_MSEC;\n this.serverConfigs = args.servers;\n this.id = args.id ?? this.makeId();\n\n if (args.id) {\n this.id = args.id;\n const cached = mcpClientInstances.get(this.id);\n\n if (cached && !equal(cached.serverConfigs, args.servers)) {\n const existingInstance = mcpClientInstances.get(this.id);\n if (existingInstance) {\n void existingInstance.disconnect();\n mcpClientInstances.delete(this.id);\n }\n }\n } else {\n this.id = this.makeId();\n }\n\n // to prevent memory leaks return the same MCP server instance when configured the same way multiple times\n const existingInstance = mcpClientInstances.get(this.id);\n if (existingInstance) {\n if (!args.id) {\n throw new Error(`MCPClient was initialized multiple times with the same configuration options.\n\nThis error is intended to prevent memory leaks.\n\nTo fix this you have three different options:\n1. If you need multiple MCPClient class instances with identical server configurations, set an id when configuring: new MCPClient({ id: \"my-unique-id\" })\n2. Call \"await client.disconnect()\" after you're done using the client and before you recreate another instance with the same options. If the identical MCPClient instance is already closed at the time of re-creating it, you will not see this error.\n3. If you only need one instance of MCPClient in your app, refactor your code so it's only created one time (ex. move it out of a loop into a higher scope code block)\n`);\n }\n return existingInstance;\n }\n\n mcpClientInstances.set(this.id, this);\n this.addToInstanceCache();\n return this;\n }\n /**\n * Provides access to elicitation-related operations for interactive user input collection.\n *\n * Elicitation allows MCP servers to request structured information from users during tool execution.\n *\n * @example\n * ```typescript\n * // Set up handler for elicitation requests from a server\n * await mcp.elicitation.onRequest('serverName', async (request) => {\n * console.log(`Server requests: ${request.message}`);\n * console.log('Schema:', request.requestedSchema);\n *\n * // Collect user input and return response\n * return {\n * action: 'accept',\n * content: { name: 'John Doe', email: 'john@example.com' }\n * };\n * });\n * ```\n */\n public get elicitation() {\n this.addToInstanceCache();\n return {\n /**\n * Sets up a handler function for elicitation requests from a specific server.\n *\n * The handler receives requests for user input and must return a response with\n * action ('accept', 'decline', or 'cancel') and optional content.\n *\n * @param serverName - Name of the server to handle elicitation requests for\n * @param handler - Function to handle elicitation requests\n * @throws {MastraError} If setting up the handler fails\n *\n * @example\n * ```typescript\n * await mcp.elicitation.onRequest('weatherServer', async (request) => {\n * // Prompt user for input\n * const userInput = await promptUser(request.requestedSchema);\n * return { action: 'accept', content: userInput };\n * });\n * ```\n */\n onRequest: async (serverName: string, handler: (request: ElicitRequest['params']) => Promise<ElicitResult>) => {\n try {\n const internalClient = await this.getConnectedClientForServer(serverName);\n return internalClient.elicitation.onRequest(handler);\n } catch (err) {\n throw new MastraError(\n {\n id: 'MCP_CLIENT_ON_REQUEST_ELICITATION_FAILED',\n domain: ErrorDomain.MCP,\n category: ErrorCategory.THIRD_PARTY,\n details: {\n serverName,\n },\n },\n err,\n );\n }\n },\n };\n }\n\n /**\n * Provides access to resource-related operations across all configured servers.\n *\n * Resources represent data exposed by MCP servers (files, database records, API responses, etc.).\n *\n * @example\n * ```typescript\n * // List all resources from all servers\n * const allResources = await mcp.resources.list();\n * Object.entries(allResources).forEach(([serverName, resources]) => {\n * console.log(`${serverName}: ${resources.length} resources`);\n * });\n *\n * // Read a specific resource\n * const content = await mcp.resources.read('weatherServer', 'file://data.json');\n *\n * // Subscribe to resource updates\n * await mcp.resources.subscribe('weatherServer', 'file://data.json');\n * await mcp.resources.onUpdated('weatherServer', async (params) => {\n * console.log(`Resource updated: ${params.uri}`);\n * });\n * ```\n */\n public get resources() {\n this.addToInstanceCache();\n return {\n /**\n * Lists all available resources from all configured servers.\n *\n * Returns a map of server names to their resource arrays. Errors for individual\n * servers are logged but don't throw - failed servers return empty arrays.\n *\n * @returns Promise resolving to object mapping server names to resource arrays\n *\n * @example\n * ```typescript\n * const resources = await mcp.resources.list();\n * console.log(resources.weatherServer); // Array of resources\n * ```\n */\n list: async (): Promise<Record<string, Resource[]>> => {\n const allResources: Record<string, Resource[]> = {};\n for (const serverName of Object.keys(this.serverConfigs)) {\n try {\n const internalClient = await this.getConnectedClientForServer(serverName);\n allResources[serverName] = await internalClient.resources.list();\n } catch (error) {\n const mastraError = new MastraError(\n {\n id: 'MCP_CLIENT_LIST_RESOURCES_FAILED',\n domain: ErrorDomain.MCP,\n category: ErrorCategory.THIRD_PARTY,\n details: {\n serverName,\n },\n },\n error,\n );\n this.logger.trackException(mastraError);\n this.logger.error('Failed to list resources from server:', { error: mastraError.toString() });\n }\n }\n return allResources;\n },\n /**\n * Lists all available resource templates from all configured servers.\n *\n * Resource templates are URI templates (RFC 6570) describing dynamic resources.\n * Errors for individual servers are logged but don't throw.\n *\n * @returns Promise resolving to object mapping server names to template arrays\n *\n * @example\n * ```typescript\n * const templates = await mcp.resources.templates();\n * console.log(templates.weatherServer); // Array of resource templates\n * ```\n */\n templates: async (): Promise<Record<string, ResourceTemplate[]>> => {\n const allTemplates: Record<string, ResourceTemplate[]> = {};\n for (const serverName of Object.keys(this.serverConfigs)) {\n try {\n const internalClient = await this.getConnectedClientForServer(serverName);\n allTemplates[serverName] = await internalClient.resources.templates();\n } catch (error) {\n const mastraError = new MastraError(\n {\n id: 'MCP_CLIENT_LIST_RESOURCE_TEMPLATES_FAILED',\n domain: ErrorDomain.MCP,\n category: ErrorCategory.THIRD_PARTY,\n details: {\n serverName,\n },\n },\n error,\n );\n this.logger.trackException(mastraError);\n this.logger.error('Failed to list resource templates from server:', { error: mastraError.toString() });\n }\n }\n return allTemplates;\n },\n /**\n * Reads the content of a specific resource from a server.\n *\n * @param serverName - Name of the server to read from\n * @param uri - URI of the resource to read\n * @returns Promise resolving to the resource content\n * @throws {MastraError} If reading the resource fails\n *\n * @example\n * ```typescript\n * const content = await mcp.resources.read('weatherServer', 'file://config.json');\n * console.log(content.contents[0].text);\n * ```\n */\n read: async (serverName: string, uri: string) => {\n try {\n const internalClient = await this.getConnectedClientForServer(serverName);\n return internalClient.resources.read(uri);\n } catch (error) {\n throw new MastraError(\n {\n id: 'MCP_CLIENT_READ_RESOURCE_FAILED',\n domain: ErrorDomain.MCP,\n category: ErrorCategory.THIRD_PARTY,\n details: {\n serverName,\n uri,\n },\n },\n error,\n );\n }\n },\n /**\n * Subscribes to updates for a specific resource on a server.\n *\n * @param serverName - Name of the server\n * @param uri - URI of the resource to subscribe to\n * @returns Promise resolving when subscription is established\n * @throws {MastraError} If subscription fails\n *\n * @example\n * ```typescript\n * await mcp.resources.subscribe('weatherServer', 'file://config.json');\n * ```\n */\n subscribe: async (serverName: string, uri: string) => {\n try {\n const internalClient = await this.getConnectedClientForServer(serverName);\n return internalClient.resources.subscribe(uri);\n } catch (error) {\n throw new MastraError(\n {\n id: 'MCP_CLIENT_SUBSCRIBE_RESOURCE_FAILED',\n domain: ErrorDomain.MCP,\n category: ErrorCategory.THIRD_PARTY,\n details: {\n serverName,\n uri,\n },\n },\n error,\n );\n }\n },\n /**\n * Unsubscribes from updates for a specific resource on a server.\n *\n * @param serverName - Name of the server\n * @param uri - URI of the resource to unsubscribe from\n * @returns Promise resolving when unsubscription is complete\n * @throws {MastraError} If unsubscription fails\n *\n * @example\n * ```typescript\n * await mcp.resources.unsubscribe('weatherServer', 'file://config.json');\n * ```\n */\n unsubscribe: async (serverName: string, uri: string) => {\n try {\n const internalClient = await this.getConnectedClientForServer(serverName);\n return internalClient.resources.unsubscribe(uri);\n } catch (err) {\n throw new MastraError(\n {\n id: 'MCP_CLIENT_UNSUBSCRIBE_RESOURCE_FAILED',\n domain: ErrorDomain.MCP,\n category: ErrorCategory.THIRD_PARTY,\n details: {\n serverName,\n uri,\n },\n },\n err,\n );\n }\n },\n /**\n * Sets a notification handler for when subscribed resources are updated on a server.\n *\n * @param serverName - Name of the server to monitor\n * @param handler - Callback function receiving the updated resource URI\n * @returns Promise resolving when handler is registered\n * @throws {MastraError} If setting up the handler fails\n *\n * @example\n * ```typescript\n * await mcp.resources.onUpdated('weatherServer', async (params) => {\n * console.log(`Resource updated: ${params.uri}`);\n * const content = await mcp.resources.read('weatherServer', params.uri);\n * });\n * ```\n */\n onUpdated: async (serverName: string, handler: (params: { uri: string }) => void) => {\n try {\n const internalClient = await this.getConnectedClientForServer(serverName);\n return internalClient.resources.onUpdated(handler);\n } catch (err) {\n throw new MastraError(\n {\n id: 'MCP_CLIENT_ON_UPDATED_RESOURCE_FAILED',\n domain: ErrorDomain.MCP,\n category: ErrorCategory.THIRD_PARTY,\n details: {\n serverName,\n },\n },\n err,\n );\n }\n },\n /**\n * Sets a notification handler for when the resource list changes on a server.\n *\n * @param serverName - Name of the server to monitor\n * @param handler - Callback function invoked when resources are added/removed\n * @returns Promise resolving when handler is registered\n * @throws {MastraError} If setting up the handler fails\n *\n * @example\n * ```typescript\n * await mcp.resources.onListChanged('weatherServer', async () => {\n * console.log('Resource list changed, re-fetching...');\n * const resources = await mcp.resources.list();\n * });\n * ```\n */\n onListChanged: async (serverName: string, handler: () => void) => {\n try {\n const internalClient = await this.getConnectedClientForServer(serverName);\n return internalClient.resources.onListChanged(handler);\n } catch (err) {\n throw new MastraError(\n {\n id: 'MCP_CLIENT_ON_LIST_CHANGED_RESOURCE_FAILED',\n domain: ErrorDomain.MCP,\n category: ErrorCategory.THIRD_PARTY,\n details: {\n serverName,\n },\n },\n err,\n );\n }\n },\n };\n }\n\n /**\n * Provides access to prompt-related operations across all configured servers.\n *\n * Prompts are reusable message templates exposed by MCP servers that can be parameterized\n * and used for AI interactions.\n *\n * @example\n * ```typescript\n * // List all prompts from all servers\n * const allPrompts = await mcp.prompts.list();\n * Object.entries(allPrompts).forEach(([serverName, prompts]) => {\n * console.log(`${serverName}: ${prompts.map(p => p.name).join(', ')}`);\n * });\n *\n * // Get a specific prompt with arguments\n * const prompt = await mcp.prompts.get({\n * serverName: 'weatherServer',\n * name: 'forecast-template',\n * args: { city: 'London', days: 7 }\n * });\n * ```\n */\n public get prompts() {\n this.addToInstanceCache();\n return {\n /**\n * Lists all available prompts from all configured servers.\n *\n * Returns a map of server names to their prompt arrays. Errors for individual\n * servers are logged but don't throw - failed servers return empty arrays.\n *\n * @returns Promise resolving to object mapping server names to prompt arrays\n *\n * @example\n * ```typescript\n * const prompts = await mcp.prompts.list();\n * console.log(prompts.weatherServer); // Array of prompts\n * ```\n */\n list: async (): Promise<Record<string, Prompt[]>> => {\n const allPrompts: Record<string, Prompt[]> = {};\n for (const serverName of Object.keys(this.serverConfigs)) {\n try {\n const internalClient = await this.getConnectedClientForServer(serverName);\n allPrompts[serverName] = await internalClient.prompts.list();\n } catch (error) {\n const mastraError = new MastraError(\n {\n id: 'MCP_CLIENT_LIST_PROMPTS_FAILED',\n domain: ErrorDomain.MCP,\n category: ErrorCategory.THIRD_PARTY,\n details: {\n serverName,\n },\n },\n error,\n );\n this.logger.trackException(mastraError);\n this.logger.error('Failed to list prompts from server:', { error: mastraError.toString() });\n }\n }\n return allPrompts;\n },\n /**\n * Retrieves a specific prompt with its messages from a server.\n *\n * @param params - Parameters for the prompt request\n * @param params.serverName - Name of the server to retrieve from\n * @param params.name - Name of the prompt to retrieve\n * @param params.args - Optional arguments to populate the prompt template\n * @param params.version - Optional specific version of the prompt\n * @returns Promise resolving to the prompt result with messages\n * @throws {MastraError} If fetching the prompt fails\n *\n * @example\n * ```typescript\n * const prompt = await mcp.prompts.get({\n * serverName: 'weatherServer',\n * name: 'forecast',\n * args: { city: 'London' },\n * version: '1.0'\n * });\n * console.log(prompt.messages);\n * ```\n */\n get: async ({\n serverName,\n name,\n args,\n version,\n }: {\n serverName: string;\n name: string;\n args?: Record<string, any>;\n version?: string;\n }) => {\n try {\n const internalClient = await this.getConnectedClientForServer(serverName);\n return internalClient.prompts.get({ name, args, version });\n } catch (error) {\n throw new MastraError(\n {\n id: 'MCP_CLIENT_GET_PROMPT_FAILED',\n domain: ErrorDomain.MCP,\n category: ErrorCategory.THIRD_PARTY,\n details: {\n serverName,\n name,\n },\n },\n error,\n );\n }\n },\n /**\n * Sets a notification handler for when the prompt list changes on a server.\n *\n * @param serverName - Name of the server to monitor\n * @param handler - Callback function invoked when prompts are added/removed/modified\n * @returns Promise resolving when handler is registered\n * @throws {MastraError} If setting up the handler fails\n *\n * @example\n * ```typescript\n * await mcp.prompts.onListChanged('weatherServer', async () => {\n * console.log('Prompt list changed, re-fetching...');\n * const prompts = await mcp.prompts.list();\n * });\n * ```\n */\n onListChanged: async (serverName: string, handler: () => void) => {\n try {\n const internalClient = await this.getConnectedClientForServer(serverName);\n return internalClient.prompts.onListChanged(handler);\n } catch (error) {\n throw new MastraError(\n {\n id: 'MCP_CLIENT_ON_LIST_CHANGED_PROMPT_FAILED',\n domain: ErrorDomain.MCP,\n category: ErrorCategory.THIRD_PARTY,\n details: {\n serverName,\n },\n },\n error,\n );\n }\n },\n };\n }\n\n private addToInstanceCache() {\n if (!mcpClientInstances.has(this.id)) {\n mcpClientInstances.set(this.id, this);\n }\n }\n\n private makeId() {\n const text = JSON.stringify(this.serverConfigs).normalize('NFKC');\n const idNamespace = uuidv5(`MCPClient`, uuidv5.DNS);\n\n return uuidv5(text, idNamespace);\n }\n\n /**\n * Disconnects from all MCP servers and cleans up resources.\n *\n * This method gracefully closes all server connections and clears internal caches.\n * Safe to call multiple times - subsequent calls will wait for the first disconnect to complete.\n *\n * @example\n * ```typescript\n * // Cleanup on application shutdown\n * process.on('SIGTERM', async () => {\n * await mcp.disconnect();\n * process.exit(0);\n * });\n * ```\n */\n public async disconnect() {\n // Helps to prevent race condition\n // If there is already a disconnect ongoing, return the existing promise.\n if (this.disconnectPromise) {\n return this.disconnectPromise;\n }\n\n this.disconnectPromise = (async () => {\n try {\n mcpClientInstances.delete(this.id);\n\n // Disconnect all clients in the cache\n await Promise.all(Array.from(this.mcpClientsById.values()).map(client => client.disconnect()));\n this.mcpClientsById.clear();\n } finally {\n this.disconnectPromise = null;\n }\n })();\n\n return this.disconnectPromise;\n }\n\n /**\n * Retrieves all tools from all configured servers with namespaced names.\n *\n * Tool names are namespaced as `serverName_toolName` to prevent conflicts between servers.\n * This method is intended to be passed directly to an Agent definition.\n *\n * @returns Object mapping namespaced tool names to tool implementations\n * @throws {MastraError} If retrieving tools fails\n *\n * @example\n * ```typescript\n * const agent = new Agent({\n * id: 'multi-tool-agent',\n * name: 'Multi-tool Agent',\n * instructions: 'You have access to weather and stock tools.',\n * model: 'openai/gpt-4',\n * tools: await mcp.listTools(), // weather_getWeather, stockPrice_getPrice\n * });\n * ```\n */\n public async listTools(): Promise<Record<string, Tool<any, any, any, any>>> {\n this.addToInstanceCache();\n const connectedTools: Record<string, Tool<any, any, any, any>> = {};\n\n try {\n await this.eachClientTools(async ({ serverName, tools }) => {\n for (const [toolName, toolConfig] of Object.entries(tools)) {\n connectedTools[`${serverName}_${toolName}`] = toolConfig; // namespace tool to prevent tool name conflicts between servers\n }\n });\n } catch (error) {\n throw new MastraError(\n {\n id: 'MCP_CLIENT_GET_TOOLS_FAILED',\n domain: ErrorDomain.MCP,\n category: ErrorCategory.THIRD_PARTY,\n },\n error,\n );\n }\n\n return connectedTools;\n }\n\n /**\n * Returns toolsets organized by server name for dynamic tool injection.\n *\n * Unlike listTools(), this returns tools grouped by server without namespacing.\n * This is intended to be passed dynamically to the generate() or stream() method.\n *\n * @returns Object mapping server names to their tool collections\n * @throws {MastraError} If retrieving toolsets fails\n *\n * @example\n * ```typescript\n * const agent = new Agent({\n * id: 'dynamic-agent',\n * name: 'Dynamic Agent',\n * instructions: 'You can use tools dynamically.',\n * model: 'openai/gpt-4',\n * });\n *\n * const response = await agent.stream(prompt, {\n * toolsets: await mcp.listToolsets(), // { weather: {...}, stockPrice: {...} }\n * });\n * ```\n */\n public async listToolsets(): Promise<Record<string, Record<string, Tool<any, any, any, any>>>> {\n this.addToInstanceCache();\n const connectedToolsets: Record<string, Record<string, Tool<any, any, any, any>>> = {};\n\n try {\n await this.eachClientTools(async ({ serverName, tools }) => {\n if (tools) {\n connectedToolsets[serverName] = tools;\n }\n });\n } catch (error) {\n throw new MastraError(\n {\n id: 'MCP_CLIENT_GET_TOOLSETS_FAILED',\n domain: ErrorDomain.MCP,\n category: ErrorCategory.THIRD_PARTY,\n },\n error,\n );\n }\n\n return connectedToolsets;\n }\n\n /**\n * Gets current session IDs for all connected MCP clients using Streamable HTTP transport.\n *\n * Returns an object mapping server names to their session IDs. Only includes servers\n * that are currently connected via Streamable HTTP transport.\n *\n * @returns Object mapping server names to session IDs\n *\n * @example\n * ```typescript\n * const sessions = mcp.sessionIds;\n * console.log(sessions);\n * // { weatherServer: 'abc-123', stockServer: 'def-456' }\n * ```\n */\n get sessionIds(): Record<string, string> {\n const sessionIds: Record<string, string> = {};\n for (const [serverName, client] of this.mcpClientsById.entries()) {\n if (client.sessionId) {\n sessionIds[serverName] = client.sessionId;\n }\n }\n return sessionIds;\n }\n\n private async getConnectedClient(name: string, config: MastraMCPServerDefinition): Promise<InternalMastraMCPClient> {\n if (this.disconnectPromise) {\n await this.disconnectPromise;\n }\n\n const exists = this.mcpClientsById.has(name);\n const existingClient = this.mcpClientsById.get(name);\n\n this.logger.debug(`getConnectedClient ${name} exists: ${exists}`);\n\n if (exists) {\n // This is just to satisfy Typescript since technically you could have this.mcpClientsById.set('someKey', undefined);\n // Should never reach this point basically we always create a new MastraMCPClient instance when we add to the Map.\n if (!existingClient) {\n throw new Error(`Client ${name} exists but is undefined`);\n }\n await existingClient.connect();\n return existingClient;\n }\n\n this.logger.debug(`Connecting to ${name} MCP server`);\n\n // Create client with server configuration including log handler\n const mcpClient = new InternalMastraMCPClient({\n name,\n server: config,\n timeout: config.timeout ?? this.defaultTimeout,\n });\n\n mcpClient.__setLogger(this.logger);\n\n this.mcpClientsById.set(name, mcpClient);\n\n try {\n await mcpClient.connect();\n } catch (e) {\n const mastraError = new MastraError(\n {\n id: 'MCP_CLIENT_CONNECT_FAILED',\n domain: ErrorDomain.MCP,\n category: ErrorCategory.THIRD_PARTY,\n text: `Failed to connect to MCP server ${name}: ${e instanceof Error ? e.stack || e.message : String(e)}`,\n details: {\n name,\n },\n },\n e,\n );\n this.logger.trackException(mastraError);\n this.logger.error('MCPClient errored connecting to MCP server:', { error: mastraError.toString() });\n this.mcpClientsById.delete(name);\n throw mastraError;\n }\n this.logger.debug(`Connected to ${name} MCP server`);\n return mcpClient;\n }\n\n private async getConnectedClientForServer(serverName: string): Promise<InternalMastraMCPClient> {\n const serverConfig = this.serverConfigs[serverName];\n if (!serverConfig) {\n throw new Error(`Server configuration not found for name: ${serverName}`);\n }\n return this.getConnectedClient(serverName, serverConfig);\n }\n\n private async eachClientTools(\n cb: (args: {\n serverName: string;\n tools: Record<string, Tool<any, any, any, any>>;\n client: InstanceType<typeof InternalMastraMCPClient>;\n }) => Promise<void>,\n ) {\n await Promise.all(\n Object.entries(this.serverConfigs).map(async ([serverName, serverConfig]) => {\n const client = await this.getConnectedClient(serverName, serverConfig);\n const tools = await client.tools();\n await cb({ serverName, tools, client });\n }),\n );\n }\n}\n","// src/utils/stream.ts\nvar StreamingApi = class {\n writer;\n encoder;\n writable;\n abortSubscribers = [];\n responseReadable;\n aborted = false;\n closed = false;\n constructor(writable, _readable) {\n this.writable = writable;\n this.writer = writable.getWriter();\n this.encoder = new TextEncoder();\n const reader = _readable.getReader();\n this.abortSubscribers.push(async () => {\n await reader.cancel();\n });\n this.responseReadable = new ReadableStream({\n async pull(controller) {\n const { done, value } = await reader.read();\n done ? controller.close() : controller.enqueue(value);\n },\n cancel: () => {\n this.abort();\n }\n });\n }\n async write(input) {\n try {\n if (typeof input === \"string\") {\n input = this.encoder.encode(input);\n }\n await this.writer.write(input);\n } catch {\n }\n return this;\n }\n async writeln(input) {\n await this.write(input + \"\\n\");\n return this;\n }\n sleep(ms) {\n return new Promise((res) => setTimeout(res, ms));\n }\n async close() {\n try {\n await this.writer.close();\n } catch {\n }\n this.closed = true;\n }\n async pipe(body) {\n this.writer.releaseLock();\n await body.pipeTo(this.writable, { preventClose: true });\n this.writer = this.writable.getWriter();\n }\n onAbort(listener) {\n this.abortSubscribers.push(listener);\n }\n abort() {\n if (!this.aborted) {\n this.aborted = true;\n this.abortSubscribers.forEach((subscriber) => subscriber());\n }\n }\n};\nexport {\n StreamingApi\n};\n","// src/helper/streaming/utils.ts\nvar isOldBunVersion = () => {\n const version = typeof Bun !== \"undefined\" ? Bun.version : void 0;\n if (version === void 0) {\n return false;\n }\n const result = version.startsWith(\"1.1\") || version.startsWith(\"1.0\") || version.startsWith(\"0.\");\n isOldBunVersion = () => result;\n return result;\n};\nexport {\n isOldBunVersion\n};\n","// src/utils/html.ts\nvar HtmlEscapedCallbackPhase = {\n Stringify: 1,\n BeforeStream: 2,\n Stream: 3\n};\nvar raw = (value, callbacks) => {\n const escapedString = new String(value);\n escapedString.isEscaped = true;\n escapedString.callbacks = callbacks;\n return escapedString;\n};\nvar escapeRe = /[&<>'\"]/;\nvar stringBufferToString = async (buffer, callbacks) => {\n let str = \"\";\n callbacks ||= [];\n const resolvedBuffer = await Promise.all(buffer);\n for (let i = resolvedBuffer.length - 1; ; i--) {\n str += resolvedBuffer[i];\n i--;\n if (i < 0) {\n break;\n }\n let r = resolvedBuffer[i];\n if (typeof r === \"object\") {\n callbacks.push(...r.callbacks || []);\n }\n const isEscaped = r.isEscaped;\n r = await (typeof r === \"object\" ? r.toString() : r);\n if (typeof r === \"object\") {\n callbacks.push(...r.callbacks || []);\n }\n if (r.isEscaped ?? isEscaped) {\n str += r;\n } else {\n const buf = [str];\n escapeToBuffer(r, buf);\n str = buf[0];\n }\n }\n return raw(str, callbacks);\n};\nvar escapeToBuffer = (str, buffer) => {\n const match = str.search(escapeRe);\n if (match === -1) {\n buffer[0] += str;\n return;\n }\n let escape;\n let index;\n let lastIndex = 0;\n for (index = match; index < str.length; index++) {\n switch (str.charCodeAt(index)) {\n case 34:\n escape = \""\";\n break;\n case 39:\n escape = \"'\";\n break;\n case 38:\n escape = \"&\";\n break;\n case 60:\n escape = \"<\";\n break;\n case 62:\n escape = \">\";\n break;\n default:\n continue;\n }\n buffer[0] += str.substring(lastIndex, index) + escape;\n lastIndex = index + 1;\n }\n buffer[0] += str.substring(lastIndex, index);\n};\nvar resolveCallbackSync = (str) => {\n const callbacks = str.callbacks;\n if (!callbacks?.length) {\n return str;\n }\n const buffer = [str];\n const context = {};\n callbacks.forEach((c) => c({ phase: HtmlEscapedCallbackPhase.Stringify, buffer, context }));\n return buffer[0];\n};\nvar resolveCallback = async (str, phase, preserveCallbacks, context, buffer) => {\n if (typeof str === \"object\" && !(str instanceof String)) {\n if (!(str instanceof Promise)) {\n str = str.toString();\n }\n if (str instanceof Promise) {\n str = await str;\n }\n }\n const callbacks = str.callbacks;\n if (!callbacks?.length) {\n return Promise.resolve(str);\n }\n if (buffer) {\n buffer[0] += str;\n } else {\n buffer = [str];\n }\n const resStr = Promise.all(callbacks.map((c) => c({ phase, buffer, context }))).then(\n (res) => Promise.all(\n res.filter(Boolean).map((str2) => resolveCallback(str2, phase, false, context, buffer))\n ).then(() => buffer[0])\n );\n if (preserveCallbacks) {\n return raw(await resStr, callbacks);\n } else {\n return resStr;\n }\n};\nexport {\n HtmlEscapedCallbackPhase,\n escapeToBuffer,\n raw,\n resolveCallback,\n resolveCallbackSync,\n stringBufferToString\n};\n","// src/helper/streaming/sse.ts\nimport { HtmlEscapedCallbackPhase, resolveCallback } from \"../../utils/html.js\";\nimport { StreamingApi } from \"../../utils/stream.js\";\nimport { isOldBunVersion } from \"./utils.js\";\nvar SSEStreamingApi = class extends StreamingApi {\n constructor(writable, readable) {\n super(writable, readable);\n }\n async writeSSE(message) {\n const data = await resolveCallback(message.data, HtmlEscapedCallbackPhase.Stringify, false, {});\n const dataLines = data.split(\"\\n\").map((line) => {\n return `data: ${line}`;\n }).join(\"\\n\");\n const sseData = [\n message.event && `event: ${message.event}`,\n dataLines,\n message.id && `id: ${message.id}`,\n message.retry && `retry: ${message.retry}`\n ].filter(Boolean).join(\"\\n\") + \"\\n\\n\";\n await this.write(sseData);\n }\n};\nvar run = async (stream, cb, onError) => {\n try {\n await cb(stream);\n } catch (e) {\n if (e instanceof Error && onError) {\n await onError(e, stream);\n await stream.writeSSE({\n event: \"error\",\n data: e.message\n });\n } else {\n console.error(e);\n }\n } finally {\n stream.close();\n }\n};\nvar contextStash = /* @__PURE__ */ new WeakMap();\nvar streamSSE = (c, cb, onError) => {\n const { readable, writable } = new TransformStream();\n const stream = new SSEStreamingApi(writable, readable);\n if (isOldBunVersion()) {\n c.req.raw.signal.addEventListener(\"abort\", () => {\n if (!stream.closed) {\n stream.abort();\n }\n });\n }\n contextStash.set(stream.responseReadable, c);\n c.header(\"Transfer-Encoding\", \"chunked\");\n c.header(\"Content-Type\", \"text/event-stream\");\n c.header(\"Cache-Control\", \"no-cache\");\n c.header(\"Connection\", \"keep-alive\");\n run(stream, cb, onError);\n return c.newResponse(stream.responseReadable);\n};\nexport {\n SSEStreamingApi,\n streamSSE\n};\n","import { JSONRPCMessageSchema, } from '@modelcontextprotocol/sdk/types.js';\nconst MAXIMUM_MESSAGE_SIZE = 4 * 1024 * 1024; // 4MB\nexport class SSETransport {\n messageUrl;\n stream;\n _sessionId;\n onclose;\n onerror;\n onmessage;\n /**\n * Creates a new SSETransport, which will direct the MPC client to POST messages to messageUrl\n */\n constructor(messageUrl, stream) {\n this.messageUrl = messageUrl;\n this.stream = stream;\n this._sessionId = crypto.randomUUID();\n this.stream.onAbort(() => {\n void this.close();\n });\n }\n get sessionId() {\n return this._sessionId;\n }\n // start() is automatically called after MCP Server connects to the transport\n async start() {\n if (this.stream == null) {\n throw new Error('Stream not initialized');\n }\n if (this.stream.closed) {\n throw new Error('SSE transport already closed!');\n }\n await this.stream.writeSSE({\n event: 'ping',\n data: '',\n });\n await this.stream.writeSSE({\n event: 'endpoint',\n data: `${this.messageUrl}?sessionId=${this.sessionId}`,\n });\n }\n async handlePostMessage(context) {\n if (this.stream?.closed == null) {\n return context.text('SSE connection not established', 500);\n }\n try {\n const contentType = context.req.header('content-type') || '';\n if (!contentType.includes('application/json')) {\n throw new Error(`Unsupported content-type: ${contentType}`);\n }\n // Check if the request body is too large\n const contentLength = Number.parseInt(context.req.header('content-length') || '0', 10);\n if (contentLength > MAXIMUM_MESSAGE_SIZE) {\n throw new Error(`Request body too large: ${contentLength} bytes`);\n }\n // Clone the request before reading the body to avoid stream issues\n const body = (await context.req.json());\n await this.handleMessage(body);\n return context.text('Accepted', 202);\n }\n catch (error) {\n this.onerror?.(error);\n return context.text('Error', 400);\n }\n }\n /**\n * Handle a client message, regardless of how it arrived. This can be used to inform the server of messages that arrive via a means different than HTTP POST.\n */\n async handleMessage(message) {\n let parsedMessage;\n try {\n parsedMessage = JSONRPCMessageSchema.parse(message);\n }\n catch (error) {\n this.onerror?.(error);\n throw error;\n }\n this.onmessage?.(parsedMessage);\n }\n async close() {\n if (this.stream?.closed) {\n this.stream.abort();\n }\n }\n async send(message) {\n if (this.stream?.closed) {\n throw new Error('Not connected');\n }\n await this.stream.writeSSE({\n event: 'message',\n data: JSON.stringify(message),\n });\n }\n}\n","import { ErrorCategory, ErrorDomain, MastraError } from '@mastra/core/error';\nimport type { IMastraLogger } from '@mastra/core/logger';\nimport type { Server } from '@modelcontextprotocol/sdk/server/index.js';\n\ninterface ServerPromptActionsDependencies {\n getLogger: () => IMastraLogger;\n getSdkServer: () => Server;\n clearDefinedPrompts: () => void;\n}\n\n/**\n * Server-side prompt actions for notifying clients about prompt changes.\n *\n * This class provides methods for MCP servers to notify connected clients when\n * the list of available prompts changes.\n */\nexport class ServerPromptActions {\n private readonly getLogger: () => IMastraLogger;\n private readonly getSdkServer: () => Server;\n private readonly clearDefinedPrompts: () => void;\n\n /**\n * @internal\n */\n constructor(dependencies: ServerPromptActionsDependencies) {\n this.getLogger = dependencies.getLogger;\n this.getSdkServer = dependencies.getSdkServer;\n this.clearDefinedPrompts = dependencies.clearDefinedPrompts;\n }\n\n /**\n * Notifies clients that the overall list of available prompts has changed.\n *\n * This clears the internal prompt cache and sends a `notifications/prompts/list_changed`\n * message to all clients, prompting them to re-fetch the prompt list.\n *\n * @throws {MastraError} If sending the notification fails\n *\n * @example\n * ```typescript\n * // After adding or modifying prompts\n * await server.prompts.notifyListChanged();\n * ```\n */\n public async notifyListChanged(): Promise<void> {\n this.getLogger().info('Prompt list change externally notified. Clearing definedPrompts and sending notification.');\n this.clearDefinedPrompts();\n try {\n await this.getSdkServer().sendPromptListChanged();\n } catch (error) {\n const mastraError = new MastraError(\n {\n id: 'MCP_SERVER_PROMPT_LIST_CHANGED_NOTIFICATION_FAILED',\n domain: ErrorDomain.MCP,\n category: ErrorCategory.THIRD_PARTY,\n text: 'Failed to send prompt list changed notification',\n },\n error,\n );\n this.getLogger().error('Failed to send prompt list changed notification:', {\n error: mastraError.toString(),\n });\n this.getLogger().trackException(mastraError);\n throw mastraError;\n }\n }\n}\n","import { ErrorCategory, ErrorDomain, MastraError } from '@mastra/core/error';\nimport type { IMastraLogger } from '@mastra/core/logger';\nimport type { Server } from '@modelcontextprotocol/sdk/server/index.js';\n\ninterface ServerResourceActionsDependencies {\n getSubscriptions: () => Set<string>;\n getLogger: () => IMastraLogger;\n getSdkServer: () => Server;\n clearDefinedResources: () => void;\n clearDefinedResourceTemplates: () => void;\n}\n\n/**\n * Server-side resource actions for notifying clients about resource changes.\n *\n * This class provides methods for MCP servers to notify connected clients when\n * resources are updated or when the resource list changes.\n */\nexport class ServerResourceActions {\n private readonly getSubscriptions: () => Set<string>;\n private readonly getLogger: () => IMastraLogger;\n private readonly getSdkServer: () => Server;\n private readonly clearDefinedResources: () => void;\n private readonly clearDefinedResourceTemplates: () => void;\n\n /**\n * @internal\n */\n constructor(dependencies: ServerResourceActionsDependencies) {\n this.getSubscriptions = dependencies.getSubscriptions;\n this.getLogger = dependencies.getLogger;\n this.getSdkServer = dependencies.getSdkServer;\n this.clearDefinedResources = dependencies.clearDefinedResources;\n this.clearDefinedResourceTemplates = dependencies.clearDefinedResourceTemplates;\n }\n\n /**\n * Notifies subscribed clients that a specific resource has been updated.\n *\n * If clients are subscribed to the resource URI, they will receive a\n * `notifications/resources/updated` message to re-fetch the resource content.\n *\n * @param params - Notification parameters\n * @param params.uri - URI of the resource that was updated\n * @throws {MastraError} If sending the notification fails\n *\n * @example\n * ```typescript\n * // After updating a file resource\n * await server.resources.notifyUpdated({ uri: 'file://data.txt' });\n * ```\n */\n public async notifyUpdated({ uri }: { uri: string }): Promise<void> {\n if (this.getSubscriptions().has(uri)) {\n this.getLogger().info(`Sending notifications/resources/updated for externally notified resource: ${uri}`);\n try {\n await this.getSdkServer().sendResourceUpdated({ uri });\n } catch (error) {\n const mastraError = new MastraError(\n {\n id: 'MCP_SERVER_RESOURCE_UPDATED_NOTIFICATION_FAILED',\n domain: ErrorDomain.MCP,\n category: ErrorCategory.THIRD_PARTY,\n text: 'Failed to send resource updated notification',\n details: {\n uri,\n },\n },\n error,\n );\n this.getLogger().trackException(mastraError);\n this.getLogger().error('Failed to send resource updated notification:', {\n error: mastraError.toString(),\n });\n throw mastraError;\n }\n } else {\n this.getLogger().debug(`Resource ${uri} was updated, but no active subscriptions for it.`);\n }\n }\n\n /**\n * Notifies clients that the overall list of available resources has changed.\n *\n * This clears the internal resource cache and sends a `notifications/resources/list_changed`\n * message to all clients, prompting them to re-fetch the resource list.\n *\n * @throws {MastraError} If sending the notification fails\n *\n * @example\n * ```typescript\n * // After adding a new resource to your resource handler\n * await server.resources.notifyListChanged();\n * ```\n */\n public async notifyListChanged(): Promise<void> {\n this.getLogger().info(\n 'Resource list change externally notified. Clearing definedResources and sending notification.',\n );\n this.clearDefinedResources(); // Clear cached resources\n this.clearDefinedResourceTemplates(); // Clear cached resource templates\n try {\n await this.getSdkServer().sendResourceListChanged();\n } catch (error) {\n const mastraError = new MastraError(\n {\n id: 'MCP_SERVER_RESOURCE_LIST_CHANGED_NOTIFICATION_FAILED',\n domain: ErrorDomain.MCP,\n category: ErrorCategory.THIRD_PARTY,\n text: 'Failed to send resource list changed notification',\n },\n error,\n );\n this.getLogger().trackException(mastraError);\n this.getLogger().error('Failed to send resource list changed notification:', {\n error: mastraError.toString(),\n });\n throw mastraError;\n }\n }\n}\n","import { randomUUID } from 'node:crypto';\nimport type * as http from 'node:http';\nimport type { ToolsInput, Agent } from '@mastra/core/agent';\nimport { ErrorCategory, ErrorDomain, MastraError } from '@mastra/core/error';\nimport { MCPServerBase } from '@mastra/core/mcp';\nimport type {\n MCPServerConfig,\n ServerInfo,\n ServerDetailInfo,\n MCPServerHonoSSEOptions,\n MCPServerSSEOptions,\n} from '@mastra/core/mcp';\nimport { RequestContext } from '@mastra/core/request-context';\nimport { createTool } from '@mastra/core/tools';\nimport type { InternalCoreTool, MCPToolType, MastraToolInvocationOptions } from '@mastra/core/tools';\nimport { makeCoreTool } from '@mastra/core/utils';\nimport type { Workflow } from '@mastra/core/workflows';\nimport { Server } from '@modelcontextprotocol/sdk/server/index.js';\nimport { SSEServerTransport } from '@modelcontextprotocol/sdk/server/sse.js';\nimport { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';\nimport { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js';\nimport type { StreamableHTTPServerTransportOptions } from '@modelcontextprotocol/sdk/server/streamableHttp.js';\nimport {\n CallToolRequestSchema,\n ListToolsRequestSchema,\n ListResourcesRequestSchema,\n ReadResourceRequestSchema,\n ListResourceTemplatesRequestSchema,\n SubscribeRequestSchema,\n UnsubscribeRequestSchema,\n ListPromptsRequestSchema,\n GetPromptRequestSchema,\n SetLevelRequestSchema,\n PromptSchema,\n} from '@modelcontextprotocol/sdk/types.js';\nimport type {\n ResourceContents,\n Resource,\n ResourceTemplate,\n ServerCapabilities,\n Prompt,\n CallToolResult,\n ElicitResult,\n ElicitRequest,\n LoggingLevel,\n} from '@modelcontextprotocol/sdk/types.js';\nimport type { SSEStreamingApi } from 'hono/streaming';\nimport { streamSSE } from 'hono/streaming';\nimport { SSETransport } from 'hono-mcp-server-sse-transport';\nimport { z } from 'zod';\nimport { ServerPromptActions } from './promptActions';\nimport { ServerResourceActions } from './resourceActions';\nimport type { MCPServerPrompts, MCPServerResources, ElicitationActions } from './types';\n/**\n * MCPServer exposes Mastra tools, agents, and workflows as a Model Context Protocol (MCP) server.\n *\n * This class allows any MCP client (like Cursor, Windsurf, or Claude Desktop) to connect and use your\n * Mastra capabilities. It supports both stdio (subprocess) and SSE (HTTP) MCP transports.\n *\n * @example\n * ```typescript\n * import { MCPServer } from '@mastra/mcp';\n * import { createTool } from '@mastra/core/tools';\n * import { z } from 'zod';\n *\n * const weatherTool = createTool({\n * id: 'getWeather',\n * description: 'Gets the current weather for a location.',\n * inputSchema: z.object({ location: z.string() }),\n * execute: async (inputData) => `Weather in ${inputData.location} is sunny.`,\n * });\n *\n * const server = new MCPServer({\n * name: 'My Weather Server',\n * version: '1.0.0',\n * tools: { weatherTool },\n * });\n *\n * await server.startStdio();\n * ```\n */\nexport class MCPServer extends MCPServerBase {\n private server: Server;\n private stdioTransport?: StdioServerTransport;\n private sseTransport?: SSEServerTransport;\n private sseHonoTransports: Map<string, SSETransport>;\n private streamableHTTPTransports: Map<string, StreamableHTTPServerTransport> = new Map();\n // Track server instances for each HTTP session\n private httpServerInstances: Map<string, Server> = new Map();\n\n private definedResources?: Resource[];\n private definedResourceTemplates?: ResourceTemplate[];\n private resourceOptions?: MCPServerResources;\n private definedPrompts?: Prompt[];\n private promptOptions?: MCPServerPrompts;\n private subscriptions: Set<string> = new Set();\n private currentLoggingLevel: LoggingLevel | undefined;\n\n /**\n * Provides methods to notify clients about resource changes.\n *\n * @example\n * ```typescript\n * // Notify that a specific resource was updated\n * await server.resources.notifyUpdated({ uri: 'file://data.txt' });\n *\n * // Notify that the resource list changed\n * await server.resources.notifyListChanged();\n * ```\n */\n public readonly resources: ServerResourceActions;\n\n /**\n * Provides methods to notify clients about prompt changes.\n *\n * @example\n * ```typescript\n * // Notify that the prompt list changed\n * await server.prompts.notifyListChanged();\n * ```\n */\n public readonly prompts: ServerPromptActions;\n\n /**\n * Provides methods for interactive user input collection during tool execution.\n *\n * @example\n * ```typescript\n * // Within a tool's execute function\n * const result = await options.elicitation.sendRequest({\n * message: 'Please provide your email address',\n * requestedSchema: {\n * type: 'object',\n * properties: {\n * email: { type: 'string', format: 'email' }\n * },\n * required: ['email']\n * }\n * });\n * ```\n */\n public readonly elicitation: ElicitationActions;\n\n /**\n * Gets the stdio transport instance if the server was started using stdio.\n *\n * This is primarily for internal checks or testing purposes.\n *\n * @returns The stdio transport instance, or undefined if not using stdio transport\n */\n public getStdioTransport(): StdioServerTransport | undefined {\n return this.stdioTransport;\n }\n\n /**\n * Gets the SSE transport instance if the server was started using SSE.\n *\n * This is primarily for internal checks or testing purposes.\n *\n * @returns The SSE transport instance, or undefined if not using SSE transport\n */\n public getSseTransport(): SSEServerTransport | undefined {\n return this.sseTransport;\n }\n\n /**\n * Gets the Hono SSE transport instance for a specific session.\n *\n * This is primarily for internal checks or testing purposes.\n *\n * @param sessionId - The session identifier\n * @returns The Hono SSE transport instance, or undefined if session not found\n */\n public getSseHonoTransport(sessionId: string): SSETransport | undefined {\n return this.sseHonoTransports.get(sessionId);\n }\n\n /**\n * Gets the underlying MCP SDK Server instance.\n *\n * This provides access to the low-level server instance for advanced use cases.\n *\n * @returns The Server instance from @modelcontextprotocol/sdk\n */\n public getServer(): Server {\n return this.server;\n }\n\n /**\n * Creates a new MCPServer instance.\n *\n * The server exposes tools, agents, and workflows to MCP clients. Agents are automatically\n * converted to tools named `ask_<agentKey>`, and workflows become tools named `run_<workflowKey>`.\n *\n * @param opts - Configuration options for the server\n * @param opts.name - Descriptive name for the server (e.g., 'My Weather Server')\n * @param opts.version - Semantic version of the server (e.g., '1.0.0')\n * @param opts.tools - Object mapping tool names to tool definitions\n * @param opts.agents - Optional object mapping agent identifiers to Agent instances\n * @param opts.workflows - Optional object mapping workflow identifiers to Workflow instances\n * @param opts.resources - Optional resource configuration for exposing data and content\n * @param opts.prompts - Optional prompt configuration for exposing reusable templates\n * @param opts.id - Optional unique identifier (generated if not provided)\n * @param opts.description - Optional description of what the server does\n *\n * @example\n * ```typescript\n * import { MCPServer } from '@mastra/mcp';\n * import { Agent } from '@mastra/core/agent';\n * import { createTool } from '@mastra/core/tools';\n * import { z } from 'zod';\n *\n * const myAgent = new Agent({\n * id: 'helper',\n * name: 'Helper Agent',\n * description: 'A helpful assistant',\n * instructions: 'You are helpful.',\n * model: 'openai/gpt-4o-mini',\n * });\n *\n * const server = new MCPServer({\n * name: 'My Server',\n * version: '1.0.0',\n * tools: {\n * weatherTool: createTool({\n * id: 'getWeather',\n * description: 'Gets weather',\n * inputSchema: z.object({ location: z.string() }),\n * execute: async (inputData) => `Sunny in ${inputData.location}`,\n * })\n * },\n * agents: { myAgent },\n * });\n * ```\n */\n constructor(opts: MCPServerConfig & { resources?: MCPServerResources; prompts?: MCPServerPrompts }) {\n super(opts);\n this.resourceOptions = opts.resources;\n this.promptOptions = opts.prompts;\n\n const capabilities: ServerCapabilities = {\n tools: {},\n logging: { enabled: true },\n elicitation: {},\n };\n\n if (opts.resources) {\n capabilities.resources = { subscribe: true, listChanged: true };\n }\n\n if (opts.prompts) {\n capabilities.prompts = { listChanged: true };\n }\n\n this.server = new Server({ name: this.name, version: this.version }, { capabilities });\n\n this.logger.info(\n `Initialized MCPServer '${this.name}' v${this.version} (ID: ${this.id}) with tools: ${Object.keys(this.convertedTools).join(', ')} and resources. Capabilities: ${JSON.stringify(capabilities)}`,\n );\n\n this.sseHonoTransports = new Map();\n\n // Register all handlers on the main server instance\n this.registerHandlersOnServer(this.server);\n\n this.resources = new ServerResourceActions({\n getSubscriptions: () => this.subscriptions,\n getLogger: () => this.logger,\n getSdkServer: () => this.server,\n clearDefinedResources: () => {\n this.definedResources = undefined;\n },\n clearDefinedResourceTemplates: () => {\n this.definedResourceTemplates = undefined;\n },\n });\n\n this.prompts = new ServerPromptActions({\n getLogger: () => this.logger,\n getSdkServer: () => this.server,\n clearDefinedPrompts: () => {\n this.definedPrompts = undefined;\n },\n });\n\n this.elicitation = {\n sendRequest: async request => {\n return this.handleElicitationRequest(request);\n },\n };\n }\n\n /**\n * Handle an elicitation request by sending it to the connected client.\n * This method sends an elicitation/create request to the client and waits for the response.\n *\n * @param request - The elicitation request containing message and schema\n * @param serverInstance - Optional server instance to use; defaults to main server for backward compatibility\n * @returns Promise that resolves to the client's response\n */\n private async handleElicitationRequest(\n request: ElicitRequest['params'],\n serverInstance?: Server,\n ): Promise<ElicitResult> {\n this.logger.debug(`Sending elicitation request: ${request.message}`);\n\n const server = serverInstance || this.server;\n const response = await server.elicitInput(request);\n\n this.logger.debug(`Received elicitation response: ${JSON.stringify(response)}`);\n\n return response;\n }\n\n /**\n * Creates a new Server instance configured with all handlers for HTTP sessions.\n * Each HTTP client connection gets its own Server instance to avoid routing conflicts.\n */\n private createServerInstance(): Server {\n const capabilities: ServerCapabilities = {\n tools: {},\n logging: { enabled: true },\n elicitation: {},\n };\n\n if (this.resourceOptions) {\n capabilities.resources = { subscribe: true, listChanged: true };\n }\n\n if (this.promptOptions) {\n capabilities.prompts = { listChanged: true };\n }\n\n const serverInstance = new Server({ name: this.name, version: this.version }, { capabilities });\n\n // Register all handlers on the new server instance\n this.registerHandlersOnServer(serverInstance);\n\n return serverInstance;\n }\n\n /**\n * Registers all MCP handlers on a given server instance.\n * This allows us to create multiple server instances with identical functionality.\n */\n private registerHandlersOnServer(serverInstance: Server) {\n // List tools handler\n serverInstance.setRequestHandler(ListToolsRequestSchema, async () => {\n this.logger.debug('Handling ListTools request');\n return {\n tools: Object.values(this.convertedTools).map(tool => {\n const toolSpec: any = {\n name: tool.id || 'unknown',\n description: tool.description,\n inputSchema: tool.parameters.jsonSchema,\n };\n if (tool.outputSchema) {\n toolSpec.outputSchema = tool.outputSchema.jsonSchema;\n }\n return toolSpec;\n }),\n };\n });\n\n // Call tool handler\n serverInstance.setRequestHandler(CallToolRequestSchema, async (request, extra) => {\n const startTime = Date.now();\n try {\n const tool = this.convertedTools[request.params.name];\n if (!tool) {\n this.logger.warn(`CallTool: Unknown tool '${request.params.name}' requested.`);\n return {\n content: [{ type: 'text', text: `Unknown tool: ${request.params.name}` }],\n isError: true,\n };\n }\n\n const validation = tool.parameters.validate?.(request.params.arguments ?? {});\n if (validation && !validation.success) {\n this.logger.warn(`CallTool: Invalid tool arguments for '${request.params.name}'`, {\n errors: validation.error,\n });\n\n // Format validation errors for agent understanding\n let errorMessages = 'Validation failed';\n if ('errors' in validation.error && Array.isArray(validation.error.errors)) {\n errorMessages = validation.error.errors\n .map((e: any) => `- ${e.path?.join('.') || 'root'}: ${e.message}`)\n .join('\\n');\n } else if (validation.error instanceof Error) {\n errorMessages = validation.error.message;\n }\n\n return {\n content: [\n {\n type: 'text',\n text: `Tool validation failed. Please fix the following errors and try again:\\n${errorMessages}\\n\\nProvided arguments: ${JSON.stringify(request.params.arguments, null, 2)}`,\n },\n ],\n isError: true, // Set to true so the LLM sees the error and can self-correct\n };\n }\n if (!tool.execute) {\n this.logger.warn(`CallTool: Tool '${request.params.name}' does not have an execute function.`);\n return {\n content: [{ type: 'text', text: `Tool '${request.params.name}' does not have an execute function.` }],\n isError: true,\n };\n }\n\n // Create session-aware elicitation for this tool execution\n const sessionElicitation = {\n sendRequest: async (request: ElicitRequest['params']) => {\n return this.handleElicitationRequest(request, serverInstance);\n },\n };\n\n const mcpOptions: MastraToolInvocationOptions = {\n messages: [],\n toolCallId: '',\n // Pass MCP-specific context through the mcp property\n mcp: {\n elicitation: sessionElicitation,\n extra,\n },\n // @ts-ignore this is to let people know that the elicitation and extra keys are now nested under mcp.elicitation and mcp.extra in tool arguments\n get elicitation() {\n throw new Error(`The \"elicitation\" key is now nested under \"mcp.elicitation\" in tool arguments`);\n },\n get extra() {\n throw new Error(`The \"extra\" key is now nested under \"mcp.extra\" in tool arguments`);\n },\n };\n\n const result = await tool.execute(validation?.value ?? request.params.arguments ?? {}, mcpOptions);\n\n this.logger.debug(`CallTool: Tool '${request.params.name}' executed successfully with result:`, result);\n const duration = Date.now() - startTime;\n this.logger.info(`Tool '${request.params.name}' executed successfully in ${duration}ms.`);\n\n const response: CallToolResult = { isError: false, content: [] };\n\n if (tool.outputSchema) {\n // Handle both cases: tools that return { structuredContent: ... } and tools that return the plain object\n let structuredContent;\n if (result && typeof result === 'object' && 'structuredContent' in result) {\n // Tool returned { structuredContent: ... } format (MCP-aware tool)\n structuredContent = result.structuredContent;\n } else {\n // Tool returned plain object, wrap it automatically for backward compatibility\n structuredContent = result;\n }\n\n const outputValidation = tool.outputSchema.validate?.(structuredContent ?? {});\n if (outputValidation && !outputValidation.success) {\n this.logger.warn(`CallTool: Invalid structured content for '${request.params.name}'`, {\n errors: outputValidation.error,\n });\n throw new Error(\n `Invalid structured content for tool ${request.params.name}: ${JSON.stringify(outputValidation.error)}`,\n );\n }\n response.structuredContent = structuredContent;\n }\n\n if (response.structuredContent) {\n response.content = [{ type: 'text', text: JSON.stringify(response.structuredContent) }];\n } else {\n response.content = [\n {\n type: 'text',\n text: typeof result === 'string' ? result : JSON.stringify(result),\n },\n ];\n }\n\n return response;\n } catch (error) {\n const duration = Date.now() - startTime;\n if (error instanceof z.ZodError) {\n this.logger.warn('Invalid tool arguments', {\n tool: request.params.name,\n errors: error.errors,\n duration: `${duration}ms`,\n });\n return {\n content: [\n {\n type: 'text',\n text: `Invalid arguments: ${error.errors.map(e => `${e.path.join('.')}: ${e.message}`).join(', ')}`,\n },\n ],\n isError: true,\n };\n }\n this.logger.error(`Tool execution failed: ${request.params.name}`, { error });\n return {\n content: [{ type: 'text', text: `Error: ${error instanceof Error ? error.message : String(error)}` }],\n isError: true,\n };\n }\n });\n\n // Set logging level handler\n serverInstance.setRequestHandler(SetLevelRequestSchema, async request => {\n this.currentLoggingLevel = request.params.level;\n this.logger.debug(`Logging level set to: ${request.params.level}`);\n return {};\n });\n\n // Register resource handlers if resources are configured\n if (this.resourceOptions) {\n this.registerResourceHandlersOnServer(serverInstance);\n }\n\n // Register prompt handlers if prompts are configured\n if (this.promptOptions) {\n this.registerPromptHandlersOnServer(serverInstance);\n }\n }\n\n /**\n * Registers resource-related handlers on a server instance.\n */\n private registerResourceHandlersOnServer(serverInstance: Server) {\n const capturedResourceOptions = this.resourceOptions;\n if (!capturedResourceOptions) return;\n\n // List resources handler\n if (capturedResourceOptions.listResources) {\n serverInstance.setRequestHandler(ListResourcesRequestSchema, async (_request, extra) => {\n this.logger.debug('Handling ListResources request');\n if (this.definedResources) {\n return { resources: this.definedResources };\n } else {\n try {\n const resources = await capturedResourceOptions.listResources!({ extra });\n this.definedResources = resources;\n this.logger.debug(`Fetched and cached ${this.definedResources.length} resources.`);\n return { resources: this.definedResources };\n } catch (error) {\n this.logger.error('Error fetching resources via listResources():', { error });\n throw error;\n }\n }\n });\n }\n\n // Read resource handler\n if (capturedResourceOptions.getResourceContent) {\n serverInstance.setRequestHandler(ReadResourceRequestSchema, async (request, extra) => {\n const startTime = Date.now();\n const uri = request.params.uri;\n this.logger.debug(`Handling ReadResource request for URI: ${uri}`);\n\n if (!this.definedResources) {\n const resources = await this.resourceOptions?.listResources?.({ extra });\n if (!resources) throw new Error('Failed to load resources');\n this.definedResources = resources;\n }\n\n const resource = this.definedResources?.find(r => r.uri === uri);\n\n if (!resource) {\n this.logger.warn(`ReadResource: Unknown resource URI '${uri}' requested.`);\n throw new Error(`Resource not found: ${uri}`);\n }\n\n try {\n const resourcesOrResourceContent = await capturedResourceOptions.getResourceContent({ uri, extra });\n const resourcesContent = Array.isArray(resourcesOrResourceContent)\n ? resourcesOrResourceContent\n : [resourcesOrResourceContent];\n const contents: ResourceContents[] = resourcesContent.map(resourceContent => {\n const contentItem: ResourceContents = {\n uri: resource.uri,\n mimeType: resource.mimeType,\n };\n if ('text' in resourceContent) {\n contentItem.text = resourceContent.text;\n }\n\n if ('blob' in resourceContent) {\n contentItem.blob = resourceContent.blob;\n }\n\n return contentItem;\n });\n const duration = Date.now() - startTime;\n this.logger.info(`Resource '${uri}' read successfully in ${duration}ms.`);\n return {\n contents,\n };\n } catch (error) {\n const duration = Date.now() - startTime;\n this.logger.error(`Failed to get content for resource URI '${uri}' in ${duration}ms`, { error });\n throw error;\n }\n });\n }\n\n // Resource templates handler\n if (capturedResourceOptions.resourceTemplates) {\n serverInstance.setRequestHandler(ListResourceTemplatesRequestSchema, async (_request, extra) => {\n this.logger.debug('Handling ListResourceTemplates request');\n if (this.definedResourceTemplates) {\n return { resourceTemplates: this.definedResourceTemplates };\n } else {\n try {\n const templates = await capturedResourceOptions.resourceTemplates!({ extra });\n this.definedResourceTemplates = templates;\n this.logger.debug(`Fetched and cached ${this.definedResourceTemplates.length} resource templates.`);\n return { resourceTemplates: this.definedResourceTemplates };\n } catch (error) {\n this.logger.error('Error fetching resource templates via resourceTemplates():', { error });\n throw error;\n }\n }\n });\n }\n\n // Subscribe/unsubscribe handlers\n serverInstance.setRequestHandler(SubscribeRequestSchema, async (request: { params: { uri: string } }) => {\n const uri = request.params.uri;\n this.logger.info(`Received resources/subscribe request for URI: ${uri}`);\n this.subscriptions.add(uri);\n return {};\n });\n\n serverInstance.setRequestHandler(UnsubscribeRequestSchema, async (request: { params: { uri: string } }) => {\n const uri = request.params.uri;\n this.logger.info(`Received resources/unsubscribe request for URI: ${uri}`);\n this.subscriptions.delete(uri);\n return {};\n });\n }\n\n /**\n * Registers prompt-related handlers on a server instance.\n */\n private registerPromptHandlersOnServer(serverInstance: Server) {\n const capturedPromptOptions = this.promptOptions;\n if (!capturedPromptOptions) return;\n\n // List prompts handler\n if (capturedPromptOptions.listPrompts) {\n serverInstance.setRequestHandler(ListPromptsRequestSchema, async (_request, extra) => {\n this.logger.debug('Handling ListPrompts request');\n if (this.definedPrompts) {\n return {\n prompts: this.definedPrompts?.map(p => ({ ...p, version: p.version ?? undefined })),\n };\n } else {\n try {\n const prompts = await capturedPromptOptions.listPrompts({ extra });\n for (const prompt of prompts) {\n PromptSchema.parse(prompt);\n }\n this.definedPrompts = prompts;\n this.logger.debug(`Fetched and cached ${this.definedPrompts.length} prompts.`);\n return {\n prompts: this.definedPrompts?.map(p => ({ ...p, version: p.version ?? undefined })),\n };\n } catch (error) {\n this.logger.error('Error fetching prompts via listPrompts():', {\n error: error instanceof Error ? error.message : String(error),\n });\n throw error;\n }\n }\n });\n }\n\n // Get prompt handler\n if (capturedPromptOptions.getPromptMessages) {\n serverInstance.setRequestHandler(\n GetPromptRequestSchema,\n async (request: { params: { name: string; version?: string; arguments?: any } }, extra) => {\n const startTime = Date.now();\n const { name, version, arguments: args } = request.params;\n if (!this.definedPrompts) {\n const prompts = await this.promptOptions?.listPrompts?.({ extra });\n if (!prompts) throw new Error('Failed to load prompts');\n this.definedPrompts = prompts;\n }\n // Select prompt by name and version (if provided)\n let prompt;\n if (version) {\n prompt = this.definedPrompts?.find(p => p.name === name && p.version === version);\n } else {\n // Select the first matching name if no version is provided.\n prompt = this.definedPrompts?.find(p => p.name === name);\n }\n if (!prompt) throw new Error(`Prompt \"${name}\"${version ? ` (version ${version})` : ''} not found`);\n // Validate required arguments\n if (prompt.arguments) {\n for (const arg of prompt.arguments) {\n if (arg.required && (args?.[arg.name] === undefined || args?.[arg.name] === null)) {\n throw new Error(`Missing required argument: ${arg.name}`);\n }\n }\n }\n try {\n let messages: any[] = [];\n if (capturedPromptOptions.getPromptMessages) {\n messages = await capturedPromptOptions.getPromptMessages({ name, version, args, extra });\n }\n const duration = Date.now() - startTime;\n this.logger.info(\n `Prompt '${name}'${version ? ` (version ${version})` : ''} retrieved successfully in ${duration}ms.`,\n );\n return { prompt, messages };\n } catch (error) {\n const duration = Date.now() - startTime;\n this.logger.error(`Failed to get content for prompt '${name}' in ${duration}ms`, { error });\n throw error;\n }\n },\n );\n }\n }\n\n private convertAgentsToTools(\n agentsConfig?: Record<string, Agent>,\n definedConvertedTools?: Record<string, InternalCoreTool>,\n ): Record<string, InternalCoreTool> {\n const agentTools: Record<string, InternalCoreTool> = {};\n if (!agentsConfig) {\n return agentTools;\n }\n\n for (const agentKey in agentsConfig) {\n const agent = agentsConfig[agentKey];\n if (!agent || !('generate' in agent)) {\n this.logger.warn(`Agent instance for '${agentKey}' is invalid or missing a generate function. Skipping.`);\n continue;\n }\n\n const agentDescription = agent.getDescription();\n\n if (!agentDescription) {\n throw new Error(\n `Agent '${agent.name}' (key: '${agentKey}') must have a non-empty description to be used in an MCPServer.`,\n );\n }\n\n const agentToolName = `ask_${agentKey}`;\n if (definedConvertedTools?.[agentToolName] || agentTools[agentToolName]) {\n this.logger.warn(\n `Tool with name '${agentToolName}' already exists. Agent '${agentKey}' will not be added as a duplicate tool.`,\n );\n continue;\n }\n\n const agentToolDefinition = createTool({\n id: agentToolName,\n description: `Ask agent '${agent.name}' a question. Agent description: ${agentDescription}`,\n inputSchema: z.object({\n message: z.string().describe('The question or input for the agent.'),\n }),\n execute: async (inputData, context) => {\n this.logger.debug(\n `Executing agent tool '${agentToolName}' for agent '${agent.name}' with message: \"${inputData.message}\"`,\n );\n try {\n const proxiedContext = context?.requestContext || new RequestContext();\n if (context?.mcp?.extra) {\n proxiedContext.set('mcp.extra', context.mcp.extra);\n }\n\n const response = await agent.generate(inputData.message, {\n ...(context ?? {}),\n requestContext: proxiedContext,\n });\n return response;\n } catch (error) {\n this.logger.error(`Error executing agent tool '${agentToolName}' for agent '${agent.name}':`, error);\n throw error;\n }\n },\n });\n\n const options = {\n name: agentToolName,\n logger: this.logger,\n mastra: this.mastra,\n requestContext: new RequestContext(),\n tracingContext: {},\n description: agentToolDefinition.description,\n };\n const coreTool = makeCoreTool(agentToolDefinition, options) as InternalCoreTool;\n\n agentTools[agentToolName] = {\n ...coreTool,\n id: agentToolName,\n mcp: {\n toolType: 'agent',\n },\n } as InternalCoreTool;\n this.logger.info(`Registered agent '${agent.name}' (key: '${agentKey}') as tool: '${agentToolName}'`);\n }\n return agentTools;\n }\n\n private convertWorkflowsToTools(\n workflowsConfig?: Record<string, Workflow>,\n definedConvertedTools?: Record<string, InternalCoreTool>,\n ): Record<string, InternalCoreTool> {\n const workflowTools: Record<string, InternalCoreTool> = {};\n if (!workflowsConfig) {\n return workflowTools;\n }\n\n for (const workflowKey in workflowsConfig) {\n const workflow = workflowsConfig[workflowKey];\n if (!workflow || typeof workflow.createRun !== 'function') {\n this.logger.warn(\n `Workflow instance for '${workflowKey}' is invalid or missing a createRun function. Skipping.`,\n );\n continue;\n }\n\n const workflowDescription = workflow.description;\n if (!workflowDescription) {\n throw new Error(\n `Workflow '${workflow.id}' (key: '${workflowKey}') must have a non-empty description to be used in an MCPServer.`,\n );\n }\n\n const workflowToolName = `run_${workflowKey}`;\n if (definedConvertedTools?.[workflowToolName] || workflowTools[workflowToolName]) {\n this.logger.warn(\n `Tool with name '${workflowToolName}' already exists. Workflow '${workflowKey}' will not be added as a duplicate tool.`,\n );\n continue;\n }\n\n const workflowToolDefinition = createTool({\n id: workflowToolName,\n description: `Run workflow '${workflowKey}'. Workflow description: ${workflowDescription}`,\n inputSchema: workflow.inputSchema,\n execute: async (inputData, context) => {\n this.logger.debug(\n `Executing workflow tool '${workflowToolName}' for workflow '${workflow.id}' with input:`,\n inputData,\n );\n try {\n const run = await workflow.createRun({ runId: context?.requestContext?.get('runId') });\n\n const response = await run.start({\n inputData: inputData,\n requestContext: context?.requestContext,\n tracingContext: context?.tracingContext,\n });\n return response;\n } catch (error) {\n this.logger.error(\n `Error executing workflow tool '${workflowToolName}' for workflow '${workflow.id}':`,\n error,\n );\n throw error;\n }\n },\n });\n\n const options = {\n name: workflowToolName,\n logger: this.logger,\n mastra: this.mastra,\n requestContext: new RequestContext(),\n tracingContext: {},\n description: workflowToolDefinition.description,\n };\n\n const coreTool = makeCoreTool(workflowToolDefinition, options) as InternalCoreTool;\n\n workflowTools[workflowToolName] = {\n ...coreTool,\n id: workflowToolName,\n mcp: {\n toolType: 'workflow',\n },\n } as InternalCoreTool;\n this.logger.info(`Registered workflow '${workflow.id}' (key: '${workflowKey}') as tool: '${workflowToolName}'`);\n }\n return workflowTools;\n }\n\n /**\n * Convert and validate all provided tools, logging registration status.\n * Also converts agents and workflows into tools.\n * @param tools Tool definitions\n * @param agentsConfig Agent definitions to be converted to tools, expected from MCPServerConfig\n * @param workflowsConfig Workflow definitions to be converted to tools, expected from MCPServerConfig\n * @returns Converted tools registry\n */\n convertTools(\n tools: ToolsInput,\n agentsConfig?: Record<string, Agent>,\n workflowsConfig?: Record<string, Workflow>,\n ): Record<string, InternalCoreTool> {\n const definedConvertedTools: Record<string, InternalCoreTool> = {};\n\n for (const toolName of Object.keys(tools)) {\n const toolInstance = tools[toolName];\n if (!toolInstance) {\n this.logger.warn(`Tool instance for '${toolName}' is undefined. Skipping.`);\n continue;\n }\n\n if (typeof toolInstance.execute !== 'function') {\n this.logger.warn(`Tool '${toolName}' does not have a valid execute function. Skipping.`);\n continue;\n }\n\n const options = {\n name: toolName,\n requestContext: new RequestContext(),\n tracingContext: {},\n mastra: this.mastra,\n logger: this.logger,\n description: toolInstance?.description,\n };\n\n const coreTool = makeCoreTool(toolInstance, options) as InternalCoreTool;\n\n definedConvertedTools[toolName] = {\n ...coreTool,\n id: toolName,\n } as InternalCoreTool;\n this.logger.info(`Registered explicit tool: '${toolName}'`);\n }\n this.logger.info(`Total defined tools registered: ${Object.keys(definedConvertedTools).length}`);\n\n let agentDerivedTools: Record<string, InternalCoreTool> = {};\n let workflowDerivedTools: Record<string, InternalCoreTool> = {};\n try {\n agentDerivedTools = this.convertAgentsToTools(agentsConfig, definedConvertedTools);\n workflowDerivedTools = this.convertWorkflowsToTools(workflowsConfig, definedConvertedTools);\n } catch (e) {\n const mastraError = new MastraError(\n {\n id: 'MCP_SERVER_AGENT_OR_WORKFLOW_TOOL_CONVERSION_FAILED',\n domain: ErrorDomain.MCP,\n category: ErrorCategory.USER,\n },\n e,\n );\n this.logger.trackException(mastraError);\n this.logger.error('Failed to convert tools:', {\n error: mastraError.toString(),\n });\n throw mastraError;\n }\n\n const allConvertedTools = { ...definedConvertedTools, ...agentDerivedTools, ...workflowDerivedTools };\n\n const finalToolCount = Object.keys(allConvertedTools).length;\n const definedCount = Object.keys(definedConvertedTools).length;\n const fromAgentsCount = Object.keys(agentDerivedTools).length;\n const fromWorkflowsCount = Object.keys(workflowDerivedTools).length;\n this.logger.info(\n `${finalToolCount} total tools registered (${definedCount} defined + ${fromAgentsCount} agents + ${fromWorkflowsCount} workflows)`,\n );\n\n return allConvertedTools;\n }\n\n /**\n * Starts the MCP server using standard input/output (stdio) transport.\n *\n * This is typically used when running the server as a command-line program that MCP clients\n * spawn as a subprocess (e.g., integration with Windsurf, Cursor, or Claude Desktop).\n *\n * @throws {MastraError} If the stdio connection fails\n *\n * @example\n * ```typescript\n * const server = new MCPServer({\n * name: 'My Server',\n * version: '1.0.0',\n * tools: { weatherTool },\n * });\n *\n * await server.startStdio();\n * ```\n */\n public async startStdio(): Promise<void> {\n this.stdioTransport = new StdioServerTransport();\n try {\n await this.server.connect(this.stdioTransport);\n } catch (error) {\n const mastraError = new MastraError(\n {\n id: 'MCP_SERVER_STDIO_CONNECTION_FAILED',\n domain: ErrorDomain.MCP,\n category: ErrorCategory.THIRD_PARTY,\n },\n error,\n );\n this.logger.trackException(mastraError);\n this.logger.error('Failed to connect MCP server using stdio transport:', {\n error: mastraError.toString(),\n });\n throw mastraError;\n }\n this.logger.info('Started MCP Server (stdio)');\n }\n\n /**\n * Integrates the MCP server with an existing HTTP server using Server-Sent Events (SSE).\n *\n * Call this method from your web server's request handler for both the SSE and message paths.\n * This enables web-based MCP clients to connect to your server.\n *\n * @param options - Configuration for SSE integration\n * @param options.url - Parsed URL of the incoming request\n * @param options.ssePath - Path for establishing SSE connection (e.g., '/sse')\n * @param options.messagePath - Path for POSTing client messages (e.g., '/message')\n * @param options.req - Incoming HTTP request object\n * @param options.res - HTTP response object (must support .write/.end)\n *\n * @throws {MastraError} If SSE connection setup fails\n *\n * @example\n * ```typescript\n * import http from 'http';\n *\n * const httpServer = http.createServer(async (req, res) => {\n * await server.startSSE({\n * url: new URL(req.url || '', `http://localhost:1234`),\n * ssePath: '/sse',\n * messagePath: '/message',\n * req,\n * res,\n * });\n * });\n *\n * httpServer.listen(1234, () => {\n * console.log('MCP server listening on http://localhost:1234/sse');\n * });\n * ```\n */\n public async startSSE({ url, ssePath, messagePath, req, res }: MCPServerSSEOptions): Promise<void> {\n try {\n if (url.pathname === ssePath) {\n await this.connectSSE({\n messagePath,\n res,\n });\n } else if (url.pathname === messagePath) {\n this.logger.debug('Received message');\n if (!this.sseTransport) {\n res.writeHead(503);\n res.end('SSE connection not established');\n return;\n }\n await this.sseTransport.handlePostMessage(req, res);\n } else {\n this.logger.debug('Unknown path:', { path: url.pathname });\n res.writeHead(404);\n res.end();\n }\n } catch (e) {\n const mastraError = new MastraError(\n {\n id: 'MCP_SERVER_SSE_START_FAILED',\n domain: ErrorDomain.MCP,\n category: ErrorCategory.USER,\n details: {\n url: url.toString(),\n ssePath,\n messagePath,\n },\n },\n e,\n );\n this.logger.trackException(mastraError);\n this.logger.error('Failed to start MCP Server (SSE):', { error: mastraError.toString() });\n throw mastraError;\n }\n }\n\n /**\n * Integrates the MCP server with a Hono web framework using Server-Sent Events (SSE).\n *\n * Call this method from your Hono server's request handler for both the SSE and message paths.\n * This enables Hono-based web applications to expose MCP servers.\n *\n * @param options - Configuration for Hono SSE integration\n * @param options.url - Parsed URL of the incoming request\n * @param options.ssePath - Path for establishing SSE connection (e.g., '/hono-sse')\n * @param options.messagePath - Path for POSTing client messages (e.g., '/message')\n * @param options.context - Hono context object\n *\n * @throws {MastraError} If Hono SSE connection setup fails\n *\n * @example\n * ```typescript\n * import { Hono } from 'hono';\n *\n * const app = new Hono();\n *\n * app.all('*', async (c) => {\n * const url = new URL(c.req.url);\n * return await server.startHonoSSE({\n * url,\n * ssePath: '/hono-sse',\n * messagePath: '/message',\n * context: c,\n * });\n * });\n *\n * export default app;\n * ```\n */\n public async startHonoSSE({ url, ssePath, messagePath, context }: MCPServerHonoSSEOptions) {\n try {\n if (url.pathname === ssePath) {\n return streamSSE(context, async stream => {\n await this.connectHonoSSE({\n messagePath,\n stream,\n });\n });\n } else if (url.pathname === messagePath) {\n this.logger.debug('Received message');\n const sessionId = context.req.query('sessionId');\n this.logger.debug('Received message for sessionId', { sessionId });\n if (!sessionId) {\n return context.text('No sessionId provided', 400);\n }\n if (!this.sseHonoTransports.has(sessionId)) {\n return context.text(`No transport found for sessionId ${sessionId}`, 400);\n }\n const message = await this.sseHonoTransports.get(sessionId)?.handlePostMessage(context);\n if (!message) {\n return context.text('Transport not found', 400);\n }\n return message;\n } else {\n this.logger.debug('Unknown path:', { path: url.pathname });\n return context.text('Unknown path', 404);\n }\n } catch (e) {\n const mastraError = new MastraError(\n {\n id: 'MCP_SERVER_HONO_SSE_START_FAILED',\n domain: ErrorDomain.MCP,\n category: ErrorCategory.USER,\n details: {\n url: url.toString(),\n ssePath,\n messagePath,\n },\n },\n e,\n );\n this.logger.trackException(mastraError);\n this.logger.error('Failed to start MCP Server (Hono SSE):', { error: mastraError.toString() });\n throw mastraError;\n }\n }\n\n /**\n * Integrates the MCP server with an existing HTTP server using streamable HTTP transport.\n *\n * This is the recommended modern transport method, providing better session management and\n * reliability compared to SSE. Call this from your HTTP server's request handler.\n *\n * @param options - Configuration for HTTP integration\n * @param options.url - Parsed URL of the incoming request\n * @param options.httpPath - Path for the MCP endpoint (e.g., '/mcp')\n * @param options.req - Incoming HTTP request (http.IncomingMessage)\n * @param options.res - HTTP response object (http.ServerResponse)\n * @param options.options - Optional transport options\n * @param options.options.sessionIdGenerator - Function to generate unique session IDs (defaults to randomUUID)\n * @param options.options.onsessioninitialized - Callback when a new session is initialized\n * @param options.options.enableJsonResponse - If true, return JSON instead of SSE streaming\n * @param options.options.eventStore - Event store for message resumability\n * @param options.options.serverless - If true, run in stateless mode without session management (ideal for serverless environments)\n *\n * @throws {MastraError} If HTTP connection setup fails\n *\n * @example\n * ```typescript\n * import http from 'http';\n * import { randomUUID } from 'crypto';\n *\n * const httpServer = http.createServer(async (req, res) => {\n * await server.startHTTP({\n * url: new URL(req.url || '', 'http://localhost:1234'),\n * httpPath: '/mcp',\n * req,\n * res,\n * options: {\n * sessionIdGenerator: () => randomUUID(),\n * onsessioninitialized: (sessionId) => {\n * console.log(`New MCP session: ${sessionId}`);\n * },\n * },\n * });\n * });\n *\n * httpServer.listen(1234);\n * ```\n *\n * @example Serverless mode (Cloudflare Workers, Vercel Edge, etc.)\n * ```typescript\n * export default {\n * async fetch(request: Request) {\n * const url = new URL(request.url);\n * if (url.pathname === '/mcp') {\n * await server.startHTTP({\n * url,\n * httpPath: '/mcp',\n * req: request,\n * res: response,\n * options: { serverless: true },\n * });\n * }\n * return new Response('Not found', { status: 404 });\n * },\n * };\n * ```\n */\n public async startHTTP({\n url,\n httpPath,\n req,\n res,\n options = { sessionIdGenerator: () => randomUUID() },\n }: {\n url: URL;\n httpPath: string;\n req: http.IncomingMessage;\n res: http.ServerResponse<http.IncomingMessage>;\n options?: StreamableHTTPServerTransportOptions & { serverless?: boolean };\n }) {\n this.logger.debug(`startHTTP: Received ${req.method} request to ${url.pathname}`);\n\n if (url.pathname !== httpPath) {\n this.logger.debug(`startHTTP: Pathname ${url.pathname} does not match httpPath ${httpPath}. Returning 404.`);\n res.writeHead(404);\n res.end();\n return;\n }\n\n // Serverless mode: stateless, single request/response\n if (options?.serverless) {\n this.logger.debug('startHTTP: Running in serverless (stateless) mode');\n await this.handleServerlessRequest(req, res);\n return;\n }\n\n const sessionId = req.headers['mcp-session-id'] as string | undefined;\n let transport: StreamableHTTPServerTransport | undefined;\n\n this.logger.debug(\n `startHTTP: Session ID from headers: ${sessionId}. Active transports: ${Array.from(this.streamableHTTPTransports.keys()).join(', ')}`,\n );\n\n try {\n if (sessionId && this.streamableHTTPTransports.has(sessionId)) {\n // Found existing session\n transport = this.streamableHTTPTransports.get(sessionId)!;\n this.logger.debug(`startHTTP: Using existing Streamable HTTP transport for session ID: ${sessionId}`);\n\n if (req.method === 'GET') {\n this.logger.debug(\n `startHTTP: Handling GET request for existing session ${sessionId}. Calling transport.handleRequest.`,\n );\n }\n\n // Handle the request using the existing transport\n // Need to parse body for POST requests before passing to handleRequest\n const body =\n req.method === 'POST'\n ? await new Promise((resolve, reject) => {\n let data = '';\n req.on('data', chunk => (data += chunk));\n req.on('end', () => {\n try {\n resolve(JSON.parse(data));\n } catch (e) {\n reject(e);\n }\n });\n req.on('error', reject);\n })\n : undefined;\n\n await transport.handleRequest(req, res, body);\n } else {\n // No session ID or session ID not found\n this.logger.debug(`startHTTP: No existing Streamable HTTP session ID found. ${req.method}`);\n\n // Only allow new sessions via POST initialize request\n if (req.method === 'POST') {\n const body = await new Promise((resolve, reject) => {\n let data = '';\n req.on('data', chunk => (data += chunk));\n req.on('end', () => {\n try {\n resolve(JSON.parse(data));\n } catch (e) {\n reject(e);\n }\n });\n req.on('error', reject);\n });\n\n // Import isInitializeRequest from the correct path\n const { isInitializeRequest } = await import('@modelcontextprotocol/sdk/types.js');\n\n if (isInitializeRequest(body)) {\n this.logger.debug('startHTTP: Received Streamable HTTP initialize request, creating new transport.');\n\n // Create a new transport for the new session\n transport = new StreamableHTTPServerTransport({\n ...options,\n sessionIdGenerator: () => randomUUID(),\n onsessioninitialized: id => {\n this.streamableHTTPTransports.set(id, transport!);\n },\n });\n\n // Set up onclose handler to clean up transport when closed\n transport.onclose = () => {\n const closedSessionId = transport?.sessionId;\n if (closedSessionId && this.streamableHTTPTransports.has(closedSessionId)) {\n this.logger.debug(\n `startHTTP: Streamable HTTP transport closed for session ${closedSessionId}, removing from map.`,\n );\n this.streamableHTTPTransports.delete(closedSessionId);\n // Also clean up the server instance for this session\n if (this.httpServerInstances.has(closedSessionId)) {\n this.httpServerInstances.delete(closedSessionId);\n this.logger.debug(`startHTTP: Cleaned up server instance for closed session ${closedSessionId}`);\n }\n }\n };\n\n // Create a new server instance for this HTTP session\n const sessionServerInstance = this.createServerInstance();\n\n // Connect the new server instance to the new transport\n await sessionServerInstance.connect(transport);\n\n // Store both the transport and server instance when the session is initialized\n if (transport.sessionId) {\n this.streamableHTTPTransports.set(transport.sessionId, transport);\n this.httpServerInstances.set(transport.sessionId, sessionServerInstance);\n this.logger.debug(\n `startHTTP: Streamable HTTP session initialized and stored with ID: ${transport.sessionId}`,\n );\n } else {\n this.logger.warn('startHTTP: Streamable HTTP transport initialized without a session ID.');\n }\n\n // Handle the initialize request\n return await transport.handleRequest(req, res, body);\n } else {\n // POST request but not initialize, and no session ID\n this.logger.warn('startHTTP: Received non-initialize POST request without a session ID.');\n res.writeHead(400, { 'Content-Type': 'application/json' });\n res.end(\n JSON.stringify({\n jsonrpc: '2.0',\n error: {\n code: -32000,\n message: 'Bad Request: No valid session ID provided for non-initialize request',\n },\n id: (body as any)?.id ?? null, // Include original request ID if available\n }),\n );\n }\n } else {\n // Non-POST request (GET/DELETE) without a session ID\n this.logger.warn(`startHTTP: Received ${req.method} request without a session ID.`);\n res.writeHead(400, { 'Content-Type': 'application/json' });\n res.end(\n JSON.stringify({\n jsonrpc: '2.0',\n error: {\n code: -32000,\n message: `Bad Request: ${req.method} request requires a valid session ID`,\n },\n id: null,\n }),\n );\n }\n }\n } catch (error) {\n const mastraError = new MastraError(\n {\n id: 'MCP_SERVER_HTTP_CONNECTION_FAILED',\n domain: ErrorDomain.MCP,\n category: ErrorCategory.USER,\n text: 'Failed to connect MCP server using HTTP transport',\n },\n error,\n );\n this.logger.trackException(mastraError);\n this.logger.error('startHTTP: Error handling Streamable HTTP request:', { error: mastraError });\n // If headers haven't been sent, send an error response\n if (!res.headersSent) {\n res.writeHead(500, { 'Content-Type': 'application/json' });\n res.end(\n JSON.stringify({\n jsonrpc: '2.0',\n error: {\n code: -32603,\n message: 'Internal server error',\n },\n id: null, // Cannot determine original request ID in catch\n }),\n );\n }\n }\n }\n\n /**\n * Handles a stateless, serverless HTTP request without session management.\n *\n * This method bypasses all session/transport state and handles each request independently.\n * For serverless environments (Cloudflare Workers, Vercel Edge, etc.) where\n * persistent connections and session state cannot be maintained across requests.\n *\n * Each request gets a fresh transport and server instance that are discarded after the response.\n *\n * @param req - Incoming HTTP request\n * @param res - HTTP response object\n * @private\n */\n private async handleServerlessRequest(req: http.IncomingMessage, res: http.ServerResponse<http.IncomingMessage>) {\n try {\n this.logger.debug(`handleServerlessRequest: Received ${req.method} request`);\n\n // Parse the request body (for POST requests)\n const body =\n req.method === 'POST'\n ? await new Promise<any>((resolve, reject) => {\n let data = '';\n req.on('data', chunk => (data += chunk));\n req.on('end', () => {\n try {\n resolve(JSON.parse(data));\n } catch (e) {\n reject(new Error(`Invalid JSON in request body: ${e instanceof Error ? e.message : String(e)}`));\n }\n });\n req.on('error', reject);\n })\n : undefined;\n\n this.logger.debug(`handleServerlessRequest: Processing ${req.method} request`, {\n method: body?.method,\n id: body?.id,\n });\n\n // Create a transient server instance for this single request\n const transientServer = this.createServerInstance();\n\n // Create a one-time transport that handles this single request\n // sessionIdGenerator: undefined disables session management entirely\n // enableJsonResponse: true forces JSON-RPC responses instead of SSE streaming\n const tempTransport = new StreamableHTTPServerTransport({\n sessionIdGenerator: undefined,\n enableJsonResponse: true,\n });\n\n // Connect the transient server to the temporary transport\n await transientServer.connect(tempTransport);\n\n // Handle the request through the transport\n // The transport will send the response and this instance will be garbage collected\n await tempTransport.handleRequest(req, res, body);\n\n this.logger.debug(`handleServerlessRequest: Completed ${body?.method} request`, { id: body?.id });\n } catch (error) {\n const mastraError = new MastraError(\n {\n id: 'MCP_SERVER_SERVERLESS_REQUEST_FAILED',\n domain: ErrorDomain.MCP,\n category: ErrorCategory.USER,\n text: 'Failed to handle serverless MCP request',\n },\n error,\n );\n this.logger.trackException(mastraError);\n this.logger.error('handleServerlessRequest: Error handling request:', { error: mastraError });\n\n // If headers haven't been sent, send an error response\n if (!res.headersSent) {\n res.writeHead(500, { 'Content-Type': 'application/json' });\n res.end(\n JSON.stringify({\n jsonrpc: '2.0',\n error: {\n code: -32603,\n message: 'Internal server error',\n data: error instanceof Error ? error.message : String(error),\n },\n id: null,\n }),\n );\n }\n }\n }\n\n /**\n * Establishes the SSE connection for the MCP server.\n *\n * This is a lower-level method called internally by `startSSE()`. In most cases,\n * you should use `startSSE()` instead which handles both connection establishment\n * and message routing.\n *\n * @param params - Connection parameters\n * @param params.messagePath - Path for POST requests from the client\n * @param params.res - HTTP response object for the SSE stream\n * @throws {MastraError} If SSE connection establishment fails\n *\n * @example\n * ```typescript\n * // Usually called internally by startSSE()\n * await server.connectSSE({\n * messagePath: '/message',\n * res: response\n * });\n * ```\n */\n public async connectSSE({\n messagePath,\n res,\n }: {\n messagePath: string;\n res: http.ServerResponse<http.IncomingMessage>;\n }) {\n try {\n this.logger.debug('Received SSE connection');\n this.sseTransport = new SSEServerTransport(messagePath, res);\n await this.server.connect(this.sseTransport);\n\n this.server.onclose = async () => {\n this.sseTransport = undefined;\n await this.server.close();\n };\n\n res.on('close', () => {\n this.sseTransport = undefined;\n });\n } catch (e) {\n const mastraError = new MastraError(\n {\n id: 'MCP_SERVER_SSE_CONNECT_FAILED',\n domain: ErrorDomain.MCP,\n category: ErrorCategory.USER,\n details: {\n messagePath,\n },\n },\n e,\n );\n this.logger.trackException(mastraError);\n this.logger.error('Failed to connect to MCP Server (SSE):', { error: mastraError });\n throw mastraError;\n }\n }\n\n /**\n * Establishes the Hono SSE connection for the MCP server.\n *\n * This is a lower-level method called internally by `startHonoSSE()`. In most cases,\n * you should use `startHonoSSE()` instead which handles both connection establishment\n * and message routing.\n *\n * @param params - Connection parameters\n * @param params.messagePath - Path for POST requests from the client\n * @param params.stream - Hono SSE streaming API object\n * @throws {MastraError} If Hono SSE connection establishment fails\n *\n * @example\n * ```typescript\n * // Usually called internally by startHonoSSE()\n * await server.connectHonoSSE({\n * messagePath: '/message',\n * stream: sseStream\n * });\n * ```\n */\n public async connectHonoSSE({ messagePath, stream }: { messagePath: string; stream: SSEStreamingApi }) {\n this.logger.debug('Received SSE connection');\n const sseTransport = new SSETransport(messagePath, stream);\n const sessionId = sseTransport.sessionId;\n this.logger.debug('SSE Transport created with sessionId:', { sessionId });\n this.sseHonoTransports.set(sessionId, sseTransport);\n\n stream.onAbort(() => {\n this.logger.debug('SSE Transport aborted with sessionId:', { sessionId });\n this.sseHonoTransports.delete(sessionId);\n });\n try {\n await this.server.connect(sseTransport);\n this.server.onclose = async () => {\n this.logger.debug('SSE Transport closed with sessionId:', { sessionId });\n this.sseHonoTransports.delete(sessionId);\n await this.server.close();\n };\n\n while (true) {\n // This will keep the connection alive\n // You can also await for a promise that never resolves\n await stream.sleep(60_000);\n const sessionIds = Array.from(this.sseHonoTransports.keys() || []);\n this.logger.debug('Active Hono SSE sessions:', { sessionIds });\n await stream.write(':keep-alive\\n\\n');\n }\n } catch (e) {\n const mastraError = new MastraError(\n {\n id: 'MCP_SERVER_HONO_SSE_CONNECT_FAILED',\n domain: ErrorDomain.MCP,\n category: ErrorCategory.USER,\n details: {\n messagePath,\n },\n },\n e,\n );\n this.logger.trackException(mastraError);\n this.logger.error('Failed to connect to MCP Server (Hono SSE):', { error: mastraError });\n throw mastraError;\n }\n }\n\n /**\n * Closes the MCP server and releases all resources.\n *\n * This method cleanly shuts down all active transports (stdio, SSE, HTTP) and their\n * associated connections. Call this when your application is shutting down.\n *\n * @throws {MastraError} If closing the server fails\n *\n * @example\n * ```typescript\n * // Graceful shutdown\n * process.on('SIGTERM', async () => {\n * await server.close();\n * process.exit(0);\n * });\n * ```\n */\n async close() {\n try {\n if (this.stdioTransport) {\n await this.stdioTransport.close?.();\n this.stdioTransport = undefined;\n }\n if (this.sseTransport) {\n await this.sseTransport.close?.();\n this.sseTransport = undefined;\n }\n if (this.sseHonoTransports) {\n for (const transport of this.sseHonoTransports.values()) {\n await transport.close?.();\n }\n this.sseHonoTransports.clear();\n }\n // Close all active Streamable HTTP transports and their server instances\n if (this.streamableHTTPTransports) {\n for (const transport of this.streamableHTTPTransports.values()) {\n await transport.close?.();\n }\n this.streamableHTTPTransports.clear();\n }\n // Close all HTTP server instances\n if (this.httpServerInstances) {\n for (const serverInstance of this.httpServerInstances.values()) {\n await serverInstance.close?.();\n }\n this.httpServerInstances.clear();\n }\n await this.server.close();\n this.logger.info('MCP server closed.');\n } catch (error) {\n const mastraError = new MastraError(\n {\n id: 'MCP_SERVER_CLOSE_FAILED',\n domain: ErrorDomain.MCP,\n category: ErrorCategory.THIRD_PARTY,\n },\n error,\n );\n this.logger.trackException(mastraError);\n this.logger.error('Error closing MCP server:', { error: mastraError });\n throw mastraError;\n }\n }\n\n /**\n * Gets basic information about the server.\n *\n * Returns metadata including server ID, name, description, repository, and version details.\n * This information conforms to the MCP Server schema.\n *\n * @returns Server information object\n *\n * @example\n * ```typescript\n * const info = server.getServerInfo();\n * console.log(`${info.name} v${info.version_detail.version}`);\n * // Output: My Weather Server v1.0.0\n * ```\n */\n public getServerInfo(): ServerInfo {\n return {\n id: this.id,\n name: this.name,\n description: this.description,\n repository: this.repository,\n version_detail: {\n version: this.version,\n release_date: this.releaseDate,\n is_latest: this.isLatest,\n },\n };\n }\n\n /**\n * Gets detailed information about the server including packaging and deployment metadata.\n *\n * Returns extended server information with package details, remotes, and deployment configurations.\n * This information conforms to the MCP ServerDetail schema.\n *\n * @returns Detailed server information object\n *\n * @example\n * ```typescript\n * const detail = server.getServerDetail();\n * console.log(detail.package_canonical); // 'npm'\n * console.log(detail.packages); // Package installation info\n * ```\n */\n public getServerDetail(): ServerDetailInfo {\n return {\n ...this.getServerInfo(),\n package_canonical: this.packageCanonical,\n packages: this.packages,\n remotes: this.remotes,\n };\n }\n\n /**\n * Gets a list of all tools provided by this MCP server with their schemas.\n *\n * Returns information about all registered tools including explicit tools, agent-derived tools,\n * and workflow-derived tools. Includes input/output schemas and tool types.\n *\n * @returns Object containing array of tool information\n *\n * @example\n * ```typescript\n * const toolList = server.getToolListInfo();\n * toolList.tools.forEach(tool => {\n * console.log(`${tool.name}: ${tool.description}`);\n * console.log(`Type: ${tool.toolType || 'tool'}`);\n * });\n * ```\n */\n public getToolListInfo(): {\n tools: Array<{ name: string; description?: string; inputSchema: any; outputSchema?: any; toolType?: MCPToolType }>;\n } {\n this.logger.debug(`Getting tool list information for MCPServer '${this.name}'`);\n return {\n tools: Object.entries(this.convertedTools).map(([toolId, tool]) => ({\n id: toolId,\n name: tool.id || toolId,\n description: tool.description,\n inputSchema: tool.parameters?.jsonSchema || tool.parameters,\n outputSchema: tool.outputSchema?.jsonSchema || tool.outputSchema,\n toolType: tool.mcp?.toolType,\n })),\n };\n }\n\n /**\n * Gets information for a specific tool provided by this MCP server.\n *\n * Returns detailed information about a single tool including its name, description, schemas, and type.\n * Returns undefined if the tool is not found.\n *\n * @param toolId - The ID/name of the tool to retrieve\n * @returns Tool information object or undefined if not found\n *\n * @example\n * ```typescript\n * const toolInfo = server.getToolInfo('getWeather');\n * if (toolInfo) {\n * console.log(toolInfo.description);\n * console.log(toolInfo.inputSchema);\n * }\n * ```\n */\n public getToolInfo(\n toolId: string,\n ): { name: string; description?: string; inputSchema: any; outputSchema?: any; toolType?: MCPToolType } | undefined {\n const tool = this.convertedTools[toolId];\n if (!tool) {\n this.logger.debug(`Tool '${toolId}' not found on MCPServer '${this.name}'`);\n return undefined;\n }\n this.logger.debug(`Getting info for tool '${toolId}' on MCPServer '${this.name}'`);\n return {\n name: tool.id || toolId,\n description: tool.description,\n inputSchema: tool.parameters?.jsonSchema || tool.parameters,\n outputSchema: tool.outputSchema?.jsonSchema || tool.outputSchema,\n toolType: tool.mcp?.toolType,\n };\n }\n\n /**\n * Executes a specific tool provided by this MCP server.\n *\n * This method validates the tool arguments against the input schema and executes the tool.\n * If validation fails, returns an error object instead of throwing.\n *\n * @param toolId - The ID/name of the tool to execute\n * @param args - The arguments to pass to the tool's execute function\n * @param executionContext - Optional context including messages and toolCallId\n * @returns Promise resolving to the tool execution result\n * @throws {MastraError} If the tool is not found or execution fails\n *\n * @example\n * ```typescript\n * const result = await server.executeTool(\n * 'getWeather',\n * { location: 'London' },\n * { toolCallId: 'call_123' }\n * );\n * console.log(result);\n * ```\n */\n public async executeTool(\n toolId: string,\n args: any,\n executionContext?: { messages?: any[]; toolCallId?: string },\n ): Promise<any> {\n const tool = this.convertedTools[toolId];\n let validatedArgs = args;\n try {\n if (!tool) {\n this.logger.warn(`ExecuteTool: Unknown tool '${toolId}' requested on MCPServer '${this.name}'.`);\n throw new Error(`Unknown tool: ${toolId}`);\n }\n\n this.logger.debug(`ExecuteTool: Invoking '${toolId}' with arguments:`, args);\n\n if (tool.parameters instanceof z.ZodType && typeof tool.parameters.safeParse === 'function') {\n const validation = tool.parameters.safeParse(args ?? {});\n if (!validation.success) {\n const errorMessages = validation.error.errors\n .map((e: z.ZodIssue) => `- ${e.path?.join('.') || 'root'}: ${e.message}`)\n .join('\\n');\n this.logger.warn(`ExecuteTool: Invalid tool arguments for '${toolId}': ${errorMessages}`, {\n errors: validation.error.format(),\n });\n // Return validation error as a result instead of throwing\n return {\n error: true,\n message: `Tool validation failed. Please fix the following errors and try again:\\n${errorMessages}\\n\\nProvided arguments: ${JSON.stringify(args, null, 2)}`,\n validationErrors: validation.error.format(),\n };\n }\n validatedArgs = validation.data;\n } else {\n this.logger.debug(\n `ExecuteTool: Tool '${toolId}' parameters is not a Zod schema with safeParse or is undefined. Skipping validation.`,\n );\n }\n\n if (!tool.execute) {\n this.logger.error(`ExecuteTool: Tool '${toolId}' does not have an execute function.`);\n throw new Error(`Tool '${toolId}' cannot be executed.`);\n }\n } catch (error) {\n const mastraError = new MastraError(\n {\n id: 'MCP_SERVER_TOOL_EXECUTE_PREPARATION_FAILED',\n domain: ErrorDomain.MCP,\n category: ErrorCategory.USER,\n details: {\n toolId,\n args,\n },\n },\n error,\n );\n this.logger.trackException(mastraError);\n throw mastraError;\n }\n\n try {\n const finalExecutionContext = {\n messages: executionContext?.messages || [],\n toolCallId: executionContext?.toolCallId || randomUUID(),\n };\n const result = await tool.execute(validatedArgs, finalExecutionContext);\n this.logger.info(`ExecuteTool: Tool '${toolId}' executed successfully.`);\n return result;\n } catch (error) {\n const mastraError = new MastraError(\n {\n id: 'MCP_SERVER_TOOL_EXECUTE_FAILED',\n domain: ErrorDomain.MCP,\n category: ErrorCategory.USER,\n details: {\n toolId,\n validatedArgs: validatedArgs,\n },\n },\n error,\n );\n this.logger.trackException(mastraError);\n this.logger.error(`ExecuteTool: Tool execution failed for '${toolId}':`, { error });\n throw mastraError;\n }\n }\n}\n"]}
|