@mastra/core
Version:
1 lines • 39.3 kB
Source Map (JSON)
{"version":3,"file":"index.cjs","names":["MastraBase","MastraError","RegisteredLogger","slugify"],"sources":["../../src/mcp/types.ts","../../src/mcp/index.ts"],"sourcesContent":["import type * as http from 'node:http';\nimport type { JSONSchema7 } from 'json-schema';\nimport type { ToolsInput, Agent } from '../agent';\nimport type { MastraFGAPermissionInput } from '../auth/ee/interfaces/permissions.generated';\nimport type { RequestContext } from '../request-context';\nimport type { Workflow } from '../workflows';\n\nexport interface HonoContextLike {\n req: {\n header(name: string): string | undefined;\n query(name: string): string | undefined;\n json(): Promise<unknown>;\n };\n text(text: string, status?: number, headers?: Record<string, string>): Response;\n}\n\ninterface MCPServerSSEOptionsBase {\n /**\n * Parsed URL of the incoming request\n */\n url: URL;\n\n /**\n * Path for establishing the SSE connection (e.g. '/sse')\n */\n ssePath: string;\n\n /**\n * Path for POSTing client messages (e.g. '/message')\n */\n messagePath: string;\n}\n\n/**\n * Options for starting an MCP server with SSE transport\n * @deprecated The standalone HTTP+SSE transport only exists in `@mastra/mcp` 1.x; removed in the next core major.\n */\nexport interface MCPServerSSEOptions extends MCPServerSSEOptionsBase {\n /**\n * Incoming HTTP request\n */\n req: http.IncomingMessage;\n\n /**\n * HTTP response (must support .write/.end)\n */\n res: http.ServerResponse<http.IncomingMessage>;\n}\n\n/**\n * Options for starting an MCP server with Hono SSE transport\n * @deprecated The standalone HTTP+SSE transport only exists in `@mastra/mcp` 1.x; removed in the next core major.\n */\nexport interface MCPServerHonoSSEOptions extends MCPServerSSEOptionsBase {\n /**\n * Incoming Hono context\n */\n context: HonoContextLike;\n\n /**\n * Auth info for this request, surfaced to tool and agent execution as\n * `extra.authInfo`. Streamable HTTP carries this on `req.auth`; the Hono SSE\n * transport has no Node request, so adapters pass it explicitly.\n */\n authInfo?: unknown;\n}\n\nexport interface MCPServerHTTPOptions {\n /**\n * Parsed URL of the incoming request\n */\n url: URL;\n\n /**\n * Path for establishing the HTTP connection (e.g. '/mcp')\n */\n httpPath: string;\n\n /**\n * Incoming HTTP request\n */\n req: http.IncomingMessage;\n\n /**\n * HTTP response (must support .write/.end)\n */\n res: http.ServerResponse<http.IncomingMessage>;\n\n /**\n * Optional options to pass to the transport (e.g. sessionIdGenerator)\n * @deprecated Only `@mastra/mcp` 1.x reads this; MCP 2026-07-28 has no sessions. Removed in the next core major.\n */\n options?: any; // Consider typing StreamableHTTPServerTransportOptions from @modelcontextprotocol/node if possible\n}\n\n// +++ MCP Registry API Spec Types +++\n/** Describes a source code repository. */\nexport interface Repository {\n /** The URL of the repository (e.g., a GitHub URL). */\n url: string;\n /** The source control platform (e.g., 'github', 'gitlab'). */\n source: 'github' | 'gitlab' | string;\n /** A unique identifier for the repository at the source. */\n id: string;\n}\n\n/** Provides details about a specific version of an MCP server. */\nexport interface VersionDetail {\n /** The semantic version string (e.g., \"1.0.2\"). */\n version: string;\n /** The ISO 8601 date-time string when this version was released or registered. */\n release_date: string;\n /** Indicates if this version is the latest available. */\n is_latest: boolean;\n}\n\n/** Base interface for command-line arguments. */\nexport interface ArgumentInfo {\n /** The name of the argument. */\n name: string;\n /** A description of what the argument is for. */\n description: string;\n /** Whether the argument is required. */\n is_required: boolean;\n /** Whether the argument can be specified multiple times. */\n is_repeatable?: boolean;\n /** Whether the argument's value can be edited by the user (e.g., in a UI). */\n is_editable?: boolean;\n /** A list of predefined choices for the argument's value. */\n choices?: string[];\n /** The default value for the argument if not specified. */\n default_value?: string | number | boolean;\n}\n\n/** Describes a positional argument for a command. */\nexport interface PositionalArgumentInfo extends ArgumentInfo {\n /** The 0-indexed position of the argument. */\n position: number;\n}\n\n/** Describes a named argument (flag) for a command. */\nexport interface NamedArgumentInfo extends ArgumentInfo {\n /** The short flag for the argument (e.g., \"-y\"). */\n short_flag?: string;\n /** The long flag for the argument (e.g., \"--yes\"). */\n long_flag?: string;\n /** Whether the flag requires a value (e.g., `--config <value>`) or is a boolean flag. */\n requires_value?: boolean;\n}\n\n/** Describes a subcommand for a command-line tool. */\nexport interface SubcommandInfo {\n /** The name of the subcommand (e.g., \"run\", \"list\"). */\n name: string;\n /** A description of what the subcommand does. */\n description: string;\n /** Whether this subcommand is required if its parent command is used. */\n is_required?: boolean;\n /** Nested subcommands. */\n subcommands?: SubcommandInfo[];\n /** Positional arguments for this subcommand. */\n positional_arguments?: PositionalArgumentInfo[];\n /** Named arguments (flags) for this subcommand. */\n named_arguments?: NamedArgumentInfo[];\n}\n\n/** Describes a command to run an MCP server package. */\nexport interface CommandInfo {\n /** The primary command executable (e.g., \"npx\", \"docker\"). */\n name: 'npx' | 'docker' | 'pypi' | 'uvx' | string;\n /** Subcommands to append to the primary command. */\n subcommands?: SubcommandInfo[];\n /** Positional arguments for the command. */\n positional_arguments?: PositionalArgumentInfo[];\n /** Named arguments (flags) for the command. */\n named_arguments?: NamedArgumentInfo[];\n}\n\n/** Describes an environment variable required or used by an MCP server package. */\nexport interface EnvironmentVariableInfo {\n /** The name of the environment variable (e.g., \"API_KEY\"). */\n name: string;\n /** A description of what the environment variable is for. */\n description: string;\n /** Whether the environment variable is required. */\n required?: boolean;\n /** The default value for the environment variable if not set. */\n default_value?: string;\n}\n\n/** Describes an installable package for an MCP server. */\nexport interface PackageInfo {\n /** The name of the package registry (e.g., \"npm\", \"docker\"). */\n registry_name: 'npm' | 'docker' | 'pypi' | 'homebrew' | string;\n /** The name of the package. */\n name: string;\n /** The version of the package. */\n version: string;\n /** The command structure to run this package as an MCP server. */\n command?: CommandInfo;\n /** Environment variables relevant to this package. */\n environment_variables?: EnvironmentVariableInfo[];\n}\n\n/** Describes a remote endpoint for accessing an MCP server. */\nexport interface RemoteInfo {\n /** The transport type for the remote connection (e.g., \"sse\", \"streamable\"). */\n transport_type: 'streamable' | 'sse' | string;\n /** The URL of the remote endpoint. */\n url: string;\n}\n\nexport type MCPAuthInfoToUserMapper<TUser = unknown> = (args: {\n /**\n * Authentication data provided by the MCP SDK request handler `extra.authInfo`.\n */\n authInfo: unknown;\n /**\n * Full MCP SDK request handler extra object when available.\n */\n extra: Record<string, unknown>;\n /**\n * RequestContext that will be used for the MCP tool list or execution.\n * The mapper may read or set additional request-scoped values on it.\n */\n requestContext: RequestContext;\n}) => TUser | null | undefined | Promise<TUser | null | undefined>;\n\nexport interface MCPServerFGAResourceMappingEntry {\n /** The FGA resource type to authorize MCP tool checks against. */\n fgaResourceType: string;\n /**\n * Derive the FGA resource ID from the MCP request/user context.\n * Return `undefined` to fall back to the MCP tool resource ID.\n */\n deriveId?: (ctx: { user: unknown; resourceId?: string; requestContext?: RequestContext }) => string | undefined;\n}\n\nexport type MCPServerFGAPermissionMapping = Partial<Record<MastraFGAPermissionInput, string>> & Record<string, string>;\n\nexport interface MCPServerFGAConfig {\n /**\n * Map MCP server tool authorization resources independently from the Mastra\n * instance's global `tool` resource mapping.\n */\n resourceMapping?: Partial<Record<'tool' | 'tools', MCPServerFGAResourceMappingEntry>>;\n /**\n * Map MCP server tool authorization permissions independently from the Mastra\n * instance's global permission mapping.\n */\n permissionMapping?: MCPServerFGAPermissionMapping;\n}\n\n/** An icon an MCP client can display for a server (the MCP `Icon` type). */\nexport interface MCPServerIcon {\n /** URI of the icon: an `https:` URL or a `data:` URI. */\n src: string;\n /** Optional MIME type, such as `image/png` or `image/svg+xml`. */\n mimeType?: string;\n /** Optional sizes the icon is available in, such as `['48x48']` or `['any']` for scalable formats. */\n sizes?: string[];\n /** Optional theme the icon is designed for. */\n theme?: 'light' | 'dark';\n}\n\n// +++ Authoritative MCPServerConfig +++\n/** Configuration options for creating an MCPServer instance. */\nexport interface MCPServerConfig<TId extends string = string> {\n /** The display name of the MCP server. */\n name: string;\n /** The semantic version of the MCP server. */\n version: string;\n /** The tools that this MCP server will expose. */\n tools: ToolsInput;\n /**\n * Optional Agent instances to be exposed as tools.\n * Each agent will be converted into a tool named 'ask_<agentName>'.\n */\n agents?: Record<string, Agent>;\n /**\n * Optional Workflow instances to be exposed as tools.\n * Each workflow will be converted into a tool named 'run_<workflowKey>'.\n */\n workflows?: Record<string, Workflow>;\n /**\n * Optional unique identifier for the server.\n * If not provided, a UUID will be generated.\n * If provided, this ID is considered final and cannot be changed by Mastra.\n */\n id?: TId;\n /** Optional description of the MCP server. */\n description?: string;\n /** Optional human-readable display title, announced to MCP clients. Clients fall back to `name` when absent. */\n title?: string;\n /** Optional URL of the server's website, announced to MCP clients. */\n websiteUrl?: string;\n /** Optional icons clients can display for the server, announced to MCP clients. */\n icons?: MCPServerIcon[];\n /** Optional instructions describing how to use the server and its features. */\n instructions?: string;\n /**\n * Maps MCP transport auth information into the user object used by Mastra FGA.\n *\n * Self-hosted OAuth MCP transports pass authenticated identity to request\n * handlers as `extra.authInfo`; Mastra FGA checks read the authenticated user\n * from `requestContext.get('user')`. Provide this hook when the MCP server is\n * registered on an FGA-enabled Mastra instance and the transport does not\n * already put a `user` value in the request context.\n */\n mapAuthInfoToUser?: MCPAuthInfoToUserMapper;\n /**\n * Optional FGA mapping overrides for this MCP server's `tools/list` and\n * `tools/call` checks. These mappings are applied before delegating to the\n * Mastra instance FGA provider and do not affect internal agent/workflow tool\n * execution.\n */\n fga?: MCPServerFGAConfig;\n /** Optional repository information for the server's source code. */\n repository?: Repository;\n /**\n * Optional release date of this server version (ISO 8601 string).\n * Defaults to the time of instantiation if not provided.\n */\n releaseDate?: string;\n /**\n * Optional flag indicating if this is the latest version.\n * Defaults to true if not provided.\n */\n isLatest?: boolean;\n /**\n * Optional canonical packaging format if the server is distributed as a package\n * (e.g., \"npm\", \"docker\").\n */\n packageCanonical?: 'npm' | 'docker' | 'pypi' | 'crates' | string;\n /** Optional list of installable packages for this server. */\n packages?: PackageInfo[];\n /** Optional list of remote access points for this server. */\n remotes?: RemoteInfo[];\n}\n\n// +++ Server Information Structures for return types +++\n/** Basic information about an MCP server, conforming to the MCP Registry 'Server' schema. */\nexport interface ServerInfo {\n /** The unique ID of the server. */\n id: string;\n /** The name of the server. */\n name: string;\n /** A description of the server. */\n description?: string;\n /** Repository information for the server. */\n repository?: Repository;\n /** Detailed version information. */\n version_detail: VersionDetail;\n}\n\n/** Detailed information about an MCP server, conforming to the MCP Registry 'ServerDetail' schema. */\nexport interface ServerDetailInfo extends ServerInfo {\n /** The canonical packaging format, if applicable. */\n package_canonical?: MCPServerConfig['packageCanonical'];\n /** Information about installable packages for this server. */\n packages?: PackageInfo[];\n /** Information about remote access points for this server. */\n remotes?: RemoteInfo[];\n}\n\n/**\n * What `executeTool` resolves to on a server with `mcpVersion === 2`. A tool that\n * calls `context.suspend(payload)` is reported as `suspended` together with the\n * payload and its `resumeSchema` (as JSON Schema) so the caller can ask for\n * exactly that input; otherwise the tool's output is returned as `completed`. There is\n * no failure variant: a tool that throws, or input/resume data that fails the declared\n * schemas, rejects the `executeTool` promise instead (core reports schema failures as a\n * `ValidationError` output, which a 2.x server must not pass through as `completed`).\n */\nexport type MCPToolExecutionResultV2 =\n | { status: 'completed'; output: unknown }\n | { status: 'suspended'; suspendPayload: unknown; resumeSchema?: JSONSchema7 };\n\n/**\n * How a client can receive an MCP server event type.\n * @experimental\n */\nexport type MCPServerEventDeliveryMode = 'push' | 'poll' | 'webhook';\n\n/**\n * An event type a server declares, as shown in Studio. Mirrors the `events/list`\n * descriptor plus `emittable`.\n * @experimental\n */\nexport interface MCPServerEventInfo {\n name: string;\n description?: string;\n delivery: MCPServerEventDeliveryMode[];\n inputSchema?: Record<string, unknown>;\n payloadSchema?: Record<string, unknown>;\n /** Fed by `server.events.emit()` rather than a `poll` source. */\n emittable: boolean;\n}\n\n/** @experimental */\nexport interface MCPServerEventOccurrenceInfo {\n eventId: string;\n name: string;\n timestamp: string;\n data: Record<string, unknown>;\n cursor?: string | null;\n _meta?: Record<string, unknown>;\n}\n\n/** @experimental */\nexport interface MCPServerEventPollInfo {\n events: MCPServerEventOccurrenceInfo[];\n cursor: string | null;\n hasMore?: boolean;\n truncated?: boolean;\n nextPollMs?: number;\n}\n\n/**\n * A frame of a local event stream. `error` is recoverable and carries a generic message.\n * @experimental\n */\nexport type MCPServerEventStreamFrame =\n | { type: 'active'; cursor: string | null; truncated: boolean }\n | { type: 'event'; occurrence: MCPServerEventOccurrenceInfo }\n | { type: 'heartbeat'; cursor: string | null }\n | { type: 'error'; message: string }\n | { type: 'terminated' };\n\n/**\n * Error ids an {@link MCPServerEventsInspector} throws as `MastraError`s.\n * @experimental\n */\nexport const MCP_SERVER_EVENT_ERROR_IDS = {\n unknownEvent: 'MCP_SERVER_UNKNOWN_EVENT',\n unsupportedDelivery: 'MCP_SERVER_EVENT_UNSUPPORTED_DELIVERY',\n invalidArguments: 'MCP_SERVER_EVENT_INVALID_ARGUMENTS',\n forbidden: 'MCP_SERVER_EVENT_FORBIDDEN',\n notEmittable: 'MCP_SERVER_EVENT_NOT_EMITTABLE',\n invalidPayload: 'MCP_SERVER_EVENT_INVALID_PAYLOAD',\n tooManyStreams: 'MCP_SERVER_EVENT_TOO_MANY_STREAMS',\n} as const;\n\n/**\n * Runs `events/poll` and `events/stream` in-process, through the same code path as\n * the MCP protocol handlers, and sends test events. Used by Studio.\n * @experimental\n */\nexport interface MCPServerEventsInspector {\n poll(\n name: string,\n params: { arguments?: Record<string, unknown>; cursor?: string | null; maxEvents?: number },\n options?: { requestContext?: RequestContext; signal?: AbortSignal },\n ): Promise<MCPServerEventPollInfo>;\n /**\n * Validates and opens a stream. Resolves once the `active` frame is queued; `closed`\n * settles when the stream ends (terminated, server closed) or `signal` aborts.\n */\n stream(\n name: string,\n params: { arguments?: Record<string, unknown>; cursor?: string | null },\n options: {\n signal: AbortSignal;\n onFrame: (frame: MCPServerEventStreamFrame) => void;\n requestContext?: RequestContext;\n },\n ): Promise<{ closed: Promise<void> }>;\n /** Emits a test occurrence; its `eventId` is prefixed with `mastra-test-`. */\n emit(name: string, data: Record<string, unknown>): Promise<MCPServerEventOccurrenceInfo>;\n}\n\n/**\n * Status of an MCP task (SEP-2663 Tasks extension).\n * @experimental\n */\nexport type MCPServerTaskStatus = 'working' | 'input_required' | 'completed' | 'failed' | 'cancelled';\n\n/**\n * A tool, workflow or agent this server can run as an MCP task, as shown in Studio.\n * @experimental\n */\nexport interface MCPServerTaskSurfaceInfo {\n /** The exposed name, e.g. a tool name, `run_<workflow>` or `ask_<agent>`. */\n name: string;\n type: 'tool' | 'workflow' | 'agent';\n /** `always`: every call runs as a task. `auto`: only when the client asks for one. */\n mode: 'auto' | 'always';\n /** Whether an interrupted task is run again after a restart. */\n recover: boolean;\n /** Clients that don't declare the tasks extension are refused for this surface. */\n required: boolean;\n /** How long a task is kept from creation; `null` until the server closes. */\n ttlMs: number | null;\n}\n\n/**\n * How a server runs MCP tasks, as shown in Studio.\n * @experimental\n */\nexport interface MCPServerTasksInfo {\n enabled: boolean;\n /** Whether the task store can list tasks for {@link MCPServerTasksInspector}. */\n listable: boolean;\n surfaces: MCPServerTaskSurfaceInfo[];\n}\n\n/**\n * A task as shown in Studio. Never carries the task id or the principal: task ids are\n * bearer tokens and principals can identify users, so only their SHA-256 hashes appear.\n * @experimental\n */\nexport interface MCPServerTaskSummary {\n /** SHA-256 hash of the task id. Cannot be used on the MCP protocol. */\n taskKey: string;\n /** The exposed name of the tool, workflow or agent the task runs. */\n surface: string;\n status: MCPServerTaskStatus;\n statusMessage?: string;\n createdAt: string;\n lastUpdatedAt: string;\n /** When the task and its result are deleted, if it has a TTL. */\n expiresAt?: string;\n /** SHA-256 hash of the principal that created the task. */\n principalKey: string;\n /**\n * Who sent the task, readable for operators: the client id with the token subject or user id,\n * or with a short prefix of the token's hash. Never a credential. Missing for older tasks.\n */\n clientLabel?: string;\n /** Open input requests, keyed as on the wire. Only while `input_required`. */\n inputRequests?: Record<string, { method: string; params?: Record<string, unknown> }>;\n /** The `CallToolResult` of a completed task. */\n result?: Record<string, unknown>;\n /** The JSON-RPC error of a failed task. */\n error?: Record<string, unknown>;\n}\n\n/**\n * Filters and paging for {@link MCPServerTasksInspector.list}. Every filter narrows the result.\n * @experimental\n */\nexport interface MCPServerTasksListParams {\n limit?: number;\n /** `nextCursor` from the previous page. */\n cursor?: string;\n status?: MCPServerTaskStatus;\n surface?: string;\n /** Only tasks created by this principal, as its {@link MCPServerTaskSummary.principalKey}. */\n principalKey?: string;\n /** Only the task with this {@link MCPServerTaskSummary.taskKey}. */\n taskKey?: string;\n}\n\n/**\n * Lists, cancels and answers a server's MCP tasks in-process, for Studio. Cancel and answer\n * run through the same task-store code as `tasks/cancel` and `tasks/update`.\n * There is no MCP protocol equivalent of `list`.\n * @experimental\n */\nexport interface MCPServerTasksInspector {\n /** Most recently created first. `nextCursor` is set when more tasks match. */\n list(params?: MCPServerTasksListParams): Promise<{ tasks: MCPServerTaskSummary[]; nextCursor?: string }>;\n /** Finds a task by its MCP task id, which is hashed before the lookup and never kept. */\n find(taskId: string): Promise<MCPServerTaskSummary | undefined>;\n /** Resolves `false` for an unknown, expired or already finished task. */\n cancel(taskKey: string): Promise<boolean>;\n /** Resolves `false` for an unknown or expired task, or one not waiting for these inputs. */\n answer(taskKey: string, inputResponses: Record<string, Record<string, unknown>>): Promise<boolean>;\n}\n","import type { ToolsInput } from '../agent';\nimport { MastraBase } from '../base';\nimport { MastraError } from '../error';\nimport { RegisteredLogger } from '../logger';\nimport type { Mastra } from '../mastra';\nimport type { RequestContext } from '../request-context';\nimport type { InternalCoreTool, MCPToolType } from '../tools';\nimport { slugify } from '../utils/slugify';\nimport type {\n MCPServerConfig,\n MCPServerEventInfo,\n MCPServerEventsInspector,\n MCPServerHonoSSEOptions,\n MCPServerIcon,\n MCPServerHTTPOptions,\n MCPServerSSEOptions,\n MCPServerTasksInfo,\n MCPServerTasksInspector,\n PackageInfo,\n RemoteInfo,\n Repository,\n ServerDetailInfo,\n ServerInfo,\n} from './types';\nexport * from './types';\nexport type { MCPToolType } from '../tools';\n\n/**\n * Abstract base class for MCP server implementations.\n * This provides a common interface and shared functionality for all MCP servers\n * that can be registered with Mastra, including handling of server metadata.\n */\nexport abstract class MCPServerBase<TId extends string = string> extends MastraBase {\n /**\n * Set to `2` by servers that speak MCP 2026-07-28 (`@mastra/mcp` 2.x). Such a server\n * has no standalone SSE transport and its `executeTool` resolves to a\n * `MCPToolExecutionResultV2`. 1.x servers leave it undefined.\n */\n public readonly mcpVersion?: 2;\n /** Tracks if the server ID has been definitively set. */\n private idWasSet = false;\n /** The display name of the MCP server. */\n public readonly name: string;\n /** The semantic version of the MCP server. */\n public readonly version: string;\n /** Internal storage for the server's unique ID. */\n private _id: TId;\n /** A description of what the MCP server does. */\n public readonly description?: string;\n /** A human-readable display title for the MCP server. */\n public readonly title?: string;\n /** The URL of the server's website. */\n public readonly websiteUrl?: string;\n /** Icons clients can display for the server. */\n public readonly icons?: MCPServerIcon[];\n /** Optional instructions describing how to use the server and its features. */\n public readonly instructions?: string;\n /** Repository information for the server's source code. */\n public readonly repository?: Repository;\n /** The release date of this server version (ISO 8601 string). */\n public readonly releaseDate: string;\n /** Indicates if this version is the latest available. */\n public readonly isLatest: boolean;\n /** The canonical packaging format (e.g., \"npm\", \"docker\"), if applicable. */\n public readonly packageCanonical?: MCPServerConfig['packageCanonical'];\n /** Information about installable packages for this server. */\n public readonly packages?: PackageInfo[];\n /** Information about remote access points for this server. */\n public readonly remotes?: RemoteInfo[];\n /** The tools registered with and converted by this MCP server. */\n public convertedTools: Record<string, InternalCoreTool>;\n /** Reference to the Mastra instance if this server is registered with one. */\n public mastra: Mastra | undefined;\n /** Agents to be exposed as tools. */\n protected readonly agents?: MCPServerConfig['agents'];\n /** Workflows to be exposed as tools. */\n protected readonly workflows?: MCPServerConfig['workflows'];\n /** Original tools configuration for re-conversion when Mastra instance is registered. Mutable to support dynamic tool management. */\n protected originalTools: ToolsInput;\n\n /**\n * Public getter for the server's unique ID.\n * The ID is set at construction or by Mastra and is read-only afterwards.\n */\n public get id(): TId {\n return this._id;\n }\n\n /**\n * Gets a read-only view of the registered tools.\n * @returns A readonly record of converted tools.\n */\n tools(): Readonly<Record<string, InternalCoreTool>> {\n return this.convertedTools;\n }\n\n /**\n * Sets the server's unique ID. This method is typically called by Mastra when\n * registering the server, using the key provided in the Mastra configuration.\n * It ensures the ID is set only once.\n * If an ID was already provided in the MCPServerConfig, this method will be a no-op.\n * @param id The unique ID to assign to the server.\n */\n setId(id: TId) {\n if (this.idWasSet) {\n return;\n }\n this._id = id;\n this.idWasSet = true;\n }\n\n /**\n * Abstract method to convert and validate tool definitions provided to the server.\n * This method will also handle agents passed in the config.\n * @param tools Tool definitions to convert.\n * @param agents Agent definitions to convert to tools.\n * @param workflows Workflow definitions to convert to tools.\n * @returns A record of converted and validated tools.\n */\n public abstract convertTools(\n tools: ToolsInput,\n agents?: MCPServerConfig['agents'],\n workflows?: MCPServerConfig['workflows'],\n ): Record<string, InternalCoreTool>;\n\n /**\n * Internal method used by Mastra to register itself with the server.\n * @param mastra The Mastra instance.\n * @internal\n */\n __registerMastra(mastra: Mastra): void {\n this.mastra = mastra;\n // Re-convert tools now that we have the Mastra instance to populate MCP tools execute with mastra instance\n this.convertedTools = this.convertTools(this.originalTools, this.agents, this.workflows);\n\n // Auto-register tools with the Mastra instance\n if (this.originalTools && typeof this.originalTools === 'object') {\n Object.entries(this.originalTools).forEach(([key, tool]) => {\n try {\n // Only add tools that have an id property (ToolAction type)\n if (tool && typeof tool === 'object' && 'id' in tool) {\n // Use tool's intrinsic ID to avoid collisions across MCP servers\n const toolKey = typeof (tool as any).id === 'string' ? (tool as any).id : key;\n mastra.addTool(tool as any, toolKey);\n }\n } catch (error) {\n // Tool might already be registered, that's okay\n if (!(error instanceof MastraError) || error.id !== 'MASTRA_ADD_TOOL_DUPLICATE_KEY') {\n throw error;\n }\n }\n });\n }\n\n // Auto-register agents with the Mastra instance\n if (this.agents && typeof this.agents === 'object') {\n Object.entries(this.agents).forEach(([key, agent]) => {\n try {\n mastra.addAgent(agent, key);\n } catch (error) {\n // Agent might already be registered, that's okay\n if (!(error instanceof MastraError) || error.id !== 'MASTRA_ADD_AGENT_DUPLICATE_KEY') {\n throw error;\n }\n }\n });\n }\n\n // Auto-register workflows with the Mastra instance\n if (this.workflows && typeof this.workflows === 'object') {\n Object.entries(this.workflows).forEach(([key, workflow]) => {\n try {\n mastra.addWorkflow(workflow, key);\n } catch (error) {\n // Workflow might already be registered, that's okay\n if (!(error instanceof MastraError) || error.id !== 'MASTRA_ADD_WORKFLOW_DUPLICATE_KEY') {\n throw error;\n }\n }\n });\n }\n }\n\n /**\n * Constructor for the MCPServerBase.\n * @param config Configuration options for the MCP server, including metadata.\n */\n constructor(config: MCPServerConfig<TId>) {\n super({ component: RegisteredLogger.MCP_SERVER, name: config.name });\n this.name = config.name;\n this.version = config.version;\n\n // If user does not provide an ID, we will use the key from the Mastra config, but if user does not pass MCPServer\n // to Mastra, we will generate a random UUID as a backup.\n if (config.id) {\n this._id = slugify(config.id) as TId;\n this.idWasSet = true;\n } else {\n this._id = (this.mastra?.generateId() || globalThis.crypto.randomUUID()) as TId;\n }\n\n this.description = config.description;\n this.title = config.title;\n this.websiteUrl = config.websiteUrl;\n this.icons = config.icons;\n this.instructions = config.instructions;\n this.repository = config.repository;\n this.releaseDate = config.releaseDate || new Date().toISOString();\n this.isLatest = config.isLatest === undefined ? true : config.isLatest;\n this.packageCanonical = config.packageCanonical;\n this.packages = config.packages;\n this.remotes = config.remotes;\n this.agents = config.agents;\n this.workflows = config.workflows;\n this.originalTools = config.tools;\n this.convertedTools = this.convertTools(config.tools, config.agents, config.workflows);\n }\n\n /**\n * Start the MCP server using stdio transport\n * This is typically used for Windsurf integration\n */\n public abstract startStdio(): Promise<void>;\n\n /**\n * Start the MCP server using the standalone HTTP+SSE transport.\n * Only `@mastra/mcp` 1.x overrides this; MCP 2026-07-28 removed the transport, so the\n * base implementation throws and 2.x servers inherit that.\n * @deprecated Removed in the next core major together with the 1.x server contract.\n * Use `startHTTP` (Streamable HTTP) instead.\n * @param options Options for the SSE transport\n */\n public async startSSE(_options: MCPServerSSEOptions): Promise<void> {\n throw new Error(\n `MCP server '${this.id}' does not implement the standalone SSE transport (removed in MCP 2026-07-28); use startHTTP instead`,\n );\n }\n\n /**\n * Start the MCP server using the standalone Hono SSE transport.\n * Only `@mastra/mcp` 1.x overrides this; MCP 2026-07-28 removed the transport, so the\n * base implementation throws and 2.x servers inherit that.\n * @deprecated Removed in the next core major together with the 1.x server contract.\n * Use `startHTTP` (Streamable HTTP) instead.\n * @param options Options for the SSE transport\n */\n public async startHonoSSE(_options: MCPServerHonoSSEOptions): Promise<Response | undefined> {\n throw new Error(\n `MCP server '${this.id}' does not implement the standalone Hono SSE transport (removed in MCP 2026-07-28); use startHTTP instead`,\n );\n }\n\n /**\n * Start the MCP server using HTTP transport\n * @param options Options for the HTTP transport\n */\n public abstract startHTTP(options: MCPServerHTTPOptions): Promise<void>;\n\n /**\n * Close the MCP server and all its connections\n */\n public abstract close(): Promise<void>;\n\n /**\n * Gets the basic information about the server, conforming to the MCP Registry 'Server' schema.\n * This information is suitable for listing multiple servers.\n * @returns ServerInfo object containing basic server metadata.\n */\n public abstract getServerInfo(): ServerInfo;\n\n /**\n * Gets detailed information about the server, conforming to the MCP Registry 'ServerDetail' schema.\n * This includes all information from `getServerInfo` plus package and remote details.\n * @returns ServerDetailInfo object containing comprehensive server metadata.\n */\n public abstract getServerDetail(): ServerDetailInfo;\n\n /**\n * Gets a list of tools provided by this MCP server, including their schemas.\n * @returns An object containing an array of tool information.\n */\n public abstract getToolListInfo(requestContext?: RequestContext):\n | {\n tools: Array<{\n name: string;\n description?: string;\n inputSchema: any;\n outputSchema?: any;\n toolType?: MCPToolType;\n _meta?: Record<string, unknown>;\n }>;\n }\n | Promise<{\n tools: Array<{\n name: string;\n description?: string;\n inputSchema: any;\n outputSchema?: any;\n toolType?: MCPToolType;\n _meta?: Record<string, unknown>;\n }>;\n }>;\n\n /**\n * Gets information for a specific tool provided by this MCP server.\n * @param toolId The ID/name of the tool to retrieve.\n * @returns Tool information (name, description, inputSchema) or undefined if not found.\n */\n public abstract getToolInfo(toolId: string):\n | {\n name: string;\n description?: string;\n inputSchema: any;\n outputSchema?: any;\n toolType?: MCPToolType;\n _meta?: Record<string, unknown>;\n }\n | undefined\n | Promise<\n | {\n name: string;\n description?: string;\n inputSchema: any;\n outputSchema?: any;\n toolType?: MCPToolType;\n _meta?: Record<string, unknown>;\n }\n | undefined\n >;\n\n /**\n * Executes a specific tool provided by this MCP server.\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 for the tool execution (e.g., messages, toolCallId).\n * On a 2026-07-28 server a continuation passes the previous round's `resumeData` and\n * `suspendPayload`; the server supplies `context.suspend` and `context.mcp`.\n * @returns A promise that resolves to the result of the tool execution. A server with\n * `mcpVersion === 2` resolves to a `MCPToolExecutionResultV2` so a tool that suspended for\n * input is reported instead of being mistaken for a completed call; such a server declares\n * that return type on its override (the base stays `Promise<any>` so 1.x subclasses with a\n * concrete return type keep compiling).\n * @throws Error if the tool is not found, or if execution fails.\n */\n public abstract executeTool(\n toolId: string,\n args: any,\n executionContext?: {\n messages?: any[];\n toolCallId?: string;\n requestContext?: RequestContext;\n resumeData?: unknown;\n suspendPayload?: unknown;\n },\n ): Promise<any>;\n\n /**\n * Reads the content of a resource by URI.\n * @param uri The resource URI to read (e.g. `ui://weather/dashboard`).\n * @returns A promise resolving to the resource content.\n */\n public abstract readResource(uri: string): Promise<{\n contents: Array<{ uri: string; text?: string; blob?: string; mimeType?: string; _meta?: Record<string, unknown> }>;\n }>;\n\n /**\n * Lists all resources available on this MCP server.\n * @returns A promise resolving to the list of resources.\n */\n public abstract listResources(): Promise<{\n resources: Array<{\n uri: string;\n name: string;\n description?: string;\n mimeType?: string;\n _meta?: Record<string, unknown>;\n }>;\n }>;\n\n /**\n * The event types this server declares, or `undefined` when it has none.\n * Optional: implementations without events omit it.\n * @experimental\n */\n public getEventsInfo?(): { events: MCPServerEventInfo[] } | undefined;\n\n /**\n * Polls, streams, and test-emits this server's events in-process (used by Studio),\n * or `undefined` when it has none.\n * @experimental\n */\n public getEventsInspector?(): MCPServerEventsInspector | undefined;\n\n /**\n * How this server runs MCP tasks, or `undefined` when it doesn't support them.\n * Optional: implementations without tasks omit it.\n * @experimental\n */\n public getTasksInfo?(): MCPServerTasksInfo | undefined;\n\n /**\n * Lists, cancels and answers this server's MCP tasks in-process (used by Studio), or\n * `undefined` when tasks are off or the task store can't list them.\n * @experimental\n */\n public getTasksInspector?(): MCPServerTasksInspector | undefined;\n}\n"],"mappings":"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"}