@grackle-ai/web 0.136.0 → 0.136.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/assets/{KnowledgePage-C3HjBtgM.js → KnowledgePage-pdM88IVS.js} +2 -2
- package/dist/assets/{KnowledgePage-C3HjBtgM.js.map → KnowledgePage-pdM88IVS.js.map} +1 -1
- package/dist/assets/{McpAppWidget-DsHebvaE.js → McpAppWidget-D-BOXq5b.js} +2 -2
- package/dist/assets/{McpAppWidget-DsHebvaE.js.map → McpAppWidget-D-BOXq5b.js.map} +1 -1
- package/dist/assets/{SessionsListPage-eDZplqLz.js → SessionsListPage-CL-9RybL.js} +2 -2
- package/dist/assets/{SessionsListPage-eDZplqLz.js.map → SessionsListPage-CL-9RybL.js.map} +1 -1
- package/dist/assets/{grpc-D84KWgEK.js → grpc-atodrdN_.js} +6 -6
- package/dist/assets/{grpc-D84KWgEK.js.map → grpc-atodrdN_.js.map} +1 -1
- package/dist/assets/{index-Cod3rLvs.js → index-DcnUq-w_.js} +6 -6
- package/dist/assets/{index-Cod3rLvs.js.map → index-DcnUq-w_.js.map} +1 -1
- package/dist/index.html +2 -2
- package/package.json +4 -3
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"McpAppWidget-DsHebvaE.js","sources":["../../../web-components/src/utils/grackleHostStyleVariables.ts","../../../../common/temp/node_modules/.pnpm/@modelcontextprotocol+sdk@1.29.0_zod@4.3.6/node_modules/@modelcontextprotocol/sdk/dist/esm/types.js","../../../../common/temp/node_modules/.pnpm/@modelcontextprotocol+sdk@1.29.0_zod@4.3.6/node_modules/@modelcontextprotocol/sdk/dist/esm/server/zod-compat.js","../../../../common/temp/node_modules/.pnpm/@modelcontextprotocol+sdk@1.29.0_zod@4.3.6/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/interfaces.js","../../../../common/temp/node_modules/.pnpm/zod-to-json-schema@3.25.1_zod@4.3.6/node_modules/zod-to-json-schema/dist/esm/parsers/string.js","../../../../common/temp/node_modules/.pnpm/@modelcontextprotocol+sdk@1.29.0_zod@4.3.6/node_modules/@modelcontextprotocol/sdk/dist/esm/server/zod-json-schema-compat.js","../../../../common/temp/node_modules/.pnpm/@modelcontextprotocol+sdk@1.29.0_zod@4.3.6/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/protocol.js","../../../../common/temp/node_modules/.pnpm/@modelcontextprotocol+ext-apps@1.7.2_@modelcontextprotocol+sdk@1.29.0_zod@4.3.6__react-_49a9f4a3a4382c4744fd223899ec1ad9/node_modules/@modelcontextprotocol/ext-apps/dist/src/app-bridge.js","../../../web-components/src/components/display/McpAppWidget.tsx"],"sourcesContent":["import type { McpUiStyles } from \"@modelcontextprotocol/ext-apps\";\n\n/**\n * MCP Apps widgets consume a fixed, standard set of CSS custom properties\n * (`--color-*`, `--font-*`, `--border-radius-*`, `--shadow-*`). Grackle's own\n * theme tokens live under different names (`--bg-*`, `--text-*`, `--radius-*`) in\n * `src/styles/theme.scss`. This module exposes Grackle's current theme to widgets\n * under the MCP-standard names so a widget renders coherently inside the host.\n *\n * `McpUiStyles` requires the complete variable set, so we seed from the standard\n * theme-adaptive defaults (verbatim from modelcontextprotocol/ext-apps\n * examples/basic-host/src/host-styles.ts, commit 9a37ad7) and override the subset\n * we can source from Grackle's live theme.\n */\n\n/** Complete MCP-standard default style variables (theme-adaptive via `light-dark()`). */\nconst DEFAULT_MCP_STYLES: McpUiStyles = {\n \"--color-background-primary\": \"light-dark(#ffffff, #1a1a1a)\",\n \"--color-background-secondary\": \"light-dark(#f5f5f5, #2d2d2d)\",\n \"--color-background-tertiary\": \"light-dark(#e5e5e5, #404040)\",\n \"--color-background-inverse\": \"light-dark(#1a1a1a, #ffffff)\",\n \"--color-background-ghost\": \"light-dark(rgba(255,255,255,0), rgba(26,26,26,0))\",\n \"--color-background-info\": \"light-dark(#eff6ff, #1e3a5f)\",\n \"--color-background-danger\": \"light-dark(#fef2f2, #7f1d1d)\",\n \"--color-background-success\": \"light-dark(#f0fdf4, #14532d)\",\n \"--color-background-warning\": \"light-dark(#fefce8, #713f12)\",\n \"--color-background-disabled\": \"light-dark(rgba(255,255,255,0.5), rgba(26,26,26,0.5))\",\n \"--color-text-primary\": \"light-dark(#1f2937, #f3f4f6)\",\n \"--color-text-secondary\": \"light-dark(#6b7280, #9ca3af)\",\n \"--color-text-tertiary\": \"light-dark(#9ca3af, #6b7280)\",\n \"--color-text-inverse\": \"light-dark(#f3f4f6, #1f2937)\",\n \"--color-text-ghost\": \"light-dark(rgba(107,114,128,0.5), rgba(156,163,175,0.5))\",\n \"--color-text-info\": \"light-dark(#1d4ed8, #60a5fa)\",\n \"--color-text-danger\": \"light-dark(#b91c1c, #f87171)\",\n \"--color-text-success\": \"light-dark(#15803d, #4ade80)\",\n \"--color-text-warning\": \"light-dark(#a16207, #fbbf24)\",\n \"--color-text-disabled\": \"light-dark(rgba(31,41,55,0.5), rgba(243,244,246,0.5))\",\n \"--color-border-primary\": \"light-dark(#e5e7eb, #404040)\",\n \"--color-border-secondary\": \"light-dark(#d1d5db, #525252)\",\n \"--color-border-tertiary\": \"light-dark(#f3f4f6, #374151)\",\n \"--color-border-inverse\": \"light-dark(rgba(255,255,255,0.3), rgba(0,0,0,0.3))\",\n \"--color-border-ghost\": \"light-dark(rgba(229,231,235,0), rgba(64,64,64,0))\",\n \"--color-border-info\": \"light-dark(#93c5fd, #1e40af)\",\n \"--color-border-danger\": \"light-dark(#fca5a5, #991b1b)\",\n \"--color-border-success\": \"light-dark(#86efac, #166534)\",\n \"--color-border-warning\": \"light-dark(#fde047, #854d0e)\",\n \"--color-border-disabled\": \"light-dark(rgba(229,231,235,0.5), rgba(64,64,64,0.5))\",\n \"--color-ring-primary\": \"light-dark(#3b82f6, #60a5fa)\",\n \"--color-ring-secondary\": \"light-dark(#6b7280, #9ca3af)\",\n \"--color-ring-inverse\": \"light-dark(#ffffff, #1f2937)\",\n \"--color-ring-info\": \"light-dark(#2563eb, #3b82f6)\",\n \"--color-ring-danger\": \"light-dark(#dc2626, #ef4444)\",\n \"--color-ring-success\": \"light-dark(#16a34a, #22c55e)\",\n \"--color-ring-warning\": \"light-dark(#ca8a04, #eab308)\",\n \"--font-sans\": \"system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif\",\n \"--font-mono\": \"ui-monospace, 'SF Mono', Monaco, 'Cascadia Code', monospace\",\n \"--font-weight-normal\": \"400\",\n \"--font-weight-medium\": \"500\",\n \"--font-weight-semibold\": \"600\",\n \"--font-weight-bold\": \"700\",\n \"--font-text-xs-size\": \"0.75rem\",\n \"--font-text-sm-size\": \"0.875rem\",\n \"--font-text-md-size\": \"1rem\",\n \"--font-text-lg-size\": \"1.125rem\",\n \"--font-heading-xs-size\": \"0.75rem\",\n \"--font-heading-sm-size\": \"0.875rem\",\n \"--font-heading-md-size\": \"1rem\",\n \"--font-heading-lg-size\": \"1.25rem\",\n \"--font-heading-xl-size\": \"1.5rem\",\n \"--font-heading-2xl-size\": \"1.875rem\",\n \"--font-heading-3xl-size\": \"2.25rem\",\n \"--font-text-xs-line-height\": \"1.4\",\n \"--font-text-sm-line-height\": \"1.4\",\n \"--font-text-md-line-height\": \"1.5\",\n \"--font-text-lg-line-height\": \"1.5\",\n \"--font-heading-xs-line-height\": \"1.4\",\n \"--font-heading-sm-line-height\": \"1.4\",\n \"--font-heading-md-line-height\": \"1.4\",\n \"--font-heading-lg-line-height\": \"1.3\",\n \"--font-heading-xl-line-height\": \"1.25\",\n \"--font-heading-2xl-line-height\": \"1.2\",\n \"--font-heading-3xl-line-height\": \"1.1\",\n \"--border-radius-xs\": \"2px\",\n \"--border-radius-sm\": \"4px\",\n \"--border-radius-md\": \"6px\",\n \"--border-radius-lg\": \"8px\",\n \"--border-radius-xl\": \"12px\",\n \"--border-radius-full\": \"9999px\",\n \"--border-width-regular\": \"1px\",\n \"--shadow-hairline\": \"0 1px 2px 0 rgba(0, 0, 0, 0.05)\",\n \"--shadow-sm\": \"0 1px 3px 0 rgba(0, 0, 0, 0.1), 0 1px 2px -1px rgba(0, 0, 0, 0.1)\",\n \"--shadow-md\": \"0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -2px rgba(0, 0, 0, 0.1)\",\n \"--shadow-lg\": \"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)\",\n};\n\n/** MCP-standard variable name -> Grackle theme token to read its value from. */\nconst GRACKLE_TOKEN_BY_MCP_NAME: Readonly<Record<string, string>> = {\n \"--color-background-primary\": \"--bg-base\",\n \"--color-background-secondary\": \"--bg-surface\",\n \"--color-background-tertiary\": \"--bg-elevated\",\n \"--color-text-primary\": \"--text-primary\",\n \"--color-text-secondary\": \"--text-secondary\",\n \"--color-text-tertiary\": \"--text-tertiary\",\n \"--color-border-primary\": \"--border-primary\",\n \"--color-border-secondary\": \"--border-subtle\",\n \"--font-sans\": \"--font-sans\",\n \"--font-mono\": \"--font-mono\",\n \"--border-radius-sm\": \"--radius-sm\",\n \"--border-radius-md\": \"--radius-md\",\n \"--border-radius-lg\": \"--radius-lg\",\n \"--border-radius-full\": \"--radius-full\",\n};\n\n/**\n * Build the MCP-standard style-variable map from Grackle's live theme, falling\n * back to theme-adaptive defaults for any token that cannot be read.\n *\n * @returns Style variables suitable for `hostContext.styles.variables`.\n */\nexport function grackleHostStyleVariables(): McpUiStyles {\n const out: McpUiStyles = { ...DEFAULT_MCP_STYLES };\n if (typeof window === \"undefined\" || typeof document === \"undefined\") {\n return out;\n }\n const computed: CSSStyleDeclaration = window.getComputedStyle(document.documentElement);\n const writable: Record<string, string> = out as Record<string, string>;\n for (const [mcpName, grackleToken] of Object.entries(GRACKLE_TOKEN_BY_MCP_NAME)) {\n const value: string = computed.getPropertyValue(grackleToken).trim();\n if (value) {\n writable[mcpName] = value;\n }\n }\n return out;\n}\n","import * as z from 'zod/v4';\nexport const LATEST_PROTOCOL_VERSION = '2025-11-25';\nexport const DEFAULT_NEGOTIATED_PROTOCOL_VERSION = '2025-03-26';\nexport const SUPPORTED_PROTOCOL_VERSIONS = [LATEST_PROTOCOL_VERSION, '2025-06-18', '2025-03-26', '2024-11-05', '2024-10-07'];\nexport const RELATED_TASK_META_KEY = 'io.modelcontextprotocol/related-task';\n/* JSON-RPC types */\nexport const JSONRPC_VERSION = '2.0';\n/**\n * Assert 'object' type schema.\n *\n * @internal\n */\nconst AssertObjectSchema = z.custom((v) => v !== null && (typeof v === 'object' || typeof v === 'function'));\n/**\n * A progress token, used to associate progress notifications with the original request.\n */\nexport const ProgressTokenSchema = z.union([z.string(), z.number().int()]);\n/**\n * An opaque token used to represent a cursor for pagination.\n */\nexport const CursorSchema = z.string();\n/**\n * Task creation parameters, used to ask that the server create a task to represent a request.\n */\nexport const TaskCreationParamsSchema = z.looseObject({\n /**\n * Requested duration in milliseconds to retain task from creation.\n */\n ttl: z.number().optional(),\n /**\n * Time in milliseconds to wait between task status requests.\n */\n pollInterval: z.number().optional()\n});\nexport const TaskMetadataSchema = z.object({\n ttl: z.number().optional()\n});\n/**\n * Metadata for associating messages with a task.\n * Include this in the `_meta` field under the key `io.modelcontextprotocol/related-task`.\n */\nexport const RelatedTaskMetadataSchema = z.object({\n taskId: z.string()\n});\nconst RequestMetaSchema = z.looseObject({\n /**\n * If specified, the caller is requesting out-of-band progress notifications for this request (as represented by notifications/progress). The value of this parameter is an opaque token that will be attached to any subsequent notifications. The receiver is not obligated to provide these notifications.\n */\n progressToken: ProgressTokenSchema.optional(),\n /**\n * If specified, this request is related to the provided task.\n */\n [RELATED_TASK_META_KEY]: RelatedTaskMetadataSchema.optional()\n});\n/**\n * Common params for any request.\n */\nconst BaseRequestParamsSchema = z.object({\n /**\n * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage.\n */\n _meta: RequestMetaSchema.optional()\n});\n/**\n * Common params for any task-augmented request.\n */\nexport const TaskAugmentedRequestParamsSchema = BaseRequestParamsSchema.extend({\n /**\n * If specified, the caller is requesting task-augmented execution for this request.\n * The request will return a CreateTaskResult immediately, and the actual result can be\n * retrieved later via tasks/result.\n *\n * Task augmentation is subject to capability negotiation - receivers MUST declare support\n * for task augmentation of specific request types in their capabilities.\n */\n task: TaskMetadataSchema.optional()\n});\n/**\n * Checks if a value is a valid TaskAugmentedRequestParams.\n * @param value - The value to check.\n *\n * @returns True if the value is a valid TaskAugmentedRequestParams, false otherwise.\n */\nexport const isTaskAugmentedRequestParams = (value) => TaskAugmentedRequestParamsSchema.safeParse(value).success;\nexport const RequestSchema = z.object({\n method: z.string(),\n params: BaseRequestParamsSchema.loose().optional()\n});\nconst NotificationsParamsSchema = z.object({\n /**\n * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)\n * for notes on _meta usage.\n */\n _meta: RequestMetaSchema.optional()\n});\nexport const NotificationSchema = z.object({\n method: z.string(),\n params: NotificationsParamsSchema.loose().optional()\n});\nexport const ResultSchema = z.looseObject({\n /**\n * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)\n * for notes on _meta usage.\n */\n _meta: RequestMetaSchema.optional()\n});\n/**\n * A uniquely identifying ID for a request in JSON-RPC.\n */\nexport const RequestIdSchema = z.union([z.string(), z.number().int()]);\n/**\n * A request that expects a response.\n */\nexport const JSONRPCRequestSchema = z\n .object({\n jsonrpc: z.literal(JSONRPC_VERSION),\n id: RequestIdSchema,\n ...RequestSchema.shape\n})\n .strict();\nexport const isJSONRPCRequest = (value) => JSONRPCRequestSchema.safeParse(value).success;\n/**\n * A notification which does not expect a response.\n */\nexport const JSONRPCNotificationSchema = z\n .object({\n jsonrpc: z.literal(JSONRPC_VERSION),\n ...NotificationSchema.shape\n})\n .strict();\nexport const isJSONRPCNotification = (value) => JSONRPCNotificationSchema.safeParse(value).success;\n/**\n * A successful (non-error) response to a request.\n */\nexport const JSONRPCResultResponseSchema = z\n .object({\n jsonrpc: z.literal(JSONRPC_VERSION),\n id: RequestIdSchema,\n result: ResultSchema\n})\n .strict();\n/**\n * Checks if a value is a valid JSONRPCResultResponse.\n * @param value - The value to check.\n *\n * @returns True if the value is a valid JSONRPCResultResponse, false otherwise.\n */\nexport const isJSONRPCResultResponse = (value) => JSONRPCResultResponseSchema.safeParse(value).success;\n/**\n * @deprecated Use {@link isJSONRPCResultResponse} instead.\n *\n * Please note that {@link JSONRPCResponse} is a union of {@link JSONRPCResultResponse} and {@link JSONRPCErrorResponse} as per the updated JSON-RPC specification. (was previously just {@link JSONRPCResultResponse})\n */\nexport const isJSONRPCResponse = isJSONRPCResultResponse;\n/**\n * Error codes defined by the JSON-RPC specification.\n */\nexport var ErrorCode;\n(function (ErrorCode) {\n // SDK error codes\n ErrorCode[ErrorCode[\"ConnectionClosed\"] = -32000] = \"ConnectionClosed\";\n ErrorCode[ErrorCode[\"RequestTimeout\"] = -32001] = \"RequestTimeout\";\n // Standard JSON-RPC error codes\n ErrorCode[ErrorCode[\"ParseError\"] = -32700] = \"ParseError\";\n ErrorCode[ErrorCode[\"InvalidRequest\"] = -32600] = \"InvalidRequest\";\n ErrorCode[ErrorCode[\"MethodNotFound\"] = -32601] = \"MethodNotFound\";\n ErrorCode[ErrorCode[\"InvalidParams\"] = -32602] = \"InvalidParams\";\n ErrorCode[ErrorCode[\"InternalError\"] = -32603] = \"InternalError\";\n // MCP-specific error codes\n ErrorCode[ErrorCode[\"UrlElicitationRequired\"] = -32042] = \"UrlElicitationRequired\";\n})(ErrorCode || (ErrorCode = {}));\n/**\n * A response to a request that indicates an error occurred.\n */\nexport const JSONRPCErrorResponseSchema = z\n .object({\n jsonrpc: z.literal(JSONRPC_VERSION),\n id: RequestIdSchema.optional(),\n error: z.object({\n /**\n * The error type that occurred.\n */\n code: z.number().int(),\n /**\n * A short description of the error. The message SHOULD be limited to a concise single sentence.\n */\n message: z.string(),\n /**\n * Additional information about the error. The value of this member is defined by the sender (e.g. detailed error information, nested errors etc.).\n */\n data: z.unknown().optional()\n })\n})\n .strict();\n/**\n * @deprecated Use {@link JSONRPCErrorResponseSchema} instead.\n */\nexport const JSONRPCErrorSchema = JSONRPCErrorResponseSchema;\n/**\n * Checks if a value is a valid JSONRPCErrorResponse.\n * @param value - The value to check.\n *\n * @returns True if the value is a valid JSONRPCErrorResponse, false otherwise.\n */\nexport const isJSONRPCErrorResponse = (value) => JSONRPCErrorResponseSchema.safeParse(value).success;\n/**\n * @deprecated Use {@link isJSONRPCErrorResponse} instead.\n */\nexport const isJSONRPCError = isJSONRPCErrorResponse;\nexport const JSONRPCMessageSchema = z.union([\n JSONRPCRequestSchema,\n JSONRPCNotificationSchema,\n JSONRPCResultResponseSchema,\n JSONRPCErrorResponseSchema\n]);\nexport const JSONRPCResponseSchema = z.union([JSONRPCResultResponseSchema, JSONRPCErrorResponseSchema]);\n/* Empty result */\n/**\n * A response that indicates success but carries no data.\n */\nexport const EmptyResultSchema = ResultSchema.strict();\nexport const CancelledNotificationParamsSchema = NotificationsParamsSchema.extend({\n /**\n * The ID of the request to cancel.\n *\n * This MUST correspond to the ID of a request previously issued in the same direction.\n */\n requestId: RequestIdSchema.optional(),\n /**\n * An optional string describing the reason for the cancellation. This MAY be logged or presented to the user.\n */\n reason: z.string().optional()\n});\n/* Cancellation */\n/**\n * This notification can be sent by either side to indicate that it is cancelling a previously-issued request.\n *\n * The request SHOULD still be in-flight, but due to communication latency, it is always possible that this notification MAY arrive after the request has already finished.\n *\n * This notification indicates that the result will be unused, so any associated processing SHOULD cease.\n *\n * A client MUST NOT attempt to cancel its `initialize` request.\n */\nexport const CancelledNotificationSchema = NotificationSchema.extend({\n method: z.literal('notifications/cancelled'),\n params: CancelledNotificationParamsSchema\n});\n/* Base Metadata */\n/**\n * Icon schema for use in tools, prompts, resources, and implementations.\n */\nexport const IconSchema = z.object({\n /**\n * URL or data URI for the icon.\n */\n src: z.string(),\n /**\n * Optional MIME type for the icon.\n */\n mimeType: z.string().optional(),\n /**\n * Optional array of strings that specify sizes at which the icon can be used.\n * Each string should be in WxH format (e.g., `\"48x48\"`, `\"96x96\"`) or `\"any\"` for scalable formats like SVG.\n *\n * If not provided, the client should assume that the icon can be used at any size.\n */\n sizes: z.array(z.string()).optional(),\n /**\n * Optional specifier for the theme this icon is designed for. `light` indicates\n * the icon is designed to be used with a light background, and `dark` indicates\n * the icon is designed to be used with a dark background.\n *\n * If not provided, the client should assume the icon can be used with any theme.\n */\n theme: z.enum(['light', 'dark']).optional()\n});\n/**\n * Base schema to add `icons` property.\n *\n */\nexport const IconsSchema = z.object({\n /**\n * Optional set of sized icons that the client can display in a user interface.\n *\n * Clients that support rendering icons MUST support at least the following MIME types:\n * - `image/png` - PNG images (safe, universal compatibility)\n * - `image/jpeg` (and `image/jpg`) - JPEG images (safe, universal compatibility)\n *\n * Clients that support rendering icons SHOULD also support:\n * - `image/svg+xml` - SVG images (scalable but requires security precautions)\n * - `image/webp` - WebP images (modern, efficient format)\n */\n icons: z.array(IconSchema).optional()\n});\n/**\n * Base metadata interface for common properties across resources, tools, prompts, and implementations.\n */\nexport const BaseMetadataSchema = z.object({\n /** Intended for programmatic or logical use, but used as a display name in past specs or fallback */\n name: z.string(),\n /**\n * Intended for UI and end-user contexts — optimized to be human-readable and easily understood,\n * even by those unfamiliar with domain-specific terminology.\n *\n * If not provided, the name should be used for display (except for Tool,\n * where `annotations.title` should be given precedence over using `name`,\n * if present).\n */\n title: z.string().optional()\n});\n/* Initialization */\n/**\n * Describes the name and version of an MCP implementation.\n */\nexport const ImplementationSchema = BaseMetadataSchema.extend({\n ...BaseMetadataSchema.shape,\n ...IconsSchema.shape,\n version: z.string(),\n /**\n * An optional URL of the website for this implementation.\n */\n websiteUrl: z.string().optional(),\n /**\n * An optional human-readable description of what this implementation does.\n *\n * This can be used by clients or servers to provide context about their purpose\n * and capabilities. For example, a server might describe the types of resources\n * or tools it provides, while a client might describe its intended use case.\n */\n description: z.string().optional()\n});\nconst FormElicitationCapabilitySchema = z.intersection(z.object({\n applyDefaults: z.boolean().optional()\n}), z.record(z.string(), z.unknown()));\nconst ElicitationCapabilitySchema = z.preprocess(value => {\n if (value && typeof value === 'object' && !Array.isArray(value)) {\n if (Object.keys(value).length === 0) {\n return { form: {} };\n }\n }\n return value;\n}, z.intersection(z.object({\n form: FormElicitationCapabilitySchema.optional(),\n url: AssertObjectSchema.optional()\n}), z.record(z.string(), z.unknown()).optional()));\n/**\n * Task capabilities for clients, indicating which request types support task creation.\n */\nexport const ClientTasksCapabilitySchema = z.looseObject({\n /**\n * Present if the client supports listing tasks.\n */\n list: AssertObjectSchema.optional(),\n /**\n * Present if the client supports cancelling tasks.\n */\n cancel: AssertObjectSchema.optional(),\n /**\n * Capabilities for task creation on specific request types.\n */\n requests: z\n .looseObject({\n /**\n * Task support for sampling requests.\n */\n sampling: z\n .looseObject({\n createMessage: AssertObjectSchema.optional()\n })\n .optional(),\n /**\n * Task support for elicitation requests.\n */\n elicitation: z\n .looseObject({\n create: AssertObjectSchema.optional()\n })\n .optional()\n })\n .optional()\n});\n/**\n * Task capabilities for servers, indicating which request types support task creation.\n */\nexport const ServerTasksCapabilitySchema = z.looseObject({\n /**\n * Present if the server supports listing tasks.\n */\n list: AssertObjectSchema.optional(),\n /**\n * Present if the server supports cancelling tasks.\n */\n cancel: AssertObjectSchema.optional(),\n /**\n * Capabilities for task creation on specific request types.\n */\n requests: z\n .looseObject({\n /**\n * Task support for tool requests.\n */\n tools: z\n .looseObject({\n call: AssertObjectSchema.optional()\n })\n .optional()\n })\n .optional()\n});\n/**\n * Capabilities a client may support. Known capabilities are defined here, in this schema, but this is not a closed set: any client can define its own, additional capabilities.\n */\nexport const ClientCapabilitiesSchema = z.object({\n /**\n * Experimental, non-standard capabilities that the client supports.\n */\n experimental: z.record(z.string(), AssertObjectSchema).optional(),\n /**\n * Present if the client supports sampling from an LLM.\n */\n sampling: z\n .object({\n /**\n * Present if the client supports context inclusion via includeContext parameter.\n * If not declared, servers SHOULD only use `includeContext: \"none\"` (or omit it).\n */\n context: AssertObjectSchema.optional(),\n /**\n * Present if the client supports tool use via tools and toolChoice parameters.\n */\n tools: AssertObjectSchema.optional()\n })\n .optional(),\n /**\n * Present if the client supports eliciting user input.\n */\n elicitation: ElicitationCapabilitySchema.optional(),\n /**\n * Present if the client supports listing roots.\n */\n roots: z\n .object({\n /**\n * Whether the client supports issuing notifications for changes to the roots list.\n */\n listChanged: z.boolean().optional()\n })\n .optional(),\n /**\n * Present if the client supports task creation.\n */\n tasks: ClientTasksCapabilitySchema.optional(),\n /**\n * Extensions that the client supports. Keys are extension identifiers (vendor-prefix/extension-name).\n */\n extensions: z.record(z.string(), AssertObjectSchema).optional()\n});\nexport const InitializeRequestParamsSchema = BaseRequestParamsSchema.extend({\n /**\n * The latest version of the Model Context Protocol that the client supports. The client MAY decide to support older versions as well.\n */\n protocolVersion: z.string(),\n capabilities: ClientCapabilitiesSchema,\n clientInfo: ImplementationSchema\n});\n/**\n * This request is sent from the client to the server when it first connects, asking it to begin initialization.\n */\nexport const InitializeRequestSchema = RequestSchema.extend({\n method: z.literal('initialize'),\n params: InitializeRequestParamsSchema\n});\nexport const isInitializeRequest = (value) => InitializeRequestSchema.safeParse(value).success;\n/**\n * Capabilities that a server may support. Known capabilities are defined here, in this schema, but this is not a closed set: any server can define its own, additional capabilities.\n */\nexport const ServerCapabilitiesSchema = z.object({\n /**\n * Experimental, non-standard capabilities that the server supports.\n */\n experimental: z.record(z.string(), AssertObjectSchema).optional(),\n /**\n * Present if the server supports sending log messages to the client.\n */\n logging: AssertObjectSchema.optional(),\n /**\n * Present if the server supports sending completions to the client.\n */\n completions: AssertObjectSchema.optional(),\n /**\n * Present if the server offers any prompt templates.\n */\n prompts: z\n .object({\n /**\n * Whether this server supports issuing notifications for changes to the prompt list.\n */\n listChanged: z.boolean().optional()\n })\n .optional(),\n /**\n * Present if the server offers any resources to read.\n */\n resources: z\n .object({\n /**\n * Whether this server supports clients subscribing to resource updates.\n */\n subscribe: z.boolean().optional(),\n /**\n * Whether this server supports issuing notifications for changes to the resource list.\n */\n listChanged: z.boolean().optional()\n })\n .optional(),\n /**\n * Present if the server offers any tools to call.\n */\n tools: z\n .object({\n /**\n * Whether this server supports issuing notifications for changes to the tool list.\n */\n listChanged: z.boolean().optional()\n })\n .optional(),\n /**\n * Present if the server supports task creation.\n */\n tasks: ServerTasksCapabilitySchema.optional(),\n /**\n * Extensions that the server supports. Keys are extension identifiers (vendor-prefix/extension-name).\n */\n extensions: z.record(z.string(), AssertObjectSchema).optional()\n});\n/**\n * After receiving an initialize request from the client, the server sends this response.\n */\nexport const InitializeResultSchema = ResultSchema.extend({\n /**\n * The version of the Model Context Protocol that the server wants to use. This may not match the version that the client requested. If the client cannot support this version, it MUST disconnect.\n */\n protocolVersion: z.string(),\n capabilities: ServerCapabilitiesSchema,\n serverInfo: ImplementationSchema,\n /**\n * Instructions describing how to use the server and its features.\n *\n * This can be used by clients to improve the LLM's understanding of available tools, resources, etc. It can be thought of like a \"hint\" to the model. For example, this information MAY be added to the system prompt.\n */\n instructions: z.string().optional()\n});\n/**\n * This notification is sent from the client to the server after initialization has finished.\n */\nexport const InitializedNotificationSchema = NotificationSchema.extend({\n method: z.literal('notifications/initialized'),\n params: NotificationsParamsSchema.optional()\n});\nexport const isInitializedNotification = (value) => InitializedNotificationSchema.safeParse(value).success;\n/* Ping */\n/**\n * A ping, issued by either the server or the client, to check that the other party is still alive. The receiver must promptly respond, or else may be disconnected.\n */\nexport const PingRequestSchema = RequestSchema.extend({\n method: z.literal('ping'),\n params: BaseRequestParamsSchema.optional()\n});\n/* Progress notifications */\nexport const ProgressSchema = z.object({\n /**\n * The progress thus far. This should increase every time progress is made, even if the total is unknown.\n */\n progress: z.number(),\n /**\n * Total number of items to process (or total progress required), if known.\n */\n total: z.optional(z.number()),\n /**\n * An optional message describing the current progress.\n */\n message: z.optional(z.string())\n});\nexport const ProgressNotificationParamsSchema = z.object({\n ...NotificationsParamsSchema.shape,\n ...ProgressSchema.shape,\n /**\n * The progress token which was given in the initial request, used to associate this notification with the request that is proceeding.\n */\n progressToken: ProgressTokenSchema\n});\n/**\n * An out-of-band notification used to inform the receiver of a progress update for a long-running request.\n *\n * @category notifications/progress\n */\nexport const ProgressNotificationSchema = NotificationSchema.extend({\n method: z.literal('notifications/progress'),\n params: ProgressNotificationParamsSchema\n});\nexport const PaginatedRequestParamsSchema = BaseRequestParamsSchema.extend({\n /**\n * An opaque token representing the current pagination position.\n * If provided, the server should return results starting after this cursor.\n */\n cursor: CursorSchema.optional()\n});\n/* Pagination */\nexport const PaginatedRequestSchema = RequestSchema.extend({\n params: PaginatedRequestParamsSchema.optional()\n});\nexport const PaginatedResultSchema = ResultSchema.extend({\n /**\n * An opaque token representing the pagination position after the last returned result.\n * If present, there may be more results available.\n */\n nextCursor: CursorSchema.optional()\n});\n/**\n * The status of a task.\n * */\nexport const TaskStatusSchema = z.enum(['working', 'input_required', 'completed', 'failed', 'cancelled']);\n/* Tasks */\n/**\n * A pollable state object associated with a request.\n */\nexport const TaskSchema = z.object({\n taskId: z.string(),\n status: TaskStatusSchema,\n /**\n * Time in milliseconds to keep task results available after completion.\n * If null, the task has unlimited lifetime until manually cleaned up.\n */\n ttl: z.union([z.number(), z.null()]),\n /**\n * ISO 8601 timestamp when the task was created.\n */\n createdAt: z.string(),\n /**\n * ISO 8601 timestamp when the task was last updated.\n */\n lastUpdatedAt: z.string(),\n pollInterval: z.optional(z.number()),\n /**\n * Optional diagnostic message for failed tasks or other status information.\n */\n statusMessage: z.optional(z.string())\n});\n/**\n * Result returned when a task is created, containing the task data wrapped in a task field.\n */\nexport const CreateTaskResultSchema = ResultSchema.extend({\n task: TaskSchema\n});\n/**\n * Parameters for task status notification.\n */\nexport const TaskStatusNotificationParamsSchema = NotificationsParamsSchema.merge(TaskSchema);\n/**\n * A notification sent when a task's status changes.\n */\nexport const TaskStatusNotificationSchema = NotificationSchema.extend({\n method: z.literal('notifications/tasks/status'),\n params: TaskStatusNotificationParamsSchema\n});\n/**\n * A request to get the state of a specific task.\n */\nexport const GetTaskRequestSchema = RequestSchema.extend({\n method: z.literal('tasks/get'),\n params: BaseRequestParamsSchema.extend({\n taskId: z.string()\n })\n});\n/**\n * The response to a tasks/get request.\n */\nexport const GetTaskResultSchema = ResultSchema.merge(TaskSchema);\n/**\n * A request to get the result of a specific task.\n */\nexport const GetTaskPayloadRequestSchema = RequestSchema.extend({\n method: z.literal('tasks/result'),\n params: BaseRequestParamsSchema.extend({\n taskId: z.string()\n })\n});\n/**\n * The response to a tasks/result request.\n * The structure matches the result type of the original request.\n * For example, a tools/call task would return the CallToolResult structure.\n *\n */\nexport const GetTaskPayloadResultSchema = ResultSchema.loose();\n/**\n * A request to list tasks.\n */\nexport const ListTasksRequestSchema = PaginatedRequestSchema.extend({\n method: z.literal('tasks/list')\n});\n/**\n * The response to a tasks/list request.\n */\nexport const ListTasksResultSchema = PaginatedResultSchema.extend({\n tasks: z.array(TaskSchema)\n});\n/**\n * A request to cancel a specific task.\n */\nexport const CancelTaskRequestSchema = RequestSchema.extend({\n method: z.literal('tasks/cancel'),\n params: BaseRequestParamsSchema.extend({\n taskId: z.string()\n })\n});\n/**\n * The response to a tasks/cancel request.\n */\nexport const CancelTaskResultSchema = ResultSchema.merge(TaskSchema);\n/* Resources */\n/**\n * The contents of a specific resource or sub-resource.\n */\nexport const ResourceContentsSchema = z.object({\n /**\n * The URI of this resource.\n */\n uri: z.string(),\n /**\n * The MIME type of this resource, if known.\n */\n mimeType: z.optional(z.string()),\n /**\n * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)\n * for notes on _meta usage.\n */\n _meta: z.record(z.string(), z.unknown()).optional()\n});\nexport const TextResourceContentsSchema = ResourceContentsSchema.extend({\n /**\n * The text of the item. This must only be set if the item can actually be represented as text (not binary data).\n */\n text: z.string()\n});\n/**\n * A Zod schema for validating Base64 strings that is more performant and\n * robust for very large inputs than the default regex-based check. It avoids\n * stack overflows by using the native `atob` function for validation.\n */\nconst Base64Schema = z.string().refine(val => {\n try {\n // atob throws a DOMException if the string contains characters\n // that are not part of the Base64 character set.\n atob(val);\n return true;\n }\n catch {\n return false;\n }\n}, { message: 'Invalid Base64 string' });\nexport const BlobResourceContentsSchema = ResourceContentsSchema.extend({\n /**\n * A base64-encoded string representing the binary data of the item.\n */\n blob: Base64Schema\n});\n/**\n * The sender or recipient of messages and data in a conversation.\n */\nexport const RoleSchema = z.enum(['user', 'assistant']);\n/**\n * Optional annotations providing clients additional context about a resource.\n */\nexport const AnnotationsSchema = z.object({\n /**\n * Intended audience(s) for the resource.\n */\n audience: z.array(RoleSchema).optional(),\n /**\n * Importance hint for the resource, from 0 (least) to 1 (most).\n */\n priority: z.number().min(0).max(1).optional(),\n /**\n * ISO 8601 timestamp for the most recent modification.\n */\n lastModified: z.iso.datetime({ offset: true }).optional()\n});\n/**\n * A known resource that the server is capable of reading.\n */\nexport const ResourceSchema = z.object({\n ...BaseMetadataSchema.shape,\n ...IconsSchema.shape,\n /**\n * The URI of this resource.\n */\n uri: z.string(),\n /**\n * A description of what this resource represents.\n *\n * This can be used by clients to improve the LLM's understanding of available resources. It can be thought of like a \"hint\" to the model.\n */\n description: z.optional(z.string()),\n /**\n * The MIME type of this resource, if known.\n */\n mimeType: z.optional(z.string()),\n /**\n * The size of the raw resource content, in bytes (i.e., before base64 encoding or any tokenization), if known.\n *\n * This can be used by Hosts to display file sizes and estimate context window usage.\n */\n size: z.optional(z.number()),\n /**\n * Optional annotations for the client.\n */\n annotations: AnnotationsSchema.optional(),\n /**\n * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)\n * for notes on _meta usage.\n */\n _meta: z.optional(z.looseObject({}))\n});\n/**\n * A template description for resources available on the server.\n */\nexport const ResourceTemplateSchema = z.object({\n ...BaseMetadataSchema.shape,\n ...IconsSchema.shape,\n /**\n * A URI template (according to RFC 6570) that can be used to construct resource URIs.\n */\n uriTemplate: z.string(),\n /**\n * A description of what this template is for.\n *\n * This can be used by clients to improve the LLM's understanding of available resources. It can be thought of like a \"hint\" to the model.\n */\n description: z.optional(z.string()),\n /**\n * The MIME type for all resources that match this template. This should only be included if all resources matching this template have the same type.\n */\n mimeType: z.optional(z.string()),\n /**\n * Optional annotations for the client.\n */\n annotations: AnnotationsSchema.optional(),\n /**\n * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)\n * for notes on _meta usage.\n */\n _meta: z.optional(z.looseObject({}))\n});\n/**\n * Sent from the client to request a list of resources the server has.\n */\nexport const ListResourcesRequestSchema = PaginatedRequestSchema.extend({\n method: z.literal('resources/list')\n});\n/**\n * The server's response to a resources/list request from the client.\n */\nexport const ListResourcesResultSchema = PaginatedResultSchema.extend({\n resources: z.array(ResourceSchema)\n});\n/**\n * Sent from the client to request a list of resource templates the server has.\n */\nexport const ListResourceTemplatesRequestSchema = PaginatedRequestSchema.extend({\n method: z.literal('resources/templates/list')\n});\n/**\n * The server's response to a resources/templates/list request from the client.\n */\nexport const ListResourceTemplatesResultSchema = PaginatedResultSchema.extend({\n resourceTemplates: z.array(ResourceTemplateSchema)\n});\nexport const ResourceRequestParamsSchema = BaseRequestParamsSchema.extend({\n /**\n * The URI of the resource to read. The URI can use any protocol; it is up to the server how to interpret it.\n *\n * @format uri\n */\n uri: z.string()\n});\n/**\n * Parameters for a `resources/read` request.\n */\nexport const ReadResourceRequestParamsSchema = ResourceRequestParamsSchema;\n/**\n * Sent from the client to the server, to read a specific resource URI.\n */\nexport const ReadResourceRequestSchema = RequestSchema.extend({\n method: z.literal('resources/read'),\n params: ReadResourceRequestParamsSchema\n});\n/**\n * The server's response to a resources/read request from the client.\n */\nexport const ReadResourceResultSchema = ResultSchema.extend({\n contents: z.array(z.union([TextResourceContentsSchema, BlobResourceContentsSchema]))\n});\n/**\n * An optional notification from the server to the client, informing it that the list of resources it can read from has changed. This may be issued by servers without any previous subscription from the client.\n */\nexport const ResourceListChangedNotificationSchema = NotificationSchema.extend({\n method: z.literal('notifications/resources/list_changed'),\n params: NotificationsParamsSchema.optional()\n});\nexport const SubscribeRequestParamsSchema = ResourceRequestParamsSchema;\n/**\n * Sent from the client to request resources/updated notifications from the server whenever a particular resource changes.\n */\nexport const SubscribeRequestSchema = RequestSchema.extend({\n method: z.literal('resources/subscribe'),\n params: SubscribeRequestParamsSchema\n});\nexport const UnsubscribeRequestParamsSchema = ResourceRequestParamsSchema;\n/**\n * Sent from the client to request cancellation of resources/updated notifications from the server. This should follow a previous resources/subscribe request.\n */\nexport const UnsubscribeRequestSchema = RequestSchema.extend({\n method: z.literal('resources/unsubscribe'),\n params: UnsubscribeRequestParamsSchema\n});\n/**\n * Parameters for a `notifications/resources/updated` notification.\n */\nexport const ResourceUpdatedNotificationParamsSchema = NotificationsParamsSchema.extend({\n /**\n * The URI of the resource that has been updated. This might be a sub-resource of the one that the client actually subscribed to.\n */\n uri: z.string()\n});\n/**\n * A notification from the server to the client, informing it that a resource has changed and may need to be read again. This should only be sent if the client previously sent a resources/subscribe request.\n */\nexport const ResourceUpdatedNotificationSchema = NotificationSchema.extend({\n method: z.literal('notifications/resources/updated'),\n params: ResourceUpdatedNotificationParamsSchema\n});\n/* Prompts */\n/**\n * Describes an argument that a prompt can accept.\n */\nexport const PromptArgumentSchema = z.object({\n /**\n * The name of the argument.\n */\n name: z.string(),\n /**\n * A human-readable description of the argument.\n */\n description: z.optional(z.string()),\n /**\n * Whether this argument must be provided.\n */\n required: z.optional(z.boolean())\n});\n/**\n * A prompt or prompt template that the server offers.\n */\nexport const PromptSchema = z.object({\n ...BaseMetadataSchema.shape,\n ...IconsSchema.shape,\n /**\n * An optional description of what this prompt provides\n */\n description: z.optional(z.string()),\n /**\n * A list of arguments to use for templating the prompt.\n */\n arguments: z.optional(z.array(PromptArgumentSchema)),\n /**\n * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)\n * for notes on _meta usage.\n */\n _meta: z.optional(z.looseObject({}))\n});\n/**\n * Sent from the client to request a list of prompts and prompt templates the server has.\n */\nexport const ListPromptsRequestSchema = PaginatedRequestSchema.extend({\n method: z.literal('prompts/list')\n});\n/**\n * The server's response to a prompts/list request from the client.\n */\nexport const ListPromptsResultSchema = PaginatedResultSchema.extend({\n prompts: z.array(PromptSchema)\n});\n/**\n * Parameters for a `prompts/get` request.\n */\nexport const GetPromptRequestParamsSchema = BaseRequestParamsSchema.extend({\n /**\n * The name of the prompt or prompt template.\n */\n name: z.string(),\n /**\n * Arguments to use for templating the prompt.\n */\n arguments: z.record(z.string(), z.string()).optional()\n});\n/**\n * Used by the client to get a prompt provided by the server.\n */\nexport const GetPromptRequestSchema = RequestSchema.extend({\n method: z.literal('prompts/get'),\n params: GetPromptRequestParamsSchema\n});\n/**\n * Text provided to or from an LLM.\n */\nexport const TextContentSchema = z.object({\n type: z.literal('text'),\n /**\n * The text content of the message.\n */\n text: z.string(),\n /**\n * Optional annotations for the client.\n */\n annotations: AnnotationsSchema.optional(),\n /**\n * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)\n * for notes on _meta usage.\n */\n _meta: z.record(z.string(), z.unknown()).optional()\n});\n/**\n * An image provided to or from an LLM.\n */\nexport const ImageContentSchema = z.object({\n type: z.literal('image'),\n /**\n * The base64-encoded image data.\n */\n data: Base64Schema,\n /**\n * The MIME type of the image. Different providers may support different image types.\n */\n mimeType: z.string(),\n /**\n * Optional annotations for the client.\n */\n annotations: AnnotationsSchema.optional(),\n /**\n * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)\n * for notes on _meta usage.\n */\n _meta: z.record(z.string(), z.unknown()).optional()\n});\n/**\n * An Audio provided to or from an LLM.\n */\nexport const AudioContentSchema = z.object({\n type: z.literal('audio'),\n /**\n * The base64-encoded audio data.\n */\n data: Base64Schema,\n /**\n * The MIME type of the audio. Different providers may support different audio types.\n */\n mimeType: z.string(),\n /**\n * Optional annotations for the client.\n */\n annotations: AnnotationsSchema.optional(),\n /**\n * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)\n * for notes on _meta usage.\n */\n _meta: z.record(z.string(), z.unknown()).optional()\n});\n/**\n * A tool call request from an assistant (LLM).\n * Represents the assistant's request to use a tool.\n */\nexport const ToolUseContentSchema = z.object({\n type: z.literal('tool_use'),\n /**\n * The name of the tool to invoke.\n * Must match a tool name from the request's tools array.\n */\n name: z.string(),\n /**\n * Unique identifier for this tool call.\n * Used to correlate with ToolResultContent in subsequent messages.\n */\n id: z.string(),\n /**\n * Arguments to pass to the tool.\n * Must conform to the tool's inputSchema.\n */\n input: z.record(z.string(), z.unknown()),\n /**\n * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)\n * for notes on _meta usage.\n */\n _meta: z.record(z.string(), z.unknown()).optional()\n});\n/**\n * The contents of a resource, embedded into a prompt or tool call result.\n */\nexport const EmbeddedResourceSchema = z.object({\n type: z.literal('resource'),\n resource: z.union([TextResourceContentsSchema, BlobResourceContentsSchema]),\n /**\n * Optional annotations for the client.\n */\n annotations: AnnotationsSchema.optional(),\n /**\n * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)\n * for notes on _meta usage.\n */\n _meta: z.record(z.string(), z.unknown()).optional()\n});\n/**\n * A resource that the server is capable of reading, included in a prompt or tool call result.\n *\n * Note: resource links returned by tools are not guaranteed to appear in the results of `resources/list` requests.\n */\nexport const ResourceLinkSchema = ResourceSchema.extend({\n type: z.literal('resource_link')\n});\n/**\n * A content block that can be used in prompts and tool results.\n */\nexport const ContentBlockSchema = z.union([\n TextContentSchema,\n ImageContentSchema,\n AudioContentSchema,\n ResourceLinkSchema,\n EmbeddedResourceSchema\n]);\n/**\n * Describes a message returned as part of a prompt.\n */\nexport const PromptMessageSchema = z.object({\n role: RoleSchema,\n content: ContentBlockSchema\n});\n/**\n * The server's response to a prompts/get request from the client.\n */\nexport const GetPromptResultSchema = ResultSchema.extend({\n /**\n * An optional description for the prompt.\n */\n description: z.string().optional(),\n messages: z.array(PromptMessageSchema)\n});\n/**\n * An optional notification from the server to the client, informing it that the list of prompts it offers has changed. This may be issued by servers without any previous subscription from the client.\n */\nexport const PromptListChangedNotificationSchema = NotificationSchema.extend({\n method: z.literal('notifications/prompts/list_changed'),\n params: NotificationsParamsSchema.optional()\n});\n/* Tools */\n/**\n * Additional properties describing a Tool to clients.\n *\n * NOTE: all properties in ToolAnnotations are **hints**.\n * They are not guaranteed to provide a faithful description of\n * tool behavior (including descriptive properties like `title`).\n *\n * Clients should never make tool use decisions based on ToolAnnotations\n * received from untrusted servers.\n */\nexport const ToolAnnotationsSchema = z.object({\n /**\n * A human-readable title for the tool.\n */\n title: z.string().optional(),\n /**\n * If true, the tool does not modify its environment.\n *\n * Default: false\n */\n readOnlyHint: z.boolean().optional(),\n /**\n * If true, the tool may perform destructive updates to its environment.\n * If false, the tool performs only additive updates.\n *\n * (This property is meaningful only when `readOnlyHint == false`)\n *\n * Default: true\n */\n destructiveHint: z.boolean().optional(),\n /**\n * If true, calling the tool repeatedly with the same arguments\n * will have no additional effect on the its environment.\n *\n * (This property is meaningful only when `readOnlyHint == false`)\n *\n * Default: false\n */\n idempotentHint: z.boolean().optional(),\n /**\n * If true, this tool may interact with an \"open world\" of external\n * entities. If false, the tool's domain of interaction is closed.\n * For example, the world of a web search tool is open, whereas that\n * of a memory tool is not.\n *\n * Default: true\n */\n openWorldHint: z.boolean().optional()\n});\n/**\n * Execution-related properties for a tool.\n */\nexport const ToolExecutionSchema = z.object({\n /**\n * Indicates the tool's preference for task-augmented execution.\n * - \"required\": Clients MUST invoke the tool as a task\n * - \"optional\": Clients MAY invoke the tool as a task or normal request\n * - \"forbidden\": Clients MUST NOT attempt to invoke the tool as a task\n *\n * If not present, defaults to \"forbidden\".\n */\n taskSupport: z.enum(['required', 'optional', 'forbidden']).optional()\n});\n/**\n * Definition for a tool the client can call.\n */\nexport const ToolSchema = z.object({\n ...BaseMetadataSchema.shape,\n ...IconsSchema.shape,\n /**\n * A human-readable description of the tool.\n */\n description: z.string().optional(),\n /**\n * A JSON Schema 2020-12 object defining the expected parameters for the tool.\n * Must have type: 'object' at the root level per MCP spec.\n */\n inputSchema: z\n .object({\n type: z.literal('object'),\n properties: z.record(z.string(), AssertObjectSchema).optional(),\n required: z.array(z.string()).optional()\n })\n .catchall(z.unknown()),\n /**\n * An optional JSON Schema 2020-12 object defining the structure of the tool's output\n * returned in the structuredContent field of a CallToolResult.\n * Must have type: 'object' at the root level per MCP spec.\n */\n outputSchema: z\n .object({\n type: z.literal('object'),\n properties: z.record(z.string(), AssertObjectSchema).optional(),\n required: z.array(z.string()).optional()\n })\n .catchall(z.unknown())\n .optional(),\n /**\n * Optional additional tool information.\n */\n annotations: ToolAnnotationsSchema.optional(),\n /**\n * Execution-related properties for this tool.\n */\n execution: ToolExecutionSchema.optional(),\n /**\n * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)\n * for notes on _meta usage.\n */\n _meta: z.record(z.string(), z.unknown()).optional()\n});\n/**\n * Sent from the client to request a list of tools the server has.\n */\nexport const ListToolsRequestSchema = PaginatedRequestSchema.extend({\n method: z.literal('tools/list')\n});\n/**\n * The server's response to a tools/list request from the client.\n */\nexport const ListToolsResultSchema = PaginatedResultSchema.extend({\n tools: z.array(ToolSchema)\n});\n/**\n * The server's response to a tool call.\n */\nexport const CallToolResultSchema = ResultSchema.extend({\n /**\n * A list of content objects that represent the result of the tool call.\n *\n * If the Tool does not define an outputSchema, this field MUST be present in the result.\n * For backwards compatibility, this field is always present, but it may be empty.\n */\n content: z.array(ContentBlockSchema).default([]),\n /**\n * An object containing structured tool output.\n *\n * If the Tool defines an outputSchema, this field MUST be present in the result, and contain a JSON object that matches the schema.\n */\n structuredContent: z.record(z.string(), z.unknown()).optional(),\n /**\n * Whether the tool call ended in an error.\n *\n * If not set, this is assumed to be false (the call was successful).\n *\n * Any errors that originate from the tool SHOULD be reported inside the result\n * object, with `isError` set to true, _not_ as an MCP protocol-level error\n * response. Otherwise, the LLM would not be able to see that an error occurred\n * and self-correct.\n *\n * However, any errors in _finding_ the tool, an error indicating that the\n * server does not support tool calls, or any other exceptional conditions,\n * should be reported as an MCP error response.\n */\n isError: z.boolean().optional()\n});\n/**\n * CallToolResultSchema extended with backwards compatibility to protocol version 2024-10-07.\n */\nexport const CompatibilityCallToolResultSchema = CallToolResultSchema.or(ResultSchema.extend({\n toolResult: z.unknown()\n}));\n/**\n * Parameters for a `tools/call` request.\n */\nexport const CallToolRequestParamsSchema = TaskAugmentedRequestParamsSchema.extend({\n /**\n * The name of the tool to call.\n */\n name: z.string(),\n /**\n * Arguments to pass to the tool.\n */\n arguments: z.record(z.string(), z.unknown()).optional()\n});\n/**\n * Used by the client to invoke a tool provided by the server.\n */\nexport const CallToolRequestSchema = RequestSchema.extend({\n method: z.literal('tools/call'),\n params: CallToolRequestParamsSchema\n});\n/**\n * An optional notification from the server to the client, informing it that the list of tools it offers has changed. This may be issued by servers without any previous subscription from the client.\n */\nexport const ToolListChangedNotificationSchema = NotificationSchema.extend({\n method: z.literal('notifications/tools/list_changed'),\n params: NotificationsParamsSchema.optional()\n});\n/**\n * Base schema for list changed subscription options (without callback).\n * Used internally for Zod validation of autoRefresh and debounceMs.\n */\nexport const ListChangedOptionsBaseSchema = z.object({\n /**\n * If true, the list will be refreshed automatically when a list changed notification is received.\n * The callback will be called with the updated list.\n *\n * If false, the callback will be called with null items, allowing manual refresh.\n *\n * @default true\n */\n autoRefresh: z.boolean().default(true),\n /**\n * Debounce time in milliseconds for list changed notification processing.\n *\n * Multiple notifications received within this timeframe will only trigger one refresh.\n * Set to 0 to disable debouncing.\n *\n * @default 300\n */\n debounceMs: z.number().int().nonnegative().default(300)\n});\n/* Logging */\n/**\n * The severity of a log message.\n */\nexport const LoggingLevelSchema = z.enum(['debug', 'info', 'notice', 'warning', 'error', 'critical', 'alert', 'emergency']);\n/**\n * Parameters for a `logging/setLevel` request.\n */\nexport const SetLevelRequestParamsSchema = BaseRequestParamsSchema.extend({\n /**\n * The level of logging that the client wants to receive from the server. The server should send all logs at this level and higher (i.e., more severe) to the client as notifications/logging/message.\n */\n level: LoggingLevelSchema\n});\n/**\n * A request from the client to the server, to enable or adjust logging.\n */\nexport const SetLevelRequestSchema = RequestSchema.extend({\n method: z.literal('logging/setLevel'),\n params: SetLevelRequestParamsSchema\n});\n/**\n * Parameters for a `notifications/message` notification.\n */\nexport const LoggingMessageNotificationParamsSchema = NotificationsParamsSchema.extend({\n /**\n * The severity of this log message.\n */\n level: LoggingLevelSchema,\n /**\n * An optional name of the logger issuing this message.\n */\n logger: z.string().optional(),\n /**\n * The data to be logged, such as a string message or an object. Any JSON serializable type is allowed here.\n */\n data: z.unknown()\n});\n/**\n * Notification of a log message passed from server to client. If no logging/setLevel request has been sent from the client, the server MAY decide which messages to send automatically.\n */\nexport const LoggingMessageNotificationSchema = NotificationSchema.extend({\n method: z.literal('notifications/message'),\n params: LoggingMessageNotificationParamsSchema\n});\n/* Sampling */\n/**\n * Hints to use for model selection.\n */\nexport const ModelHintSchema = z.object({\n /**\n * A hint for a model name.\n */\n name: z.string().optional()\n});\n/**\n * The server's preferences for model selection, requested of the client during sampling.\n */\nexport const ModelPreferencesSchema = z.object({\n /**\n * Optional hints to use for model selection.\n */\n hints: z.array(ModelHintSchema).optional(),\n /**\n * How much to prioritize cost when selecting a model.\n */\n costPriority: z.number().min(0).max(1).optional(),\n /**\n * How much to prioritize sampling speed (latency) when selecting a model.\n */\n speedPriority: z.number().min(0).max(1).optional(),\n /**\n * How much to prioritize intelligence and capabilities when selecting a model.\n */\n intelligencePriority: z.number().min(0).max(1).optional()\n});\n/**\n * Controls tool usage behavior in sampling requests.\n */\nexport const ToolChoiceSchema = z.object({\n /**\n * Controls when tools are used:\n * - \"auto\": Model decides whether to use tools (default)\n * - \"required\": Model MUST use at least one tool before completing\n * - \"none\": Model MUST NOT use any tools\n */\n mode: z.enum(['auto', 'required', 'none']).optional()\n});\n/**\n * The result of a tool execution, provided by the user (server).\n * Represents the outcome of invoking a tool requested via ToolUseContent.\n */\nexport const ToolResultContentSchema = z.object({\n type: z.literal('tool_result'),\n toolUseId: z.string().describe('The unique identifier for the corresponding tool call.'),\n content: z.array(ContentBlockSchema).default([]),\n structuredContent: z.object({}).loose().optional(),\n isError: z.boolean().optional(),\n /**\n * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)\n * for notes on _meta usage.\n */\n _meta: z.record(z.string(), z.unknown()).optional()\n});\n/**\n * Basic content types for sampling responses (without tool use).\n * Used for backwards-compatible CreateMessageResult when tools are not used.\n */\nexport const SamplingContentSchema = z.discriminatedUnion('type', [TextContentSchema, ImageContentSchema, AudioContentSchema]);\n/**\n * Content block types allowed in sampling messages.\n * This includes text, image, audio, tool use requests, and tool results.\n */\nexport const SamplingMessageContentBlockSchema = z.discriminatedUnion('type', [\n TextContentSchema,\n ImageContentSchema,\n AudioContentSchema,\n ToolUseContentSchema,\n ToolResultContentSchema\n]);\n/**\n * Describes a message issued to or received from an LLM API.\n */\nexport const SamplingMessageSchema = z.object({\n role: RoleSchema,\n content: z.union([SamplingMessageContentBlockSchema, z.array(SamplingMessageContentBlockSchema)]),\n /**\n * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)\n * for notes on _meta usage.\n */\n _meta: z.record(z.string(), z.unknown()).optional()\n});\n/**\n * Parameters for a `sampling/createMessage` request.\n */\nexport const CreateMessageRequestParamsSchema = TaskAugmentedRequestParamsSchema.extend({\n messages: z.array(SamplingMessageSchema),\n /**\n * The server's preferences for which model to select. The client MAY modify or omit this request.\n */\n modelPreferences: ModelPreferencesSchema.optional(),\n /**\n * An optional system prompt the server wants to use for sampling. The client MAY modify or omit this prompt.\n */\n systemPrompt: z.string().optional(),\n /**\n * A request to include context from one or more MCP servers (including the caller), to be attached to the prompt.\n * The client MAY ignore this request.\n *\n * Default is \"none\". Values \"thisServer\" and \"allServers\" are soft-deprecated. Servers SHOULD only use these values if the client\n * declares ClientCapabilities.sampling.context. These values may be removed in future spec releases.\n */\n includeContext: z.enum(['none', 'thisServer', 'allServers']).optional(),\n temperature: z.number().optional(),\n /**\n * The requested maximum number of tokens to sample (to prevent runaway completions).\n *\n * The client MAY choose to sample fewer tokens than the requested maximum.\n */\n maxTokens: z.number().int(),\n stopSequences: z.array(z.string()).optional(),\n /**\n * Optional metadata to pass through to the LLM provider. The format of this metadata is provider-specific.\n */\n metadata: AssertObjectSchema.optional(),\n /**\n * Tools that the model may use during generation.\n * The client MUST return an error if this field is provided but ClientCapabilities.sampling.tools is not declared.\n */\n tools: z.array(ToolSchema).optional(),\n /**\n * Controls how the model uses tools.\n * The client MUST return an error if this field is provided but ClientCapabilities.sampling.tools is not declared.\n * Default is `{ mode: \"auto\" }`.\n */\n toolChoice: ToolChoiceSchema.optional()\n});\n/**\n * A request from the server to sample an LLM via the client. The client has full discretion over which model to select. The client should also inform the user before beginning sampling, to allow them to inspect the request (human in the loop) and decide whether to approve it.\n */\nexport const CreateMessageRequestSchema = RequestSchema.extend({\n method: z.literal('sampling/createMessage'),\n params: CreateMessageRequestParamsSchema\n});\n/**\n * The client's response to a sampling/create_message request from the server.\n * This is the backwards-compatible version that returns single content (no arrays).\n * Used when the request does not include tools.\n */\nexport const CreateMessageResultSchema = ResultSchema.extend({\n /**\n * The name of the model that generated the message.\n */\n model: z.string(),\n /**\n * The reason why sampling stopped, if known.\n *\n * Standard values:\n * - \"endTurn\": Natural end of the assistant's turn\n * - \"stopSequence\": A stop sequence was encountered\n * - \"maxTokens\": Maximum token limit was reached\n *\n * This field is an open string to allow for provider-specific stop reasons.\n */\n stopReason: z.optional(z.enum(['endTurn', 'stopSequence', 'maxTokens']).or(z.string())),\n role: RoleSchema,\n /**\n * Response content. Single content block (text, image, or audio).\n */\n content: SamplingContentSchema\n});\n/**\n * The client's response to a sampling/create_message request when tools were provided.\n * This version supports array content for tool use flows.\n */\nexport const CreateMessageResultWithToolsSchema = ResultSchema.extend({\n /**\n * The name of the model that generated the message.\n */\n model: z.string(),\n /**\n * The reason why sampling stopped, if known.\n *\n * Standard values:\n * - \"endTurn\": Natural end of the assistant's turn\n * - \"stopSequence\": A stop sequence was encountered\n * - \"maxTokens\": Maximum token limit was reached\n * - \"toolUse\": The model wants to use one or more tools\n *\n * This field is an open string to allow for provider-specific stop reasons.\n */\n stopReason: z.optional(z.enum(['endTurn', 'stopSequence', 'maxTokens', 'toolUse']).or(z.string())),\n role: RoleSchema,\n /**\n * Response content. May be a single block or array. May include ToolUseContent if stopReason is \"toolUse\".\n */\n content: z.union([SamplingMessageContentBlockSchema, z.array(SamplingMessageContentBlockSchema)])\n});\n/* Elicitation */\n/**\n * Primitive schema definition for boolean fields.\n */\nexport const BooleanSchemaSchema = z.object({\n type: z.literal('boolean'),\n title: z.string().optional(),\n description: z.string().optional(),\n default: z.boolean().optional()\n});\n/**\n * Primitive schema definition for string fields.\n */\nexport const StringSchemaSchema = z.object({\n type: z.literal('string'),\n title: z.string().optional(),\n description: z.string().optional(),\n minLength: z.number().optional(),\n maxLength: z.number().optional(),\n format: z.enum(['email', 'uri', 'date', 'date-time']).optional(),\n default: z.string().optional()\n});\n/**\n * Primitive schema definition for number fields.\n */\nexport const NumberSchemaSchema = z.object({\n type: z.enum(['number', 'integer']),\n title: z.string().optional(),\n description: z.string().optional(),\n minimum: z.number().optional(),\n maximum: z.number().optional(),\n default: z.number().optional()\n});\n/**\n * Schema for single-selection enumeration without display titles for options.\n */\nexport const UntitledSingleSelectEnumSchemaSchema = z.object({\n type: z.literal('string'),\n title: z.string().optional(),\n description: z.string().optional(),\n enum: z.array(z.string()),\n default: z.string().optional()\n});\n/**\n * Schema for single-selection enumeration with display titles for each option.\n */\nexport const TitledSingleSelectEnumSchemaSchema = z.object({\n type: z.literal('string'),\n title: z.string().optional(),\n description: z.string().optional(),\n oneOf: z.array(z.object({\n const: z.string(),\n title: z.string()\n })),\n default: z.string().optional()\n});\n/**\n * Use TitledSingleSelectEnumSchema instead.\n * This interface will be removed in a future version.\n */\nexport const LegacyTitledEnumSchemaSchema = z.object({\n type: z.literal('string'),\n title: z.string().optional(),\n description: z.string().optional(),\n enum: z.array(z.string()),\n enumNames: z.array(z.string()).optional(),\n default: z.string().optional()\n});\n// Combined single selection enumeration\nexport const SingleSelectEnumSchemaSchema = z.union([UntitledSingleSelectEnumSchemaSchema, TitledSingleSelectEnumSchemaSchema]);\n/**\n * Schema for multiple-selection enumeration without display titles for options.\n */\nexport const UntitledMultiSelectEnumSchemaSchema = z.object({\n type: z.literal('array'),\n title: z.string().optional(),\n description: z.string().optional(),\n minItems: z.number().optional(),\n maxItems: z.number().optional(),\n items: z.object({\n type: z.literal('string'),\n enum: z.array(z.string())\n }),\n default: z.array(z.string()).optional()\n});\n/**\n * Schema for multiple-selection enumeration with display titles for each option.\n */\nexport const TitledMultiSelectEnumSchemaSchema = z.object({\n type: z.literal('array'),\n title: z.string().optional(),\n description: z.string().optional(),\n minItems: z.number().optional(),\n maxItems: z.number().optional(),\n items: z.object({\n anyOf: z.array(z.object({\n const: z.string(),\n title: z.string()\n }))\n }),\n default: z.array(z.string()).optional()\n});\n/**\n * Combined schema for multiple-selection enumeration\n */\nexport const MultiSelectEnumSchemaSchema = z.union([UntitledMultiSelectEnumSchemaSchema, TitledMultiSelectEnumSchemaSchema]);\n/**\n * Primitive schema definition for enum fields.\n */\nexport const EnumSchemaSchema = z.union([LegacyTitledEnumSchemaSchema, SingleSelectEnumSchemaSchema, MultiSelectEnumSchemaSchema]);\n/**\n * Union of all primitive schema definitions.\n */\nexport const PrimitiveSchemaDefinitionSchema = z.union([EnumSchemaSchema, BooleanSchemaSchema, StringSchemaSchema, NumberSchemaSchema]);\n/**\n * Parameters for an `elicitation/create` request for form-based elicitation.\n */\nexport const ElicitRequestFormParamsSchema = TaskAugmentedRequestParamsSchema.extend({\n /**\n * The elicitation mode.\n *\n * Optional for backward compatibility. Clients MUST treat missing mode as \"form\".\n */\n mode: z.literal('form').optional(),\n /**\n * The message to present to the user describing what information is being requested.\n */\n message: z.string(),\n /**\n * A restricted subset of JSON Schema.\n * Only top-level properties are allowed, without nesting.\n */\n requestedSchema: z.object({\n type: z.literal('object'),\n properties: z.record(z.string(), PrimitiveSchemaDefinitionSchema),\n required: z.array(z.string()).optional()\n })\n});\n/**\n * Parameters for an `elicitation/create` request for URL-based elicitation.\n */\nexport const ElicitRequestURLParamsSchema = TaskAugmentedRequestParamsSchema.extend({\n /**\n * The elicitation mode.\n */\n mode: z.literal('url'),\n /**\n * The message to present to the user explaining why the interaction is needed.\n */\n message: z.string(),\n /**\n * The ID of the elicitation, which must be unique within the context of the server.\n * The client MUST treat this ID as an opaque value.\n */\n elicitationId: z.string(),\n /**\n * The URL that the user should navigate to.\n */\n url: z.string().url()\n});\n/**\n * The parameters for a request to elicit additional information from the user via the client.\n */\nexport const ElicitRequestParamsSchema = z.union([ElicitRequestFormParamsSchema, ElicitRequestURLParamsSchema]);\n/**\n * A request from the server to elicit user input via the client.\n * The client should present the message and form fields to the user (form mode)\n * or navigate to a URL (URL mode).\n */\nexport const ElicitRequestSchema = RequestSchema.extend({\n method: z.literal('elicitation/create'),\n params: ElicitRequestParamsSchema\n});\n/**\n * Parameters for a `notifications/elicitation/complete` notification.\n *\n * @category notifications/elicitation/complete\n */\nexport const ElicitationCompleteNotificationParamsSchema = NotificationsParamsSchema.extend({\n /**\n * The ID of the elicitation that completed.\n */\n elicitationId: z.string()\n});\n/**\n * A notification from the server to the client, informing it of a completion of an out-of-band elicitation request.\n *\n * @category notifications/elicitation/complete\n */\nexport const ElicitationCompleteNotificationSchema = NotificationSchema.extend({\n method: z.literal('notifications/elicitation/complete'),\n params: ElicitationCompleteNotificationParamsSchema\n});\n/**\n * The client's response to an elicitation/create request from the server.\n */\nexport const ElicitResultSchema = ResultSchema.extend({\n /**\n * The user action in response to the elicitation.\n * - \"accept\": User submitted the form/confirmed the action\n * - \"decline\": User explicitly decline the action\n * - \"cancel\": User dismissed without making an explicit choice\n */\n action: z.enum(['accept', 'decline', 'cancel']),\n /**\n * The submitted form data, only present when action is \"accept\".\n * Contains values matching the requested schema.\n * Per MCP spec, content is \"typically omitted\" for decline/cancel actions.\n * We normalize null to undefined for leniency while maintaining type compatibility.\n */\n content: z.preprocess(val => (val === null ? undefined : val), z.record(z.string(), z.union([z.string(), z.number(), z.boolean(), z.array(z.string())])).optional())\n});\n/* Autocomplete */\n/**\n * A reference to a resource or resource template definition.\n */\nexport const ResourceTemplateReferenceSchema = z.object({\n type: z.literal('ref/resource'),\n /**\n * The URI or URI template of the resource.\n */\n uri: z.string()\n});\n/**\n * @deprecated Use ResourceTemplateReferenceSchema instead\n */\nexport const ResourceReferenceSchema = ResourceTemplateReferenceSchema;\n/**\n * Identifies a prompt.\n */\nexport const PromptReferenceSchema = z.object({\n type: z.literal('ref/prompt'),\n /**\n * The name of the prompt or prompt template\n */\n name: z.string()\n});\n/**\n * Parameters for a `completion/complete` request.\n */\nexport const CompleteRequestParamsSchema = BaseRequestParamsSchema.extend({\n ref: z.union([PromptReferenceSchema, ResourceTemplateReferenceSchema]),\n /**\n * The argument's information\n */\n argument: z.object({\n /**\n * The name of the argument\n */\n name: z.string(),\n /**\n * The value of the argument to use for completion matching.\n */\n value: z.string()\n }),\n context: z\n .object({\n /**\n * Previously-resolved variables in a URI template or prompt.\n */\n arguments: z.record(z.string(), z.string()).optional()\n })\n .optional()\n});\n/**\n * A request from the client to the server, to ask for completion options.\n */\nexport const CompleteRequestSchema = RequestSchema.extend({\n method: z.literal('completion/complete'),\n params: CompleteRequestParamsSchema\n});\nexport function assertCompleteRequestPrompt(request) {\n if (request.params.ref.type !== 'ref/prompt') {\n throw new TypeError(`Expected CompleteRequestPrompt, but got ${request.params.ref.type}`);\n }\n void request;\n}\nexport function assertCompleteRequestResourceTemplate(request) {\n if (request.params.ref.type !== 'ref/resource') {\n throw new TypeError(`Expected CompleteRequestResourceTemplate, but got ${request.params.ref.type}`);\n }\n void request;\n}\n/**\n * The server's response to a completion/complete request\n */\nexport const CompleteResultSchema = ResultSchema.extend({\n completion: z.looseObject({\n /**\n * An array of completion values. Must not exceed 100 items.\n */\n values: z.array(z.string()).max(100),\n /**\n * The total number of completion options available. This can exceed the number of values actually sent in the response.\n */\n total: z.optional(z.number().int()),\n /**\n * Indicates whether there are additional completion options beyond those provided in the current response, even if the exact total is unknown.\n */\n hasMore: z.optional(z.boolean())\n })\n});\n/* Roots */\n/**\n * Represents a root directory or file that the server can operate on.\n */\nexport const RootSchema = z.object({\n /**\n * The URI identifying the root. This *must* start with file:// for now.\n */\n uri: z.string().startsWith('file://'),\n /**\n * An optional name for the root.\n */\n name: z.string().optional(),\n /**\n * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)\n * for notes on _meta usage.\n */\n _meta: z.record(z.string(), z.unknown()).optional()\n});\n/**\n * Sent from the server to request a list of root URIs from the client.\n */\nexport const ListRootsRequestSchema = RequestSchema.extend({\n method: z.literal('roots/list'),\n params: BaseRequestParamsSchema.optional()\n});\n/**\n * The client's response to a roots/list request from the server.\n */\nexport const ListRootsResultSchema = ResultSchema.extend({\n roots: z.array(RootSchema)\n});\n/**\n * A notification from the client to the server, informing it that the list of roots has changed.\n */\nexport const RootsListChangedNotificationSchema = NotificationSchema.extend({\n method: z.literal('notifications/roots/list_changed'),\n params: NotificationsParamsSchema.optional()\n});\n/* Client messages */\nexport const ClientRequestSchema = z.union([\n PingRequestSchema,\n InitializeRequestSchema,\n CompleteRequestSchema,\n SetLevelRequestSchema,\n GetPromptRequestSchema,\n ListPromptsRequestSchema,\n ListResourcesRequestSchema,\n ListResourceTemplatesRequestSchema,\n ReadResourceRequestSchema,\n SubscribeRequestSchema,\n UnsubscribeRequestSchema,\n CallToolRequestSchema,\n ListToolsRequestSchema,\n GetTaskRequestSchema,\n GetTaskPayloadRequestSchema,\n ListTasksRequestSchema,\n CancelTaskRequestSchema\n]);\nexport const ClientNotificationSchema = z.union([\n CancelledNotificationSchema,\n ProgressNotificationSchema,\n InitializedNotificationSchema,\n RootsListChangedNotificationSchema,\n TaskStatusNotificationSchema\n]);\nexport const ClientResultSchema = z.union([\n EmptyResultSchema,\n CreateMessageResultSchema,\n CreateMessageResultWithToolsSchema,\n ElicitResultSchema,\n ListRootsResultSchema,\n GetTaskResultSchema,\n ListTasksResultSchema,\n CreateTaskResultSchema\n]);\n/* Server messages */\nexport const ServerRequestSchema = z.union([\n PingRequestSchema,\n CreateMessageRequestSchema,\n ElicitRequestSchema,\n ListRootsRequestSchema,\n GetTaskRequestSchema,\n GetTaskPayloadRequestSchema,\n ListTasksRequestSchema,\n CancelTaskRequestSchema\n]);\nexport const ServerNotificationSchema = z.union([\n CancelledNotificationSchema,\n ProgressNotificationSchema,\n LoggingMessageNotificationSchema,\n ResourceUpdatedNotificationSchema,\n ResourceListChangedNotificationSchema,\n ToolListChangedNotificationSchema,\n PromptListChangedNotificationSchema,\n TaskStatusNotificationSchema,\n ElicitationCompleteNotificationSchema\n]);\nexport const ServerResultSchema = z.union([\n EmptyResultSchema,\n InitializeResultSchema,\n CompleteResultSchema,\n GetPromptResultSchema,\n ListPromptsResultSchema,\n ListResourcesResultSchema,\n ListResourceTemplatesResultSchema,\n ReadResourceResultSchema,\n CallToolResultSchema,\n ListToolsResultSchema,\n GetTaskResultSchema,\n ListTasksResultSchema,\n CreateTaskResultSchema\n]);\nexport class McpError extends Error {\n constructor(code, message, data) {\n super(`MCP error ${code}: ${message}`);\n this.code = code;\n this.data = data;\n this.name = 'McpError';\n }\n /**\n * Factory method to create the appropriate error type based on the error code and data\n */\n static fromError(code, message, data) {\n // Check for specific error types\n if (code === ErrorCode.UrlElicitationRequired && data) {\n const errorData = data;\n if (errorData.elicitations) {\n return new UrlElicitationRequiredError(errorData.elicitations, message);\n }\n }\n // Default to generic McpError\n return new McpError(code, message, data);\n }\n}\n/**\n * Specialized error type when a tool requires a URL mode elicitation.\n * This makes it nicer for the client to handle since there is specific data to work with instead of just a code to check against.\n */\nexport class UrlElicitationRequiredError extends McpError {\n constructor(elicitations, message = `URL elicitation${elicitations.length > 1 ? 's' : ''} required`) {\n super(ErrorCode.UrlElicitationRequired, message, {\n elicitations: elicitations\n });\n }\n get elicitations() {\n return this.data?.elicitations ?? [];\n }\n}\n//# sourceMappingURL=types.js.map","// zod-compat.ts\n// ----------------------------------------------------\n// Unified types + helpers to accept Zod v3 and v4 (Mini)\n// ----------------------------------------------------\nimport * as z3rt from 'zod/v3';\nimport * as z4mini from 'zod/v4-mini';\n// --- Runtime detection ---\nexport function isZ4Schema(s) {\n // Present on Zod 4 (Classic & Mini) schemas; absent on Zod 3\n const schema = s;\n return !!schema._zod;\n}\n// --- Schema construction ---\nexport function objectFromShape(shape) {\n const values = Object.values(shape);\n if (values.length === 0)\n return z4mini.object({}); // default to v4 Mini\n const allV4 = values.every(isZ4Schema);\n const allV3 = values.every(s => !isZ4Schema(s));\n if (allV4)\n return z4mini.object(shape);\n if (allV3)\n return z3rt.object(shape);\n throw new Error('Mixed Zod versions detected in object shape.');\n}\n// --- Unified parsing ---\nexport function safeParse(schema, data) {\n if (isZ4Schema(schema)) {\n // Mini exposes top-level safeParse\n const result = z4mini.safeParse(schema, data);\n return result;\n }\n const v3Schema = schema;\n const result = v3Schema.safeParse(data);\n return result;\n}\nexport async function safeParseAsync(schema, data) {\n if (isZ4Schema(schema)) {\n // Mini exposes top-level safeParseAsync\n const result = await z4mini.safeParseAsync(schema, data);\n return result;\n }\n const v3Schema = schema;\n const result = await v3Schema.safeParseAsync(data);\n return result;\n}\n// --- Shape extraction ---\nexport function getObjectShape(schema) {\n if (!schema)\n return undefined;\n // Zod v3 exposes `.shape`; Zod v4 keeps the shape on `_zod.def.shape`\n let rawShape;\n if (isZ4Schema(schema)) {\n const v4Schema = schema;\n rawShape = v4Schema._zod?.def?.shape;\n }\n else {\n const v3Schema = schema;\n rawShape = v3Schema.shape;\n }\n if (!rawShape)\n return undefined;\n if (typeof rawShape === 'function') {\n try {\n return rawShape();\n }\n catch {\n return undefined;\n }\n }\n return rawShape;\n}\n// --- Schema normalization ---\n/**\n * Normalizes a schema to an object schema. Handles both:\n * - Already-constructed object schemas (v3 or v4)\n * - Raw shapes that need to be wrapped into object schemas\n */\nexport function normalizeObjectSchema(schema) {\n if (!schema)\n return undefined;\n // First check if it's a raw shape (Record<string, AnySchema>)\n // Raw shapes don't have _def or _zod properties and aren't schemas themselves\n if (typeof schema === 'object') {\n // Check if it's actually a ZodRawShapeCompat (not a schema instance)\n // by checking if it lacks schema-like internal properties\n const asV3 = schema;\n const asV4 = schema;\n // If it's not a schema instance (no _def or _zod), it might be a raw shape\n if (!asV3._def && !asV4._zod) {\n // Check if all values are schemas (heuristic to confirm it's a raw shape)\n const values = Object.values(schema);\n if (values.length > 0 &&\n values.every(v => typeof v === 'object' &&\n v !== null &&\n (v._def !== undefined ||\n v._zod !== undefined ||\n typeof v.parse === 'function'))) {\n return objectFromShape(schema);\n }\n }\n }\n // If we get here, it should be an AnySchema (not a raw shape)\n // Check if it's already an object schema\n if (isZ4Schema(schema)) {\n // Check if it's a v4 object\n const v4Schema = schema;\n const def = v4Schema._zod?.def;\n if (def && (def.type === 'object' || def.shape !== undefined)) {\n return schema;\n }\n }\n else {\n // Check if it's a v3 object\n const v3Schema = schema;\n if (v3Schema.shape !== undefined) {\n return schema;\n }\n }\n return undefined;\n}\n// --- Error message extraction ---\n/**\n * Safely extracts an error message from a parse result error.\n * Zod errors can have different structures, so we handle various cases.\n */\nexport function getParseErrorMessage(error) {\n if (error && typeof error === 'object') {\n // Try common error structures\n if ('message' in error && typeof error.message === 'string') {\n return error.message;\n }\n if ('issues' in error && Array.isArray(error.issues) && error.issues.length > 0) {\n const firstIssue = error.issues[0];\n if (firstIssue && typeof firstIssue === 'object' && 'message' in firstIssue) {\n return String(firstIssue.message);\n }\n }\n // Fallback: try to stringify the error\n try {\n return JSON.stringify(error);\n }\n catch {\n return String(error);\n }\n }\n return String(error);\n}\n// --- Schema metadata access ---\n/**\n * Gets the description from a schema, if available.\n * Works with both Zod v3 and v4.\n *\n * Both versions expose a `.description` getter that returns the description\n * from their respective internal storage (v3: _def, v4: globalRegistry).\n */\nexport function getSchemaDescription(schema) {\n return schema.description;\n}\n/**\n * Checks if a schema is optional.\n * Works with both Zod v3 and v4.\n */\nexport function isSchemaOptional(schema) {\n if (isZ4Schema(schema)) {\n const v4Schema = schema;\n return v4Schema._zod?.def?.type === 'optional';\n }\n const v3Schema = schema;\n // v3 has isOptional() method\n if (typeof schema.isOptional === 'function') {\n return schema.isOptional();\n }\n return v3Schema._def?.typeName === 'ZodOptional';\n}\n/**\n * Gets the literal value from a schema, if it's a literal schema.\n * Works with both Zod v3 and v4.\n * Returns undefined if the schema is not a literal or the value cannot be determined.\n */\nexport function getLiteralValue(schema) {\n if (isZ4Schema(schema)) {\n const v4Schema = schema;\n const def = v4Schema._zod?.def;\n if (def) {\n // Try various ways to get the literal value\n if (def.value !== undefined)\n return def.value;\n if (Array.isArray(def.values) && def.values.length > 0) {\n return def.values[0];\n }\n }\n }\n const v3Schema = schema;\n const def = v3Schema._def;\n if (def) {\n if (def.value !== undefined)\n return def.value;\n if (Array.isArray(def.values) && def.values.length > 0) {\n return def.values[0];\n }\n }\n // Fallback: check for direct value property (some Zod versions)\n const directValue = schema.value;\n if (directValue !== undefined)\n return directValue;\n return undefined;\n}\n//# sourceMappingURL=zod-compat.js.map","/**\n * Experimental task interfaces for MCP SDK.\n * WARNING: These APIs are experimental and may change without notice.\n */\n/**\n * Checks if a task status represents a terminal state.\n * Terminal states are those where the task has finished and will not change.\n *\n * @param status - The task status to check\n * @returns True if the status is terminal (completed, failed, or cancelled)\n * @experimental\n */\nexport function isTerminal(status) {\n return status === 'completed' || status === 'failed' || status === 'cancelled';\n}\n//# sourceMappingURL=interfaces.js.map","import { setResponseValueAndErrors } from \"../errorMessages.js\";\nlet emojiRegex = undefined;\n/**\n * Generated from the regular expressions found here as of 2024-05-22:\n * https://github.com/colinhacks/zod/blob/master/src/types.ts.\n *\n * Expressions with /i flag have been changed accordingly.\n */\nexport const zodPatterns = {\n /**\n * `c` was changed to `[cC]` to replicate /i flag\n */\n cuid: /^[cC][^\\s-]{8,}$/,\n cuid2: /^[0-9a-z]+$/,\n ulid: /^[0-9A-HJKMNP-TV-Z]{26}$/,\n /**\n * `a-z` was added to replicate /i flag\n */\n email: /^(?!\\.)(?!.*\\.\\.)([a-zA-Z0-9_'+\\-\\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\\-]*\\.)+[a-zA-Z]{2,}$/,\n /**\n * Constructed a valid Unicode RegExp\n *\n * Lazily instantiate since this type of regex isn't supported\n * in all envs (e.g. React Native).\n *\n * See:\n * https://github.com/colinhacks/zod/issues/2433\n * Fix in Zod:\n * https://github.com/colinhacks/zod/commit/9340fd51e48576a75adc919bff65dbc4a5d4c99b\n */\n emoji: () => {\n if (emojiRegex === undefined) {\n emojiRegex = RegExp(\"^(\\\\p{Extended_Pictographic}|\\\\p{Emoji_Component})+$\", \"u\");\n }\n return emojiRegex;\n },\n /**\n * Unused\n */\n uuid: /^[0-9a-fA-F]{8}\\b-[0-9a-fA-F]{4}\\b-[0-9a-fA-F]{4}\\b-[0-9a-fA-F]{4}\\b-[0-9a-fA-F]{12}$/,\n /**\n * Unused\n */\n ipv4: /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,\n ipv4Cidr: /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\/(3[0-2]|[12]?[0-9])$/,\n /**\n * Unused\n */\n ipv6: /^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,\n ipv6Cidr: /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,\n base64: /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,\n base64url: /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,\n nanoid: /^[a-zA-Z0-9_-]{21}$/,\n jwt: /^[A-Za-z0-9-_]+\\.[A-Za-z0-9-_]+\\.[A-Za-z0-9-_]*$/,\n};\nexport function parseStringDef(def, refs) {\n const res = {\n type: \"string\",\n };\n if (def.checks) {\n for (const check of def.checks) {\n switch (check.kind) {\n case \"min\":\n setResponseValueAndErrors(res, \"minLength\", typeof res.minLength === \"number\"\n ? Math.max(res.minLength, check.value)\n : check.value, check.message, refs);\n break;\n case \"max\":\n setResponseValueAndErrors(res, \"maxLength\", typeof res.maxLength === \"number\"\n ? Math.min(res.maxLength, check.value)\n : check.value, check.message, refs);\n break;\n case \"email\":\n switch (refs.emailStrategy) {\n case \"format:email\":\n addFormat(res, \"email\", check.message, refs);\n break;\n case \"format:idn-email\":\n addFormat(res, \"idn-email\", check.message, refs);\n break;\n case \"pattern:zod\":\n addPattern(res, zodPatterns.email, check.message, refs);\n break;\n }\n break;\n case \"url\":\n addFormat(res, \"uri\", check.message, refs);\n break;\n case \"uuid\":\n addFormat(res, \"uuid\", check.message, refs);\n break;\n case \"regex\":\n addPattern(res, check.regex, check.message, refs);\n break;\n case \"cuid\":\n addPattern(res, zodPatterns.cuid, check.message, refs);\n break;\n case \"cuid2\":\n addPattern(res, zodPatterns.cuid2, check.message, refs);\n break;\n case \"startsWith\":\n addPattern(res, RegExp(`^${escapeLiteralCheckValue(check.value, refs)}`), check.message, refs);\n break;\n case \"endsWith\":\n addPattern(res, RegExp(`${escapeLiteralCheckValue(check.value, refs)}$`), check.message, refs);\n break;\n case \"datetime\":\n addFormat(res, \"date-time\", check.message, refs);\n break;\n case \"date\":\n addFormat(res, \"date\", check.message, refs);\n break;\n case \"time\":\n addFormat(res, \"time\", check.message, refs);\n break;\n case \"duration\":\n addFormat(res, \"duration\", check.message, refs);\n break;\n case \"length\":\n setResponseValueAndErrors(res, \"minLength\", typeof res.minLength === \"number\"\n ? Math.max(res.minLength, check.value)\n : check.value, check.message, refs);\n setResponseValueAndErrors(res, \"maxLength\", typeof res.maxLength === \"number\"\n ? Math.min(res.maxLength, check.value)\n : check.value, check.message, refs);\n break;\n case \"includes\": {\n addPattern(res, RegExp(escapeLiteralCheckValue(check.value, refs)), check.message, refs);\n break;\n }\n case \"ip\": {\n if (check.version !== \"v6\") {\n addFormat(res, \"ipv4\", check.message, refs);\n }\n if (check.version !== \"v4\") {\n addFormat(res, \"ipv6\", check.message, refs);\n }\n break;\n }\n case \"base64url\":\n addPattern(res, zodPatterns.base64url, check.message, refs);\n break;\n case \"jwt\":\n addPattern(res, zodPatterns.jwt, check.message, refs);\n break;\n case \"cidr\": {\n if (check.version !== \"v6\") {\n addPattern(res, zodPatterns.ipv4Cidr, check.message, refs);\n }\n if (check.version !== \"v4\") {\n addPattern(res, zodPatterns.ipv6Cidr, check.message, refs);\n }\n break;\n }\n case \"emoji\":\n addPattern(res, zodPatterns.emoji(), check.message, refs);\n break;\n case \"ulid\": {\n addPattern(res, zodPatterns.ulid, check.message, refs);\n break;\n }\n case \"base64\": {\n switch (refs.base64Strategy) {\n case \"format:binary\": {\n addFormat(res, \"binary\", check.message, refs);\n break;\n }\n case \"contentEncoding:base64\": {\n setResponseValueAndErrors(res, \"contentEncoding\", \"base64\", check.message, refs);\n break;\n }\n case \"pattern:zod\": {\n addPattern(res, zodPatterns.base64, check.message, refs);\n break;\n }\n }\n break;\n }\n case \"nanoid\": {\n addPattern(res, zodPatterns.nanoid, check.message, refs);\n }\n case \"toLowerCase\":\n case \"toUpperCase\":\n case \"trim\":\n break;\n default:\n ((_) => { })(check);\n }\n }\n }\n return res;\n}\nfunction escapeLiteralCheckValue(literal, refs) {\n return refs.patternStrategy === \"escape\"\n ? escapeNonAlphaNumeric(literal)\n : literal;\n}\nconst ALPHA_NUMERIC = new Set(\"ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789\");\nfunction escapeNonAlphaNumeric(source) {\n let result = \"\";\n for (let i = 0; i < source.length; i++) {\n if (!ALPHA_NUMERIC.has(source[i])) {\n result += \"\\\\\";\n }\n result += source[i];\n }\n return result;\n}\n// Adds a \"format\" keyword to the schema. If a format exists, both formats will be joined in an allOf-node, along with subsequent ones.\nfunction addFormat(schema, value, message, refs) {\n if (schema.format || schema.anyOf?.some((x) => x.format)) {\n if (!schema.anyOf) {\n schema.anyOf = [];\n }\n if (schema.format) {\n schema.anyOf.push({\n format: schema.format,\n ...(schema.errorMessage &&\n refs.errorMessages && {\n errorMessage: { format: schema.errorMessage.format },\n }),\n });\n delete schema.format;\n if (schema.errorMessage) {\n delete schema.errorMessage.format;\n if (Object.keys(schema.errorMessage).length === 0) {\n delete schema.errorMessage;\n }\n }\n }\n schema.anyOf.push({\n format: value,\n ...(message &&\n refs.errorMessages && { errorMessage: { format: message } }),\n });\n }\n else {\n setResponseValueAndErrors(schema, \"format\", value, message, refs);\n }\n}\n// Adds a \"pattern\" keyword to the schema. If a pattern exists, both patterns will be joined in an allOf-node, along with subsequent ones.\nfunction addPattern(schema, regex, message, refs) {\n if (schema.pattern || schema.allOf?.some((x) => x.pattern)) {\n if (!schema.allOf) {\n schema.allOf = [];\n }\n if (schema.pattern) {\n schema.allOf.push({\n pattern: schema.pattern,\n ...(schema.errorMessage &&\n refs.errorMessages && {\n errorMessage: { pattern: schema.errorMessage.pattern },\n }),\n });\n delete schema.pattern;\n if (schema.errorMessage) {\n delete schema.errorMessage.pattern;\n if (Object.keys(schema.errorMessage).length === 0) {\n delete schema.errorMessage;\n }\n }\n }\n schema.allOf.push({\n pattern: stringifyRegExpWithFlags(regex, refs),\n ...(message &&\n refs.errorMessages && { errorMessage: { pattern: message } }),\n });\n }\n else {\n setResponseValueAndErrors(schema, \"pattern\", stringifyRegExpWithFlags(regex, refs), message, refs);\n }\n}\n// Mutate z.string.regex() in a best attempt to accommodate for regex flags when applyRegexFlags is true\nfunction stringifyRegExpWithFlags(regex, refs) {\n if (!refs.applyRegexFlags || !regex.flags) {\n return regex.source;\n }\n // Currently handled flags\n const flags = {\n i: regex.flags.includes(\"i\"),\n m: regex.flags.includes(\"m\"),\n s: regex.flags.includes(\"s\"), // `.` matches newlines\n };\n // The general principle here is to step through each character, one at a time, applying mutations as flags require. We keep track when the current character is escaped, and when it's inside a group /like [this]/ or (also) a range like /[a-z]/. The following is fairly brittle imperative code; edit at your peril!\n const source = flags.i ? regex.source.toLowerCase() : regex.source;\n let pattern = \"\";\n let isEscaped = false;\n let inCharGroup = false;\n let inCharRange = false;\n for (let i = 0; i < source.length; i++) {\n if (isEscaped) {\n pattern += source[i];\n isEscaped = false;\n continue;\n }\n if (flags.i) {\n if (inCharGroup) {\n if (source[i].match(/[a-z]/)) {\n if (inCharRange) {\n pattern += source[i];\n pattern += `${source[i - 2]}-${source[i]}`.toUpperCase();\n inCharRange = false;\n }\n else if (source[i + 1] === \"-\" && source[i + 2]?.match(/[a-z]/)) {\n pattern += source[i];\n inCharRange = true;\n }\n else {\n pattern += `${source[i]}${source[i].toUpperCase()}`;\n }\n continue;\n }\n }\n else if (source[i].match(/[a-z]/)) {\n pattern += `[${source[i]}${source[i].toUpperCase()}]`;\n continue;\n }\n }\n if (flags.m) {\n if (source[i] === \"^\") {\n pattern += `(^|(?<=[\\r\\n]))`;\n continue;\n }\n else if (source[i] === \"$\") {\n pattern += `($|(?=[\\r\\n]))`;\n continue;\n }\n }\n if (flags.s && source[i] === \".\") {\n pattern += inCharGroup ? `${source[i]}\\r\\n` : `[${source[i]}\\r\\n]`;\n continue;\n }\n pattern += source[i];\n if (source[i] === \"\\\\\") {\n isEscaped = true;\n }\n else if (inCharGroup && source[i] === \"]\") {\n inCharGroup = false;\n }\n else if (!inCharGroup && source[i] === \"[\") {\n inCharGroup = true;\n }\n }\n try {\n new RegExp(pattern);\n }\n catch {\n console.warn(`Could not convert regex pattern at ${refs.currentPath.join(\"/\")} to a flag-independent form! Falling back to the flag-ignorant source`);\n return regex.source;\n }\n return pattern;\n}\n","// zod-json-schema-compat.ts\n// ----------------------------------------------------\n// JSON Schema conversion for both Zod v3 and Zod v4 (Mini)\n// v3 uses your vendored converter; v4 uses Mini's toJSONSchema\n// ----------------------------------------------------\nimport * as z4mini from 'zod/v4-mini';\nimport { getObjectShape, safeParse, isZ4Schema, getLiteralValue } from './zod-compat.js';\nimport { zodToJsonSchema } from 'zod-to-json-schema';\nfunction mapMiniTarget(t) {\n if (!t)\n return 'draft-7';\n if (t === 'jsonSchema7' || t === 'draft-7')\n return 'draft-7';\n if (t === 'jsonSchema2019-09' || t === 'draft-2020-12')\n return 'draft-2020-12';\n return 'draft-7'; // fallback\n}\nexport function toJsonSchemaCompat(schema, opts) {\n if (isZ4Schema(schema)) {\n // v4 branch — use Mini's built-in toJSONSchema\n return z4mini.toJSONSchema(schema, {\n target: mapMiniTarget(opts?.target),\n io: opts?.pipeStrategy ?? 'input'\n });\n }\n // v3 branch — use vendored converter\n return zodToJsonSchema(schema, {\n strictUnions: opts?.strictUnions ?? true,\n pipeStrategy: opts?.pipeStrategy ?? 'input'\n });\n}\nexport function getMethodLiteral(schema) {\n const shape = getObjectShape(schema);\n const methodSchema = shape?.method;\n if (!methodSchema) {\n throw new Error('Schema is missing a method literal');\n }\n const value = getLiteralValue(methodSchema);\n if (typeof value !== 'string') {\n throw new Error('Schema method literal must be a string');\n }\n return value;\n}\nexport function parseWithCompat(schema, data) {\n const result = safeParse(schema, data);\n if (!result.success) {\n throw result.error;\n }\n return result.data;\n}\n//# sourceMappingURL=zod-json-schema-compat.js.map","import { safeParse } from '../server/zod-compat.js';\nimport { CancelledNotificationSchema, CreateTaskResultSchema, ErrorCode, GetTaskRequestSchema, GetTaskResultSchema, GetTaskPayloadRequestSchema, ListTasksRequestSchema, ListTasksResultSchema, CancelTaskRequestSchema, CancelTaskResultSchema, isJSONRPCErrorResponse, isJSONRPCRequest, isJSONRPCResultResponse, isJSONRPCNotification, McpError, PingRequestSchema, ProgressNotificationSchema, RELATED_TASK_META_KEY, TaskStatusNotificationSchema, isTaskAugmentedRequestParams } from '../types.js';\nimport { isTerminal } from '../experimental/tasks/interfaces.js';\nimport { getMethodLiteral, parseWithCompat } from '../server/zod-json-schema-compat.js';\n/**\n * The default request timeout, in miliseconds.\n */\nexport const DEFAULT_REQUEST_TIMEOUT_MSEC = 60000;\n/**\n * Implements MCP protocol framing on top of a pluggable transport, including\n * features like request/response linking, notifications, and progress.\n */\nexport class Protocol {\n constructor(_options) {\n this._options = _options;\n this._requestMessageId = 0;\n this._requestHandlers = new Map();\n this._requestHandlerAbortControllers = new Map();\n this._notificationHandlers = new Map();\n this._responseHandlers = new Map();\n this._progressHandlers = new Map();\n this._timeoutInfo = new Map();\n this._pendingDebouncedNotifications = new Set();\n // Maps task IDs to progress tokens to keep handlers alive after CreateTaskResult\n this._taskProgressTokens = new Map();\n this._requestResolvers = new Map();\n this.setNotificationHandler(CancelledNotificationSchema, notification => {\n this._oncancel(notification);\n });\n this.setNotificationHandler(ProgressNotificationSchema, notification => {\n this._onprogress(notification);\n });\n this.setRequestHandler(PingRequestSchema, \n // Automatic pong by default.\n _request => ({}));\n // Install task handlers if TaskStore is provided\n this._taskStore = _options?.taskStore;\n this._taskMessageQueue = _options?.taskMessageQueue;\n if (this._taskStore) {\n this.setRequestHandler(GetTaskRequestSchema, async (request, extra) => {\n const task = await this._taskStore.getTask(request.params.taskId, extra.sessionId);\n if (!task) {\n throw new McpError(ErrorCode.InvalidParams, 'Failed to retrieve task: Task not found');\n }\n // Per spec: tasks/get responses SHALL NOT include related-task metadata\n // as the taskId parameter is the source of truth\n // @ts-expect-error SendResultT cannot contain GetTaskResult, but we include it in our derived types everywhere else\n return {\n ...task\n };\n });\n this.setRequestHandler(GetTaskPayloadRequestSchema, async (request, extra) => {\n const handleTaskResult = async () => {\n const taskId = request.params.taskId;\n // Deliver queued messages\n if (this._taskMessageQueue) {\n let queuedMessage;\n while ((queuedMessage = await this._taskMessageQueue.dequeue(taskId, extra.sessionId))) {\n // Handle response and error messages by routing them to the appropriate resolver\n if (queuedMessage.type === 'response' || queuedMessage.type === 'error') {\n const message = queuedMessage.message;\n const requestId = message.id;\n // Lookup resolver in _requestResolvers map\n const resolver = this._requestResolvers.get(requestId);\n if (resolver) {\n // Remove resolver from map after invocation\n this._requestResolvers.delete(requestId);\n // Invoke resolver with response or error\n if (queuedMessage.type === 'response') {\n resolver(message);\n }\n else {\n // Convert JSONRPCError to McpError\n const errorMessage = message;\n const error = new McpError(errorMessage.error.code, errorMessage.error.message, errorMessage.error.data);\n resolver(error);\n }\n }\n else {\n // Handle missing resolver gracefully with error logging\n const messageType = queuedMessage.type === 'response' ? 'Response' : 'Error';\n this._onerror(new Error(`${messageType} handler missing for request ${requestId}`));\n }\n // Continue to next message\n continue;\n }\n // Send the message on the response stream by passing the relatedRequestId\n // This tells the transport to write the message to the tasks/result response stream\n await this._transport?.send(queuedMessage.message, { relatedRequestId: extra.requestId });\n }\n }\n // Now check task status\n const task = await this._taskStore.getTask(taskId, extra.sessionId);\n if (!task) {\n throw new McpError(ErrorCode.InvalidParams, `Task not found: ${taskId}`);\n }\n // Block if task is not terminal (we've already delivered all queued messages above)\n if (!isTerminal(task.status)) {\n // Wait for status change or new messages\n await this._waitForTaskUpdate(taskId, extra.signal);\n // After waking up, recursively call to deliver any new messages or result\n return await handleTaskResult();\n }\n // If task is terminal, return the result\n if (isTerminal(task.status)) {\n const result = await this._taskStore.getTaskResult(taskId, extra.sessionId);\n this._clearTaskQueue(taskId);\n return {\n ...result,\n _meta: {\n ...result._meta,\n [RELATED_TASK_META_KEY]: {\n taskId: taskId\n }\n }\n };\n }\n return await handleTaskResult();\n };\n return await handleTaskResult();\n });\n this.setRequestHandler(ListTasksRequestSchema, async (request, extra) => {\n try {\n const { tasks, nextCursor } = await this._taskStore.listTasks(request.params?.cursor, extra.sessionId);\n // @ts-expect-error SendResultT cannot contain ListTasksResult, but we include it in our derived types everywhere else\n return {\n tasks,\n nextCursor,\n _meta: {}\n };\n }\n catch (error) {\n throw new McpError(ErrorCode.InvalidParams, `Failed to list tasks: ${error instanceof Error ? error.message : String(error)}`);\n }\n });\n this.setRequestHandler(CancelTaskRequestSchema, async (request, extra) => {\n try {\n // Get the current task to check if it's in a terminal state, in case the implementation is not atomic\n const task = await this._taskStore.getTask(request.params.taskId, extra.sessionId);\n if (!task) {\n throw new McpError(ErrorCode.InvalidParams, `Task not found: ${request.params.taskId}`);\n }\n // Reject cancellation of terminal tasks\n if (isTerminal(task.status)) {\n throw new McpError(ErrorCode.InvalidParams, `Cannot cancel task in terminal status: ${task.status}`);\n }\n await this._taskStore.updateTaskStatus(request.params.taskId, 'cancelled', 'Client cancelled task execution.', extra.sessionId);\n this._clearTaskQueue(request.params.taskId);\n const cancelledTask = await this._taskStore.getTask(request.params.taskId, extra.sessionId);\n if (!cancelledTask) {\n // Task was deleted during cancellation (e.g., cleanup happened)\n throw new McpError(ErrorCode.InvalidParams, `Task not found after cancellation: ${request.params.taskId}`);\n }\n return {\n _meta: {},\n ...cancelledTask\n };\n }\n catch (error) {\n // Re-throw McpError as-is\n if (error instanceof McpError) {\n throw error;\n }\n throw new McpError(ErrorCode.InvalidRequest, `Failed to cancel task: ${error instanceof Error ? error.message : String(error)}`);\n }\n });\n }\n }\n async _oncancel(notification) {\n if (!notification.params.requestId) {\n return;\n }\n // Handle request cancellation\n const controller = this._requestHandlerAbortControllers.get(notification.params.requestId);\n controller?.abort(notification.params.reason);\n }\n _setupTimeout(messageId, timeout, maxTotalTimeout, onTimeout, resetTimeoutOnProgress = false) {\n this._timeoutInfo.set(messageId, {\n timeoutId: setTimeout(onTimeout, timeout),\n startTime: Date.now(),\n timeout,\n maxTotalTimeout,\n resetTimeoutOnProgress,\n onTimeout\n });\n }\n _resetTimeout(messageId) {\n const info = this._timeoutInfo.get(messageId);\n if (!info)\n return false;\n const totalElapsed = Date.now() - info.startTime;\n if (info.maxTotalTimeout && totalElapsed >= info.maxTotalTimeout) {\n this._timeoutInfo.delete(messageId);\n throw McpError.fromError(ErrorCode.RequestTimeout, 'Maximum total timeout exceeded', {\n maxTotalTimeout: info.maxTotalTimeout,\n totalElapsed\n });\n }\n clearTimeout(info.timeoutId);\n info.timeoutId = setTimeout(info.onTimeout, info.timeout);\n return true;\n }\n _cleanupTimeout(messageId) {\n const info = this._timeoutInfo.get(messageId);\n if (info) {\n clearTimeout(info.timeoutId);\n this._timeoutInfo.delete(messageId);\n }\n }\n /**\n * Attaches to the given transport, starts it, and starts listening for messages.\n *\n * The Protocol object assumes ownership of the Transport, replacing any callbacks that have already been set, and expects that it is the only user of the Transport instance going forward.\n */\n async connect(transport) {\n if (this._transport) {\n throw new Error('Already connected to a transport. Call close() before connecting to a new transport, or use a separate Protocol instance per connection.');\n }\n this._transport = transport;\n const _onclose = this.transport?.onclose;\n this._transport.onclose = () => {\n _onclose?.();\n this._onclose();\n };\n const _onerror = this.transport?.onerror;\n this._transport.onerror = (error) => {\n _onerror?.(error);\n this._onerror(error);\n };\n const _onmessage = this._transport?.onmessage;\n this._transport.onmessage = (message, extra) => {\n _onmessage?.(message, extra);\n if (isJSONRPCResultResponse(message) || isJSONRPCErrorResponse(message)) {\n this._onresponse(message);\n }\n else if (isJSONRPCRequest(message)) {\n this._onrequest(message, extra);\n }\n else if (isJSONRPCNotification(message)) {\n this._onnotification(message);\n }\n else {\n this._onerror(new Error(`Unknown message type: ${JSON.stringify(message)}`));\n }\n };\n await this._transport.start();\n }\n _onclose() {\n const responseHandlers = this._responseHandlers;\n this._responseHandlers = new Map();\n this._progressHandlers.clear();\n this._taskProgressTokens.clear();\n this._pendingDebouncedNotifications.clear();\n for (const info of this._timeoutInfo.values()) {\n clearTimeout(info.timeoutId);\n }\n this._timeoutInfo.clear();\n // Abort all in-flight request handlers so they stop sending messages\n for (const controller of this._requestHandlerAbortControllers.values()) {\n controller.abort();\n }\n this._requestHandlerAbortControllers.clear();\n const error = McpError.fromError(ErrorCode.ConnectionClosed, 'Connection closed');\n this._transport = undefined;\n this.onclose?.();\n for (const handler of responseHandlers.values()) {\n handler(error);\n }\n }\n _onerror(error) {\n this.onerror?.(error);\n }\n _onnotification(notification) {\n const handler = this._notificationHandlers.get(notification.method) ?? this.fallbackNotificationHandler;\n // Ignore notifications not being subscribed to.\n if (handler === undefined) {\n return;\n }\n // Starting with Promise.resolve() puts any synchronous errors into the monad as well.\n Promise.resolve()\n .then(() => handler(notification))\n .catch(error => this._onerror(new Error(`Uncaught error in notification handler: ${error}`)));\n }\n _onrequest(request, extra) {\n const handler = this._requestHandlers.get(request.method) ?? this.fallbackRequestHandler;\n // Capture the current transport at request time to ensure responses go to the correct client\n const capturedTransport = this._transport;\n // Extract taskId from request metadata if present (needed early for method not found case)\n const relatedTaskId = request.params?._meta?.[RELATED_TASK_META_KEY]?.taskId;\n if (handler === undefined) {\n const errorResponse = {\n jsonrpc: '2.0',\n id: request.id,\n error: {\n code: ErrorCode.MethodNotFound,\n message: 'Method not found'\n }\n };\n // Queue or send the error response based on whether this is a task-related request\n if (relatedTaskId && this._taskMessageQueue) {\n this._enqueueTaskMessage(relatedTaskId, {\n type: 'error',\n message: errorResponse,\n timestamp: Date.now()\n }, capturedTransport?.sessionId).catch(error => this._onerror(new Error(`Failed to enqueue error response: ${error}`)));\n }\n else {\n capturedTransport\n ?.send(errorResponse)\n .catch(error => this._onerror(new Error(`Failed to send an error response: ${error}`)));\n }\n return;\n }\n const abortController = new AbortController();\n this._requestHandlerAbortControllers.set(request.id, abortController);\n const taskCreationParams = isTaskAugmentedRequestParams(request.params) ? request.params.task : undefined;\n const taskStore = this._taskStore ? this.requestTaskStore(request, capturedTransport?.sessionId) : undefined;\n const fullExtra = {\n signal: abortController.signal,\n sessionId: capturedTransport?.sessionId,\n _meta: request.params?._meta,\n sendNotification: async (notification) => {\n if (abortController.signal.aborted)\n return;\n // Include related-task metadata if this request is part of a task\n const notificationOptions = { relatedRequestId: request.id };\n if (relatedTaskId) {\n notificationOptions.relatedTask = { taskId: relatedTaskId };\n }\n await this.notification(notification, notificationOptions);\n },\n sendRequest: async (r, resultSchema, options) => {\n if (abortController.signal.aborted) {\n throw new McpError(ErrorCode.ConnectionClosed, 'Request was cancelled');\n }\n // Include related-task metadata if this request is part of a task\n const requestOptions = { ...options, relatedRequestId: request.id };\n if (relatedTaskId && !requestOptions.relatedTask) {\n requestOptions.relatedTask = { taskId: relatedTaskId };\n }\n // Set task status to input_required when sending a request within a task context\n // Use the taskId from options (explicit) or fall back to relatedTaskId (inherited)\n const effectiveTaskId = requestOptions.relatedTask?.taskId ?? relatedTaskId;\n if (effectiveTaskId && taskStore) {\n await taskStore.updateTaskStatus(effectiveTaskId, 'input_required');\n }\n return await this.request(r, resultSchema, requestOptions);\n },\n authInfo: extra?.authInfo,\n requestId: request.id,\n requestInfo: extra?.requestInfo,\n taskId: relatedTaskId,\n taskStore: taskStore,\n taskRequestedTtl: taskCreationParams?.ttl,\n closeSSEStream: extra?.closeSSEStream,\n closeStandaloneSSEStream: extra?.closeStandaloneSSEStream\n };\n // Starting with Promise.resolve() puts any synchronous errors into the monad as well.\n Promise.resolve()\n .then(() => {\n // If this request asked for task creation, check capability first\n if (taskCreationParams) {\n // Check if the request method supports task creation\n this.assertTaskHandlerCapability(request.method);\n }\n })\n .then(() => handler(request, fullExtra))\n .then(async (result) => {\n if (abortController.signal.aborted) {\n // Request was cancelled\n return;\n }\n const response = {\n result,\n jsonrpc: '2.0',\n id: request.id\n };\n // Queue or send the response based on whether this is a task-related request\n if (relatedTaskId && this._taskMessageQueue) {\n await this._enqueueTaskMessage(relatedTaskId, {\n type: 'response',\n message: response,\n timestamp: Date.now()\n }, capturedTransport?.sessionId);\n }\n else {\n await capturedTransport?.send(response);\n }\n }, async (error) => {\n if (abortController.signal.aborted) {\n // Request was cancelled\n return;\n }\n const errorResponse = {\n jsonrpc: '2.0',\n id: request.id,\n error: {\n code: Number.isSafeInteger(error['code']) ? error['code'] : ErrorCode.InternalError,\n message: error.message ?? 'Internal error',\n ...(error['data'] !== undefined && { data: error['data'] })\n }\n };\n // Queue or send the error response based on whether this is a task-related request\n if (relatedTaskId && this._taskMessageQueue) {\n await this._enqueueTaskMessage(relatedTaskId, {\n type: 'error',\n message: errorResponse,\n timestamp: Date.now()\n }, capturedTransport?.sessionId);\n }\n else {\n await capturedTransport?.send(errorResponse);\n }\n })\n .catch(error => this._onerror(new Error(`Failed to send response: ${error}`)))\n .finally(() => {\n // Only delete if the stored controller is still ours; after close()+connect(),\n // a new connection may have reused the same request ID with a different controller.\n if (this._requestHandlerAbortControllers.get(request.id) === abortController) {\n this._requestHandlerAbortControllers.delete(request.id);\n }\n });\n }\n _onprogress(notification) {\n const { progressToken, ...params } = notification.params;\n const messageId = Number(progressToken);\n const handler = this._progressHandlers.get(messageId);\n if (!handler) {\n this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(notification)}`));\n return;\n }\n const responseHandler = this._responseHandlers.get(messageId);\n const timeoutInfo = this._timeoutInfo.get(messageId);\n if (timeoutInfo && responseHandler && timeoutInfo.resetTimeoutOnProgress) {\n try {\n this._resetTimeout(messageId);\n }\n catch (error) {\n // Clean up if maxTotalTimeout was exceeded\n this._responseHandlers.delete(messageId);\n this._progressHandlers.delete(messageId);\n this._cleanupTimeout(messageId);\n responseHandler(error);\n return;\n }\n }\n handler(params);\n }\n _onresponse(response) {\n const messageId = Number(response.id);\n // Check if this is a response to a queued request\n const resolver = this._requestResolvers.get(messageId);\n if (resolver) {\n this._requestResolvers.delete(messageId);\n if (isJSONRPCResultResponse(response)) {\n resolver(response);\n }\n else {\n const error = new McpError(response.error.code, response.error.message, response.error.data);\n resolver(error);\n }\n return;\n }\n const handler = this._responseHandlers.get(messageId);\n if (handler === undefined) {\n this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(response)}`));\n return;\n }\n this._responseHandlers.delete(messageId);\n this._cleanupTimeout(messageId);\n // Keep progress handler alive for CreateTaskResult responses\n let isTaskResponse = false;\n if (isJSONRPCResultResponse(response) && response.result && typeof response.result === 'object') {\n const result = response.result;\n if (result.task && typeof result.task === 'object') {\n const task = result.task;\n if (typeof task.taskId === 'string') {\n isTaskResponse = true;\n this._taskProgressTokens.set(task.taskId, messageId);\n }\n }\n }\n if (!isTaskResponse) {\n this._progressHandlers.delete(messageId);\n }\n if (isJSONRPCResultResponse(response)) {\n handler(response);\n }\n else {\n const error = McpError.fromError(response.error.code, response.error.message, response.error.data);\n handler(error);\n }\n }\n get transport() {\n return this._transport;\n }\n /**\n * Closes the connection.\n */\n async close() {\n await this._transport?.close();\n }\n /**\n * Sends a request and returns an AsyncGenerator that yields response messages.\n * The generator is guaranteed to end with either a 'result' or 'error' message.\n *\n * @example\n * ```typescript\n * const stream = protocol.requestStream(request, resultSchema, options);\n * for await (const message of stream) {\n * switch (message.type) {\n * case 'taskCreated':\n * console.log('Task created:', message.task.taskId);\n * break;\n * case 'taskStatus':\n * console.log('Task status:', message.task.status);\n * break;\n * case 'result':\n * console.log('Final result:', message.result);\n * break;\n * case 'error':\n * console.error('Error:', message.error);\n * break;\n * }\n * }\n * ```\n *\n * @experimental Use `client.experimental.tasks.requestStream()` to access this method.\n */\n async *requestStream(request, resultSchema, options) {\n const { task } = options ?? {};\n // For non-task requests, just yield the result\n if (!task) {\n try {\n const result = await this.request(request, resultSchema, options);\n yield { type: 'result', result };\n }\n catch (error) {\n yield {\n type: 'error',\n error: error instanceof McpError ? error : new McpError(ErrorCode.InternalError, String(error))\n };\n }\n return;\n }\n // For task-augmented requests, we need to poll for status\n // First, make the request to create the task\n let taskId;\n try {\n // Send the request and get the CreateTaskResult\n const createResult = await this.request(request, CreateTaskResultSchema, options);\n // Extract taskId from the result\n if (createResult.task) {\n taskId = createResult.task.taskId;\n yield { type: 'taskCreated', task: createResult.task };\n }\n else {\n throw new McpError(ErrorCode.InternalError, 'Task creation did not return a task');\n }\n // Poll for task completion\n while (true) {\n // Get current task status\n const task = await this.getTask({ taskId }, options);\n yield { type: 'taskStatus', task };\n // Check if task is terminal\n if (isTerminal(task.status)) {\n if (task.status === 'completed') {\n // Get the final result\n const result = await this.getTaskResult({ taskId }, resultSchema, options);\n yield { type: 'result', result };\n }\n else if (task.status === 'failed') {\n yield {\n type: 'error',\n error: new McpError(ErrorCode.InternalError, `Task ${taskId} failed`)\n };\n }\n else if (task.status === 'cancelled') {\n yield {\n type: 'error',\n error: new McpError(ErrorCode.InternalError, `Task ${taskId} was cancelled`)\n };\n }\n return;\n }\n // When input_required, call tasks/result to deliver queued messages\n // (elicitation, sampling) via SSE and block until terminal\n if (task.status === 'input_required') {\n const result = await this.getTaskResult({ taskId }, resultSchema, options);\n yield { type: 'result', result };\n return;\n }\n // Wait before polling again\n const pollInterval = task.pollInterval ?? this._options?.defaultTaskPollInterval ?? 1000;\n await new Promise(resolve => setTimeout(resolve, pollInterval));\n // Check if cancelled\n options?.signal?.throwIfAborted();\n }\n }\n catch (error) {\n yield {\n type: 'error',\n error: error instanceof McpError ? error : new McpError(ErrorCode.InternalError, String(error))\n };\n }\n }\n /**\n * Sends a request and waits for a response.\n *\n * Do not use this method to emit notifications! Use notification() instead.\n */\n request(request, resultSchema, options) {\n const { relatedRequestId, resumptionToken, onresumptiontoken, task, relatedTask } = options ?? {};\n // Send the request\n return new Promise((resolve, reject) => {\n const earlyReject = (error) => {\n reject(error);\n };\n if (!this._transport) {\n earlyReject(new Error('Not connected'));\n return;\n }\n if (this._options?.enforceStrictCapabilities === true) {\n try {\n this.assertCapabilityForMethod(request.method);\n // If task creation is requested, also check task capabilities\n if (task) {\n this.assertTaskCapability(request.method);\n }\n }\n catch (e) {\n earlyReject(e);\n return;\n }\n }\n options?.signal?.throwIfAborted();\n const messageId = this._requestMessageId++;\n const jsonrpcRequest = {\n ...request,\n jsonrpc: '2.0',\n id: messageId\n };\n if (options?.onprogress) {\n this._progressHandlers.set(messageId, options.onprogress);\n jsonrpcRequest.params = {\n ...request.params,\n _meta: {\n ...(request.params?._meta || {}),\n progressToken: messageId\n }\n };\n }\n // Augment with task creation parameters if provided\n if (task) {\n jsonrpcRequest.params = {\n ...jsonrpcRequest.params,\n task: task\n };\n }\n // Augment with related task metadata if relatedTask is provided\n if (relatedTask) {\n jsonrpcRequest.params = {\n ...jsonrpcRequest.params,\n _meta: {\n ...(jsonrpcRequest.params?._meta || {}),\n [RELATED_TASK_META_KEY]: relatedTask\n }\n };\n }\n const cancel = (reason) => {\n this._responseHandlers.delete(messageId);\n this._progressHandlers.delete(messageId);\n this._cleanupTimeout(messageId);\n this._transport\n ?.send({\n jsonrpc: '2.0',\n method: 'notifications/cancelled',\n params: {\n requestId: messageId,\n reason: String(reason)\n }\n }, { relatedRequestId, resumptionToken, onresumptiontoken })\n .catch(error => this._onerror(new Error(`Failed to send cancellation: ${error}`)));\n // Wrap the reason in an McpError if it isn't already\n const error = reason instanceof McpError ? reason : new McpError(ErrorCode.RequestTimeout, String(reason));\n reject(error);\n };\n this._responseHandlers.set(messageId, response => {\n if (options?.signal?.aborted) {\n return;\n }\n if (response instanceof Error) {\n return reject(response);\n }\n try {\n const parseResult = safeParse(resultSchema, response.result);\n if (!parseResult.success) {\n // Type guard: if success is false, error is guaranteed to exist\n reject(parseResult.error);\n }\n else {\n resolve(parseResult.data);\n }\n }\n catch (error) {\n reject(error);\n }\n });\n options?.signal?.addEventListener('abort', () => {\n cancel(options?.signal?.reason);\n });\n const timeout = options?.timeout ?? DEFAULT_REQUEST_TIMEOUT_MSEC;\n const timeoutHandler = () => cancel(McpError.fromError(ErrorCode.RequestTimeout, 'Request timed out', { timeout }));\n this._setupTimeout(messageId, timeout, options?.maxTotalTimeout, timeoutHandler, options?.resetTimeoutOnProgress ?? false);\n // Queue request if related to a task\n const relatedTaskId = relatedTask?.taskId;\n if (relatedTaskId) {\n // Store the response resolver for this request so responses can be routed back\n const responseResolver = (response) => {\n const handler = this._responseHandlers.get(messageId);\n if (handler) {\n handler(response);\n }\n else {\n // Log error when resolver is missing, but don't fail\n this._onerror(new Error(`Response handler missing for side-channeled request ${messageId}`));\n }\n };\n this._requestResolvers.set(messageId, responseResolver);\n this._enqueueTaskMessage(relatedTaskId, {\n type: 'request',\n message: jsonrpcRequest,\n timestamp: Date.now()\n }).catch(error => {\n this._cleanupTimeout(messageId);\n reject(error);\n });\n // Don't send through transport - queued messages are delivered via tasks/result only\n // This prevents duplicate delivery for bidirectional transports\n }\n else {\n // No related task - send through transport normally\n this._transport.send(jsonrpcRequest, { relatedRequestId, resumptionToken, onresumptiontoken }).catch(error => {\n this._cleanupTimeout(messageId);\n reject(error);\n });\n }\n });\n }\n /**\n * Gets the current status of a task.\n *\n * @experimental Use `client.experimental.tasks.getTask()` to access this method.\n */\n async getTask(params, options) {\n // @ts-expect-error SendRequestT cannot directly contain GetTaskRequest, but we ensure all type instantiations contain it anyways\n return this.request({ method: 'tasks/get', params }, GetTaskResultSchema, options);\n }\n /**\n * Retrieves the result of a completed task.\n *\n * @experimental Use `client.experimental.tasks.getTaskResult()` to access this method.\n */\n async getTaskResult(params, resultSchema, options) {\n // @ts-expect-error SendRequestT cannot directly contain GetTaskPayloadRequest, but we ensure all type instantiations contain it anyways\n return this.request({ method: 'tasks/result', params }, resultSchema, options);\n }\n /**\n * Lists tasks, optionally starting from a pagination cursor.\n *\n * @experimental Use `client.experimental.tasks.listTasks()` to access this method.\n */\n async listTasks(params, options) {\n // @ts-expect-error SendRequestT cannot directly contain ListTasksRequest, but we ensure all type instantiations contain it anyways\n return this.request({ method: 'tasks/list', params }, ListTasksResultSchema, options);\n }\n /**\n * Cancels a specific task.\n *\n * @experimental Use `client.experimental.tasks.cancelTask()` to access this method.\n */\n async cancelTask(params, options) {\n // @ts-expect-error SendRequestT cannot directly contain CancelTaskRequest, but we ensure all type instantiations contain it anyways\n return this.request({ method: 'tasks/cancel', params }, CancelTaskResultSchema, options);\n }\n /**\n * Emits a notification, which is a one-way message that does not expect a response.\n */\n async notification(notification, options) {\n if (!this._transport) {\n throw new Error('Not connected');\n }\n this.assertNotificationCapability(notification.method);\n // Queue notification if related to a task\n const relatedTaskId = options?.relatedTask?.taskId;\n if (relatedTaskId) {\n // Build the JSONRPC notification with metadata\n const jsonrpcNotification = {\n ...notification,\n jsonrpc: '2.0',\n params: {\n ...notification.params,\n _meta: {\n ...(notification.params?._meta || {}),\n [RELATED_TASK_META_KEY]: options.relatedTask\n }\n }\n };\n await this._enqueueTaskMessage(relatedTaskId, {\n type: 'notification',\n message: jsonrpcNotification,\n timestamp: Date.now()\n });\n // Don't send through transport - queued messages are delivered via tasks/result only\n // This prevents duplicate delivery for bidirectional transports\n return;\n }\n const debouncedMethods = this._options?.debouncedNotificationMethods ?? [];\n // A notification can only be debounced if it's in the list AND it's \"simple\"\n // (i.e., has no parameters and no related request ID or related task that could be lost).\n const canDebounce = debouncedMethods.includes(notification.method) && !notification.params && !options?.relatedRequestId && !options?.relatedTask;\n if (canDebounce) {\n // If a notification of this type is already scheduled, do nothing.\n if (this._pendingDebouncedNotifications.has(notification.method)) {\n return;\n }\n // Mark this notification type as pending.\n this._pendingDebouncedNotifications.add(notification.method);\n // Schedule the actual send to happen in the next microtask.\n // This allows all synchronous calls in the current event loop tick to be coalesced.\n Promise.resolve().then(() => {\n // Un-mark the notification so the next one can be scheduled.\n this._pendingDebouncedNotifications.delete(notification.method);\n // SAFETY CHECK: If the connection was closed while this was pending, abort.\n if (!this._transport) {\n return;\n }\n let jsonrpcNotification = {\n ...notification,\n jsonrpc: '2.0'\n };\n // Augment with related task metadata if relatedTask is provided\n if (options?.relatedTask) {\n jsonrpcNotification = {\n ...jsonrpcNotification,\n params: {\n ...jsonrpcNotification.params,\n _meta: {\n ...(jsonrpcNotification.params?._meta || {}),\n [RELATED_TASK_META_KEY]: options.relatedTask\n }\n }\n };\n }\n // Send the notification, but don't await it here to avoid blocking.\n // Handle potential errors with a .catch().\n this._transport?.send(jsonrpcNotification, options).catch(error => this._onerror(error));\n });\n // Return immediately.\n return;\n }\n let jsonrpcNotification = {\n ...notification,\n jsonrpc: '2.0'\n };\n // Augment with related task metadata if relatedTask is provided\n if (options?.relatedTask) {\n jsonrpcNotification = {\n ...jsonrpcNotification,\n params: {\n ...jsonrpcNotification.params,\n _meta: {\n ...(jsonrpcNotification.params?._meta || {}),\n [RELATED_TASK_META_KEY]: options.relatedTask\n }\n }\n };\n }\n await this._transport.send(jsonrpcNotification, options);\n }\n /**\n * Registers a handler to invoke when this protocol object receives a request with the given method.\n *\n * Note that this will replace any previous request handler for the same method.\n */\n setRequestHandler(requestSchema, handler) {\n const method = getMethodLiteral(requestSchema);\n this.assertRequestHandlerCapability(method);\n this._requestHandlers.set(method, (request, extra) => {\n const parsed = parseWithCompat(requestSchema, request);\n return Promise.resolve(handler(parsed, extra));\n });\n }\n /**\n * Removes the request handler for the given method.\n */\n removeRequestHandler(method) {\n this._requestHandlers.delete(method);\n }\n /**\n * Asserts that a request handler has not already been set for the given method, in preparation for a new one being automatically installed.\n */\n assertCanSetRequestHandler(method) {\n if (this._requestHandlers.has(method)) {\n throw new Error(`A request handler for ${method} already exists, which would be overridden`);\n }\n }\n /**\n * Registers a handler to invoke when this protocol object receives a notification with the given method.\n *\n * Note that this will replace any previous notification handler for the same method.\n */\n setNotificationHandler(notificationSchema, handler) {\n const method = getMethodLiteral(notificationSchema);\n this._notificationHandlers.set(method, notification => {\n const parsed = parseWithCompat(notificationSchema, notification);\n return Promise.resolve(handler(parsed));\n });\n }\n /**\n * Removes the notification handler for the given method.\n */\n removeNotificationHandler(method) {\n this._notificationHandlers.delete(method);\n }\n /**\n * Cleans up the progress handler associated with a task.\n * This should be called when a task reaches a terminal status.\n */\n _cleanupTaskProgressHandler(taskId) {\n const progressToken = this._taskProgressTokens.get(taskId);\n if (progressToken !== undefined) {\n this._progressHandlers.delete(progressToken);\n this._taskProgressTokens.delete(taskId);\n }\n }\n /**\n * Enqueues a task-related message for side-channel delivery via tasks/result.\n * @param taskId The task ID to associate the message with\n * @param message The message to enqueue\n * @param sessionId Optional session ID for binding the operation to a specific session\n * @throws Error if taskStore is not configured or if enqueue fails (e.g., queue overflow)\n *\n * Note: If enqueue fails, it's the TaskMessageQueue implementation's responsibility to handle\n * the error appropriately (e.g., by failing the task, logging, etc.). The Protocol layer\n * simply propagates the error.\n */\n async _enqueueTaskMessage(taskId, message, sessionId) {\n // Task message queues are only used when taskStore is configured\n if (!this._taskStore || !this._taskMessageQueue) {\n throw new Error('Cannot enqueue task message: taskStore and taskMessageQueue are not configured');\n }\n const maxQueueSize = this._options?.maxTaskQueueSize;\n await this._taskMessageQueue.enqueue(taskId, message, sessionId, maxQueueSize);\n }\n /**\n * Clears the message queue for a task and rejects any pending request resolvers.\n * @param taskId The task ID whose queue should be cleared\n * @param sessionId Optional session ID for binding the operation to a specific session\n */\n async _clearTaskQueue(taskId, sessionId) {\n if (this._taskMessageQueue) {\n // Reject any pending request resolvers\n const messages = await this._taskMessageQueue.dequeueAll(taskId, sessionId);\n for (const message of messages) {\n if (message.type === 'request' && isJSONRPCRequest(message.message)) {\n // Extract request ID from the message\n const requestId = message.message.id;\n const resolver = this._requestResolvers.get(requestId);\n if (resolver) {\n resolver(new McpError(ErrorCode.InternalError, 'Task cancelled or completed'));\n this._requestResolvers.delete(requestId);\n }\n else {\n // Log error when resolver is missing during cleanup for better observability\n this._onerror(new Error(`Resolver missing for request ${requestId} during task ${taskId} cleanup`));\n }\n }\n }\n }\n }\n /**\n * Waits for a task update (new messages or status change) with abort signal support.\n * Uses polling to check for updates at the task's configured poll interval.\n * @param taskId The task ID to wait for\n * @param signal Abort signal to cancel the wait\n * @returns Promise that resolves when an update occurs or rejects if aborted\n */\n async _waitForTaskUpdate(taskId, signal) {\n // Get the task's poll interval, falling back to default\n let interval = this._options?.defaultTaskPollInterval ?? 1000;\n try {\n const task = await this._taskStore?.getTask(taskId);\n if (task?.pollInterval) {\n interval = task.pollInterval;\n }\n }\n catch {\n // Use default interval if task lookup fails\n }\n return new Promise((resolve, reject) => {\n if (signal.aborted) {\n reject(new McpError(ErrorCode.InvalidRequest, 'Request cancelled'));\n return;\n }\n // Wait for the poll interval, then resolve so caller can check for updates\n const timeoutId = setTimeout(resolve, interval);\n // Clean up timeout and reject if aborted\n signal.addEventListener('abort', () => {\n clearTimeout(timeoutId);\n reject(new McpError(ErrorCode.InvalidRequest, 'Request cancelled'));\n }, { once: true });\n });\n }\n requestTaskStore(request, sessionId) {\n const taskStore = this._taskStore;\n if (!taskStore) {\n throw new Error('No task store configured');\n }\n return {\n createTask: async (taskParams) => {\n if (!request) {\n throw new Error('No request provided');\n }\n return await taskStore.createTask(taskParams, request.id, {\n method: request.method,\n params: request.params\n }, sessionId);\n },\n getTask: async (taskId) => {\n const task = await taskStore.getTask(taskId, sessionId);\n if (!task) {\n throw new McpError(ErrorCode.InvalidParams, 'Failed to retrieve task: Task not found');\n }\n return task;\n },\n storeTaskResult: async (taskId, status, result) => {\n await taskStore.storeTaskResult(taskId, status, result, sessionId);\n // Get updated task state and send notification\n const task = await taskStore.getTask(taskId, sessionId);\n if (task) {\n const notification = TaskStatusNotificationSchema.parse({\n method: 'notifications/tasks/status',\n params: task\n });\n await this.notification(notification);\n if (isTerminal(task.status)) {\n this._cleanupTaskProgressHandler(taskId);\n // Don't clear queue here - it will be cleared after delivery via tasks/result\n }\n }\n },\n getTaskResult: taskId => {\n return taskStore.getTaskResult(taskId, sessionId);\n },\n updateTaskStatus: async (taskId, status, statusMessage) => {\n // Check if task exists\n const task = await taskStore.getTask(taskId, sessionId);\n if (!task) {\n throw new McpError(ErrorCode.InvalidParams, `Task \"${taskId}\" not found - it may have been cleaned up`);\n }\n // Don't allow transitions from terminal states\n if (isTerminal(task.status)) {\n throw new McpError(ErrorCode.InvalidParams, `Cannot update task \"${taskId}\" from terminal status \"${task.status}\" to \"${status}\". Terminal states (completed, failed, cancelled) cannot transition to other states.`);\n }\n await taskStore.updateTaskStatus(taskId, status, statusMessage, sessionId);\n // Get updated task state and send notification\n const updatedTask = await taskStore.getTask(taskId, sessionId);\n if (updatedTask) {\n const notification = TaskStatusNotificationSchema.parse({\n method: 'notifications/tasks/status',\n params: updatedTask\n });\n await this.notification(notification);\n if (isTerminal(updatedTask.status)) {\n this._cleanupTaskProgressHandler(taskId);\n // Don't clear queue here - it will be cleared after delivery via tasks/result\n }\n }\n },\n listTasks: cursor => {\n return taskStore.listTasks(cursor, sessionId);\n }\n };\n }\n}\nfunction isPlainObject(value) {\n return value !== null && typeof value === 'object' && !Array.isArray(value);\n}\nexport function mergeCapabilities(base, additional) {\n const result = { ...base };\n for (const key in additional) {\n const k = key;\n const addValue = additional[k];\n if (addValue === undefined)\n continue;\n const baseValue = result[k];\n if (isPlainObject(baseValue) && isPlainObject(addValue)) {\n result[k] = { ...baseValue, ...addValue };\n }\n else {\n result[k] = addValue;\n }\n }\n return result;\n}\n//# sourceMappingURL=protocol.js.map","var ZQ=((X)=>typeof require<\"u\"?require:typeof Proxy<\"u\"?new Proxy(X,{get:(Y,Z)=>(typeof require<\"u\"?require:Y)[Z]}):X)(function(X){if(typeof require<\"u\")return require.apply(this,arguments);throw Error('Dynamic require of \"'+X+'\" is not supported')});import{CallToolRequestSchema as iQ,CallToolResultSchema as XQ,CreateMessageRequestSchema as nQ,ListPromptsRequestSchema as cQ,ListPromptsResultSchema as lQ,ListResourcesRequestSchema as rQ,ListResourcesResultSchema as oQ,ListResourceTemplatesRequestSchema as sQ,ListResourceTemplatesResultSchema as tQ,ListToolsResultSchema as aQ,LoggingMessageNotificationSchema as eQ,PingRequestSchema as QX,PromptListChangedNotificationSchema as XX,ReadResourceRequestSchema as YX,ReadResourceResultSchema as ZX,ResourceListChangedNotificationSchema as $X,ToolListChangedNotificationSchema as JX}from\"@modelcontextprotocol/sdk/types.js\";import{Protocol as $Q}from\"@modelcontextprotocol/sdk/shared/protocol.js\";class _ extends $Q{_registeredMethods=new Set;_eventSlots=new Map;onEventDispatch(X,Y){}_ensureEventSlot(X){let Y=this._eventSlots.get(X);if(!Y){let Z=this.eventSchemas[X];if(!Z)throw Error(`Unknown event: ${String(X)}`);Y={listeners:[]},this._eventSlots.set(X,Y);let $=Z.shape.method.value;this._registeredMethods.add($);let J=Y;super.setNotificationHandler(Z,(K)=>{let D=K.params;this.onEventDispatch(X,D),J.onHandler?.(D);for(let G of[...J.listeners])G(D)})}return Y}setEventHandler(X,Y){let Z=this._ensureEventSlot(X);if(Z.onHandler&&Y)console.warn(`[MCP Apps] on${String(X)} handler replaced. Use addEventListener(\"${String(X)}\", …) to add multiple listeners without replacing.`);Z.onHandler=Y}getEventHandler(X){return this._eventSlots.get(X)?.onHandler}addEventListener(X,Y){this._ensureEventSlot(X).listeners.push(Y)}removeEventListener(X,Y){let Z=this._eventSlots.get(X);if(!Z)return;let $=Z.listeners.indexOf(Y);if($!==-1)Z.listeners.splice($,1)}setRequestHandler=(X,Y)=>{this._assertMethodNotRegistered(X,\"setRequestHandler\"),super.setRequestHandler(X,Y)};setNotificationHandler=(X,Y)=>{this._assertMethodNotRegistered(X,\"setNotificationHandler\"),super.setNotificationHandler(X,Y)};warnIfRequestHandlerReplaced(X,Y,Z){if(Y&&Z)console.warn(`[MCP Apps] ${X} handler replaced. Previous handler will no longer be called.`)}replaceRequestHandler=(X,Y)=>{let Z=X.shape.method.value;this._registeredMethods.add(Z),super.setRequestHandler(X,Y)};_assertMethodNotRegistered(X,Y){let Z=X.shape.method.value;if(this._registeredMethods.has(Z))throw Error(`Handler for \"${Z}\" already registered (via ${Y}). Use addEventListener() to attach multiple listeners, or the on* setter for replace semantics.`);this._registeredMethods.add(Z)}}var j=\"2026-01-26\",JQ=\"ui/open-link\",KQ=\"ui/download-file\",DQ=\"ui/message\",GQ=\"ui/notifications/sandbox-proxy-ready\",NQ=\"ui/notifications/sandbox-resource-ready\",WQ=\"ui/notifications/size-changed\",jQ=\"ui/notifications/tool-input\",V=\"ui/notifications/tool-input-partial\",BQ=\"ui/notifications/tool-result\",_Q=\"ui/notifications/tool-cancelled\",EQ=\"ui/notifications/host-context-changed\",OQ=\"ui/notifications/request-teardown\",zQ=\"ui/resource-teardown\",IQ=\"ui/initialize\",VQ=\"ui/notifications/initialized\",FQ=\"ui/request-display-mode\";import{z as Q}from\"zod/v4\";import{ContentBlockSchema as c,CallToolResultSchema as LQ,EmbeddedResourceSchema as PQ,ImplementationSchema as l,RequestIdSchema as AQ,ResourceLinkSchema as UQ,ToolSchema as wQ}from\"@modelcontextprotocol/sdk/types.js\";var r=Q.union([Q.literal(\"light\"),Q.literal(\"dark\")]).describe(\"Color theme preference for the host environment.\"),B=Q.union([Q.literal(\"inline\"),Q.literal(\"fullscreen\"),Q.literal(\"pip\")]).describe(\"Display mode for UI presentation.\"),HQ=Q.union([Q.literal(\"--color-background-primary\"),Q.literal(\"--color-background-secondary\"),Q.literal(\"--color-background-tertiary\"),Q.literal(\"--color-background-inverse\"),Q.literal(\"--color-background-ghost\"),Q.literal(\"--color-background-info\"),Q.literal(\"--color-background-danger\"),Q.literal(\"--color-background-success\"),Q.literal(\"--color-background-warning\"),Q.literal(\"--color-background-disabled\"),Q.literal(\"--color-text-primary\"),Q.literal(\"--color-text-secondary\"),Q.literal(\"--color-text-tertiary\"),Q.literal(\"--color-text-inverse\"),Q.literal(\"--color-text-ghost\"),Q.literal(\"--color-text-info\"),Q.literal(\"--color-text-danger\"),Q.literal(\"--color-text-success\"),Q.literal(\"--color-text-warning\"),Q.literal(\"--color-text-disabled\"),Q.literal(\"--color-border-primary\"),Q.literal(\"--color-border-secondary\"),Q.literal(\"--color-border-tertiary\"),Q.literal(\"--color-border-inverse\"),Q.literal(\"--color-border-ghost\"),Q.literal(\"--color-border-info\"),Q.literal(\"--color-border-danger\"),Q.literal(\"--color-border-success\"),Q.literal(\"--color-border-warning\"),Q.literal(\"--color-border-disabled\"),Q.literal(\"--color-ring-primary\"),Q.literal(\"--color-ring-secondary\"),Q.literal(\"--color-ring-inverse\"),Q.literal(\"--color-ring-info\"),Q.literal(\"--color-ring-danger\"),Q.literal(\"--color-ring-success\"),Q.literal(\"--color-ring-warning\"),Q.literal(\"--font-sans\"),Q.literal(\"--font-mono\"),Q.literal(\"--font-weight-normal\"),Q.literal(\"--font-weight-medium\"),Q.literal(\"--font-weight-semibold\"),Q.literal(\"--font-weight-bold\"),Q.literal(\"--font-text-xs-size\"),Q.literal(\"--font-text-sm-size\"),Q.literal(\"--font-text-md-size\"),Q.literal(\"--font-text-lg-size\"),Q.literal(\"--font-heading-xs-size\"),Q.literal(\"--font-heading-sm-size\"),Q.literal(\"--font-heading-md-size\"),Q.literal(\"--font-heading-lg-size\"),Q.literal(\"--font-heading-xl-size\"),Q.literal(\"--font-heading-2xl-size\"),Q.literal(\"--font-heading-3xl-size\"),Q.literal(\"--font-text-xs-line-height\"),Q.literal(\"--font-text-sm-line-height\"),Q.literal(\"--font-text-md-line-height\"),Q.literal(\"--font-text-lg-line-height\"),Q.literal(\"--font-heading-xs-line-height\"),Q.literal(\"--font-heading-sm-line-height\"),Q.literal(\"--font-heading-md-line-height\"),Q.literal(\"--font-heading-lg-line-height\"),Q.literal(\"--font-heading-xl-line-height\"),Q.literal(\"--font-heading-2xl-line-height\"),Q.literal(\"--font-heading-3xl-line-height\"),Q.literal(\"--border-radius-xs\"),Q.literal(\"--border-radius-sm\"),Q.literal(\"--border-radius-md\"),Q.literal(\"--border-radius-lg\"),Q.literal(\"--border-radius-xl\"),Q.literal(\"--border-radius-full\"),Q.literal(\"--border-width-regular\"),Q.literal(\"--shadow-hairline\"),Q.literal(\"--shadow-sm\"),Q.literal(\"--shadow-md\"),Q.literal(\"--shadow-lg\")]).describe(\"CSS variable keys available to MCP apps for theming.\"),RQ=Q.record(HQ.describe(`Style variables for theming MCP apps.\n\nIndividual style keys are optional - hosts may provide any subset of these values.\nValues are strings containing CSS values (colors, sizes, font stacks, etc.).\n\nNote: This type uses \\`Record<K, string | undefined>\\` rather than \\`Partial<Record<K, string>>\\`\nfor compatibility with Zod schema generation. Both are functionally equivalent for validation.`),Q.union([Q.string(),Q.undefined()]).describe(`Style variables for theming MCP apps.\n\nIndividual style keys are optional - hosts may provide any subset of these values.\nValues are strings containing CSS values (colors, sizes, font stacks, etc.).\n\nNote: This type uses \\`Record<K, string | undefined>\\` rather than \\`Partial<Record<K, string>>\\`\nfor compatibility with Zod schema generation. Both are functionally equivalent for validation.`)).describe(`Style variables for theming MCP apps.\n\nIndividual style keys are optional - hosts may provide any subset of these values.\nValues are strings containing CSS values (colors, sizes, font stacks, etc.).\n\nNote: This type uses \\`Record<K, string | undefined>\\` rather than \\`Partial<Record<K, string>>\\`\nfor compatibility with Zod schema generation. Both are functionally equivalent for validation.`),L=Q.object({method:Q.literal(\"ui/open-link\"),params:Q.object({url:Q.string().describe(\"URL to open in the host's browser\")})}),P=Q.object({isError:Q.boolean().optional().describe(\"True if the host failed to open the URL (e.g., due to security policy).\")}).passthrough(),A=Q.object({isError:Q.boolean().optional().describe(\"True if the download failed (e.g., user cancelled or host denied).\")}).passthrough(),U=Q.object({isError:Q.boolean().optional().describe(\"True if the host rejected or failed to deliver the message.\")}).passthrough(),w=Q.object({method:Q.literal(\"ui/notifications/sandbox-proxy-ready\"),params:Q.object({})}),O=Q.object({connectDomains:Q.array(Q.string()).optional().describe(`Origins for network requests (fetch/XHR/WebSocket).\n\n- Maps to CSP \\`connect-src\\` directive\n- Empty or omitted → no network connections (secure default)`),resourceDomains:Q.array(Q.string()).optional().describe(\"Origins for static resources (images, scripts, stylesheets, fonts, media).\\n\\n- Maps to CSP `img-src`, `script-src`, `style-src`, `font-src`, `media-src` directives\\n- Wildcard subdomains supported: `https://*.example.com`\\n- Empty or omitted → no network resources (secure default)\"),frameDomains:Q.array(Q.string()).optional().describe(\"Origins for nested iframes.\\n\\n- Maps to CSP `frame-src` directive\\n- Empty or omitted → no nested iframes allowed (`frame-src 'none'`)\"),baseUriDomains:Q.array(Q.string()).optional().describe(\"Allowed base URIs for the document.\\n\\n- Maps to CSP `base-uri` directive\\n- Empty or omitted → only same origin allowed (`base-uri 'self'`)\")}),z=Q.object({camera:Q.object({}).optional().describe(\"Request camera access.\\n\\nMaps to Permission Policy `camera` feature.\"),microphone:Q.object({}).optional().describe(\"Request microphone access.\\n\\nMaps to Permission Policy `microphone` feature.\"),geolocation:Q.object({}).optional().describe(\"Request geolocation access.\\n\\nMaps to Permission Policy `geolocation` feature.\"),clipboardWrite:Q.object({}).optional().describe(\"Request clipboard write access.\\n\\nMaps to Permission Policy `clipboard-write` feature.\")}),H=Q.object({method:Q.literal(\"ui/notifications/size-changed\"),params:Q.object({width:Q.number().optional().describe(\"New width in pixels.\"),height:Q.number().optional().describe(\"New height in pixels.\")})}),R=Q.object({method:Q.literal(\"ui/notifications/tool-input\"),params:Q.object({arguments:Q.record(Q.string(),Q.unknown().describe(\"Complete tool call arguments as key-value pairs.\")).optional().describe(\"Complete tool call arguments as key-value pairs.\")})}),T=Q.object({method:Q.literal(\"ui/notifications/tool-input-partial\"),params:Q.object({arguments:Q.record(Q.string(),Q.unknown().describe(\"Partial tool call arguments (incomplete, may change).\")).optional().describe(\"Partial tool call arguments (incomplete, may change).\")})}),M=Q.object({method:Q.literal(\"ui/notifications/tool-cancelled\"),params:Q.object({reason:Q.string().optional().describe('Optional reason for the cancellation (e.g., \"user action\", \"timeout\").')})}),o=Q.object({fonts:Q.string().optional()}),s=Q.object({variables:RQ.optional().describe(\"CSS variables for theming the app.\"),css:o.optional().describe(\"CSS blocks that apps can inject.\")}),C=Q.object({method:Q.literal(\"ui/resource-teardown\"),params:Q.object({})}),S=Q.record(Q.string(),Q.unknown()),F=Q.object({text:Q.object({}).optional().describe(\"Host supports text content blocks.\"),image:Q.object({}).optional().describe(\"Host supports image content blocks.\"),audio:Q.object({}).optional().describe(\"Host supports audio content blocks.\"),resource:Q.object({}).optional().describe(\"Host supports resource content blocks.\"),resourceLink:Q.object({}).optional().describe(\"Host supports resource link content blocks.\"),structuredContent:Q.object({}).optional().describe(\"Host supports structured content.\")}),q=Q.object({method:Q.literal(\"ui/notifications/request-teardown\"),params:Q.object({}).optional()}),t=Q.object({experimental:Q.object({}).optional().describe(\"Experimental features (structure TBD).\"),openLinks:Q.object({}).optional().describe(\"Host supports opening external URLs.\"),downloadFile:Q.object({}).optional().describe(\"Host supports file downloads via ui/download-file.\"),serverTools:Q.object({listChanged:Q.boolean().optional().describe(\"Host supports tools/list_changed notifications.\")}).optional().describe(\"Host can proxy tool calls to the MCP server.\"),serverResources:Q.object({listChanged:Q.boolean().optional().describe(\"Host supports resources/list_changed notifications.\")}).optional().describe(\"Host can proxy resource reads to the MCP server.\"),logging:Q.object({}).optional().describe(\"Host accepts log messages.\"),sandbox:Q.object({permissions:z.optional().describe(\"Permissions granted by the host (camera, microphone, geolocation).\"),csp:O.optional().describe(\"CSP domains approved by the host.\")}).optional().describe(\"Sandbox configuration applied by the host.\"),updateModelContext:F.optional().describe(\"Host accepts context updates (ui/update-model-context) to be included in the model's context for future turns.\"),message:F.optional().describe(\"Host supports receiving content messages (ui/message) from the view.\"),sampling:Q.object({tools:Q.object({}).optional().describe(\"Host supports tool use via `tools` and `toolChoice` parameters.\")}).optional().describe(\"Host supports LLM sampling (sampling/createMessage) from the view.\\nMirrors the MCP `ClientCapabilities.sampling` shape so hosts can pass it through.\")}),a=Q.object({experimental:Q.object({}).optional().describe(\"Experimental features (structure TBD).\"),tools:Q.object({listChanged:Q.boolean().optional().describe(\"App supports tools/list_changed notifications.\")}).optional().describe(\"App exposes MCP-style tools that the host can call.\"),availableDisplayModes:Q.array(B).optional().describe(\"Display modes the app supports.\")}),y=Q.object({method:Q.literal(\"ui/notifications/initialized\"),params:Q.object({}).optional()}),TQ=Q.object({csp:O.optional().describe(\"Content Security Policy configuration for UI resources.\"),permissions:z.optional().describe(\"Sandbox permissions requested by the UI resource.\"),domain:Q.string().optional().describe(`Dedicated origin for view sandbox.\n\nUseful when views need stable, dedicated origins for OAuth callbacks, CORS policies, or API key allowlists.\n\n**Host-dependent:** The format and validation rules for this field are determined by each host. Servers MUST consult host-specific documentation for the expected domain format. Common patterns include:\n- Hash-based subdomains (e.g., \\`{hash}.claudemcpcontent.com\\`)\n- URL-derived subdomains (e.g., \\`www-example-com.oaiusercontent.com\\`)\n\nIf omitted, host uses default sandbox origin (typically per-conversation).`),prefersBorder:Q.boolean().optional().describe(`Visual boundary preference - true if view prefers a visible border.\n\nBoolean requesting whether a visible border and background is provided by the host. Specifying an explicit value for this is recommended because hosts' defaults may vary.\n\n- \\`true\\`: request visible border + background\n- \\`false\\`: request no visible border + background\n- omitted: host decides border`)}),I=Q.object({method:Q.literal(\"ui/request-display-mode\"),params:Q.object({mode:B.describe(\"The display mode being requested.\")})}),g=Q.object({mode:B.describe(\"The display mode that was actually set. May differ from requested if not supported.\")}).passthrough(),e=Q.union([Q.literal(\"model\"),Q.literal(\"app\")]).describe(\"Tool visibility scope - who can access the tool.\"),MQ=Q.object({resourceUri:Q.string().optional(),visibility:Q.array(e).optional().describe(`Who can access this tool. Default: [\"model\", \"app\"]\n- \"model\": Tool visible to and callable by the agent\n- \"app\": Tool callable by the app from this server only`),csp:Q.never().optional(),permissions:Q.never().optional()}),OX=Q.object({mimeTypes:Q.array(Q.string()).optional().describe('Array of supported MIME types for UI resources.\\nMust include `\"text/html;profile=mcp-app\"` for MCP Apps support.')}),f=Q.object({method:Q.literal(\"ui/download-file\"),params:Q.object({contents:Q.array(Q.union([PQ,UQ])).describe(\"Resource contents to download — embedded (inline data) or linked (host fetches). Uses standard MCP resource types.\")})}),k=Q.object({method:Q.literal(\"ui/message\"),params:Q.object({role:Q.literal(\"user\").describe('Message role, currently only \"user\" is supported.'),content:Q.array(c).describe(\"Message content blocks (text, image, etc.).\")})}),CQ=Q.object({method:Q.literal(\"ui/notifications/sandbox-resource-ready\"),params:Q.object({html:Q.string().describe(\"HTML content to load into the inner iframe.\"),sandbox:Q.string().optional().describe(\"Optional override for the inner iframe's sandbox attribute.\"),csp:O.optional().describe(\"CSP configuration from resource metadata.\"),permissions:z.optional().describe(\"Sandbox permissions from resource metadata.\")})}),v=Q.object({method:Q.literal(\"ui/notifications/tool-result\"),params:LQ.describe(\"Standard MCP tool execution result.\")}),x=Q.object({toolInfo:Q.object({id:AQ.optional().describe(\"JSON-RPC id of the tools/call request.\"),tool:wQ.describe(\"Tool definition including name, inputSchema, etc.\")}).optional().describe(\"Metadata of the tool call that instantiated this App.\"),theme:r.optional().describe(\"Current color theme preference.\"),styles:s.optional().describe(\"Style configuration for theming the app.\"),displayMode:B.optional().describe(\"How the UI is currently displayed.\"),availableDisplayModes:Q.array(B).optional().describe(\"Display modes the host supports.\"),containerDimensions:Q.union([Q.object({height:Q.number().describe(\"Fixed container height in pixels.\")}),Q.object({maxHeight:Q.union([Q.number(),Q.undefined()]).optional().describe(\"Maximum container height in pixels.\")})]).and(Q.union([Q.object({width:Q.number().describe(\"Fixed container width in pixels.\")}),Q.object({maxWidth:Q.union([Q.number(),Q.undefined()]).optional().describe(\"Maximum container width in pixels.\")})])).optional().describe(`Container dimensions. Represents the dimensions of the iframe or other\ncontainer holding the app. Specify either width or maxWidth, and either height or maxHeight.`),locale:Q.string().optional().describe(\"User's language and region preference in BCP 47 format.\"),timeZone:Q.string().optional().describe(\"User's timezone in IANA format.\"),userAgent:Q.string().optional().describe(\"Host application identifier.\"),platform:Q.union([Q.literal(\"web\"),Q.literal(\"desktop\"),Q.literal(\"mobile\")]).optional().describe(\"Platform type for responsive design decisions.\"),deviceCapabilities:Q.object({touch:Q.boolean().optional().describe(\"Whether the device supports touch input.\"),hover:Q.boolean().optional().describe(\"Whether the device supports hover interactions.\")}).optional().describe(\"Device input capabilities.\"),safeAreaInsets:Q.object({top:Q.number().describe(\"Top safe area inset in pixels.\"),right:Q.number().describe(\"Right safe area inset in pixels.\"),bottom:Q.number().describe(\"Bottom safe area inset in pixels.\"),left:Q.number().describe(\"Left safe area inset in pixels.\")}).optional().describe(\"Mobile safe area boundaries in pixels.\")}).passthrough(),b=Q.object({method:Q.literal(\"ui/notifications/host-context-changed\"),params:x.describe(\"Partial context update containing only changed fields.\")}),d=Q.object({method:Q.literal(\"ui/update-model-context\"),params:Q.object({content:Q.array(c).optional().describe(\"Context content blocks (text, image, etc.).\"),structuredContent:Q.record(Q.string(),Q.unknown().describe(\"Structured content for machine-readable context data.\")).optional().describe(\"Structured content for machine-readable context data.\")})}),u=Q.object({method:Q.literal(\"ui/initialize\"),params:Q.object({appInfo:l.describe(\"App identification (name and version).\"),appCapabilities:a.describe(\"Features and capabilities this app provides.\"),protocolVersion:Q.string().describe(\"Protocol version this app supports.\")})}),h=Q.object({protocolVersion:Q.string().describe('Negotiated protocol version string (e.g., \"2025-11-21\").'),hostInfo:l.describe(\"Host application identification and version.\"),hostCapabilities:t.describe(\"Features and capabilities provided by the host.\"),hostContext:x.describe(\"Rich context about the host environment.\")}).passthrough();import{mergeCapabilities as yQ}from\"@modelcontextprotocol/sdk/shared/protocol.js\";import{CallToolRequestSchema as gQ,CallToolResultSchema as fQ,CreateMessageResultSchema as kQ,CreateMessageResultWithToolsSchema as vQ,EmptyResultSchema as xQ,ListResourcesResultSchema as bQ,ListToolsRequestSchema as dQ,PingRequestSchema as uQ,ReadResourceResultSchema as hQ}from\"@modelcontextprotocol/sdk/types.js\";import{JSONRPCMessageSchema as SQ}from\"@modelcontextprotocol/sdk/types.js\";class E{eventTarget;eventSource;messageListener;constructor(X=window.parent,Y){this.eventTarget=X;this.eventSource=Y;this.messageListener=(Z)=>{if(Y&&Z.source!==this.eventSource){console.debug(\"Ignoring message from unknown source\",Z);return}let $=SQ.safeParse(Z.data);if($.success)console.debug(\"Parsed message\",$.data),this.onmessage?.($.data);else if(Z.data?.jsonrpc!==\"2.0\")console.debug(\"Ignoring non-JSON-RPC message\",$.error.message,Z);else console.error(\"Failed to parse message\",$.error.message,Z),this.onerror?.(Error(\"Invalid JSON-RPC message received: \"+$.error.message))}}async start(){window.addEventListener(\"message\",this.messageListener)}async send(X,Y){if(X.method!==V)console.debug(\"Sending message\",X);this.eventTarget.postMessage(X,\"*\")}async close(){window.removeEventListener(\"message\",this.messageListener),this.onclose?.()}onclose;onerror;onmessage;sessionId;setProtocolVersion}var qQ={target:\"draft-2020-12\"};async function m(X,Y){let Z=X[\"~standard\"];if(Z.jsonSchema)return Z.jsonSchema[Y](qQ);if(Z.vendor===\"zod\"){let{z:$}=await import(\"zod/v4\");return $.toJSONSchema(X,{io:Y})}throw Error(`Schema (vendor: ${Z.vendor}) does not implement Standard JSON Schema (~standard.jsonSchema). Use a library that does (zod v4, ArkType, Valibot) or wrap your schema accordingly.`)}async function p(X,Y,Z=\"\"){let $=await X[\"~standard\"].validate(Y);if($.issues){let J=$.issues.map((K)=>{let D=K.path?.map((G)=>typeof G===\"object\"?G.key:G).join(\".\");return D?`${D}: ${K.message}`:K.message}).join(\"; \");throw Error(Z+J)}return $.value}import{z as mQ}from\"zod/v4\";var i=\"ui/resourceUri\",pQ=\"text/html;profile=mcp-app\";class QQ extends _{_appInfo;_capabilities;options;_hostCapabilities;_hostInfo;_hostContext;_registeredTools={};_initializedSent=!1;_assertInitialized(X){if(this._initializedSent)return;let Y=`[ext-apps] App.${X}() called before connect() completed the ui/initialize handshake. Await app.connect() before calling this method, or move data loading to an ontoolresult handler.`;if(this.options?.strict)throw Error(Y);console.warn(`${Y}. This will throw in a future release.`)}eventSchemas={toolinput:R,toolinputpartial:T,toolresult:v,toolcancelled:M,hostcontextchanged:b};static ONE_SHOT_EVENTS=new Set([\"toolinput\",\"toolinputpartial\",\"toolresult\",\"toolcancelled\"]);_everHadListener=new Set;_assertHandlerTiming(X){if(!QQ.ONE_SHOT_EVENTS.has(X)||this._everHadListener.has(X))return;if(this._everHadListener.add(X),!this._initializedSent)return;let Y=`[ext-apps] \"${String(X)}\" handler registered after connect() completed the ui/initialize handshake. The host may have already sent this notification. Register handlers before calling app.connect().`;if(this.options?.strict)throw Error(Y);console.warn(Y)}setEventHandler(X,Y){if(Y)this._assertHandlerTiming(X);super.setEventHandler(X,Y)}addEventListener(X,Y){this._assertHandlerTiming(X),super.addEventListener(X,Y)}onEventDispatch(X,Y){if(X===\"hostcontextchanged\")this._hostContext={...this._hostContext,...Y}}constructor(X,Y={},Z={autoResize:!0}){super(Z);this._appInfo=X;this._capabilities=Y;this.options=Z;if(!Z.allowUnsafeEval)mQ.config({jitless:!0});this.setRequestHandler(uQ,($)=>{return console.log(\"Received ping:\",$.params),{}}),this.setEventHandler(\"hostcontextchanged\",void 0)}registerCapabilities(X){if(this.transport)throw Error(\"Cannot register capabilities after transport is established\");this._capabilities=yQ(this._capabilities,X)}registerTool(X,Y,Z){if(this._registeredTools[X])throw Error(`Tool ${X} is already registered`);let $=this,J=()=>{if($._initializedSent&&$._capabilities.tools?.listChanged)$.sendToolListChanged()},K=Y.inputSchema!==void 0,D={title:Y.title,description:Y.description,inputSchema:Y.inputSchema,outputSchema:Y.outputSchema,annotations:Y.annotations,_meta:Y._meta,enabled:!0,enable(){this.enabled=!0,J()},disable(){this.enabled=!1,J()},update(G){Object.assign(this,G),J()},remove(){if($._registeredTools[X]!==D)return;delete $._registeredTools[X],J()},handler:async(G,N)=>{if(!D.enabled)throw Error(`Tool ${X} is disabled`);let W;if(K){let n=D.inputSchema,YQ=n?await p(n,G??{},`Invalid input for tool ${X}: `):G??{};W=await Z(YQ,N)}else W=await Z(N);if(D.outputSchema&&!W.isError)W.structuredContent=await p(D.outputSchema,W.structuredContent,`Invalid output for tool ${X}: `);return W}};if(this._registeredTools[X]=D,!this._capabilities.tools&&!this.transport)this.registerCapabilities({tools:{listChanged:!0}});return this.ensureToolHandlersInitialized(),J(),D}_toolHandlersInitialized=!1;ensureToolHandlersInitialized(){if(this._toolHandlersInitialized)return;this._toolHandlersInitialized=!0,this.oncalltool=async(X,Y)=>{let Z=this._registeredTools[X.name];if(!Z)throw Error(`Tool ${X.name} not found`);return Z.handler(X.arguments,Y)},this.onlisttools=async(X,Y)=>{return{tools:await Promise.all(Object.entries(this._registeredTools).filter(([$,J])=>J.enabled).map(async([$,J])=>{let K={name:$,title:J.title,description:J.description,inputSchema:J.inputSchema?await m(J.inputSchema,\"input\"):{type:\"object\",properties:{}}};if(J.outputSchema)K.outputSchema=await m(J.outputSchema,\"output\");if(J.annotations)K.annotations=J.annotations;if(J._meta)K._meta=J._meta;return K}))}}}async sendToolListChanged(X={}){this._assertInitialized(\"sendToolListChanged\"),await this.notification({method:\"notifications/tools/list_changed\",params:X})}getHostCapabilities(){return this._hostCapabilities}getHostVersion(){return this._hostInfo}getHostContext(){return this._hostContext}get ontoolinput(){return this.getEventHandler(\"toolinput\")}set ontoolinput(X){this.setEventHandler(\"toolinput\",X)}get ontoolinputpartial(){return this.getEventHandler(\"toolinputpartial\")}set ontoolinputpartial(X){this.setEventHandler(\"toolinputpartial\",X)}get ontoolresult(){return this.getEventHandler(\"toolresult\")}set ontoolresult(X){this.setEventHandler(\"toolresult\",X)}get ontoolcancelled(){return this.getEventHandler(\"toolcancelled\")}set ontoolcancelled(X){this.setEventHandler(\"toolcancelled\",X)}get onhostcontextchanged(){return this.getEventHandler(\"hostcontextchanged\")}set onhostcontextchanged(X){this.setEventHandler(\"hostcontextchanged\",X)}_onteardown;get onteardown(){return this._onteardown}set onteardown(X){this.warnIfRequestHandlerReplaced(\"onteardown\",this._onteardown,X),this._onteardown=X,this.replaceRequestHandler(C,(Y,Z)=>{if(!this._onteardown)throw Error(\"No onteardown handler set\");return this._onteardown(Y.params,Z)})}_oncalltool;get oncalltool(){return this._oncalltool}set oncalltool(X){this.warnIfRequestHandlerReplaced(\"oncalltool\",this._oncalltool,X),this._oncalltool=X,this.replaceRequestHandler(gQ,(Y,Z)=>{if(!this._oncalltool)throw Error(\"No oncalltool handler set\");return this._oncalltool(Y.params,Z)})}_onlisttools;get onlisttools(){return this._onlisttools}set onlisttools(X){this.warnIfRequestHandlerReplaced(\"onlisttools\",this._onlisttools,X),this._onlisttools=X,this.replaceRequestHandler(dQ,(Y,Z)=>{if(!this._onlisttools)throw Error(\"No onlisttools handler set\");return this._onlisttools(Y.params,Z)})}assertCapabilityForMethod(X){switch(X){case\"sampling/createMessage\":if(!this._hostCapabilities?.sampling)throw Error(`Host does not support sampling (required for ${X})`);break}}assertRequestHandlerCapability(X){switch(X){case\"tools/call\":case\"tools/list\":if(!this._capabilities.tools)throw Error(`Client does not support tool capability (required for ${X})`);return;case\"ping\":case\"ui/resource-teardown\":return;default:throw Error(`No handler for method ${X} registered`)}}assertNotificationCapability(X){}assertTaskCapability(X){throw Error(\"Tasks are not supported in MCP Apps\")}assertTaskHandlerCapability(X){throw Error(\"Task handlers are not supported in MCP Apps\")}async callServerTool(X,Y){if(this._assertInitialized(\"callServerTool\"),typeof X===\"string\")throw Error(`callServerTool() expects an object as its first argument, but received a string (\"${X}\"). Did you mean: callServerTool({ name: \"${X}\", arguments: { ... } })?`);return await this.request({method:\"tools/call\",params:X},fQ,{onprogress:()=>{},resetTimeoutOnProgress:!0,...Y})}async readServerResource(X,Y){return this._assertInitialized(\"readServerResource\"),await this.request({method:\"resources/read\",params:X},hQ,Y)}async listServerResources(X,Y){return this._assertInitialized(\"listServerResources\"),await this.request({method:\"resources/list\",params:X},bQ,Y)}async createSamplingMessage(X,Y){this._assertInitialized(\"createSamplingMessage\");let Z=X.tools?vQ:kQ;return await this.request({method:\"sampling/createMessage\",params:X},Z,Y)}sendMessage(X,Y){return this._assertInitialized(\"sendMessage\"),this.request({method:\"ui/message\",params:X},U,Y)}sendLog(X){return this.notification({method:\"notifications/message\",params:X})}updateModelContext(X,Y){return this._assertInitialized(\"updateModelContext\"),this.request({method:\"ui/update-model-context\",params:X},xQ,Y)}openLink(X,Y){return this._assertInitialized(\"openLink\"),this.request({method:\"ui/open-link\",params:X},P,Y)}sendOpenLink=this.openLink;downloadFile(X,Y){return this._assertInitialized(\"downloadFile\"),this.request({method:\"ui/download-file\",params:X},A,Y)}requestTeardown(X={}){return this.notification({method:\"ui/notifications/request-teardown\",params:X})}requestDisplayMode(X,Y){return this._assertInitialized(\"requestDisplayMode\"),this.request({method:\"ui/request-display-mode\",params:X},g,Y)}sendSizeChanged(X){return this.notification({method:\"ui/notifications/size-changed\",params:X})}setupSizeChangedNotifications(){let X=!1,Y=0,Z=0,$=()=>{if(X)return;X=!0,requestAnimationFrame(()=>{X=!1;let K=document.documentElement,D=K.style.height;K.style.height=\"max-content\";let G=Math.ceil(K.getBoundingClientRect().height);K.style.height=D;let N=Math.ceil(window.innerWidth);if(N!==Y||G!==Z)Y=N,Z=G,this.sendSizeChanged({width:N,height:G})})};$();let J=new ResizeObserver($);return J.observe(document.documentElement),J.observe(document.body),()=>J.disconnect()}async connect(X=new E(window.parent,window.parent),Y){if(this.transport)throw Error(\"App is already connected. Call close() before connecting again.\");this._initializedSent=!1,await super.connect(X);try{let Z=await this.request({method:\"ui/initialize\",params:{appCapabilities:this._capabilities,appInfo:this._appInfo,protocolVersion:j}},h,Y);if(Z===void 0)throw Error(`Server sent invalid initialize result: ${Z}`);if(this._hostCapabilities=Z.hostCapabilities,this._hostInfo=Z.hostInfo,this._hostContext=Z.hostContext,await this.notification({method:\"ui/notifications/initialized\"}),this._initializedSent=!0,this.options?.autoResize)this.setupSizeChangedNotifications()}catch(Z){throw this.close(),Z}}}function FZ(X){let Z=X._meta?.ui?.resourceUri;if(Z===void 0)Z=X._meta?.[i];if(typeof Z===\"string\"&&Z.startsWith(\"ui://\"))return Z;else if(Z!==void 0)throw Error(`Invalid UI resource URI: ${JSON.stringify(Z)}`);return}function LZ(X){let Z=X._meta?.ui?.visibility;if(!Z)return!1;if(Z.length===1&&Z[0]===\"model\")return!0;return!1}function PZ(X){let Z=X._meta?.ui?.visibility;if(!Z)return!1;if(Z.length===1&&Z[0]===\"app\")return!0;return!1}function AZ(X){if(!X)return\"\";let Y=[];if(X.camera)Y.push(\"camera\");if(X.microphone)Y.push(\"microphone\");if(X.geolocation)Y.push(\"geolocation\");if(X.clipboardWrite)Y.push(\"clipboard-write\");return Y.join(\"; \")}var KX=[j];class DX extends _{_client;_hostInfo;_capabilities;_appCapabilities;_hostContext={};_appInfo;_initializedReceived=!1;_baseReplaceRequestHandler=this.replaceRequestHandler;replaceRequestHandler=(X,Y)=>{this._baseReplaceRequestHandler(X,(Z,$)=>{if(!this._initializedReceived)console.warn(`[ext-apps] AppBridge received '${Z.method}' before ui/notifications/initialized. The View is calling host methods before completing the handshake; it should await app.connect() first.`);return Y(Z,$)})};eventSchemas={sizechange:H,sandboxready:w,initialized:y,requestteardown:q,loggingmessage:eQ};constructor(X,Y,Z,$){super($);this._client=X;this._hostInfo=Y;this._capabilities=Z;this.addEventListener(\"initialized\",()=>{this._initializedReceived=!0}),this._hostContext=$?.hostContext||{},this.setRequestHandler(u,(J)=>this._oninitialize(J)),this.setRequestHandler(QX,(J,K)=>{return this.onping?.(J.params,K),{}}),this.replaceRequestHandler(I,(J)=>{return{mode:this._hostContext.displayMode??\"inline\"}})}getAppCapabilities(){return this._appCapabilities}getAppVersion(){return this._appInfo}onping;get onsizechange(){return this.getEventHandler(\"sizechange\")}set onsizechange(X){this.setEventHandler(\"sizechange\",X)}get onsandboxready(){return this.getEventHandler(\"sandboxready\")}set onsandboxready(X){this.setEventHandler(\"sandboxready\",X)}get oninitialized(){return this.getEventHandler(\"initialized\")}set oninitialized(X){this.setEventHandler(\"initialized\",X)}_onmessage;get onmessage(){return this._onmessage}set onmessage(X){this.warnIfRequestHandlerReplaced(\"onmessage\",this._onmessage,X),this._onmessage=X,this.replaceRequestHandler(k,async(Y,Z)=>{if(!this._onmessage)throw Error(\"No onmessage handler set\");return this._onmessage(Y.params,Z)})}_onopenlink;get onopenlink(){return this._onopenlink}set onopenlink(X){this.warnIfRequestHandlerReplaced(\"onopenlink\",this._onopenlink,X),this._onopenlink=X,this.replaceRequestHandler(L,async(Y,Z)=>{if(!this._onopenlink)throw Error(\"No onopenlink handler set\");return this._onopenlink(Y.params,Z)})}_ondownloadfile;get ondownloadfile(){return this._ondownloadfile}set ondownloadfile(X){this.warnIfRequestHandlerReplaced(\"ondownloadfile\",this._ondownloadfile,X),this._ondownloadfile=X,this.replaceRequestHandler(f,async(Y,Z)=>{if(!this._ondownloadfile)throw Error(\"No ondownloadfile handler set\");return this._ondownloadfile(Y.params,Z)})}get onrequestteardown(){return this.getEventHandler(\"requestteardown\")}set onrequestteardown(X){this.setEventHandler(\"requestteardown\",X)}_onrequestdisplaymode;get onrequestdisplaymode(){return this._onrequestdisplaymode}set onrequestdisplaymode(X){this.warnIfRequestHandlerReplaced(\"onrequestdisplaymode\",this._onrequestdisplaymode,X),this._onrequestdisplaymode=X,this.replaceRequestHandler(I,async(Y,Z)=>{if(!this._onrequestdisplaymode)throw Error(\"No onrequestdisplaymode handler set\");return this._onrequestdisplaymode(Y.params,Z)})}get onloggingmessage(){return this.getEventHandler(\"loggingmessage\")}set onloggingmessage(X){this.setEventHandler(\"loggingmessage\",X)}_onupdatemodelcontext;get onupdatemodelcontext(){return this._onupdatemodelcontext}set onupdatemodelcontext(X){this.warnIfRequestHandlerReplaced(\"onupdatemodelcontext\",this._onupdatemodelcontext,X),this._onupdatemodelcontext=X,this.replaceRequestHandler(d,async(Y,Z)=>{if(!this._onupdatemodelcontext)throw Error(\"No onupdatemodelcontext handler set\");return this._onupdatemodelcontext(Y.params,Z)})}_oncalltool;get oncalltool(){return this._oncalltool}set oncalltool(X){this.warnIfRequestHandlerReplaced(\"oncalltool\",this._oncalltool,X),this._oncalltool=X,this.replaceRequestHandler(iQ,async(Y,Z)=>{if(!this._oncalltool)throw Error(\"No oncalltool handler set\");return this._oncalltool(Y.params,Z)})}set oncreatesamplingmessage(X){this.setRequestHandler(nQ,async(Y,Z)=>{return X(Y.params,Z)})}sendToolListChanged(X={}){return this.notification({method:\"notifications/tools/list_changed\",params:X})}_onlistresources;get onlistresources(){return this._onlistresources}set onlistresources(X){this.warnIfRequestHandlerReplaced(\"onlistresources\",this._onlistresources,X),this._onlistresources=X,this.replaceRequestHandler(rQ,async(Y,Z)=>{if(!this._onlistresources)throw Error(\"No onlistresources handler set\");return this._onlistresources(Y.params,Z)})}_onlistresourcetemplates;get onlistresourcetemplates(){return this._onlistresourcetemplates}set onlistresourcetemplates(X){this.warnIfRequestHandlerReplaced(\"onlistresourcetemplates\",this._onlistresourcetemplates,X),this._onlistresourcetemplates=X,this.replaceRequestHandler(sQ,async(Y,Z)=>{if(!this._onlistresourcetemplates)throw Error(\"No onlistresourcetemplates handler set\");return this._onlistresourcetemplates(Y.params,Z)})}_onreadresource;get onreadresource(){return this._onreadresource}set onreadresource(X){this.warnIfRequestHandlerReplaced(\"onreadresource\",this._onreadresource,X),this._onreadresource=X,this.replaceRequestHandler(YX,async(Y,Z)=>{if(!this._onreadresource)throw Error(\"No onreadresource handler set\");return this._onreadresource(Y.params,Z)})}sendResourceListChanged(X={}){return this.notification({method:\"notifications/resources/list_changed\",params:X})}_onlistprompts;get onlistprompts(){return this._onlistprompts}set onlistprompts(X){this.warnIfRequestHandlerReplaced(\"onlistprompts\",this._onlistprompts,X),this._onlistprompts=X,this.replaceRequestHandler(cQ,async(Y,Z)=>{if(!this._onlistprompts)throw Error(\"No onlistprompts handler set\");return this._onlistprompts(Y.params,Z)})}sendPromptListChanged(X={}){return this.notification({method:\"notifications/prompts/list_changed\",params:X})}assertCapabilityForMethod(X){}assertRequestHandlerCapability(X){}assertNotificationCapability(X){}assertTaskCapability(X){throw Error(\"Tasks are not supported in MCP Apps\")}assertTaskHandlerCapability(X){throw Error(\"Task handlers are not supported in MCP Apps\")}getCapabilities(){return this._capabilities}async _oninitialize(X){let Y=X.params.protocolVersion;if(this._appInfo!==void 0)console.warn(\"[ext-apps] AppBridge received a second ui/initialize. The View may be double-mounting (e.g. React StrictMode in dev) without closing the previous App instance. Responding normally; the latest appInfo/appCapabilities replace the previous values.\");return this._appCapabilities=X.params.appCapabilities,this._appInfo=X.params.appInfo,{protocolVersion:KX.includes(Y)?Y:j,hostCapabilities:this.getCapabilities(),hostInfo:this._hostInfo,hostContext:this._hostContext}}setHostContext(X){let Y={},Z=!1;for(let $ of Object.keys(X)){let J=this._hostContext[$],K=X[$];if(GX(J,K))continue;Y[$]=K,Z=!0}if(Z)this._hostContext=X,this.sendHostContextChange(Y)}sendHostContextChange(X){return this.notification({method:\"ui/notifications/host-context-changed\",params:X})}sendToolInput(X){return this.notification({method:\"ui/notifications/tool-input\",params:X})}sendToolInputPartial(X){return this.notification({method:\"ui/notifications/tool-input-partial\",params:X})}sendToolResult(X){return this.notification({method:\"ui/notifications/tool-result\",params:X})}sendToolCancelled(X){return this.notification({method:\"ui/notifications/tool-cancelled\",params:X})}sendSandboxResourceReady(X){return this.notification({method:\"ui/notifications/sandbox-resource-ready\",params:X})}teardownResource(X,Y){return this.request({method:\"ui/resource-teardown\",params:X},S,Y)}sendResourceTeardown=this.teardownResource;callTool(X,Y){return this.request({method:\"tools/call\",params:X},XQ,Y)}listTools(X,Y){return this.request({method:\"tools/list\",params:X},aQ,Y)}async connect(X){if(this.transport)throw Error(\"AppBridge is already connected. Call close() before connecting again.\");if(this._initializedReceived=!1,this._client){let Y=this._client.getServerCapabilities();if(!Y)throw Error(\"Client server capabilities not available\");if(Y.tools){if(this.oncalltool=async(Z,$)=>{return this._client.request({method:\"tools/call\",params:Z},XQ,{signal:$.signal})},Y.tools.listChanged)this._client.setNotificationHandler(JX,(Z)=>this.sendToolListChanged(Z.params))}if(Y.resources){if(this.onlistresources=async(Z,$)=>{return this._client.request({method:\"resources/list\",params:Z},oQ,{signal:$.signal})},this.onlistresourcetemplates=async(Z,$)=>{return this._client.request({method:\"resources/templates/list\",params:Z},tQ,{signal:$.signal})},this.onreadresource=async(Z,$)=>{return this._client.request({method:\"resources/read\",params:Z},ZX,{signal:$.signal})},Y.resources.listChanged)this._client.setNotificationHandler($X,(Z)=>this.sendResourceListChanged(Z.params))}if(Y.prompts){if(this.onlistprompts=async(Z,$)=>{return this._client.request({method:\"prompts/list\",params:Z},lQ,{signal:$.signal})},Y.prompts.listChanged)this._client.setNotificationHandler(XX,(Z)=>this.sendPromptListChanged(Z.params))}}return super.connect(X)}}function GX(X,Y){return JSON.stringify(X)===JSON.stringify(Y)}export{LZ as isToolVisibilityModelOnly,PZ as isToolVisibilityAppOnly,FZ as getToolUiResourceUri,AZ as buildAllowAttribute,BQ as TOOL_RESULT_METHOD,V as TOOL_INPUT_PARTIAL_METHOD,jQ as TOOL_INPUT_METHOD,_Q as TOOL_CANCELLED_METHOD,KX as SUPPORTED_PROTOCOL_VERSIONS,WQ as SIZE_CHANGED_METHOD,NQ as SANDBOX_RESOURCE_READY_METHOD,GQ as SANDBOX_PROXY_READY_METHOD,i as RESOURCE_URI_META_KEY,zQ as RESOURCE_TEARDOWN_METHOD,pQ as RESOURCE_MIME_TYPE,OQ as REQUEST_TEARDOWN_METHOD,FQ as REQUEST_DISPLAY_MODE_METHOD,E as PostMessageTransport,JQ as OPEN_LINK_METHOD,d as McpUiUpdateModelContextRequestSchema,e as McpUiToolVisibilitySchema,v as McpUiToolResultNotificationSchema,MQ as McpUiToolMetaSchema,T as McpUiToolInputPartialNotificationSchema,R as McpUiToolInputNotificationSchema,M as McpUiToolCancelledNotificationSchema,r as McpUiThemeSchema,F as McpUiSupportedContentBlockModalitiesSchema,H as McpUiSizeChangedNotificationSchema,CQ as McpUiSandboxResourceReadyNotificationSchema,w as McpUiSandboxProxyReadyNotificationSchema,S as McpUiResourceTeardownResultSchema,C as McpUiResourceTeardownRequestSchema,z as McpUiResourcePermissionsSchema,TQ as McpUiResourceMetaSchema,O as McpUiResourceCspSchema,q as McpUiRequestTeardownNotificationSchema,g as McpUiRequestDisplayModeResultSchema,I as McpUiRequestDisplayModeRequestSchema,P as McpUiOpenLinkResultSchema,L as McpUiOpenLinkRequestSchema,U as McpUiMessageResultSchema,k as McpUiMessageRequestSchema,y as McpUiInitializedNotificationSchema,h as McpUiInitializeResultSchema,u as McpUiInitializeRequestSchema,s as McpUiHostStylesSchema,o as McpUiHostCssSchema,x as McpUiHostContextSchema,b as McpUiHostContextChangedNotificationSchema,t as McpUiHostCapabilitiesSchema,A as McpUiDownloadFileResultSchema,f as McpUiDownloadFileRequestSchema,B as McpUiDisplayModeSchema,a as McpUiAppCapabilitiesSchema,DQ as MESSAGE_METHOD,j as LATEST_PROTOCOL_VERSION,IQ as INITIALIZE_METHOD,VQ as INITIALIZED_METHOD,EQ as HOST_CONTEXT_CHANGED_METHOD,KQ as DOWNLOAD_FILE_METHOD,DX as AppBridge};\n","import { useEffect, useRef, useState, type JSX } from \"react\";\nimport {\n AppBridge,\n PostMessageTransport,\n buildAllowAttribute,\n type McpUiResourceCsp,\n type McpUiResourcePermissions,\n} from \"@modelcontextprotocol/ext-apps/app-bridge\";\nimport type { McpUiStyles } from \"@modelcontextprotocol/ext-apps\";\nimport type { CallToolResult } from \"@modelcontextprotocol/sdk/types.js\";\nimport { grackleHostStyleVariables } from \"../../utils/grackleHostStyleVariables.js\";\n\n/** Notification method the outer sandbox proxy posts once it is ready. */\nconst SANDBOX_PROXY_READY: string = \"ui/notifications/sandbox-proxy-ready\";\n\n/** Default host identity reported to widgets during the MCP Apps handshake. */\nconst DEFAULT_HOST_INFO: Readonly<{ name: string; version: string }> = {\n name: \"Grackle\",\n version: \"0.0.0\",\n};\n\n/** URL schemes the default link handler is permitted to open. */\nconst SAFE_LINK_PROTOCOLS: ReadonlySet<string> = new Set([\"http:\", \"https:\"]);\n\n/** True if `url` parses as an `http(s)` URL safe to open in a new browsing context. */\nfunction isSafeHttpUrl(url: string): boolean {\n try {\n return SAFE_LINK_PROTOCOLS.has(new URL(url).protocol);\n } catch {\n return false;\n }\n}\n\n/** A tool call the widget asked the host to run on its behalf. */\nexport interface McpAppWidgetCallToolParams {\n name: string;\n arguments?: Record<string, unknown>;\n}\n\n/**\n * Props for {@link McpAppWidget}. Presentational only — all data and side\n * effects arrive as props (no `useGrackle()`).\n */\nexport interface McpAppWidgetProps {\n /** Widget HTML (`text/html;profile=mcp-app` contents) rendered in the sandbox. */\n widgetHtml: string;\n /** URL of the sandbox proxy, served from a DIFFERENT origin than the host. */\n sandboxProxyUrl: string;\n /** Tool input delivered to the widget via `ui/notifications/tool-input`. */\n toolInput?: Record<string, unknown>;\n /** Tool result delivered to the widget via `ui/notifications/tool-result`. */\n toolResult?: CallToolResult;\n /** Content-Security-Policy domains for the widget (from the resource `_meta.ui`). */\n csp?: McpUiResourceCsp;\n /** Permissions to grant the widget iframe (from the resource `_meta.ui`). */\n permissions?: McpUiResourcePermissions;\n /** Style variables for `hostContext.styles`; defaults to Grackle's live theme. */\n hostStyleVariables?: McpUiStyles;\n /** Color theme reported to the widget; defaults to the document's `data-theme`. */\n theme?: \"light\" | \"dark\";\n /** Host identity reported to the widget; defaults to {@link DEFAULT_HOST_INFO}. */\n hostInfo?: { name: string; version: string };\n /** Handle a tool call the widget requests (no MCP client is wired in T1). */\n onCallTool?: (params: McpAppWidgetCallToolParams) => Promise<CallToolResult>;\n /** Handle a link the widget asks the host to open. */\n onOpenLink?: (url: string) => void;\n /** Handle a message the widget asks the host to surface. */\n onSendMessage?: (message: unknown) => void;\n /** Handle a model-context update pushed by the widget. */\n onUpdateModelContext?: (context: unknown) => void;\n /** Notified when the widget requests a new size. */\n onSizeChange?: (size: { width?: number; height?: number }) => void;\n}\n\n/** Resolve the active theme, preferring the prop, then the document, then light. */\nfunction resolveTheme(theme: McpAppWidgetProps[\"theme\"]): \"light\" | \"dark\" {\n if (theme) {\n return theme;\n }\n if (typeof document !== \"undefined\") {\n const attr: string | null = document.documentElement.getAttribute(\"data-theme\");\n if (attr === \"dark\") {\n return \"dark\";\n }\n }\n return \"light\";\n}\n\n/**\n * Point the iframe at the sandbox proxy and resolve once the proxy reports\n * ready. Returns `false` if the iframe was already loaded (guards against an\n * accidental double-invoke) or if `signal` aborts before the proxy responds.\n *\n * The ready listener is bound to `signal` so it is removed on effect cleanup,\n * and only messages from the proxy window AND its expected origin are accepted.\n */\nfunction loadSandboxProxy(\n iframe: HTMLIFrameElement,\n sandboxProxyUrl: string,\n proxyOrigin: string,\n csp: McpUiResourceCsp | undefined,\n permissions: McpUiResourcePermissions | undefined,\n signal: AbortSignal,\n): Promise<boolean> {\n if (iframe.src) {\n return Promise.resolve(false);\n }\n iframe.setAttribute(\"sandbox\", \"allow-scripts allow-same-origin allow-forms\");\n const allow: string = buildAllowAttribute(permissions);\n if (allow) {\n iframe.setAttribute(\"allow\", allow);\n }\n const ready: Promise<boolean> = new Promise<boolean>((resolve) => {\n const listener = (event: MessageEvent): void => {\n const data: { method?: string } | undefined = event.data as { method?: string } | undefined;\n if (\n event.source === iframe.contentWindow &&\n event.origin === proxyOrigin &&\n data?.method === SANDBOX_PROXY_READY\n ) {\n resolve(true);\n }\n };\n // `{ signal }` removes the listener automatically on effect cleanup, so it\n // never outlives the component even if the proxy never responds.\n window.addEventListener(\"message\", listener, { signal });\n signal.addEventListener(\"abort\", () => resolve(false), { once: true });\n });\n const url: URL = new URL(sandboxProxyUrl, window.location.href);\n if (csp) {\n url.searchParams.set(\"csp\", JSON.stringify(csp));\n }\n iframe.src = url.href;\n return ready;\n}\n\n/** Swallow a settled promise's rejection (the host outlives transient widget errors). */\nfunction ignoreRejection(promise: Promise<unknown> | void): void {\n Promise.resolve(promise).catch(() => undefined);\n}\n\n/**\n * Renders an MCP Apps widget (untrusted HTML) inside a double-iframe sandbox and\n * drives it over the `ext-apps` `AppBridge` postMessage protocol.\n *\n * The Grackle chat pane is not an MCP client, so this constructs the bridge with\n * `null` (no client) and serves tool input/result from props. Wiring the bridge\n * to a live MCP server is a later ticket (#1238).\n */\nexport function McpAppWidget(props: McpAppWidgetProps): JSX.Element {\n const {\n widgetHtml,\n sandboxProxyUrl,\n csp,\n permissions,\n hostStyleVariables,\n theme,\n hostInfo,\n toolInput,\n toolResult,\n onCallTool,\n onOpenLink,\n onSendMessage,\n onUpdateModelContext,\n onSizeChange,\n } = props;\n\n // Fail fast on the isolation-breaking misconfiguration: the sandbox proxy MUST\n // be a different origin than the host, otherwise `window.top` is reachable and\n // the double-iframe guarantee is void.\n if (\n typeof window !== \"undefined\" &&\n new URL(sandboxProxyUrl, window.location.href).origin === window.location.origin\n ) {\n throw new Error(\n \"McpAppWidget: sandboxProxyUrl must be served from a DIFFERENT origin than the host.\",\n );\n }\n\n const iframeRef = useRef<HTMLIFrameElement>(null);\n const bridgeRef = useRef<AppBridge | undefined>(undefined);\n // Flips true once the ui/initialize handshake completes; the tool-input/result\n // effects below key on it so late-arriving props still reach the widget.\n const [initialized, setInitialized] = useState<boolean>(false);\n\n // Keep the latest callbacks in a ref so the setup effect can be keyed only on\n // the widget identity (re-running it would reload the iframe).\n const handlers = useRef({\n onCallTool,\n onOpenLink,\n onSendMessage,\n onUpdateModelContext,\n onSizeChange,\n });\n handlers.current = { onCallTool, onOpenLink, onSendMessage, onUpdateModelContext, onSizeChange };\n\n // csp/permissions are part of the widget identity (they affect the proxy URL\n // and sendSandboxResourceReady), so the iframe must reload when they change.\n const cspKey: string = JSON.stringify(csp ?? null);\n const permissionsKey: string = JSON.stringify(permissions ?? null);\n\n useEffect(() => {\n const iframe: HTMLIFrameElement | null = iframeRef.current;\n if (!iframe) {\n return undefined;\n }\n\n // Origin of the proxy, used to validate inbound proxy messages. The\n // different-origin invariant is enforced at render time (see above).\n const proxyOrigin: string = new URL(sandboxProxyUrl, window.location.href).origin;\n const abortController: AbortController = new AbortController();\n const { signal } = abortController;\n // Read abort state through a function so TS flow-analysis can't narrow it to\n // a constant across the awaits below (cleanup flips it asynchronously).\n const isAborted = (): boolean => signal.aborted;\n let resizeObserver: ResizeObserver | undefined;\n\n const run = async (): Promise<void> => {\n const firstTime: boolean = await loadSandboxProxy(\n iframe,\n sandboxProxyUrl,\n proxyOrigin,\n csp,\n permissions,\n signal,\n );\n if (!firstTime || isAborted()) {\n return;\n }\n\n const bridge = new AppBridge(\n null,\n hostInfo ?? DEFAULT_HOST_INFO,\n { openLinks: {}, updateModelContext: { text: {} } },\n {\n hostContext: {\n theme: resolveTheme(theme),\n platform: \"web\",\n styles: { variables: hostStyleVariables ?? grackleHostStyleVariables() },\n containerDimensions: { maxHeight: 6000 },\n displayMode: \"inline\",\n availableDisplayModes: [\"inline\"],\n },\n },\n );\n bridgeRef.current = bridge;\n\n bridge.oncalltool = async (params): Promise<CallToolResult> => {\n const handler = handlers.current.onCallTool;\n if (handler) {\n return handler({ name: params.name, arguments: params.arguments });\n }\n return {\n isError: true,\n content: [{ type: \"text\", text: \"No MCP client is connected to this host.\" }],\n };\n };\n bridge.onopenlink = async ({ url }): Promise<Record<string, never>> => {\n const handler = handlers.current.onOpenLink;\n if (handler) {\n handler(url);\n } else if (isSafeHttpUrl(url)) {\n // Only http(s) — never javascript:/data: from an untrusted widget.\n window.open(url, \"_blank\", \"noopener,noreferrer\");\n }\n return {};\n };\n bridge.onmessage = async (params): Promise<Record<string, never>> => {\n handlers.current.onSendMessage?.(params);\n return {};\n };\n bridge.onupdatemodelcontext = async (params): Promise<Record<string, never>> => {\n handlers.current.onUpdateModelContext?.(params);\n return {};\n };\n bridge.onsizechange = ({ width, height }): void => {\n if (width !== undefined) {\n iframe.style.minWidth = `min(${width}px, 100%)`;\n }\n if (height !== undefined) {\n iframe.style.height = `${height}px`;\n }\n handlers.current.onSizeChange?.({ width, height });\n };\n bridge.onrequestdisplaymode = async (): Promise<{ mode: \"inline\" }> => ({ mode: \"inline\" });\n\n const handshakeComplete: Promise<void> = new Promise<void>((resolve) => {\n bridge.oninitialized = (): void => resolve();\n });\n\n await bridge.connect(\n new PostMessageTransport(iframe.contentWindow as Window, iframe.contentWindow as Window),\n );\n if (isAborted()) {\n return;\n }\n await bridge.sendSandboxResourceReady({ html: widgetHtml, csp, permissions });\n await handshakeComplete;\n if (isAborted()) {\n return;\n }\n // Tool input/result are delivered (and kept in sync) by the effects below\n // now that the handshake is complete.\n setInitialized(true);\n\n resizeObserver = new ResizeObserver(([entry]) => {\n const width: number = Math.round(entry.contentRect.width);\n if (width > 0) {\n ignoreRejection(\n bridge.sendHostContextChange({ containerDimensions: { width, maxHeight: 6000 } }),\n );\n }\n });\n resizeObserver.observe(iframe);\n };\n\n run().catch(() => undefined);\n\n return (): void => {\n abortController.abort();\n setInitialized(false);\n resizeObserver?.disconnect();\n const bridge: AppBridge | undefined = bridgeRef.current;\n bridgeRef.current = undefined;\n if (bridge) {\n ignoreRejection(bridge.teardownResource({}));\n }\n iframe.removeAttribute(\"src\");\n };\n // Setup is keyed on the widget identity (html + proxy URL + csp/permissions).\n // Tool input/result and theme updates flow via the dedicated effects below.\n }, [widgetHtml, sandboxProxyUrl, cspKey, permissionsKey]);\n\n // Deliver tool input after the handshake, and whenever it changes afterwards.\n useEffect(() => {\n if (!initialized) {\n return;\n }\n ignoreRejection(bridgeRef.current?.sendToolInput({ arguments: toolInput ?? {} }));\n }, [initialized, toolInput]);\n\n // Deliver the tool result once it is available, and whenever it changes. The\n // host commonly renders the widget before the result exists.\n useEffect(() => {\n if (!initialized || !toolResult) {\n return;\n }\n ignoreRejection(bridgeRef.current?.sendToolResult(toolResult));\n }, [initialized, toolResult]);\n\n // Propagate theme + style-variable changes to a live widget. When\n // hostStyleVariables is omitted, the Grackle token values themselves change\n // with the theme, so the resolved variables are re-sent too.\n useEffect(() => {\n ignoreRejection(\n bridgeRef.current?.sendHostContextChange({\n theme: resolveTheme(theme),\n styles: { variables: hostStyleVariables ?? grackleHostStyleVariables() },\n }),\n );\n }, [theme, hostStyleVariables]);\n\n return (\n <iframe\n ref={iframeRef}\n data-testid=\"mcp-app-widget\"\n title=\"MCP App widget\"\n style={{ width: \"100%\", border: \"none\", display: \"block\" }}\n />\n );\n}\n"],"names":["DEFAULT_MCP_STYLES","GRACKLE_TOKEN_BY_MCP_NAME","grackleHostStyleVariables","out","computed","writable","mcpName","grackleToken","value","RELATED_TASK_META_KEY","JSONRPC_VERSION","AssertObjectSchema","z.custom","v","ProgressTokenSchema","z.union","z.string","z.number","CursorSchema","z.looseObject","TaskMetadataSchema","z.object","RelatedTaskMetadataSchema","RequestMetaSchema","BaseRequestParamsSchema","TaskAugmentedRequestParamsSchema","isTaskAugmentedRequestParams","RequestSchema","NotificationsParamsSchema","NotificationSchema","ResultSchema","RequestIdSchema","JSONRPCRequestSchema","z\n .object","z.literal","isJSONRPCRequest","JSONRPCNotificationSchema","isJSONRPCNotification","JSONRPCResultResponseSchema","isJSONRPCResultResponse","ErrorCode","JSONRPCErrorResponseSchema","z.unknown","isJSONRPCErrorResponse","JSONRPCMessageSchema","EmptyResultSchema","CancelledNotificationParamsSchema","CancelledNotificationSchema","IconSchema","z.array","z.enum","IconsSchema","BaseMetadataSchema","ImplementationSchema","FormElicitationCapabilitySchema","z.intersection","z.boolean","z.record","ElicitationCapabilitySchema","z.preprocess","ClientTasksCapabilitySchema","z\n .looseObject","z\n .looseObject","ServerTasksCapabilitySchema","ClientCapabilitiesSchema","z\n .object","InitializeRequestParamsSchema","InitializeRequestSchema","ServerCapabilitiesSchema","InitializeResultSchema","InitializedNotificationSchema","PingRequestSchema","ProgressSchema","z.optional","ProgressNotificationParamsSchema","ProgressNotificationSchema","PaginatedRequestParamsSchema","PaginatedRequestSchema","PaginatedResultSchema","TaskStatusSchema","TaskSchema","z.null","CreateTaskResultSchema","TaskStatusNotificationParamsSchema","TaskStatusNotificationSchema","GetTaskRequestSchema","GetTaskResultSchema","GetTaskPayloadRequestSchema","ListTasksRequestSchema","ListTasksResultSchema","CancelTaskRequestSchema","CancelTaskResultSchema","ResourceContentsSchema","TextResourceContentsSchema","Base64Schema","val","BlobResourceContentsSchema","RoleSchema","AnnotationsSchema","z.iso.datetime","ResourceSchema","ResourceTemplateSchema","ListResourcesRequestSchema","ListResourcesResultSchema","ListResourceTemplatesRequestSchema","ListResourceTemplatesResultSchema","ResourceRequestParamsSchema","ReadResourceRequestParamsSchema","ReadResourceRequestSchema","ReadResourceResultSchema","ResourceListChangedNotificationSchema","SubscribeRequestParamsSchema","SubscribeRequestSchema","UnsubscribeRequestParamsSchema","UnsubscribeRequestSchema","ResourceUpdatedNotificationParamsSchema","ResourceUpdatedNotificationSchema","PromptArgumentSchema","PromptSchema","ListPromptsRequestSchema","ListPromptsResultSchema","GetPromptRequestParamsSchema","GetPromptRequestSchema","TextContentSchema","ImageContentSchema","AudioContentSchema","ToolUseContentSchema","EmbeddedResourceSchema","ResourceLinkSchema","ContentBlockSchema","PromptMessageSchema","GetPromptResultSchema","PromptListChangedNotificationSchema","ToolAnnotationsSchema","ToolExecutionSchema","ToolSchema","ListToolsRequestSchema","ListToolsResultSchema","CallToolResultSchema","CallToolRequestParamsSchema","CallToolRequestSchema","ToolListChangedNotificationSchema","LoggingLevelSchema","SetLevelRequestParamsSchema","SetLevelRequestSchema","LoggingMessageNotificationParamsSchema","LoggingMessageNotificationSchema","ModelHintSchema","ModelPreferencesSchema","ToolChoiceSchema","ToolResultContentSchema","SamplingContentSchema","z.discriminatedUnion","SamplingMessageContentBlockSchema","SamplingMessageSchema","CreateMessageRequestParamsSchema","CreateMessageRequestSchema","CreateMessageResultSchema","CreateMessageResultWithToolsSchema","BooleanSchemaSchema","StringSchemaSchema","NumberSchemaSchema","UntitledSingleSelectEnumSchemaSchema","TitledSingleSelectEnumSchemaSchema","LegacyTitledEnumSchemaSchema","SingleSelectEnumSchemaSchema","UntitledMultiSelectEnumSchemaSchema","TitledMultiSelectEnumSchemaSchema","MultiSelectEnumSchemaSchema","EnumSchemaSchema","PrimitiveSchemaDefinitionSchema","ElicitRequestFormParamsSchema","ElicitRequestURLParamsSchema","ElicitRequestParamsSchema","ElicitRequestSchema","ElicitationCompleteNotificationParamsSchema","ElicitationCompleteNotificationSchema","ElicitResultSchema","ResourceTemplateReferenceSchema","PromptReferenceSchema","CompleteRequestParamsSchema","CompleteRequestSchema","CompleteResultSchema","RootSchema","ListRootsRequestSchema","ListRootsResultSchema","RootsListChangedNotificationSchema","McpError","code","message","data","errorData","UrlElicitationRequiredError","elicitations","_a","isZ4Schema","s","safeParse","schema","z4mini.safeParse","getObjectShape","rawShape","_b","getLiteralValue","def","directValue","isTerminal","status","getMethodLiteral","shape","methodSchema","parseWithCompat","result","DEFAULT_REQUEST_TIMEOUT_MSEC","Protocol","_options","notification","_request","request","extra","task","handleTaskResult","taskId","queuedMessage","requestId","resolver","errorMessage","error","messageType","tasks","nextCursor","cancelledTask","controller","messageId","timeout","maxTotalTimeout","onTimeout","resetTimeoutOnProgress","info","totalElapsed","transport","_onclose","_onerror","_onmessage","_c","responseHandlers","handler","capturedTransport","relatedTaskId","errorResponse","abortController","taskCreationParams","taskStore","fullExtra","_d","notificationOptions","r","resultSchema","options","requestOptions","effectiveTaskId","response","progressToken","params","responseHandler","timeoutInfo","isTaskResponse","createResult","pollInterval","resolve","relatedRequestId","resumptionToken","onresumptiontoken","relatedTask","reject","earlyReject","e","jsonrpcRequest","cancel","reason","parseResult","_e","timeoutHandler","responseResolver","jsonrpcNotification","requestSchema","method","parsed","notificationSchema","sessionId","maxQueueSize","messages","signal","interval","timeoutId","taskParams","statusMessage","updatedTask","cursor","X","Y","Z","_","$Q","__publicField","$","J","K","D","G","j","V","Q.union","Q.literal","B","HQ","RQ","Q.record","Q.string","Q.undefined","L","Q.object","Q.boolean","w","O","Q.array","z","H","Q.number","Q.unknown","o","S","F","q","t","a","y","I","Q.never","f","PQ","UQ","k","c","LQ","x","AQ","wQ","d","u","l","E","SQ","AZ","KX","DX","eQ","QX","iQ","nQ","rQ","sQ","YX","cQ","GX","XQ","aQ","JX","oQ","tQ","ZX","$X","lQ","XX","SANDBOX_PROXY_READY","DEFAULT_HOST_INFO","SAFE_LINK_PROTOCOLS","isSafeHttpUrl","url","resolveTheme","theme","loadSandboxProxy","iframe","sandboxProxyUrl","proxyOrigin","csp","permissions","allow","buildAllowAttribute","ready","listener","event","ignoreRejection","promise","McpAppWidget","props","widgetHtml","hostStyleVariables","hostInfo","toolInput","toolResult","onCallTool","onOpenLink","onSendMessage","onUpdateModelContext","onSizeChange","iframeRef","useRef","bridgeRef","initialized","setInitialized","useState","handlers","cspKey","permissionsKey","useEffect","isAborted","resizeObserver","bridge","AppBridge","width","height","handshakeComplete","PostMessageTransport","entry","jsx"],"mappings":"sZAgBA,MAAMA,GAAkC,CACtC,6BAA8B,+BAC9B,+BAAgC,+BAChC,8BAA+B,+BAC/B,6BAA8B,+BAC9B,2BAA4B,oDAC5B,0BAA2B,+BAC3B,4BAA6B,+BAC7B,6BAA8B,+BAC9B,6BAA8B,+BAC9B,8BAA+B,wDAC/B,uBAAwB,+BACxB,yBAA0B,+BAC1B,wBAAyB,+BACzB,uBAAwB,+BACxB,qBAAsB,2DACtB,oBAAqB,+BACrB,sBAAuB,+BACvB,uBAAwB,+BACxB,uBAAwB,+BACxB,wBAAyB,wDACzB,yBAA0B,+BAC1B,2BAA4B,+BAC5B,0BAA2B,+BAC3B,yBAA0B,qDAC1B,uBAAwB,oDACxB,sBAAuB,+BACvB,wBAAyB,+BACzB,yBAA0B,+BAC1B,yBAA0B,+BAC1B,0BAA2B,wDAC3B,uBAAwB,+BACxB,yBAA0B,+BAC1B,uBAAwB,+BACxB,oBAAqB,+BACrB,sBAAuB,+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EAAmB,sBAAsB,CACvC,MAAOyL,GAAaC,CAAK,EACzB,OAAQ,CAAE,UAAWiB,GAAsB3Y,IAA0B,CAAE,EACxE,CAEL,EAAG,CAAC0X,EAAOiB,CAAkB,CAAC,EAG5B4B,GAAAA,IAAC,SAAA,CACC,IAAKnB,EACL,cAAY,iBACZ,MAAM,iBACN,MAAO,CAAE,MAAO,OAAQ,OAAQ,OAAQ,QAAS,OAAA,CAAQ,CAAA,CAG/D","x_google_ignoreList":[1,2,3,4,5,6,7]}
|
|
1
|
+
{"version":3,"file":"McpAppWidget-D-BOXq5b.js","sources":["../../../web-components/src/utils/grackleHostStyleVariables.ts","../../../../common/temp/node_modules/.pnpm/@modelcontextprotocol+sdk@1.29.0_zod@4.3.6/node_modules/@modelcontextprotocol/sdk/dist/esm/types.js","../../../../common/temp/node_modules/.pnpm/@modelcontextprotocol+sdk@1.29.0_zod@4.3.6/node_modules/@modelcontextprotocol/sdk/dist/esm/server/zod-compat.js","../../../../common/temp/node_modules/.pnpm/@modelcontextprotocol+sdk@1.29.0_zod@4.3.6/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/interfaces.js","../../../../common/temp/node_modules/.pnpm/zod-to-json-schema@3.25.1_zod@4.3.6/node_modules/zod-to-json-schema/dist/esm/parsers/string.js","../../../../common/temp/node_modules/.pnpm/@modelcontextprotocol+sdk@1.29.0_zod@4.3.6/node_modules/@modelcontextprotocol/sdk/dist/esm/server/zod-json-schema-compat.js","../../../../common/temp/node_modules/.pnpm/@modelcontextprotocol+sdk@1.29.0_zod@4.3.6/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/protocol.js","../../../../common/temp/node_modules/.pnpm/@modelcontextprotocol+ext-apps@1.7.2_@modelcontextprotocol+sdk@1.29.0_zod@4.3.6__react-_49a9f4a3a4382c4744fd223899ec1ad9/node_modules/@modelcontextprotocol/ext-apps/dist/src/app-bridge.js","../../../web-components/src/components/display/McpAppWidget.tsx"],"sourcesContent":["import type { McpUiStyles } from \"@modelcontextprotocol/ext-apps\";\n\n/**\n * MCP Apps widgets consume a fixed, standard set of CSS custom properties\n * (`--color-*`, `--font-*`, `--border-radius-*`, `--shadow-*`). Grackle's own\n * theme tokens live under different names (`--bg-*`, `--text-*`, `--radius-*`) in\n * `src/styles/theme.scss`. This module exposes Grackle's current theme to widgets\n * under the MCP-standard names so a widget renders coherently inside the host.\n *\n * `McpUiStyles` requires the complete variable set, so we seed from the standard\n * theme-adaptive defaults (verbatim from modelcontextprotocol/ext-apps\n * examples/basic-host/src/host-styles.ts, commit 9a37ad7) and override the subset\n * we can source from Grackle's live theme.\n */\n\n/** Complete MCP-standard default style variables (theme-adaptive via `light-dark()`). */\nconst DEFAULT_MCP_STYLES: McpUiStyles = {\n \"--color-background-primary\": \"light-dark(#ffffff, #1a1a1a)\",\n \"--color-background-secondary\": \"light-dark(#f5f5f5, #2d2d2d)\",\n \"--color-background-tertiary\": \"light-dark(#e5e5e5, #404040)\",\n \"--color-background-inverse\": \"light-dark(#1a1a1a, #ffffff)\",\n \"--color-background-ghost\": \"light-dark(rgba(255,255,255,0), rgba(26,26,26,0))\",\n \"--color-background-info\": \"light-dark(#eff6ff, #1e3a5f)\",\n \"--color-background-danger\": \"light-dark(#fef2f2, #7f1d1d)\",\n \"--color-background-success\": \"light-dark(#f0fdf4, #14532d)\",\n \"--color-background-warning\": \"light-dark(#fefce8, #713f12)\",\n \"--color-background-disabled\": \"light-dark(rgba(255,255,255,0.5), rgba(26,26,26,0.5))\",\n \"--color-text-primary\": \"light-dark(#1f2937, #f3f4f6)\",\n \"--color-text-secondary\": \"light-dark(#6b7280, #9ca3af)\",\n \"--color-text-tertiary\": \"light-dark(#9ca3af, #6b7280)\",\n \"--color-text-inverse\": \"light-dark(#f3f4f6, #1f2937)\",\n \"--color-text-ghost\": \"light-dark(rgba(107,114,128,0.5), rgba(156,163,175,0.5))\",\n \"--color-text-info\": \"light-dark(#1d4ed8, #60a5fa)\",\n \"--color-text-danger\": \"light-dark(#b91c1c, #f87171)\",\n \"--color-text-success\": \"light-dark(#15803d, #4ade80)\",\n \"--color-text-warning\": \"light-dark(#a16207, #fbbf24)\",\n \"--color-text-disabled\": \"light-dark(rgba(31,41,55,0.5), rgba(243,244,246,0.5))\",\n \"--color-border-primary\": \"light-dark(#e5e7eb, #404040)\",\n \"--color-border-secondary\": \"light-dark(#d1d5db, #525252)\",\n \"--color-border-tertiary\": \"light-dark(#f3f4f6, #374151)\",\n \"--color-border-inverse\": \"light-dark(rgba(255,255,255,0.3), rgba(0,0,0,0.3))\",\n \"--color-border-ghost\": \"light-dark(rgba(229,231,235,0), rgba(64,64,64,0))\",\n \"--color-border-info\": \"light-dark(#93c5fd, #1e40af)\",\n \"--color-border-danger\": \"light-dark(#fca5a5, #991b1b)\",\n \"--color-border-success\": \"light-dark(#86efac, #166534)\",\n \"--color-border-warning\": \"light-dark(#fde047, #854d0e)\",\n \"--color-border-disabled\": \"light-dark(rgba(229,231,235,0.5), rgba(64,64,64,0.5))\",\n \"--color-ring-primary\": \"light-dark(#3b82f6, #60a5fa)\",\n \"--color-ring-secondary\": \"light-dark(#6b7280, #9ca3af)\",\n \"--color-ring-inverse\": \"light-dark(#ffffff, #1f2937)\",\n \"--color-ring-info\": \"light-dark(#2563eb, #3b82f6)\",\n \"--color-ring-danger\": \"light-dark(#dc2626, #ef4444)\",\n \"--color-ring-success\": \"light-dark(#16a34a, #22c55e)\",\n \"--color-ring-warning\": \"light-dark(#ca8a04, #eab308)\",\n \"--font-sans\": \"system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif\",\n \"--font-mono\": \"ui-monospace, 'SF Mono', Monaco, 'Cascadia Code', monospace\",\n \"--font-weight-normal\": \"400\",\n \"--font-weight-medium\": \"500\",\n \"--font-weight-semibold\": \"600\",\n \"--font-weight-bold\": \"700\",\n \"--font-text-xs-size\": \"0.75rem\",\n \"--font-text-sm-size\": \"0.875rem\",\n \"--font-text-md-size\": \"1rem\",\n \"--font-text-lg-size\": \"1.125rem\",\n \"--font-heading-xs-size\": \"0.75rem\",\n \"--font-heading-sm-size\": \"0.875rem\",\n \"--font-heading-md-size\": \"1rem\",\n \"--font-heading-lg-size\": \"1.25rem\",\n \"--font-heading-xl-size\": \"1.5rem\",\n \"--font-heading-2xl-size\": \"1.875rem\",\n \"--font-heading-3xl-size\": \"2.25rem\",\n \"--font-text-xs-line-height\": \"1.4\",\n \"--font-text-sm-line-height\": \"1.4\",\n \"--font-text-md-line-height\": \"1.5\",\n \"--font-text-lg-line-height\": \"1.5\",\n \"--font-heading-xs-line-height\": \"1.4\",\n \"--font-heading-sm-line-height\": \"1.4\",\n \"--font-heading-md-line-height\": \"1.4\",\n \"--font-heading-lg-line-height\": \"1.3\",\n \"--font-heading-xl-line-height\": \"1.25\",\n \"--font-heading-2xl-line-height\": \"1.2\",\n \"--font-heading-3xl-line-height\": \"1.1\",\n \"--border-radius-xs\": \"2px\",\n \"--border-radius-sm\": \"4px\",\n \"--border-radius-md\": \"6px\",\n \"--border-radius-lg\": \"8px\",\n \"--border-radius-xl\": \"12px\",\n \"--border-radius-full\": \"9999px\",\n \"--border-width-regular\": \"1px\",\n \"--shadow-hairline\": \"0 1px 2px 0 rgba(0, 0, 0, 0.05)\",\n \"--shadow-sm\": \"0 1px 3px 0 rgba(0, 0, 0, 0.1), 0 1px 2px -1px rgba(0, 0, 0, 0.1)\",\n \"--shadow-md\": \"0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -2px rgba(0, 0, 0, 0.1)\",\n \"--shadow-lg\": \"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)\",\n};\n\n/** MCP-standard variable name -> Grackle theme token to read its value from. */\nconst GRACKLE_TOKEN_BY_MCP_NAME: Readonly<Record<string, string>> = {\n \"--color-background-primary\": \"--bg-base\",\n \"--color-background-secondary\": \"--bg-surface\",\n \"--color-background-tertiary\": \"--bg-elevated\",\n \"--color-text-primary\": \"--text-primary\",\n \"--color-text-secondary\": \"--text-secondary\",\n \"--color-text-tertiary\": \"--text-tertiary\",\n \"--color-border-primary\": \"--border-primary\",\n \"--color-border-secondary\": \"--border-subtle\",\n \"--font-sans\": \"--font-sans\",\n \"--font-mono\": \"--font-mono\",\n \"--border-radius-sm\": \"--radius-sm\",\n \"--border-radius-md\": \"--radius-md\",\n \"--border-radius-lg\": \"--radius-lg\",\n \"--border-radius-full\": \"--radius-full\",\n};\n\n/**\n * Build the MCP-standard style-variable map from Grackle's live theme, falling\n * back to theme-adaptive defaults for any token that cannot be read.\n *\n * @returns Style variables suitable for `hostContext.styles.variables`.\n */\nexport function grackleHostStyleVariables(): McpUiStyles {\n const out: McpUiStyles = { ...DEFAULT_MCP_STYLES };\n if (typeof window === \"undefined\" || typeof document === \"undefined\") {\n return out;\n }\n const computed: CSSStyleDeclaration = window.getComputedStyle(document.documentElement);\n const writable: Record<string, string> = out as Record<string, string>;\n for (const [mcpName, grackleToken] of Object.entries(GRACKLE_TOKEN_BY_MCP_NAME)) {\n const value: string = computed.getPropertyValue(grackleToken).trim();\n if (value) {\n writable[mcpName] = value;\n }\n }\n return out;\n}\n","import * as z from 'zod/v4';\nexport const LATEST_PROTOCOL_VERSION = '2025-11-25';\nexport const DEFAULT_NEGOTIATED_PROTOCOL_VERSION = '2025-03-26';\nexport const SUPPORTED_PROTOCOL_VERSIONS = [LATEST_PROTOCOL_VERSION, '2025-06-18', '2025-03-26', '2024-11-05', '2024-10-07'];\nexport const RELATED_TASK_META_KEY = 'io.modelcontextprotocol/related-task';\n/* JSON-RPC types */\nexport const JSONRPC_VERSION = '2.0';\n/**\n * Assert 'object' type schema.\n *\n * @internal\n */\nconst AssertObjectSchema = z.custom((v) => v !== null && (typeof v === 'object' || typeof v === 'function'));\n/**\n * A progress token, used to associate progress notifications with the original request.\n */\nexport const ProgressTokenSchema = z.union([z.string(), z.number().int()]);\n/**\n * An opaque token used to represent a cursor for pagination.\n */\nexport const CursorSchema = z.string();\n/**\n * Task creation parameters, used to ask that the server create a task to represent a request.\n */\nexport const TaskCreationParamsSchema = z.looseObject({\n /**\n * Requested duration in milliseconds to retain task from creation.\n */\n ttl: z.number().optional(),\n /**\n * Time in milliseconds to wait between task status requests.\n */\n pollInterval: z.number().optional()\n});\nexport const TaskMetadataSchema = z.object({\n ttl: z.number().optional()\n});\n/**\n * Metadata for associating messages with a task.\n * Include this in the `_meta` field under the key `io.modelcontextprotocol/related-task`.\n */\nexport const RelatedTaskMetadataSchema = z.object({\n taskId: z.string()\n});\nconst RequestMetaSchema = z.looseObject({\n /**\n * If specified, the caller is requesting out-of-band progress notifications for this request (as represented by notifications/progress). The value of this parameter is an opaque token that will be attached to any subsequent notifications. The receiver is not obligated to provide these notifications.\n */\n progressToken: ProgressTokenSchema.optional(),\n /**\n * If specified, this request is related to the provided task.\n */\n [RELATED_TASK_META_KEY]: RelatedTaskMetadataSchema.optional()\n});\n/**\n * Common params for any request.\n */\nconst BaseRequestParamsSchema = z.object({\n /**\n * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage.\n */\n _meta: RequestMetaSchema.optional()\n});\n/**\n * Common params for any task-augmented request.\n */\nexport const TaskAugmentedRequestParamsSchema = BaseRequestParamsSchema.extend({\n /**\n * If specified, the caller is requesting task-augmented execution for this request.\n * The request will return a CreateTaskResult immediately, and the actual result can be\n * retrieved later via tasks/result.\n *\n * Task augmentation is subject to capability negotiation - receivers MUST declare support\n * for task augmentation of specific request types in their capabilities.\n */\n task: TaskMetadataSchema.optional()\n});\n/**\n * Checks if a value is a valid TaskAugmentedRequestParams.\n * @param value - The value to check.\n *\n * @returns True if the value is a valid TaskAugmentedRequestParams, false otherwise.\n */\nexport const isTaskAugmentedRequestParams = (value) => TaskAugmentedRequestParamsSchema.safeParse(value).success;\nexport const RequestSchema = z.object({\n method: z.string(),\n params: BaseRequestParamsSchema.loose().optional()\n});\nconst NotificationsParamsSchema = z.object({\n /**\n * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)\n * for notes on _meta usage.\n */\n _meta: RequestMetaSchema.optional()\n});\nexport const NotificationSchema = z.object({\n method: z.string(),\n params: NotificationsParamsSchema.loose().optional()\n});\nexport const ResultSchema = z.looseObject({\n /**\n * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)\n * for notes on _meta usage.\n */\n _meta: RequestMetaSchema.optional()\n});\n/**\n * A uniquely identifying ID for a request in JSON-RPC.\n */\nexport const RequestIdSchema = z.union([z.string(), z.number().int()]);\n/**\n * A request that expects a response.\n */\nexport const JSONRPCRequestSchema = z\n .object({\n jsonrpc: z.literal(JSONRPC_VERSION),\n id: RequestIdSchema,\n ...RequestSchema.shape\n})\n .strict();\nexport const isJSONRPCRequest = (value) => JSONRPCRequestSchema.safeParse(value).success;\n/**\n * A notification which does not expect a response.\n */\nexport const JSONRPCNotificationSchema = z\n .object({\n jsonrpc: z.literal(JSONRPC_VERSION),\n ...NotificationSchema.shape\n})\n .strict();\nexport const isJSONRPCNotification = (value) => JSONRPCNotificationSchema.safeParse(value).success;\n/**\n * A successful (non-error) response to a request.\n */\nexport const JSONRPCResultResponseSchema = z\n .object({\n jsonrpc: z.literal(JSONRPC_VERSION),\n id: RequestIdSchema,\n result: ResultSchema\n})\n .strict();\n/**\n * Checks if a value is a valid JSONRPCResultResponse.\n * @param value - The value to check.\n *\n * @returns True if the value is a valid JSONRPCResultResponse, false otherwise.\n */\nexport const isJSONRPCResultResponse = (value) => JSONRPCResultResponseSchema.safeParse(value).success;\n/**\n * @deprecated Use {@link isJSONRPCResultResponse} instead.\n *\n * Please note that {@link JSONRPCResponse} is a union of {@link JSONRPCResultResponse} and {@link JSONRPCErrorResponse} as per the updated JSON-RPC specification. (was previously just {@link JSONRPCResultResponse})\n */\nexport const isJSONRPCResponse = isJSONRPCResultResponse;\n/**\n * Error codes defined by the JSON-RPC specification.\n */\nexport var ErrorCode;\n(function (ErrorCode) {\n // SDK error codes\n ErrorCode[ErrorCode[\"ConnectionClosed\"] = -32000] = \"ConnectionClosed\";\n ErrorCode[ErrorCode[\"RequestTimeout\"] = -32001] = \"RequestTimeout\";\n // Standard JSON-RPC error codes\n ErrorCode[ErrorCode[\"ParseError\"] = -32700] = \"ParseError\";\n ErrorCode[ErrorCode[\"InvalidRequest\"] = -32600] = \"InvalidRequest\";\n ErrorCode[ErrorCode[\"MethodNotFound\"] = -32601] = \"MethodNotFound\";\n ErrorCode[ErrorCode[\"InvalidParams\"] = -32602] = \"InvalidParams\";\n ErrorCode[ErrorCode[\"InternalError\"] = -32603] = \"InternalError\";\n // MCP-specific error codes\n ErrorCode[ErrorCode[\"UrlElicitationRequired\"] = -32042] = \"UrlElicitationRequired\";\n})(ErrorCode || (ErrorCode = {}));\n/**\n * A response to a request that indicates an error occurred.\n */\nexport const JSONRPCErrorResponseSchema = z\n .object({\n jsonrpc: z.literal(JSONRPC_VERSION),\n id: RequestIdSchema.optional(),\n error: z.object({\n /**\n * The error type that occurred.\n */\n code: z.number().int(),\n /**\n * A short description of the error. The message SHOULD be limited to a concise single sentence.\n */\n message: z.string(),\n /**\n * Additional information about the error. The value of this member is defined by the sender (e.g. detailed error information, nested errors etc.).\n */\n data: z.unknown().optional()\n })\n})\n .strict();\n/**\n * @deprecated Use {@link JSONRPCErrorResponseSchema} instead.\n */\nexport const JSONRPCErrorSchema = JSONRPCErrorResponseSchema;\n/**\n * Checks if a value is a valid JSONRPCErrorResponse.\n * @param value - The value to check.\n *\n * @returns True if the value is a valid JSONRPCErrorResponse, false otherwise.\n */\nexport const isJSONRPCErrorResponse = (value) => JSONRPCErrorResponseSchema.safeParse(value).success;\n/**\n * @deprecated Use {@link isJSONRPCErrorResponse} instead.\n */\nexport const isJSONRPCError = isJSONRPCErrorResponse;\nexport const JSONRPCMessageSchema = z.union([\n JSONRPCRequestSchema,\n JSONRPCNotificationSchema,\n JSONRPCResultResponseSchema,\n JSONRPCErrorResponseSchema\n]);\nexport const JSONRPCResponseSchema = z.union([JSONRPCResultResponseSchema, JSONRPCErrorResponseSchema]);\n/* Empty result */\n/**\n * A response that indicates success but carries no data.\n */\nexport const EmptyResultSchema = ResultSchema.strict();\nexport const CancelledNotificationParamsSchema = NotificationsParamsSchema.extend({\n /**\n * The ID of the request to cancel.\n *\n * This MUST correspond to the ID of a request previously issued in the same direction.\n */\n requestId: RequestIdSchema.optional(),\n /**\n * An optional string describing the reason for the cancellation. This MAY be logged or presented to the user.\n */\n reason: z.string().optional()\n});\n/* Cancellation */\n/**\n * This notification can be sent by either side to indicate that it is cancelling a previously-issued request.\n *\n * The request SHOULD still be in-flight, but due to communication latency, it is always possible that this notification MAY arrive after the request has already finished.\n *\n * This notification indicates that the result will be unused, so any associated processing SHOULD cease.\n *\n * A client MUST NOT attempt to cancel its `initialize` request.\n */\nexport const CancelledNotificationSchema = NotificationSchema.extend({\n method: z.literal('notifications/cancelled'),\n params: CancelledNotificationParamsSchema\n});\n/* Base Metadata */\n/**\n * Icon schema for use in tools, prompts, resources, and implementations.\n */\nexport const IconSchema = z.object({\n /**\n * URL or data URI for the icon.\n */\n src: z.string(),\n /**\n * Optional MIME type for the icon.\n */\n mimeType: z.string().optional(),\n /**\n * Optional array of strings that specify sizes at which the icon can be used.\n * Each string should be in WxH format (e.g., `\"48x48\"`, `\"96x96\"`) or `\"any\"` for scalable formats like SVG.\n *\n * If not provided, the client should assume that the icon can be used at any size.\n */\n sizes: z.array(z.string()).optional(),\n /**\n * Optional specifier for the theme this icon is designed for. `light` indicates\n * the icon is designed to be used with a light background, and `dark` indicates\n * the icon is designed to be used with a dark background.\n *\n * If not provided, the client should assume the icon can be used with any theme.\n */\n theme: z.enum(['light', 'dark']).optional()\n});\n/**\n * Base schema to add `icons` property.\n *\n */\nexport const IconsSchema = z.object({\n /**\n * Optional set of sized icons that the client can display in a user interface.\n *\n * Clients that support rendering icons MUST support at least the following MIME types:\n * - `image/png` - PNG images (safe, universal compatibility)\n * - `image/jpeg` (and `image/jpg`) - JPEG images (safe, universal compatibility)\n *\n * Clients that support rendering icons SHOULD also support:\n * - `image/svg+xml` - SVG images (scalable but requires security precautions)\n * - `image/webp` - WebP images (modern, efficient format)\n */\n icons: z.array(IconSchema).optional()\n});\n/**\n * Base metadata interface for common properties across resources, tools, prompts, and implementations.\n */\nexport const BaseMetadataSchema = z.object({\n /** Intended for programmatic or logical use, but used as a display name in past specs or fallback */\n name: z.string(),\n /**\n * Intended for UI and end-user contexts — optimized to be human-readable and easily understood,\n * even by those unfamiliar with domain-specific terminology.\n *\n * If not provided, the name should be used for display (except for Tool,\n * where `annotations.title` should be given precedence over using `name`,\n * if present).\n */\n title: z.string().optional()\n});\n/* Initialization */\n/**\n * Describes the name and version of an MCP implementation.\n */\nexport const ImplementationSchema = BaseMetadataSchema.extend({\n ...BaseMetadataSchema.shape,\n ...IconsSchema.shape,\n version: z.string(),\n /**\n * An optional URL of the website for this implementation.\n */\n websiteUrl: z.string().optional(),\n /**\n * An optional human-readable description of what this implementation does.\n *\n * This can be used by clients or servers to provide context about their purpose\n * and capabilities. For example, a server might describe the types of resources\n * or tools it provides, while a client might describe its intended use case.\n */\n description: z.string().optional()\n});\nconst FormElicitationCapabilitySchema = z.intersection(z.object({\n applyDefaults: z.boolean().optional()\n}), z.record(z.string(), z.unknown()));\nconst ElicitationCapabilitySchema = z.preprocess(value => {\n if (value && typeof value === 'object' && !Array.isArray(value)) {\n if (Object.keys(value).length === 0) {\n return { form: {} };\n }\n }\n return value;\n}, z.intersection(z.object({\n form: FormElicitationCapabilitySchema.optional(),\n url: AssertObjectSchema.optional()\n}), z.record(z.string(), z.unknown()).optional()));\n/**\n * Task capabilities for clients, indicating which request types support task creation.\n */\nexport const ClientTasksCapabilitySchema = z.looseObject({\n /**\n * Present if the client supports listing tasks.\n */\n list: AssertObjectSchema.optional(),\n /**\n * Present if the client supports cancelling tasks.\n */\n cancel: AssertObjectSchema.optional(),\n /**\n * Capabilities for task creation on specific request types.\n */\n requests: z\n .looseObject({\n /**\n * Task support for sampling requests.\n */\n sampling: z\n .looseObject({\n createMessage: AssertObjectSchema.optional()\n })\n .optional(),\n /**\n * Task support for elicitation requests.\n */\n elicitation: z\n .looseObject({\n create: AssertObjectSchema.optional()\n })\n .optional()\n })\n .optional()\n});\n/**\n * Task capabilities for servers, indicating which request types support task creation.\n */\nexport const ServerTasksCapabilitySchema = z.looseObject({\n /**\n * Present if the server supports listing tasks.\n */\n list: AssertObjectSchema.optional(),\n /**\n * Present if the server supports cancelling tasks.\n */\n cancel: AssertObjectSchema.optional(),\n /**\n * Capabilities for task creation on specific request types.\n */\n requests: z\n .looseObject({\n /**\n * Task support for tool requests.\n */\n tools: z\n .looseObject({\n call: AssertObjectSchema.optional()\n })\n .optional()\n })\n .optional()\n});\n/**\n * Capabilities a client may support. Known capabilities are defined here, in this schema, but this is not a closed set: any client can define its own, additional capabilities.\n */\nexport const ClientCapabilitiesSchema = z.object({\n /**\n * Experimental, non-standard capabilities that the client supports.\n */\n experimental: z.record(z.string(), AssertObjectSchema).optional(),\n /**\n * Present if the client supports sampling from an LLM.\n */\n sampling: z\n .object({\n /**\n * Present if the client supports context inclusion via includeContext parameter.\n * If not declared, servers SHOULD only use `includeContext: \"none\"` (or omit it).\n */\n context: AssertObjectSchema.optional(),\n /**\n * Present if the client supports tool use via tools and toolChoice parameters.\n */\n tools: AssertObjectSchema.optional()\n })\n .optional(),\n /**\n * Present if the client supports eliciting user input.\n */\n elicitation: ElicitationCapabilitySchema.optional(),\n /**\n * Present if the client supports listing roots.\n */\n roots: z\n .object({\n /**\n * Whether the client supports issuing notifications for changes to the roots list.\n */\n listChanged: z.boolean().optional()\n })\n .optional(),\n /**\n * Present if the client supports task creation.\n */\n tasks: ClientTasksCapabilitySchema.optional(),\n /**\n * Extensions that the client supports. Keys are extension identifiers (vendor-prefix/extension-name).\n */\n extensions: z.record(z.string(), AssertObjectSchema).optional()\n});\nexport const InitializeRequestParamsSchema = BaseRequestParamsSchema.extend({\n /**\n * The latest version of the Model Context Protocol that the client supports. The client MAY decide to support older versions as well.\n */\n protocolVersion: z.string(),\n capabilities: ClientCapabilitiesSchema,\n clientInfo: ImplementationSchema\n});\n/**\n * This request is sent from the client to the server when it first connects, asking it to begin initialization.\n */\nexport const InitializeRequestSchema = RequestSchema.extend({\n method: z.literal('initialize'),\n params: InitializeRequestParamsSchema\n});\nexport const isInitializeRequest = (value) => InitializeRequestSchema.safeParse(value).success;\n/**\n * Capabilities that a server may support. Known capabilities are defined here, in this schema, but this is not a closed set: any server can define its own, additional capabilities.\n */\nexport const ServerCapabilitiesSchema = z.object({\n /**\n * Experimental, non-standard capabilities that the server supports.\n */\n experimental: z.record(z.string(), AssertObjectSchema).optional(),\n /**\n * Present if the server supports sending log messages to the client.\n */\n logging: AssertObjectSchema.optional(),\n /**\n * Present if the server supports sending completions to the client.\n */\n completions: AssertObjectSchema.optional(),\n /**\n * Present if the server offers any prompt templates.\n */\n prompts: z\n .object({\n /**\n * Whether this server supports issuing notifications for changes to the prompt list.\n */\n listChanged: z.boolean().optional()\n })\n .optional(),\n /**\n * Present if the server offers any resources to read.\n */\n resources: z\n .object({\n /**\n * Whether this server supports clients subscribing to resource updates.\n */\n subscribe: z.boolean().optional(),\n /**\n * Whether this server supports issuing notifications for changes to the resource list.\n */\n listChanged: z.boolean().optional()\n })\n .optional(),\n /**\n * Present if the server offers any tools to call.\n */\n tools: z\n .object({\n /**\n * Whether this server supports issuing notifications for changes to the tool list.\n */\n listChanged: z.boolean().optional()\n })\n .optional(),\n /**\n * Present if the server supports task creation.\n */\n tasks: ServerTasksCapabilitySchema.optional(),\n /**\n * Extensions that the server supports. Keys are extension identifiers (vendor-prefix/extension-name).\n */\n extensions: z.record(z.string(), AssertObjectSchema).optional()\n});\n/**\n * After receiving an initialize request from the client, the server sends this response.\n */\nexport const InitializeResultSchema = ResultSchema.extend({\n /**\n * The version of the Model Context Protocol that the server wants to use. This may not match the version that the client requested. If the client cannot support this version, it MUST disconnect.\n */\n protocolVersion: z.string(),\n capabilities: ServerCapabilitiesSchema,\n serverInfo: ImplementationSchema,\n /**\n * Instructions describing how to use the server and its features.\n *\n * This can be used by clients to improve the LLM's understanding of available tools, resources, etc. It can be thought of like a \"hint\" to the model. For example, this information MAY be added to the system prompt.\n */\n instructions: z.string().optional()\n});\n/**\n * This notification is sent from the client to the server after initialization has finished.\n */\nexport const InitializedNotificationSchema = NotificationSchema.extend({\n method: z.literal('notifications/initialized'),\n params: NotificationsParamsSchema.optional()\n});\nexport const isInitializedNotification = (value) => InitializedNotificationSchema.safeParse(value).success;\n/* Ping */\n/**\n * A ping, issued by either the server or the client, to check that the other party is still alive. The receiver must promptly respond, or else may be disconnected.\n */\nexport const PingRequestSchema = RequestSchema.extend({\n method: z.literal('ping'),\n params: BaseRequestParamsSchema.optional()\n});\n/* Progress notifications */\nexport const ProgressSchema = z.object({\n /**\n * The progress thus far. This should increase every time progress is made, even if the total is unknown.\n */\n progress: z.number(),\n /**\n * Total number of items to process (or total progress required), if known.\n */\n total: z.optional(z.number()),\n /**\n * An optional message describing the current progress.\n */\n message: z.optional(z.string())\n});\nexport const ProgressNotificationParamsSchema = z.object({\n ...NotificationsParamsSchema.shape,\n ...ProgressSchema.shape,\n /**\n * The progress token which was given in the initial request, used to associate this notification with the request that is proceeding.\n */\n progressToken: ProgressTokenSchema\n});\n/**\n * An out-of-band notification used to inform the receiver of a progress update for a long-running request.\n *\n * @category notifications/progress\n */\nexport const ProgressNotificationSchema = NotificationSchema.extend({\n method: z.literal('notifications/progress'),\n params: ProgressNotificationParamsSchema\n});\nexport const PaginatedRequestParamsSchema = BaseRequestParamsSchema.extend({\n /**\n * An opaque token representing the current pagination position.\n * If provided, the server should return results starting after this cursor.\n */\n cursor: CursorSchema.optional()\n});\n/* Pagination */\nexport const PaginatedRequestSchema = RequestSchema.extend({\n params: PaginatedRequestParamsSchema.optional()\n});\nexport const PaginatedResultSchema = ResultSchema.extend({\n /**\n * An opaque token representing the pagination position after the last returned result.\n * If present, there may be more results available.\n */\n nextCursor: CursorSchema.optional()\n});\n/**\n * The status of a task.\n * */\nexport const TaskStatusSchema = z.enum(['working', 'input_required', 'completed', 'failed', 'cancelled']);\n/* Tasks */\n/**\n * A pollable state object associated with a request.\n */\nexport const TaskSchema = z.object({\n taskId: z.string(),\n status: TaskStatusSchema,\n /**\n * Time in milliseconds to keep task results available after completion.\n * If null, the task has unlimited lifetime until manually cleaned up.\n */\n ttl: z.union([z.number(), z.null()]),\n /**\n * ISO 8601 timestamp when the task was created.\n */\n createdAt: z.string(),\n /**\n * ISO 8601 timestamp when the task was last updated.\n */\n lastUpdatedAt: z.string(),\n pollInterval: z.optional(z.number()),\n /**\n * Optional diagnostic message for failed tasks or other status information.\n */\n statusMessage: z.optional(z.string())\n});\n/**\n * Result returned when a task is created, containing the task data wrapped in a task field.\n */\nexport const CreateTaskResultSchema = ResultSchema.extend({\n task: TaskSchema\n});\n/**\n * Parameters for task status notification.\n */\nexport const TaskStatusNotificationParamsSchema = NotificationsParamsSchema.merge(TaskSchema);\n/**\n * A notification sent when a task's status changes.\n */\nexport const TaskStatusNotificationSchema = NotificationSchema.extend({\n method: z.literal('notifications/tasks/status'),\n params: TaskStatusNotificationParamsSchema\n});\n/**\n * A request to get the state of a specific task.\n */\nexport const GetTaskRequestSchema = RequestSchema.extend({\n method: z.literal('tasks/get'),\n params: BaseRequestParamsSchema.extend({\n taskId: z.string()\n })\n});\n/**\n * The response to a tasks/get request.\n */\nexport const GetTaskResultSchema = ResultSchema.merge(TaskSchema);\n/**\n * A request to get the result of a specific task.\n */\nexport const GetTaskPayloadRequestSchema = RequestSchema.extend({\n method: z.literal('tasks/result'),\n params: BaseRequestParamsSchema.extend({\n taskId: z.string()\n })\n});\n/**\n * The response to a tasks/result request.\n * The structure matches the result type of the original request.\n * For example, a tools/call task would return the CallToolResult structure.\n *\n */\nexport const GetTaskPayloadResultSchema = ResultSchema.loose();\n/**\n * A request to list tasks.\n */\nexport const ListTasksRequestSchema = PaginatedRequestSchema.extend({\n method: z.literal('tasks/list')\n});\n/**\n * The response to a tasks/list request.\n */\nexport const ListTasksResultSchema = PaginatedResultSchema.extend({\n tasks: z.array(TaskSchema)\n});\n/**\n * A request to cancel a specific task.\n */\nexport const CancelTaskRequestSchema = RequestSchema.extend({\n method: z.literal('tasks/cancel'),\n params: BaseRequestParamsSchema.extend({\n taskId: z.string()\n })\n});\n/**\n * The response to a tasks/cancel request.\n */\nexport const CancelTaskResultSchema = ResultSchema.merge(TaskSchema);\n/* Resources */\n/**\n * The contents of a specific resource or sub-resource.\n */\nexport const ResourceContentsSchema = z.object({\n /**\n * The URI of this resource.\n */\n uri: z.string(),\n /**\n * The MIME type of this resource, if known.\n */\n mimeType: z.optional(z.string()),\n /**\n * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)\n * for notes on _meta usage.\n */\n _meta: z.record(z.string(), z.unknown()).optional()\n});\nexport const TextResourceContentsSchema = ResourceContentsSchema.extend({\n /**\n * The text of the item. This must only be set if the item can actually be represented as text (not binary data).\n */\n text: z.string()\n});\n/**\n * A Zod schema for validating Base64 strings that is more performant and\n * robust for very large inputs than the default regex-based check. It avoids\n * stack overflows by using the native `atob` function for validation.\n */\nconst Base64Schema = z.string().refine(val => {\n try {\n // atob throws a DOMException if the string contains characters\n // that are not part of the Base64 character set.\n atob(val);\n return true;\n }\n catch {\n return false;\n }\n}, { message: 'Invalid Base64 string' });\nexport const BlobResourceContentsSchema = ResourceContentsSchema.extend({\n /**\n * A base64-encoded string representing the binary data of the item.\n */\n blob: Base64Schema\n});\n/**\n * The sender or recipient of messages and data in a conversation.\n */\nexport const RoleSchema = z.enum(['user', 'assistant']);\n/**\n * Optional annotations providing clients additional context about a resource.\n */\nexport const AnnotationsSchema = z.object({\n /**\n * Intended audience(s) for the resource.\n */\n audience: z.array(RoleSchema).optional(),\n /**\n * Importance hint for the resource, from 0 (least) to 1 (most).\n */\n priority: z.number().min(0).max(1).optional(),\n /**\n * ISO 8601 timestamp for the most recent modification.\n */\n lastModified: z.iso.datetime({ offset: true }).optional()\n});\n/**\n * A known resource that the server is capable of reading.\n */\nexport const ResourceSchema = z.object({\n ...BaseMetadataSchema.shape,\n ...IconsSchema.shape,\n /**\n * The URI of this resource.\n */\n uri: z.string(),\n /**\n * A description of what this resource represents.\n *\n * This can be used by clients to improve the LLM's understanding of available resources. It can be thought of like a \"hint\" to the model.\n */\n description: z.optional(z.string()),\n /**\n * The MIME type of this resource, if known.\n */\n mimeType: z.optional(z.string()),\n /**\n * The size of the raw resource content, in bytes (i.e., before base64 encoding or any tokenization), if known.\n *\n * This can be used by Hosts to display file sizes and estimate context window usage.\n */\n size: z.optional(z.number()),\n /**\n * Optional annotations for the client.\n */\n annotations: AnnotationsSchema.optional(),\n /**\n * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)\n * for notes on _meta usage.\n */\n _meta: z.optional(z.looseObject({}))\n});\n/**\n * A template description for resources available on the server.\n */\nexport const ResourceTemplateSchema = z.object({\n ...BaseMetadataSchema.shape,\n ...IconsSchema.shape,\n /**\n * A URI template (according to RFC 6570) that can be used to construct resource URIs.\n */\n uriTemplate: z.string(),\n /**\n * A description of what this template is for.\n *\n * This can be used by clients to improve the LLM's understanding of available resources. It can be thought of like a \"hint\" to the model.\n */\n description: z.optional(z.string()),\n /**\n * The MIME type for all resources that match this template. This should only be included if all resources matching this template have the same type.\n */\n mimeType: z.optional(z.string()),\n /**\n * Optional annotations for the client.\n */\n annotations: AnnotationsSchema.optional(),\n /**\n * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)\n * for notes on _meta usage.\n */\n _meta: z.optional(z.looseObject({}))\n});\n/**\n * Sent from the client to request a list of resources the server has.\n */\nexport const ListResourcesRequestSchema = PaginatedRequestSchema.extend({\n method: z.literal('resources/list')\n});\n/**\n * The server's response to a resources/list request from the client.\n */\nexport const ListResourcesResultSchema = PaginatedResultSchema.extend({\n resources: z.array(ResourceSchema)\n});\n/**\n * Sent from the client to request a list of resource templates the server has.\n */\nexport const ListResourceTemplatesRequestSchema = PaginatedRequestSchema.extend({\n method: z.literal('resources/templates/list')\n});\n/**\n * The server's response to a resources/templates/list request from the client.\n */\nexport const ListResourceTemplatesResultSchema = PaginatedResultSchema.extend({\n resourceTemplates: z.array(ResourceTemplateSchema)\n});\nexport const ResourceRequestParamsSchema = BaseRequestParamsSchema.extend({\n /**\n * The URI of the resource to read. The URI can use any protocol; it is up to the server how to interpret it.\n *\n * @format uri\n */\n uri: z.string()\n});\n/**\n * Parameters for a `resources/read` request.\n */\nexport const ReadResourceRequestParamsSchema = ResourceRequestParamsSchema;\n/**\n * Sent from the client to the server, to read a specific resource URI.\n */\nexport const ReadResourceRequestSchema = RequestSchema.extend({\n method: z.literal('resources/read'),\n params: ReadResourceRequestParamsSchema\n});\n/**\n * The server's response to a resources/read request from the client.\n */\nexport const ReadResourceResultSchema = ResultSchema.extend({\n contents: z.array(z.union([TextResourceContentsSchema, BlobResourceContentsSchema]))\n});\n/**\n * An optional notification from the server to the client, informing it that the list of resources it can read from has changed. This may be issued by servers without any previous subscription from the client.\n */\nexport const ResourceListChangedNotificationSchema = NotificationSchema.extend({\n method: z.literal('notifications/resources/list_changed'),\n params: NotificationsParamsSchema.optional()\n});\nexport const SubscribeRequestParamsSchema = ResourceRequestParamsSchema;\n/**\n * Sent from the client to request resources/updated notifications from the server whenever a particular resource changes.\n */\nexport const SubscribeRequestSchema = RequestSchema.extend({\n method: z.literal('resources/subscribe'),\n params: SubscribeRequestParamsSchema\n});\nexport const UnsubscribeRequestParamsSchema = ResourceRequestParamsSchema;\n/**\n * Sent from the client to request cancellation of resources/updated notifications from the server. This should follow a previous resources/subscribe request.\n */\nexport const UnsubscribeRequestSchema = RequestSchema.extend({\n method: z.literal('resources/unsubscribe'),\n params: UnsubscribeRequestParamsSchema\n});\n/**\n * Parameters for a `notifications/resources/updated` notification.\n */\nexport const ResourceUpdatedNotificationParamsSchema = NotificationsParamsSchema.extend({\n /**\n * The URI of the resource that has been updated. This might be a sub-resource of the one that the client actually subscribed to.\n */\n uri: z.string()\n});\n/**\n * A notification from the server to the client, informing it that a resource has changed and may need to be read again. This should only be sent if the client previously sent a resources/subscribe request.\n */\nexport const ResourceUpdatedNotificationSchema = NotificationSchema.extend({\n method: z.literal('notifications/resources/updated'),\n params: ResourceUpdatedNotificationParamsSchema\n});\n/* Prompts */\n/**\n * Describes an argument that a prompt can accept.\n */\nexport const PromptArgumentSchema = z.object({\n /**\n * The name of the argument.\n */\n name: z.string(),\n /**\n * A human-readable description of the argument.\n */\n description: z.optional(z.string()),\n /**\n * Whether this argument must be provided.\n */\n required: z.optional(z.boolean())\n});\n/**\n * A prompt or prompt template that the server offers.\n */\nexport const PromptSchema = z.object({\n ...BaseMetadataSchema.shape,\n ...IconsSchema.shape,\n /**\n * An optional description of what this prompt provides\n */\n description: z.optional(z.string()),\n /**\n * A list of arguments to use for templating the prompt.\n */\n arguments: z.optional(z.array(PromptArgumentSchema)),\n /**\n * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)\n * for notes on _meta usage.\n */\n _meta: z.optional(z.looseObject({}))\n});\n/**\n * Sent from the client to request a list of prompts and prompt templates the server has.\n */\nexport const ListPromptsRequestSchema = PaginatedRequestSchema.extend({\n method: z.literal('prompts/list')\n});\n/**\n * The server's response to a prompts/list request from the client.\n */\nexport const ListPromptsResultSchema = PaginatedResultSchema.extend({\n prompts: z.array(PromptSchema)\n});\n/**\n * Parameters for a `prompts/get` request.\n */\nexport const GetPromptRequestParamsSchema = BaseRequestParamsSchema.extend({\n /**\n * The name of the prompt or prompt template.\n */\n name: z.string(),\n /**\n * Arguments to use for templating the prompt.\n */\n arguments: z.record(z.string(), z.string()).optional()\n});\n/**\n * Used by the client to get a prompt provided by the server.\n */\nexport const GetPromptRequestSchema = RequestSchema.extend({\n method: z.literal('prompts/get'),\n params: GetPromptRequestParamsSchema\n});\n/**\n * Text provided to or from an LLM.\n */\nexport const TextContentSchema = z.object({\n type: z.literal('text'),\n /**\n * The text content of the message.\n */\n text: z.string(),\n /**\n * Optional annotations for the client.\n */\n annotations: AnnotationsSchema.optional(),\n /**\n * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)\n * for notes on _meta usage.\n */\n _meta: z.record(z.string(), z.unknown()).optional()\n});\n/**\n * An image provided to or from an LLM.\n */\nexport const ImageContentSchema = z.object({\n type: z.literal('image'),\n /**\n * The base64-encoded image data.\n */\n data: Base64Schema,\n /**\n * The MIME type of the image. Different providers may support different image types.\n */\n mimeType: z.string(),\n /**\n * Optional annotations for the client.\n */\n annotations: AnnotationsSchema.optional(),\n /**\n * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)\n * for notes on _meta usage.\n */\n _meta: z.record(z.string(), z.unknown()).optional()\n});\n/**\n * An Audio provided to or from an LLM.\n */\nexport const AudioContentSchema = z.object({\n type: z.literal('audio'),\n /**\n * The base64-encoded audio data.\n */\n data: Base64Schema,\n /**\n * The MIME type of the audio. Different providers may support different audio types.\n */\n mimeType: z.string(),\n /**\n * Optional annotations for the client.\n */\n annotations: AnnotationsSchema.optional(),\n /**\n * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)\n * for notes on _meta usage.\n */\n _meta: z.record(z.string(), z.unknown()).optional()\n});\n/**\n * A tool call request from an assistant (LLM).\n * Represents the assistant's request to use a tool.\n */\nexport const ToolUseContentSchema = z.object({\n type: z.literal('tool_use'),\n /**\n * The name of the tool to invoke.\n * Must match a tool name from the request's tools array.\n */\n name: z.string(),\n /**\n * Unique identifier for this tool call.\n * Used to correlate with ToolResultContent in subsequent messages.\n */\n id: z.string(),\n /**\n * Arguments to pass to the tool.\n * Must conform to the tool's inputSchema.\n */\n input: z.record(z.string(), z.unknown()),\n /**\n * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)\n * for notes on _meta usage.\n */\n _meta: z.record(z.string(), z.unknown()).optional()\n});\n/**\n * The contents of a resource, embedded into a prompt or tool call result.\n */\nexport const EmbeddedResourceSchema = z.object({\n type: z.literal('resource'),\n resource: z.union([TextResourceContentsSchema, BlobResourceContentsSchema]),\n /**\n * Optional annotations for the client.\n */\n annotations: AnnotationsSchema.optional(),\n /**\n * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)\n * for notes on _meta usage.\n */\n _meta: z.record(z.string(), z.unknown()).optional()\n});\n/**\n * A resource that the server is capable of reading, included in a prompt or tool call result.\n *\n * Note: resource links returned by tools are not guaranteed to appear in the results of `resources/list` requests.\n */\nexport const ResourceLinkSchema = ResourceSchema.extend({\n type: z.literal('resource_link')\n});\n/**\n * A content block that can be used in prompts and tool results.\n */\nexport const ContentBlockSchema = z.union([\n TextContentSchema,\n ImageContentSchema,\n AudioContentSchema,\n ResourceLinkSchema,\n EmbeddedResourceSchema\n]);\n/**\n * Describes a message returned as part of a prompt.\n */\nexport const PromptMessageSchema = z.object({\n role: RoleSchema,\n content: ContentBlockSchema\n});\n/**\n * The server's response to a prompts/get request from the client.\n */\nexport const GetPromptResultSchema = ResultSchema.extend({\n /**\n * An optional description for the prompt.\n */\n description: z.string().optional(),\n messages: z.array(PromptMessageSchema)\n});\n/**\n * An optional notification from the server to the client, informing it that the list of prompts it offers has changed. This may be issued by servers without any previous subscription from the client.\n */\nexport const PromptListChangedNotificationSchema = NotificationSchema.extend({\n method: z.literal('notifications/prompts/list_changed'),\n params: NotificationsParamsSchema.optional()\n});\n/* Tools */\n/**\n * Additional properties describing a Tool to clients.\n *\n * NOTE: all properties in ToolAnnotations are **hints**.\n * They are not guaranteed to provide a faithful description of\n * tool behavior (including descriptive properties like `title`).\n *\n * Clients should never make tool use decisions based on ToolAnnotations\n * received from untrusted servers.\n */\nexport const ToolAnnotationsSchema = z.object({\n /**\n * A human-readable title for the tool.\n */\n title: z.string().optional(),\n /**\n * If true, the tool does not modify its environment.\n *\n * Default: false\n */\n readOnlyHint: z.boolean().optional(),\n /**\n * If true, the tool may perform destructive updates to its environment.\n * If false, the tool performs only additive updates.\n *\n * (This property is meaningful only when `readOnlyHint == false`)\n *\n * Default: true\n */\n destructiveHint: z.boolean().optional(),\n /**\n * If true, calling the tool repeatedly with the same arguments\n * will have no additional effect on the its environment.\n *\n * (This property is meaningful only when `readOnlyHint == false`)\n *\n * Default: false\n */\n idempotentHint: z.boolean().optional(),\n /**\n * If true, this tool may interact with an \"open world\" of external\n * entities. If false, the tool's domain of interaction is closed.\n * For example, the world of a web search tool is open, whereas that\n * of a memory tool is not.\n *\n * Default: true\n */\n openWorldHint: z.boolean().optional()\n});\n/**\n * Execution-related properties for a tool.\n */\nexport const ToolExecutionSchema = z.object({\n /**\n * Indicates the tool's preference for task-augmented execution.\n * - \"required\": Clients MUST invoke the tool as a task\n * - \"optional\": Clients MAY invoke the tool as a task or normal request\n * - \"forbidden\": Clients MUST NOT attempt to invoke the tool as a task\n *\n * If not present, defaults to \"forbidden\".\n */\n taskSupport: z.enum(['required', 'optional', 'forbidden']).optional()\n});\n/**\n * Definition for a tool the client can call.\n */\nexport const ToolSchema = z.object({\n ...BaseMetadataSchema.shape,\n ...IconsSchema.shape,\n /**\n * A human-readable description of the tool.\n */\n description: z.string().optional(),\n /**\n * A JSON Schema 2020-12 object defining the expected parameters for the tool.\n * Must have type: 'object' at the root level per MCP spec.\n */\n inputSchema: z\n .object({\n type: z.literal('object'),\n properties: z.record(z.string(), AssertObjectSchema).optional(),\n required: z.array(z.string()).optional()\n })\n .catchall(z.unknown()),\n /**\n * An optional JSON Schema 2020-12 object defining the structure of the tool's output\n * returned in the structuredContent field of a CallToolResult.\n * Must have type: 'object' at the root level per MCP spec.\n */\n outputSchema: z\n .object({\n type: z.literal('object'),\n properties: z.record(z.string(), AssertObjectSchema).optional(),\n required: z.array(z.string()).optional()\n })\n .catchall(z.unknown())\n .optional(),\n /**\n * Optional additional tool information.\n */\n annotations: ToolAnnotationsSchema.optional(),\n /**\n * Execution-related properties for this tool.\n */\n execution: ToolExecutionSchema.optional(),\n /**\n * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)\n * for notes on _meta usage.\n */\n _meta: z.record(z.string(), z.unknown()).optional()\n});\n/**\n * Sent from the client to request a list of tools the server has.\n */\nexport const ListToolsRequestSchema = PaginatedRequestSchema.extend({\n method: z.literal('tools/list')\n});\n/**\n * The server's response to a tools/list request from the client.\n */\nexport const ListToolsResultSchema = PaginatedResultSchema.extend({\n tools: z.array(ToolSchema)\n});\n/**\n * The server's response to a tool call.\n */\nexport const CallToolResultSchema = ResultSchema.extend({\n /**\n * A list of content objects that represent the result of the tool call.\n *\n * If the Tool does not define an outputSchema, this field MUST be present in the result.\n * For backwards compatibility, this field is always present, but it may be empty.\n */\n content: z.array(ContentBlockSchema).default([]),\n /**\n * An object containing structured tool output.\n *\n * If the Tool defines an outputSchema, this field MUST be present in the result, and contain a JSON object that matches the schema.\n */\n structuredContent: z.record(z.string(), z.unknown()).optional(),\n /**\n * Whether the tool call ended in an error.\n *\n * If not set, this is assumed to be false (the call was successful).\n *\n * Any errors that originate from the tool SHOULD be reported inside the result\n * object, with `isError` set to true, _not_ as an MCP protocol-level error\n * response. Otherwise, the LLM would not be able to see that an error occurred\n * and self-correct.\n *\n * However, any errors in _finding_ the tool, an error indicating that the\n * server does not support tool calls, or any other exceptional conditions,\n * should be reported as an MCP error response.\n */\n isError: z.boolean().optional()\n});\n/**\n * CallToolResultSchema extended with backwards compatibility to protocol version 2024-10-07.\n */\nexport const CompatibilityCallToolResultSchema = CallToolResultSchema.or(ResultSchema.extend({\n toolResult: z.unknown()\n}));\n/**\n * Parameters for a `tools/call` request.\n */\nexport const CallToolRequestParamsSchema = TaskAugmentedRequestParamsSchema.extend({\n /**\n * The name of the tool to call.\n */\n name: z.string(),\n /**\n * Arguments to pass to the tool.\n */\n arguments: z.record(z.string(), z.unknown()).optional()\n});\n/**\n * Used by the client to invoke a tool provided by the server.\n */\nexport const CallToolRequestSchema = RequestSchema.extend({\n method: z.literal('tools/call'),\n params: CallToolRequestParamsSchema\n});\n/**\n * An optional notification from the server to the client, informing it that the list of tools it offers has changed. This may be issued by servers without any previous subscription from the client.\n */\nexport const ToolListChangedNotificationSchema = NotificationSchema.extend({\n method: z.literal('notifications/tools/list_changed'),\n params: NotificationsParamsSchema.optional()\n});\n/**\n * Base schema for list changed subscription options (without callback).\n * Used internally for Zod validation of autoRefresh and debounceMs.\n */\nexport const ListChangedOptionsBaseSchema = z.object({\n /**\n * If true, the list will be refreshed automatically when a list changed notification is received.\n * The callback will be called with the updated list.\n *\n * If false, the callback will be called with null items, allowing manual refresh.\n *\n * @default true\n */\n autoRefresh: z.boolean().default(true),\n /**\n * Debounce time in milliseconds for list changed notification processing.\n *\n * Multiple notifications received within this timeframe will only trigger one refresh.\n * Set to 0 to disable debouncing.\n *\n * @default 300\n */\n debounceMs: z.number().int().nonnegative().default(300)\n});\n/* Logging */\n/**\n * The severity of a log message.\n */\nexport const LoggingLevelSchema = z.enum(['debug', 'info', 'notice', 'warning', 'error', 'critical', 'alert', 'emergency']);\n/**\n * Parameters for a `logging/setLevel` request.\n */\nexport const SetLevelRequestParamsSchema = BaseRequestParamsSchema.extend({\n /**\n * The level of logging that the client wants to receive from the server. The server should send all logs at this level and higher (i.e., more severe) to the client as notifications/logging/message.\n */\n level: LoggingLevelSchema\n});\n/**\n * A request from the client to the server, to enable or adjust logging.\n */\nexport const SetLevelRequestSchema = RequestSchema.extend({\n method: z.literal('logging/setLevel'),\n params: SetLevelRequestParamsSchema\n});\n/**\n * Parameters for a `notifications/message` notification.\n */\nexport const LoggingMessageNotificationParamsSchema = NotificationsParamsSchema.extend({\n /**\n * The severity of this log message.\n */\n level: LoggingLevelSchema,\n /**\n * An optional name of the logger issuing this message.\n */\n logger: z.string().optional(),\n /**\n * The data to be logged, such as a string message or an object. Any JSON serializable type is allowed here.\n */\n data: z.unknown()\n});\n/**\n * Notification of a log message passed from server to client. If no logging/setLevel request has been sent from the client, the server MAY decide which messages to send automatically.\n */\nexport const LoggingMessageNotificationSchema = NotificationSchema.extend({\n method: z.literal('notifications/message'),\n params: LoggingMessageNotificationParamsSchema\n});\n/* Sampling */\n/**\n * Hints to use for model selection.\n */\nexport const ModelHintSchema = z.object({\n /**\n * A hint for a model name.\n */\n name: z.string().optional()\n});\n/**\n * The server's preferences for model selection, requested of the client during sampling.\n */\nexport const ModelPreferencesSchema = z.object({\n /**\n * Optional hints to use for model selection.\n */\n hints: z.array(ModelHintSchema).optional(),\n /**\n * How much to prioritize cost when selecting a model.\n */\n costPriority: z.number().min(0).max(1).optional(),\n /**\n * How much to prioritize sampling speed (latency) when selecting a model.\n */\n speedPriority: z.number().min(0).max(1).optional(),\n /**\n * How much to prioritize intelligence and capabilities when selecting a model.\n */\n intelligencePriority: z.number().min(0).max(1).optional()\n});\n/**\n * Controls tool usage behavior in sampling requests.\n */\nexport const ToolChoiceSchema = z.object({\n /**\n * Controls when tools are used:\n * - \"auto\": Model decides whether to use tools (default)\n * - \"required\": Model MUST use at least one tool before completing\n * - \"none\": Model MUST NOT use any tools\n */\n mode: z.enum(['auto', 'required', 'none']).optional()\n});\n/**\n * The result of a tool execution, provided by the user (server).\n * Represents the outcome of invoking a tool requested via ToolUseContent.\n */\nexport const ToolResultContentSchema = z.object({\n type: z.literal('tool_result'),\n toolUseId: z.string().describe('The unique identifier for the corresponding tool call.'),\n content: z.array(ContentBlockSchema).default([]),\n structuredContent: z.object({}).loose().optional(),\n isError: z.boolean().optional(),\n /**\n * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)\n * for notes on _meta usage.\n */\n _meta: z.record(z.string(), z.unknown()).optional()\n});\n/**\n * Basic content types for sampling responses (without tool use).\n * Used for backwards-compatible CreateMessageResult when tools are not used.\n */\nexport const SamplingContentSchema = z.discriminatedUnion('type', [TextContentSchema, ImageContentSchema, AudioContentSchema]);\n/**\n * Content block types allowed in sampling messages.\n * This includes text, image, audio, tool use requests, and tool results.\n */\nexport const SamplingMessageContentBlockSchema = z.discriminatedUnion('type', [\n TextContentSchema,\n ImageContentSchema,\n AudioContentSchema,\n ToolUseContentSchema,\n ToolResultContentSchema\n]);\n/**\n * Describes a message issued to or received from an LLM API.\n */\nexport const SamplingMessageSchema = z.object({\n role: RoleSchema,\n content: z.union([SamplingMessageContentBlockSchema, z.array(SamplingMessageContentBlockSchema)]),\n /**\n * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)\n * for notes on _meta usage.\n */\n _meta: z.record(z.string(), z.unknown()).optional()\n});\n/**\n * Parameters for a `sampling/createMessage` request.\n */\nexport const CreateMessageRequestParamsSchema = TaskAugmentedRequestParamsSchema.extend({\n messages: z.array(SamplingMessageSchema),\n /**\n * The server's preferences for which model to select. The client MAY modify or omit this request.\n */\n modelPreferences: ModelPreferencesSchema.optional(),\n /**\n * An optional system prompt the server wants to use for sampling. The client MAY modify or omit this prompt.\n */\n systemPrompt: z.string().optional(),\n /**\n * A request to include context from one or more MCP servers (including the caller), to be attached to the prompt.\n * The client MAY ignore this request.\n *\n * Default is \"none\". Values \"thisServer\" and \"allServers\" are soft-deprecated. Servers SHOULD only use these values if the client\n * declares ClientCapabilities.sampling.context. These values may be removed in future spec releases.\n */\n includeContext: z.enum(['none', 'thisServer', 'allServers']).optional(),\n temperature: z.number().optional(),\n /**\n * The requested maximum number of tokens to sample (to prevent runaway completions).\n *\n * The client MAY choose to sample fewer tokens than the requested maximum.\n */\n maxTokens: z.number().int(),\n stopSequences: z.array(z.string()).optional(),\n /**\n * Optional metadata to pass through to the LLM provider. The format of this metadata is provider-specific.\n */\n metadata: AssertObjectSchema.optional(),\n /**\n * Tools that the model may use during generation.\n * The client MUST return an error if this field is provided but ClientCapabilities.sampling.tools is not declared.\n */\n tools: z.array(ToolSchema).optional(),\n /**\n * Controls how the model uses tools.\n * The client MUST return an error if this field is provided but ClientCapabilities.sampling.tools is not declared.\n * Default is `{ mode: \"auto\" }`.\n */\n toolChoice: ToolChoiceSchema.optional()\n});\n/**\n * A request from the server to sample an LLM via the client. The client has full discretion over which model to select. The client should also inform the user before beginning sampling, to allow them to inspect the request (human in the loop) and decide whether to approve it.\n */\nexport const CreateMessageRequestSchema = RequestSchema.extend({\n method: z.literal('sampling/createMessage'),\n params: CreateMessageRequestParamsSchema\n});\n/**\n * The client's response to a sampling/create_message request from the server.\n * This is the backwards-compatible version that returns single content (no arrays).\n * Used when the request does not include tools.\n */\nexport const CreateMessageResultSchema = ResultSchema.extend({\n /**\n * The name of the model that generated the message.\n */\n model: z.string(),\n /**\n * The reason why sampling stopped, if known.\n *\n * Standard values:\n * - \"endTurn\": Natural end of the assistant's turn\n * - \"stopSequence\": A stop sequence was encountered\n * - \"maxTokens\": Maximum token limit was reached\n *\n * This field is an open string to allow for provider-specific stop reasons.\n */\n stopReason: z.optional(z.enum(['endTurn', 'stopSequence', 'maxTokens']).or(z.string())),\n role: RoleSchema,\n /**\n * Response content. Single content block (text, image, or audio).\n */\n content: SamplingContentSchema\n});\n/**\n * The client's response to a sampling/create_message request when tools were provided.\n * This version supports array content for tool use flows.\n */\nexport const CreateMessageResultWithToolsSchema = ResultSchema.extend({\n /**\n * The name of the model that generated the message.\n */\n model: z.string(),\n /**\n * The reason why sampling stopped, if known.\n *\n * Standard values:\n * - \"endTurn\": Natural end of the assistant's turn\n * - \"stopSequence\": A stop sequence was encountered\n * - \"maxTokens\": Maximum token limit was reached\n * - \"toolUse\": The model wants to use one or more tools\n *\n * This field is an open string to allow for provider-specific stop reasons.\n */\n stopReason: z.optional(z.enum(['endTurn', 'stopSequence', 'maxTokens', 'toolUse']).or(z.string())),\n role: RoleSchema,\n /**\n * Response content. May be a single block or array. May include ToolUseContent if stopReason is \"toolUse\".\n */\n content: z.union([SamplingMessageContentBlockSchema, z.array(SamplingMessageContentBlockSchema)])\n});\n/* Elicitation */\n/**\n * Primitive schema definition for boolean fields.\n */\nexport const BooleanSchemaSchema = z.object({\n type: z.literal('boolean'),\n title: z.string().optional(),\n description: z.string().optional(),\n default: z.boolean().optional()\n});\n/**\n * Primitive schema definition for string fields.\n */\nexport const StringSchemaSchema = z.object({\n type: z.literal('string'),\n title: z.string().optional(),\n description: z.string().optional(),\n minLength: z.number().optional(),\n maxLength: z.number().optional(),\n format: z.enum(['email', 'uri', 'date', 'date-time']).optional(),\n default: z.string().optional()\n});\n/**\n * Primitive schema definition for number fields.\n */\nexport const NumberSchemaSchema = z.object({\n type: z.enum(['number', 'integer']),\n title: z.string().optional(),\n description: z.string().optional(),\n minimum: z.number().optional(),\n maximum: z.number().optional(),\n default: z.number().optional()\n});\n/**\n * Schema for single-selection enumeration without display titles for options.\n */\nexport const UntitledSingleSelectEnumSchemaSchema = z.object({\n type: z.literal('string'),\n title: z.string().optional(),\n description: z.string().optional(),\n enum: z.array(z.string()),\n default: z.string().optional()\n});\n/**\n * Schema for single-selection enumeration with display titles for each option.\n */\nexport const TitledSingleSelectEnumSchemaSchema = z.object({\n type: z.literal('string'),\n title: z.string().optional(),\n description: z.string().optional(),\n oneOf: z.array(z.object({\n const: z.string(),\n title: z.string()\n })),\n default: z.string().optional()\n});\n/**\n * Use TitledSingleSelectEnumSchema instead.\n * This interface will be removed in a future version.\n */\nexport const LegacyTitledEnumSchemaSchema = z.object({\n type: z.literal('string'),\n title: z.string().optional(),\n description: z.string().optional(),\n enum: z.array(z.string()),\n enumNames: z.array(z.string()).optional(),\n default: z.string().optional()\n});\n// Combined single selection enumeration\nexport const SingleSelectEnumSchemaSchema = z.union([UntitledSingleSelectEnumSchemaSchema, TitledSingleSelectEnumSchemaSchema]);\n/**\n * Schema for multiple-selection enumeration without display titles for options.\n */\nexport const UntitledMultiSelectEnumSchemaSchema = z.object({\n type: z.literal('array'),\n title: z.string().optional(),\n description: z.string().optional(),\n minItems: z.number().optional(),\n maxItems: z.number().optional(),\n items: z.object({\n type: z.literal('string'),\n enum: z.array(z.string())\n }),\n default: z.array(z.string()).optional()\n});\n/**\n * Schema for multiple-selection enumeration with display titles for each option.\n */\nexport const TitledMultiSelectEnumSchemaSchema = z.object({\n type: z.literal('array'),\n title: z.string().optional(),\n description: z.string().optional(),\n minItems: z.number().optional(),\n maxItems: z.number().optional(),\n items: z.object({\n anyOf: z.array(z.object({\n const: z.string(),\n title: z.string()\n }))\n }),\n default: z.array(z.string()).optional()\n});\n/**\n * Combined schema for multiple-selection enumeration\n */\nexport const MultiSelectEnumSchemaSchema = z.union([UntitledMultiSelectEnumSchemaSchema, TitledMultiSelectEnumSchemaSchema]);\n/**\n * Primitive schema definition for enum fields.\n */\nexport const EnumSchemaSchema = z.union([LegacyTitledEnumSchemaSchema, SingleSelectEnumSchemaSchema, MultiSelectEnumSchemaSchema]);\n/**\n * Union of all primitive schema definitions.\n */\nexport const PrimitiveSchemaDefinitionSchema = z.union([EnumSchemaSchema, BooleanSchemaSchema, StringSchemaSchema, NumberSchemaSchema]);\n/**\n * Parameters for an `elicitation/create` request for form-based elicitation.\n */\nexport const ElicitRequestFormParamsSchema = TaskAugmentedRequestParamsSchema.extend({\n /**\n * The elicitation mode.\n *\n * Optional for backward compatibility. Clients MUST treat missing mode as \"form\".\n */\n mode: z.literal('form').optional(),\n /**\n * The message to present to the user describing what information is being requested.\n */\n message: z.string(),\n /**\n * A restricted subset of JSON Schema.\n * Only top-level properties are allowed, without nesting.\n */\n requestedSchema: z.object({\n type: z.literal('object'),\n properties: z.record(z.string(), PrimitiveSchemaDefinitionSchema),\n required: z.array(z.string()).optional()\n })\n});\n/**\n * Parameters for an `elicitation/create` request for URL-based elicitation.\n */\nexport const ElicitRequestURLParamsSchema = TaskAugmentedRequestParamsSchema.extend({\n /**\n * The elicitation mode.\n */\n mode: z.literal('url'),\n /**\n * The message to present to the user explaining why the interaction is needed.\n */\n message: z.string(),\n /**\n * The ID of the elicitation, which must be unique within the context of the server.\n * The client MUST treat this ID as an opaque value.\n */\n elicitationId: z.string(),\n /**\n * The URL that the user should navigate to.\n */\n url: z.string().url()\n});\n/**\n * The parameters for a request to elicit additional information from the user via the client.\n */\nexport const ElicitRequestParamsSchema = z.union([ElicitRequestFormParamsSchema, ElicitRequestURLParamsSchema]);\n/**\n * A request from the server to elicit user input via the client.\n * The client should present the message and form fields to the user (form mode)\n * or navigate to a URL (URL mode).\n */\nexport const ElicitRequestSchema = RequestSchema.extend({\n method: z.literal('elicitation/create'),\n params: ElicitRequestParamsSchema\n});\n/**\n * Parameters for a `notifications/elicitation/complete` notification.\n *\n * @category notifications/elicitation/complete\n */\nexport const ElicitationCompleteNotificationParamsSchema = NotificationsParamsSchema.extend({\n /**\n * The ID of the elicitation that completed.\n */\n elicitationId: z.string()\n});\n/**\n * A notification from the server to the client, informing it of a completion of an out-of-band elicitation request.\n *\n * @category notifications/elicitation/complete\n */\nexport const ElicitationCompleteNotificationSchema = NotificationSchema.extend({\n method: z.literal('notifications/elicitation/complete'),\n params: ElicitationCompleteNotificationParamsSchema\n});\n/**\n * The client's response to an elicitation/create request from the server.\n */\nexport const ElicitResultSchema = ResultSchema.extend({\n /**\n * The user action in response to the elicitation.\n * - \"accept\": User submitted the form/confirmed the action\n * - \"decline\": User explicitly decline the action\n * - \"cancel\": User dismissed without making an explicit choice\n */\n action: z.enum(['accept', 'decline', 'cancel']),\n /**\n * The submitted form data, only present when action is \"accept\".\n * Contains values matching the requested schema.\n * Per MCP spec, content is \"typically omitted\" for decline/cancel actions.\n * We normalize null to undefined for leniency while maintaining type compatibility.\n */\n content: z.preprocess(val => (val === null ? undefined : val), z.record(z.string(), z.union([z.string(), z.number(), z.boolean(), z.array(z.string())])).optional())\n});\n/* Autocomplete */\n/**\n * A reference to a resource or resource template definition.\n */\nexport const ResourceTemplateReferenceSchema = z.object({\n type: z.literal('ref/resource'),\n /**\n * The URI or URI template of the resource.\n */\n uri: z.string()\n});\n/**\n * @deprecated Use ResourceTemplateReferenceSchema instead\n */\nexport const ResourceReferenceSchema = ResourceTemplateReferenceSchema;\n/**\n * Identifies a prompt.\n */\nexport const PromptReferenceSchema = z.object({\n type: z.literal('ref/prompt'),\n /**\n * The name of the prompt or prompt template\n */\n name: z.string()\n});\n/**\n * Parameters for a `completion/complete` request.\n */\nexport const CompleteRequestParamsSchema = BaseRequestParamsSchema.extend({\n ref: z.union([PromptReferenceSchema, ResourceTemplateReferenceSchema]),\n /**\n * The argument's information\n */\n argument: z.object({\n /**\n * The name of the argument\n */\n name: z.string(),\n /**\n * The value of the argument to use for completion matching.\n */\n value: z.string()\n }),\n context: z\n .object({\n /**\n * Previously-resolved variables in a URI template or prompt.\n */\n arguments: z.record(z.string(), z.string()).optional()\n })\n .optional()\n});\n/**\n * A request from the client to the server, to ask for completion options.\n */\nexport const CompleteRequestSchema = RequestSchema.extend({\n method: z.literal('completion/complete'),\n params: CompleteRequestParamsSchema\n});\nexport function assertCompleteRequestPrompt(request) {\n if (request.params.ref.type !== 'ref/prompt') {\n throw new TypeError(`Expected CompleteRequestPrompt, but got ${request.params.ref.type}`);\n }\n void request;\n}\nexport function assertCompleteRequestResourceTemplate(request) {\n if (request.params.ref.type !== 'ref/resource') {\n throw new TypeError(`Expected CompleteRequestResourceTemplate, but got ${request.params.ref.type}`);\n }\n void request;\n}\n/**\n * The server's response to a completion/complete request\n */\nexport const CompleteResultSchema = ResultSchema.extend({\n completion: z.looseObject({\n /**\n * An array of completion values. Must not exceed 100 items.\n */\n values: z.array(z.string()).max(100),\n /**\n * The total number of completion options available. This can exceed the number of values actually sent in the response.\n */\n total: z.optional(z.number().int()),\n /**\n * Indicates whether there are additional completion options beyond those provided in the current response, even if the exact total is unknown.\n */\n hasMore: z.optional(z.boolean())\n })\n});\n/* Roots */\n/**\n * Represents a root directory or file that the server can operate on.\n */\nexport const RootSchema = z.object({\n /**\n * The URI identifying the root. This *must* start with file:// for now.\n */\n uri: z.string().startsWith('file://'),\n /**\n * An optional name for the root.\n */\n name: z.string().optional(),\n /**\n * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)\n * for notes on _meta usage.\n */\n _meta: z.record(z.string(), z.unknown()).optional()\n});\n/**\n * Sent from the server to request a list of root URIs from the client.\n */\nexport const ListRootsRequestSchema = RequestSchema.extend({\n method: z.literal('roots/list'),\n params: BaseRequestParamsSchema.optional()\n});\n/**\n * The client's response to a roots/list request from the server.\n */\nexport const ListRootsResultSchema = ResultSchema.extend({\n roots: z.array(RootSchema)\n});\n/**\n * A notification from the client to the server, informing it that the list of roots has changed.\n */\nexport const RootsListChangedNotificationSchema = NotificationSchema.extend({\n method: z.literal('notifications/roots/list_changed'),\n params: NotificationsParamsSchema.optional()\n});\n/* Client messages */\nexport const ClientRequestSchema = z.union([\n PingRequestSchema,\n InitializeRequestSchema,\n CompleteRequestSchema,\n SetLevelRequestSchema,\n GetPromptRequestSchema,\n ListPromptsRequestSchema,\n ListResourcesRequestSchema,\n ListResourceTemplatesRequestSchema,\n ReadResourceRequestSchema,\n SubscribeRequestSchema,\n UnsubscribeRequestSchema,\n CallToolRequestSchema,\n ListToolsRequestSchema,\n GetTaskRequestSchema,\n GetTaskPayloadRequestSchema,\n ListTasksRequestSchema,\n CancelTaskRequestSchema\n]);\nexport const ClientNotificationSchema = z.union([\n CancelledNotificationSchema,\n ProgressNotificationSchema,\n InitializedNotificationSchema,\n RootsListChangedNotificationSchema,\n TaskStatusNotificationSchema\n]);\nexport const ClientResultSchema = z.union([\n EmptyResultSchema,\n CreateMessageResultSchema,\n CreateMessageResultWithToolsSchema,\n ElicitResultSchema,\n ListRootsResultSchema,\n GetTaskResultSchema,\n ListTasksResultSchema,\n CreateTaskResultSchema\n]);\n/* Server messages */\nexport const ServerRequestSchema = z.union([\n PingRequestSchema,\n CreateMessageRequestSchema,\n ElicitRequestSchema,\n ListRootsRequestSchema,\n GetTaskRequestSchema,\n GetTaskPayloadRequestSchema,\n ListTasksRequestSchema,\n CancelTaskRequestSchema\n]);\nexport const ServerNotificationSchema = z.union([\n CancelledNotificationSchema,\n ProgressNotificationSchema,\n LoggingMessageNotificationSchema,\n ResourceUpdatedNotificationSchema,\n ResourceListChangedNotificationSchema,\n ToolListChangedNotificationSchema,\n PromptListChangedNotificationSchema,\n TaskStatusNotificationSchema,\n ElicitationCompleteNotificationSchema\n]);\nexport const ServerResultSchema = z.union([\n EmptyResultSchema,\n InitializeResultSchema,\n CompleteResultSchema,\n GetPromptResultSchema,\n ListPromptsResultSchema,\n ListResourcesResultSchema,\n ListResourceTemplatesResultSchema,\n ReadResourceResultSchema,\n CallToolResultSchema,\n ListToolsResultSchema,\n GetTaskResultSchema,\n ListTasksResultSchema,\n CreateTaskResultSchema\n]);\nexport class McpError extends Error {\n constructor(code, message, data) {\n super(`MCP error ${code}: ${message}`);\n this.code = code;\n this.data = data;\n this.name = 'McpError';\n }\n /**\n * Factory method to create the appropriate error type based on the error code and data\n */\n static fromError(code, message, data) {\n // Check for specific error types\n if (code === ErrorCode.UrlElicitationRequired && data) {\n const errorData = data;\n if (errorData.elicitations) {\n return new UrlElicitationRequiredError(errorData.elicitations, message);\n }\n }\n // Default to generic McpError\n return new McpError(code, message, data);\n }\n}\n/**\n * Specialized error type when a tool requires a URL mode elicitation.\n * This makes it nicer for the client to handle since there is specific data to work with instead of just a code to check against.\n */\nexport class UrlElicitationRequiredError extends McpError {\n constructor(elicitations, message = `URL elicitation${elicitations.length > 1 ? 's' : ''} required`) {\n super(ErrorCode.UrlElicitationRequired, message, {\n elicitations: elicitations\n });\n }\n get elicitations() {\n return this.data?.elicitations ?? [];\n }\n}\n//# sourceMappingURL=types.js.map","// zod-compat.ts\n// ----------------------------------------------------\n// Unified types + helpers to accept Zod v3 and v4 (Mini)\n// ----------------------------------------------------\nimport * as z3rt from 'zod/v3';\nimport * as z4mini from 'zod/v4-mini';\n// --- Runtime detection ---\nexport function isZ4Schema(s) {\n // Present on Zod 4 (Classic & Mini) schemas; absent on Zod 3\n const schema = s;\n return !!schema._zod;\n}\n// --- Schema construction ---\nexport function objectFromShape(shape) {\n const values = Object.values(shape);\n if (values.length === 0)\n return z4mini.object({}); // default to v4 Mini\n const allV4 = values.every(isZ4Schema);\n const allV3 = values.every(s => !isZ4Schema(s));\n if (allV4)\n return z4mini.object(shape);\n if (allV3)\n return z3rt.object(shape);\n throw new Error('Mixed Zod versions detected in object shape.');\n}\n// --- Unified parsing ---\nexport function safeParse(schema, data) {\n if (isZ4Schema(schema)) {\n // Mini exposes top-level safeParse\n const result = z4mini.safeParse(schema, data);\n return result;\n }\n const v3Schema = schema;\n const result = v3Schema.safeParse(data);\n return result;\n}\nexport async function safeParseAsync(schema, data) {\n if (isZ4Schema(schema)) {\n // Mini exposes top-level safeParseAsync\n const result = await z4mini.safeParseAsync(schema, data);\n return result;\n }\n const v3Schema = schema;\n const result = await v3Schema.safeParseAsync(data);\n return result;\n}\n// --- Shape extraction ---\nexport function getObjectShape(schema) {\n if (!schema)\n return undefined;\n // Zod v3 exposes `.shape`; Zod v4 keeps the shape on `_zod.def.shape`\n let rawShape;\n if (isZ4Schema(schema)) {\n const v4Schema = schema;\n rawShape = v4Schema._zod?.def?.shape;\n }\n else {\n const v3Schema = schema;\n rawShape = v3Schema.shape;\n }\n if (!rawShape)\n return undefined;\n if (typeof rawShape === 'function') {\n try {\n return rawShape();\n }\n catch {\n return undefined;\n }\n }\n return rawShape;\n}\n// --- Schema normalization ---\n/**\n * Normalizes a schema to an object schema. Handles both:\n * - Already-constructed object schemas (v3 or v4)\n * - Raw shapes that need to be wrapped into object schemas\n */\nexport function normalizeObjectSchema(schema) {\n if (!schema)\n return undefined;\n // First check if it's a raw shape (Record<string, AnySchema>)\n // Raw shapes don't have _def or _zod properties and aren't schemas themselves\n if (typeof schema === 'object') {\n // Check if it's actually a ZodRawShapeCompat (not a schema instance)\n // by checking if it lacks schema-like internal properties\n const asV3 = schema;\n const asV4 = schema;\n // If it's not a schema instance (no _def or _zod), it might be a raw shape\n if (!asV3._def && !asV4._zod) {\n // Check if all values are schemas (heuristic to confirm it's a raw shape)\n const values = Object.values(schema);\n if (values.length > 0 &&\n values.every(v => typeof v === 'object' &&\n v !== null &&\n (v._def !== undefined ||\n v._zod !== undefined ||\n typeof v.parse === 'function'))) {\n return objectFromShape(schema);\n }\n }\n }\n // If we get here, it should be an AnySchema (not a raw shape)\n // Check if it's already an object schema\n if (isZ4Schema(schema)) {\n // Check if it's a v4 object\n const v4Schema = schema;\n const def = v4Schema._zod?.def;\n if (def && (def.type === 'object' || def.shape !== undefined)) {\n return schema;\n }\n }\n else {\n // Check if it's a v3 object\n const v3Schema = schema;\n if (v3Schema.shape !== undefined) {\n return schema;\n }\n }\n return undefined;\n}\n// --- Error message extraction ---\n/**\n * Safely extracts an error message from a parse result error.\n * Zod errors can have different structures, so we handle various cases.\n */\nexport function getParseErrorMessage(error) {\n if (error && typeof error === 'object') {\n // Try common error structures\n if ('message' in error && typeof error.message === 'string') {\n return error.message;\n }\n if ('issues' in error && Array.isArray(error.issues) && error.issues.length > 0) {\n const firstIssue = error.issues[0];\n if (firstIssue && typeof firstIssue === 'object' && 'message' in firstIssue) {\n return String(firstIssue.message);\n }\n }\n // Fallback: try to stringify the error\n try {\n return JSON.stringify(error);\n }\n catch {\n return String(error);\n }\n }\n return String(error);\n}\n// --- Schema metadata access ---\n/**\n * Gets the description from a schema, if available.\n * Works with both Zod v3 and v4.\n *\n * Both versions expose a `.description` getter that returns the description\n * from their respective internal storage (v3: _def, v4: globalRegistry).\n */\nexport function getSchemaDescription(schema) {\n return schema.description;\n}\n/**\n * Checks if a schema is optional.\n * Works with both Zod v3 and v4.\n */\nexport function isSchemaOptional(schema) {\n if (isZ4Schema(schema)) {\n const v4Schema = schema;\n return v4Schema._zod?.def?.type === 'optional';\n }\n const v3Schema = schema;\n // v3 has isOptional() method\n if (typeof schema.isOptional === 'function') {\n return schema.isOptional();\n }\n return v3Schema._def?.typeName === 'ZodOptional';\n}\n/**\n * Gets the literal value from a schema, if it's a literal schema.\n * Works with both Zod v3 and v4.\n * Returns undefined if the schema is not a literal or the value cannot be determined.\n */\nexport function getLiteralValue(schema) {\n if (isZ4Schema(schema)) {\n const v4Schema = schema;\n const def = v4Schema._zod?.def;\n if (def) {\n // Try various ways to get the literal value\n if (def.value !== undefined)\n return def.value;\n if (Array.isArray(def.values) && def.values.length > 0) {\n return def.values[0];\n }\n }\n }\n const v3Schema = schema;\n const def = v3Schema._def;\n if (def) {\n if (def.value !== undefined)\n return def.value;\n if (Array.isArray(def.values) && def.values.length > 0) {\n return def.values[0];\n }\n }\n // Fallback: check for direct value property (some Zod versions)\n const directValue = schema.value;\n if (directValue !== undefined)\n return directValue;\n return undefined;\n}\n//# sourceMappingURL=zod-compat.js.map","/**\n * Experimental task interfaces for MCP SDK.\n * WARNING: These APIs are experimental and may change without notice.\n */\n/**\n * Checks if a task status represents a terminal state.\n * Terminal states are those where the task has finished and will not change.\n *\n * @param status - The task status to check\n * @returns True if the status is terminal (completed, failed, or cancelled)\n * @experimental\n */\nexport function isTerminal(status) {\n return status === 'completed' || status === 'failed' || status === 'cancelled';\n}\n//# sourceMappingURL=interfaces.js.map","import { setResponseValueAndErrors } from \"../errorMessages.js\";\nlet emojiRegex = undefined;\n/**\n * Generated from the regular expressions found here as of 2024-05-22:\n * https://github.com/colinhacks/zod/blob/master/src/types.ts.\n *\n * Expressions with /i flag have been changed accordingly.\n */\nexport const zodPatterns = {\n /**\n * `c` was changed to `[cC]` to replicate /i flag\n */\n cuid: /^[cC][^\\s-]{8,}$/,\n cuid2: /^[0-9a-z]+$/,\n ulid: /^[0-9A-HJKMNP-TV-Z]{26}$/,\n /**\n * `a-z` was added to replicate /i flag\n */\n email: /^(?!\\.)(?!.*\\.\\.)([a-zA-Z0-9_'+\\-\\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\\-]*\\.)+[a-zA-Z]{2,}$/,\n /**\n * Constructed a valid Unicode RegExp\n *\n * Lazily instantiate since this type of regex isn't supported\n * in all envs (e.g. React Native).\n *\n * See:\n * https://github.com/colinhacks/zod/issues/2433\n * Fix in Zod:\n * https://github.com/colinhacks/zod/commit/9340fd51e48576a75adc919bff65dbc4a5d4c99b\n */\n emoji: () => {\n if (emojiRegex === undefined) {\n emojiRegex = RegExp(\"^(\\\\p{Extended_Pictographic}|\\\\p{Emoji_Component})+$\", \"u\");\n }\n return emojiRegex;\n },\n /**\n * Unused\n */\n uuid: /^[0-9a-fA-F]{8}\\b-[0-9a-fA-F]{4}\\b-[0-9a-fA-F]{4}\\b-[0-9a-fA-F]{4}\\b-[0-9a-fA-F]{12}$/,\n /**\n * Unused\n */\n ipv4: /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,\n ipv4Cidr: /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\/(3[0-2]|[12]?[0-9])$/,\n /**\n * Unused\n */\n ipv6: /^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,\n ipv6Cidr: /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,\n base64: /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,\n base64url: /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,\n nanoid: /^[a-zA-Z0-9_-]{21}$/,\n jwt: /^[A-Za-z0-9-_]+\\.[A-Za-z0-9-_]+\\.[A-Za-z0-9-_]*$/,\n};\nexport function parseStringDef(def, refs) {\n const res = {\n type: \"string\",\n };\n if (def.checks) {\n for (const check of def.checks) {\n switch (check.kind) {\n case \"min\":\n setResponseValueAndErrors(res, \"minLength\", typeof res.minLength === \"number\"\n ? Math.max(res.minLength, check.value)\n : check.value, check.message, refs);\n break;\n case \"max\":\n setResponseValueAndErrors(res, \"maxLength\", typeof res.maxLength === \"number\"\n ? Math.min(res.maxLength, check.value)\n : check.value, check.message, refs);\n break;\n case \"email\":\n switch (refs.emailStrategy) {\n case \"format:email\":\n addFormat(res, \"email\", check.message, refs);\n break;\n case \"format:idn-email\":\n addFormat(res, \"idn-email\", check.message, refs);\n break;\n case \"pattern:zod\":\n addPattern(res, zodPatterns.email, check.message, refs);\n break;\n }\n break;\n case \"url\":\n addFormat(res, \"uri\", check.message, refs);\n break;\n case \"uuid\":\n addFormat(res, \"uuid\", check.message, refs);\n break;\n case \"regex\":\n addPattern(res, check.regex, check.message, refs);\n break;\n case \"cuid\":\n addPattern(res, zodPatterns.cuid, check.message, refs);\n break;\n case \"cuid2\":\n addPattern(res, zodPatterns.cuid2, check.message, refs);\n break;\n case \"startsWith\":\n addPattern(res, RegExp(`^${escapeLiteralCheckValue(check.value, refs)}`), check.message, refs);\n break;\n case \"endsWith\":\n addPattern(res, RegExp(`${escapeLiteralCheckValue(check.value, refs)}$`), check.message, refs);\n break;\n case \"datetime\":\n addFormat(res, \"date-time\", check.message, refs);\n break;\n case \"date\":\n addFormat(res, \"date\", check.message, refs);\n break;\n case \"time\":\n addFormat(res, \"time\", check.message, refs);\n break;\n case \"duration\":\n addFormat(res, \"duration\", check.message, refs);\n break;\n case \"length\":\n setResponseValueAndErrors(res, \"minLength\", typeof res.minLength === \"number\"\n ? Math.max(res.minLength, check.value)\n : check.value, check.message, refs);\n setResponseValueAndErrors(res, \"maxLength\", typeof res.maxLength === \"number\"\n ? Math.min(res.maxLength, check.value)\n : check.value, check.message, refs);\n break;\n case \"includes\": {\n addPattern(res, RegExp(escapeLiteralCheckValue(check.value, refs)), check.message, refs);\n break;\n }\n case \"ip\": {\n if (check.version !== \"v6\") {\n addFormat(res, \"ipv4\", check.message, refs);\n }\n if (check.version !== \"v4\") {\n addFormat(res, \"ipv6\", check.message, refs);\n }\n break;\n }\n case \"base64url\":\n addPattern(res, zodPatterns.base64url, check.message, refs);\n break;\n case \"jwt\":\n addPattern(res, zodPatterns.jwt, check.message, refs);\n break;\n case \"cidr\": {\n if (check.version !== \"v6\") {\n addPattern(res, zodPatterns.ipv4Cidr, check.message, refs);\n }\n if (check.version !== \"v4\") {\n addPattern(res, zodPatterns.ipv6Cidr, check.message, refs);\n }\n break;\n }\n case \"emoji\":\n addPattern(res, zodPatterns.emoji(), check.message, refs);\n break;\n case \"ulid\": {\n addPattern(res, zodPatterns.ulid, check.message, refs);\n break;\n }\n case \"base64\": {\n switch (refs.base64Strategy) {\n case \"format:binary\": {\n addFormat(res, \"binary\", check.message, refs);\n break;\n }\n case \"contentEncoding:base64\": {\n setResponseValueAndErrors(res, \"contentEncoding\", \"base64\", check.message, refs);\n break;\n }\n case \"pattern:zod\": {\n addPattern(res, zodPatterns.base64, check.message, refs);\n break;\n }\n }\n break;\n }\n case \"nanoid\": {\n addPattern(res, zodPatterns.nanoid, check.message, refs);\n }\n case \"toLowerCase\":\n case \"toUpperCase\":\n case \"trim\":\n break;\n default:\n ((_) => { })(check);\n }\n }\n }\n return res;\n}\nfunction escapeLiteralCheckValue(literal, refs) {\n return refs.patternStrategy === \"escape\"\n ? escapeNonAlphaNumeric(literal)\n : literal;\n}\nconst ALPHA_NUMERIC = new Set(\"ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789\");\nfunction escapeNonAlphaNumeric(source) {\n let result = \"\";\n for (let i = 0; i < source.length; i++) {\n if (!ALPHA_NUMERIC.has(source[i])) {\n result += \"\\\\\";\n }\n result += source[i];\n }\n return result;\n}\n// Adds a \"format\" keyword to the schema. If a format exists, both formats will be joined in an allOf-node, along with subsequent ones.\nfunction addFormat(schema, value, message, refs) {\n if (schema.format || schema.anyOf?.some((x) => x.format)) {\n if (!schema.anyOf) {\n schema.anyOf = [];\n }\n if (schema.format) {\n schema.anyOf.push({\n format: schema.format,\n ...(schema.errorMessage &&\n refs.errorMessages && {\n errorMessage: { format: schema.errorMessage.format },\n }),\n });\n delete schema.format;\n if (schema.errorMessage) {\n delete schema.errorMessage.format;\n if (Object.keys(schema.errorMessage).length === 0) {\n delete schema.errorMessage;\n }\n }\n }\n schema.anyOf.push({\n format: value,\n ...(message &&\n refs.errorMessages && { errorMessage: { format: message } }),\n });\n }\n else {\n setResponseValueAndErrors(schema, \"format\", value, message, refs);\n }\n}\n// Adds a \"pattern\" keyword to the schema. If a pattern exists, both patterns will be joined in an allOf-node, along with subsequent ones.\nfunction addPattern(schema, regex, message, refs) {\n if (schema.pattern || schema.allOf?.some((x) => x.pattern)) {\n if (!schema.allOf) {\n schema.allOf = [];\n }\n if (schema.pattern) {\n schema.allOf.push({\n pattern: schema.pattern,\n ...(schema.errorMessage &&\n refs.errorMessages && {\n errorMessage: { pattern: schema.errorMessage.pattern },\n }),\n });\n delete schema.pattern;\n if (schema.errorMessage) {\n delete schema.errorMessage.pattern;\n if (Object.keys(schema.errorMessage).length === 0) {\n delete schema.errorMessage;\n }\n }\n }\n schema.allOf.push({\n pattern: stringifyRegExpWithFlags(regex, refs),\n ...(message &&\n refs.errorMessages && { errorMessage: { pattern: message } }),\n });\n }\n else {\n setResponseValueAndErrors(schema, \"pattern\", stringifyRegExpWithFlags(regex, refs), message, refs);\n }\n}\n// Mutate z.string.regex() in a best attempt to accommodate for regex flags when applyRegexFlags is true\nfunction stringifyRegExpWithFlags(regex, refs) {\n if (!refs.applyRegexFlags || !regex.flags) {\n return regex.source;\n }\n // Currently handled flags\n const flags = {\n i: regex.flags.includes(\"i\"),\n m: regex.flags.includes(\"m\"),\n s: regex.flags.includes(\"s\"), // `.` matches newlines\n };\n // The general principle here is to step through each character, one at a time, applying mutations as flags require. We keep track when the current character is escaped, and when it's inside a group /like [this]/ or (also) a range like /[a-z]/. The following is fairly brittle imperative code; edit at your peril!\n const source = flags.i ? regex.source.toLowerCase() : regex.source;\n let pattern = \"\";\n let isEscaped = false;\n let inCharGroup = false;\n let inCharRange = false;\n for (let i = 0; i < source.length; i++) {\n if (isEscaped) {\n pattern += source[i];\n isEscaped = false;\n continue;\n }\n if (flags.i) {\n if (inCharGroup) {\n if (source[i].match(/[a-z]/)) {\n if (inCharRange) {\n pattern += source[i];\n pattern += `${source[i - 2]}-${source[i]}`.toUpperCase();\n inCharRange = false;\n }\n else if (source[i + 1] === \"-\" && source[i + 2]?.match(/[a-z]/)) {\n pattern += source[i];\n inCharRange = true;\n }\n else {\n pattern += `${source[i]}${source[i].toUpperCase()}`;\n }\n continue;\n }\n }\n else if (source[i].match(/[a-z]/)) {\n pattern += `[${source[i]}${source[i].toUpperCase()}]`;\n continue;\n }\n }\n if (flags.m) {\n if (source[i] === \"^\") {\n pattern += `(^|(?<=[\\r\\n]))`;\n continue;\n }\n else if (source[i] === \"$\") {\n pattern += `($|(?=[\\r\\n]))`;\n continue;\n }\n }\n if (flags.s && source[i] === \".\") {\n pattern += inCharGroup ? `${source[i]}\\r\\n` : `[${source[i]}\\r\\n]`;\n continue;\n }\n pattern += source[i];\n if (source[i] === \"\\\\\") {\n isEscaped = true;\n }\n else if (inCharGroup && source[i] === \"]\") {\n inCharGroup = false;\n }\n else if (!inCharGroup && source[i] === \"[\") {\n inCharGroup = true;\n }\n }\n try {\n new RegExp(pattern);\n }\n catch {\n console.warn(`Could not convert regex pattern at ${refs.currentPath.join(\"/\")} to a flag-independent form! Falling back to the flag-ignorant source`);\n return regex.source;\n }\n return pattern;\n}\n","// zod-json-schema-compat.ts\n// ----------------------------------------------------\n// JSON Schema conversion for both Zod v3 and Zod v4 (Mini)\n// v3 uses your vendored converter; v4 uses Mini's toJSONSchema\n// ----------------------------------------------------\nimport * as z4mini from 'zod/v4-mini';\nimport { getObjectShape, safeParse, isZ4Schema, getLiteralValue } from './zod-compat.js';\nimport { zodToJsonSchema } from 'zod-to-json-schema';\nfunction mapMiniTarget(t) {\n if (!t)\n return 'draft-7';\n if (t === 'jsonSchema7' || t === 'draft-7')\n return 'draft-7';\n if (t === 'jsonSchema2019-09' || t === 'draft-2020-12')\n return 'draft-2020-12';\n return 'draft-7'; // fallback\n}\nexport function toJsonSchemaCompat(schema, opts) {\n if (isZ4Schema(schema)) {\n // v4 branch — use Mini's built-in toJSONSchema\n return z4mini.toJSONSchema(schema, {\n target: mapMiniTarget(opts?.target),\n io: opts?.pipeStrategy ?? 'input'\n });\n }\n // v3 branch — use vendored converter\n return zodToJsonSchema(schema, {\n strictUnions: opts?.strictUnions ?? true,\n pipeStrategy: opts?.pipeStrategy ?? 'input'\n });\n}\nexport function getMethodLiteral(schema) {\n const shape = getObjectShape(schema);\n const methodSchema = shape?.method;\n if (!methodSchema) {\n throw new Error('Schema is missing a method literal');\n }\n const value = getLiteralValue(methodSchema);\n if (typeof value !== 'string') {\n throw new Error('Schema method literal must be a string');\n }\n return value;\n}\nexport function parseWithCompat(schema, data) {\n const result = safeParse(schema, data);\n if (!result.success) {\n throw result.error;\n }\n return result.data;\n}\n//# sourceMappingURL=zod-json-schema-compat.js.map","import { safeParse } from '../server/zod-compat.js';\nimport { CancelledNotificationSchema, CreateTaskResultSchema, ErrorCode, GetTaskRequestSchema, GetTaskResultSchema, GetTaskPayloadRequestSchema, ListTasksRequestSchema, ListTasksResultSchema, CancelTaskRequestSchema, CancelTaskResultSchema, isJSONRPCErrorResponse, isJSONRPCRequest, isJSONRPCResultResponse, isJSONRPCNotification, McpError, PingRequestSchema, ProgressNotificationSchema, RELATED_TASK_META_KEY, TaskStatusNotificationSchema, isTaskAugmentedRequestParams } from '../types.js';\nimport { isTerminal } from '../experimental/tasks/interfaces.js';\nimport { getMethodLiteral, parseWithCompat } from '../server/zod-json-schema-compat.js';\n/**\n * The default request timeout, in miliseconds.\n */\nexport const DEFAULT_REQUEST_TIMEOUT_MSEC = 60000;\n/**\n * Implements MCP protocol framing on top of a pluggable transport, including\n * features like request/response linking, notifications, and progress.\n */\nexport class Protocol {\n constructor(_options) {\n this._options = _options;\n this._requestMessageId = 0;\n this._requestHandlers = new Map();\n this._requestHandlerAbortControllers = new Map();\n this._notificationHandlers = new Map();\n this._responseHandlers = new Map();\n this._progressHandlers = new Map();\n this._timeoutInfo = new Map();\n this._pendingDebouncedNotifications = new Set();\n // Maps task IDs to progress tokens to keep handlers alive after CreateTaskResult\n this._taskProgressTokens = new Map();\n this._requestResolvers = new Map();\n this.setNotificationHandler(CancelledNotificationSchema, notification => {\n this._oncancel(notification);\n });\n this.setNotificationHandler(ProgressNotificationSchema, notification => {\n this._onprogress(notification);\n });\n this.setRequestHandler(PingRequestSchema, \n // Automatic pong by default.\n _request => ({}));\n // Install task handlers if TaskStore is provided\n this._taskStore = _options?.taskStore;\n this._taskMessageQueue = _options?.taskMessageQueue;\n if (this._taskStore) {\n this.setRequestHandler(GetTaskRequestSchema, async (request, extra) => {\n const task = await this._taskStore.getTask(request.params.taskId, extra.sessionId);\n if (!task) {\n throw new McpError(ErrorCode.InvalidParams, 'Failed to retrieve task: Task not found');\n }\n // Per spec: tasks/get responses SHALL NOT include related-task metadata\n // as the taskId parameter is the source of truth\n // @ts-expect-error SendResultT cannot contain GetTaskResult, but we include it in our derived types everywhere else\n return {\n ...task\n };\n });\n this.setRequestHandler(GetTaskPayloadRequestSchema, async (request, extra) => {\n const handleTaskResult = async () => {\n const taskId = request.params.taskId;\n // Deliver queued messages\n if (this._taskMessageQueue) {\n let queuedMessage;\n while ((queuedMessage = await this._taskMessageQueue.dequeue(taskId, extra.sessionId))) {\n // Handle response and error messages by routing them to the appropriate resolver\n if (queuedMessage.type === 'response' || queuedMessage.type === 'error') {\n const message = queuedMessage.message;\n const requestId = message.id;\n // Lookup resolver in _requestResolvers map\n const resolver = this._requestResolvers.get(requestId);\n if (resolver) {\n // Remove resolver from map after invocation\n this._requestResolvers.delete(requestId);\n // Invoke resolver with response or error\n if (queuedMessage.type === 'response') {\n resolver(message);\n }\n else {\n // Convert JSONRPCError to McpError\n const errorMessage = message;\n const error = new McpError(errorMessage.error.code, errorMessage.error.message, errorMessage.error.data);\n resolver(error);\n }\n }\n else {\n // Handle missing resolver gracefully with error logging\n const messageType = queuedMessage.type === 'response' ? 'Response' : 'Error';\n this._onerror(new Error(`${messageType} handler missing for request ${requestId}`));\n }\n // Continue to next message\n continue;\n }\n // Send the message on the response stream by passing the relatedRequestId\n // This tells the transport to write the message to the tasks/result response stream\n await this._transport?.send(queuedMessage.message, { relatedRequestId: extra.requestId });\n }\n }\n // Now check task status\n const task = await this._taskStore.getTask(taskId, extra.sessionId);\n if (!task) {\n throw new McpError(ErrorCode.InvalidParams, `Task not found: ${taskId}`);\n }\n // Block if task is not terminal (we've already delivered all queued messages above)\n if (!isTerminal(task.status)) {\n // Wait for status change or new messages\n await this._waitForTaskUpdate(taskId, extra.signal);\n // After waking up, recursively call to deliver any new messages or result\n return await handleTaskResult();\n }\n // If task is terminal, return the result\n if (isTerminal(task.status)) {\n const result = await this._taskStore.getTaskResult(taskId, extra.sessionId);\n this._clearTaskQueue(taskId);\n return {\n ...result,\n _meta: {\n ...result._meta,\n [RELATED_TASK_META_KEY]: {\n taskId: taskId\n }\n }\n };\n }\n return await handleTaskResult();\n };\n return await handleTaskResult();\n });\n this.setRequestHandler(ListTasksRequestSchema, async (request, extra) => {\n try {\n const { tasks, nextCursor } = await this._taskStore.listTasks(request.params?.cursor, extra.sessionId);\n // @ts-expect-error SendResultT cannot contain ListTasksResult, but we include it in our derived types everywhere else\n return {\n tasks,\n nextCursor,\n _meta: {}\n };\n }\n catch (error) {\n throw new McpError(ErrorCode.InvalidParams, `Failed to list tasks: ${error instanceof Error ? error.message : String(error)}`);\n }\n });\n this.setRequestHandler(CancelTaskRequestSchema, async (request, extra) => {\n try {\n // Get the current task to check if it's in a terminal state, in case the implementation is not atomic\n const task = await this._taskStore.getTask(request.params.taskId, extra.sessionId);\n if (!task) {\n throw new McpError(ErrorCode.InvalidParams, `Task not found: ${request.params.taskId}`);\n }\n // Reject cancellation of terminal tasks\n if (isTerminal(task.status)) {\n throw new McpError(ErrorCode.InvalidParams, `Cannot cancel task in terminal status: ${task.status}`);\n }\n await this._taskStore.updateTaskStatus(request.params.taskId, 'cancelled', 'Client cancelled task execution.', extra.sessionId);\n this._clearTaskQueue(request.params.taskId);\n const cancelledTask = await this._taskStore.getTask(request.params.taskId, extra.sessionId);\n if (!cancelledTask) {\n // Task was deleted during cancellation (e.g., cleanup happened)\n throw new McpError(ErrorCode.InvalidParams, `Task not found after cancellation: ${request.params.taskId}`);\n }\n return {\n _meta: {},\n ...cancelledTask\n };\n }\n catch (error) {\n // Re-throw McpError as-is\n if (error instanceof McpError) {\n throw error;\n }\n throw new McpError(ErrorCode.InvalidRequest, `Failed to cancel task: ${error instanceof Error ? error.message : String(error)}`);\n }\n });\n }\n }\n async _oncancel(notification) {\n if (!notification.params.requestId) {\n return;\n }\n // Handle request cancellation\n const controller = this._requestHandlerAbortControllers.get(notification.params.requestId);\n controller?.abort(notification.params.reason);\n }\n _setupTimeout(messageId, timeout, maxTotalTimeout, onTimeout, resetTimeoutOnProgress = false) {\n this._timeoutInfo.set(messageId, {\n timeoutId: setTimeout(onTimeout, timeout),\n startTime: Date.now(),\n timeout,\n maxTotalTimeout,\n resetTimeoutOnProgress,\n onTimeout\n });\n }\n _resetTimeout(messageId) {\n const info = this._timeoutInfo.get(messageId);\n if (!info)\n return false;\n const totalElapsed = Date.now() - info.startTime;\n if (info.maxTotalTimeout && totalElapsed >= info.maxTotalTimeout) {\n this._timeoutInfo.delete(messageId);\n throw McpError.fromError(ErrorCode.RequestTimeout, 'Maximum total timeout exceeded', {\n maxTotalTimeout: info.maxTotalTimeout,\n totalElapsed\n });\n }\n clearTimeout(info.timeoutId);\n info.timeoutId = setTimeout(info.onTimeout, info.timeout);\n return true;\n }\n _cleanupTimeout(messageId) {\n const info = this._timeoutInfo.get(messageId);\n if (info) {\n clearTimeout(info.timeoutId);\n this._timeoutInfo.delete(messageId);\n }\n }\n /**\n * Attaches to the given transport, starts it, and starts listening for messages.\n *\n * The Protocol object assumes ownership of the Transport, replacing any callbacks that have already been set, and expects that it is the only user of the Transport instance going forward.\n */\n async connect(transport) {\n if (this._transport) {\n throw new Error('Already connected to a transport. Call close() before connecting to a new transport, or use a separate Protocol instance per connection.');\n }\n this._transport = transport;\n const _onclose = this.transport?.onclose;\n this._transport.onclose = () => {\n _onclose?.();\n this._onclose();\n };\n const _onerror = this.transport?.onerror;\n this._transport.onerror = (error) => {\n _onerror?.(error);\n this._onerror(error);\n };\n const _onmessage = this._transport?.onmessage;\n this._transport.onmessage = (message, extra) => {\n _onmessage?.(message, extra);\n if (isJSONRPCResultResponse(message) || isJSONRPCErrorResponse(message)) {\n this._onresponse(message);\n }\n else if (isJSONRPCRequest(message)) {\n this._onrequest(message, extra);\n }\n else if (isJSONRPCNotification(message)) {\n this._onnotification(message);\n }\n else {\n this._onerror(new Error(`Unknown message type: ${JSON.stringify(message)}`));\n }\n };\n await this._transport.start();\n }\n _onclose() {\n const responseHandlers = this._responseHandlers;\n this._responseHandlers = new Map();\n this._progressHandlers.clear();\n this._taskProgressTokens.clear();\n this._pendingDebouncedNotifications.clear();\n for (const info of this._timeoutInfo.values()) {\n clearTimeout(info.timeoutId);\n }\n this._timeoutInfo.clear();\n // Abort all in-flight request handlers so they stop sending messages\n for (const controller of this._requestHandlerAbortControllers.values()) {\n controller.abort();\n }\n this._requestHandlerAbortControllers.clear();\n const error = McpError.fromError(ErrorCode.ConnectionClosed, 'Connection closed');\n this._transport = undefined;\n this.onclose?.();\n for (const handler of responseHandlers.values()) {\n handler(error);\n }\n }\n _onerror(error) {\n this.onerror?.(error);\n }\n _onnotification(notification) {\n const handler = this._notificationHandlers.get(notification.method) ?? this.fallbackNotificationHandler;\n // Ignore notifications not being subscribed to.\n if (handler === undefined) {\n return;\n }\n // Starting with Promise.resolve() puts any synchronous errors into the monad as well.\n Promise.resolve()\n .then(() => handler(notification))\n .catch(error => this._onerror(new Error(`Uncaught error in notification handler: ${error}`)));\n }\n _onrequest(request, extra) {\n const handler = this._requestHandlers.get(request.method) ?? this.fallbackRequestHandler;\n // Capture the current transport at request time to ensure responses go to the correct client\n const capturedTransport = this._transport;\n // Extract taskId from request metadata if present (needed early for method not found case)\n const relatedTaskId = request.params?._meta?.[RELATED_TASK_META_KEY]?.taskId;\n if (handler === undefined) {\n const errorResponse = {\n jsonrpc: '2.0',\n id: request.id,\n error: {\n code: ErrorCode.MethodNotFound,\n message: 'Method not found'\n }\n };\n // Queue or send the error response based on whether this is a task-related request\n if (relatedTaskId && this._taskMessageQueue) {\n this._enqueueTaskMessage(relatedTaskId, {\n type: 'error',\n message: errorResponse,\n timestamp: Date.now()\n }, capturedTransport?.sessionId).catch(error => this._onerror(new Error(`Failed to enqueue error response: ${error}`)));\n }\n else {\n capturedTransport\n ?.send(errorResponse)\n .catch(error => this._onerror(new Error(`Failed to send an error response: ${error}`)));\n }\n return;\n }\n const abortController = new AbortController();\n this._requestHandlerAbortControllers.set(request.id, abortController);\n const taskCreationParams = isTaskAugmentedRequestParams(request.params) ? request.params.task : undefined;\n const taskStore = this._taskStore ? this.requestTaskStore(request, capturedTransport?.sessionId) : undefined;\n const fullExtra = {\n signal: abortController.signal,\n sessionId: capturedTransport?.sessionId,\n _meta: request.params?._meta,\n sendNotification: async (notification) => {\n if (abortController.signal.aborted)\n return;\n // Include related-task metadata if this request is part of a task\n const notificationOptions = { relatedRequestId: request.id };\n if (relatedTaskId) {\n notificationOptions.relatedTask = { taskId: relatedTaskId };\n }\n await this.notification(notification, notificationOptions);\n },\n sendRequest: async (r, resultSchema, options) => {\n if (abortController.signal.aborted) {\n throw new McpError(ErrorCode.ConnectionClosed, 'Request was cancelled');\n }\n // Include related-task metadata if this request is part of a task\n const requestOptions = { ...options, relatedRequestId: request.id };\n if (relatedTaskId && !requestOptions.relatedTask) {\n requestOptions.relatedTask = { taskId: relatedTaskId };\n }\n // Set task status to input_required when sending a request within a task context\n // Use the taskId from options (explicit) or fall back to relatedTaskId (inherited)\n const effectiveTaskId = requestOptions.relatedTask?.taskId ?? relatedTaskId;\n if (effectiveTaskId && taskStore) {\n await taskStore.updateTaskStatus(effectiveTaskId, 'input_required');\n }\n return await this.request(r, resultSchema, requestOptions);\n },\n authInfo: extra?.authInfo,\n requestId: request.id,\n requestInfo: extra?.requestInfo,\n taskId: relatedTaskId,\n taskStore: taskStore,\n taskRequestedTtl: taskCreationParams?.ttl,\n closeSSEStream: extra?.closeSSEStream,\n closeStandaloneSSEStream: extra?.closeStandaloneSSEStream\n };\n // Starting with Promise.resolve() puts any synchronous errors into the monad as well.\n Promise.resolve()\n .then(() => {\n // If this request asked for task creation, check capability first\n if (taskCreationParams) {\n // Check if the request method supports task creation\n this.assertTaskHandlerCapability(request.method);\n }\n })\n .then(() => handler(request, fullExtra))\n .then(async (result) => {\n if (abortController.signal.aborted) {\n // Request was cancelled\n return;\n }\n const response = {\n result,\n jsonrpc: '2.0',\n id: request.id\n };\n // Queue or send the response based on whether this is a task-related request\n if (relatedTaskId && this._taskMessageQueue) {\n await this._enqueueTaskMessage(relatedTaskId, {\n type: 'response',\n message: response,\n timestamp: Date.now()\n }, capturedTransport?.sessionId);\n }\n else {\n await capturedTransport?.send(response);\n }\n }, async (error) => {\n if (abortController.signal.aborted) {\n // Request was cancelled\n return;\n }\n const errorResponse = {\n jsonrpc: '2.0',\n id: request.id,\n error: {\n code: Number.isSafeInteger(error['code']) ? error['code'] : ErrorCode.InternalError,\n message: error.message ?? 'Internal error',\n ...(error['data'] !== undefined && { data: error['data'] })\n }\n };\n // Queue or send the error response based on whether this is a task-related request\n if (relatedTaskId && this._taskMessageQueue) {\n await this._enqueueTaskMessage(relatedTaskId, {\n type: 'error',\n message: errorResponse,\n timestamp: Date.now()\n }, capturedTransport?.sessionId);\n }\n else {\n await capturedTransport?.send(errorResponse);\n }\n })\n .catch(error => this._onerror(new Error(`Failed to send response: ${error}`)))\n .finally(() => {\n // Only delete if the stored controller is still ours; after close()+connect(),\n // a new connection may have reused the same request ID with a different controller.\n if (this._requestHandlerAbortControllers.get(request.id) === abortController) {\n this._requestHandlerAbortControllers.delete(request.id);\n }\n });\n }\n _onprogress(notification) {\n const { progressToken, ...params } = notification.params;\n const messageId = Number(progressToken);\n const handler = this._progressHandlers.get(messageId);\n if (!handler) {\n this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(notification)}`));\n return;\n }\n const responseHandler = this._responseHandlers.get(messageId);\n const timeoutInfo = this._timeoutInfo.get(messageId);\n if (timeoutInfo && responseHandler && timeoutInfo.resetTimeoutOnProgress) {\n try {\n this._resetTimeout(messageId);\n }\n catch (error) {\n // Clean up if maxTotalTimeout was exceeded\n this._responseHandlers.delete(messageId);\n this._progressHandlers.delete(messageId);\n this._cleanupTimeout(messageId);\n responseHandler(error);\n return;\n }\n }\n handler(params);\n }\n _onresponse(response) {\n const messageId = Number(response.id);\n // Check if this is a response to a queued request\n const resolver = this._requestResolvers.get(messageId);\n if (resolver) {\n this._requestResolvers.delete(messageId);\n if (isJSONRPCResultResponse(response)) {\n resolver(response);\n }\n else {\n const error = new McpError(response.error.code, response.error.message, response.error.data);\n resolver(error);\n }\n return;\n }\n const handler = this._responseHandlers.get(messageId);\n if (handler === undefined) {\n this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(response)}`));\n return;\n }\n this._responseHandlers.delete(messageId);\n this._cleanupTimeout(messageId);\n // Keep progress handler alive for CreateTaskResult responses\n let isTaskResponse = false;\n if (isJSONRPCResultResponse(response) && response.result && typeof response.result === 'object') {\n const result = response.result;\n if (result.task && typeof result.task === 'object') {\n const task = result.task;\n if (typeof task.taskId === 'string') {\n isTaskResponse = true;\n this._taskProgressTokens.set(task.taskId, messageId);\n }\n }\n }\n if (!isTaskResponse) {\n this._progressHandlers.delete(messageId);\n }\n if (isJSONRPCResultResponse(response)) {\n handler(response);\n }\n else {\n const error = McpError.fromError(response.error.code, response.error.message, response.error.data);\n handler(error);\n }\n }\n get transport() {\n return this._transport;\n }\n /**\n * Closes the connection.\n */\n async close() {\n await this._transport?.close();\n }\n /**\n * Sends a request and returns an AsyncGenerator that yields response messages.\n * The generator is guaranteed to end with either a 'result' or 'error' message.\n *\n * @example\n * ```typescript\n * const stream = protocol.requestStream(request, resultSchema, options);\n * for await (const message of stream) {\n * switch (message.type) {\n * case 'taskCreated':\n * console.log('Task created:', message.task.taskId);\n * break;\n * case 'taskStatus':\n * console.log('Task status:', message.task.status);\n * break;\n * case 'result':\n * console.log('Final result:', message.result);\n * break;\n * case 'error':\n * console.error('Error:', message.error);\n * break;\n * }\n * }\n * ```\n *\n * @experimental Use `client.experimental.tasks.requestStream()` to access this method.\n */\n async *requestStream(request, resultSchema, options) {\n const { task } = options ?? {};\n // For non-task requests, just yield the result\n if (!task) {\n try {\n const result = await this.request(request, resultSchema, options);\n yield { type: 'result', result };\n }\n catch (error) {\n yield {\n type: 'error',\n error: error instanceof McpError ? error : new McpError(ErrorCode.InternalError, String(error))\n };\n }\n return;\n }\n // For task-augmented requests, we need to poll for status\n // First, make the request to create the task\n let taskId;\n try {\n // Send the request and get the CreateTaskResult\n const createResult = await this.request(request, CreateTaskResultSchema, options);\n // Extract taskId from the result\n if (createResult.task) {\n taskId = createResult.task.taskId;\n yield { type: 'taskCreated', task: createResult.task };\n }\n else {\n throw new McpError(ErrorCode.InternalError, 'Task creation did not return a task');\n }\n // Poll for task completion\n while (true) {\n // Get current task status\n const task = await this.getTask({ taskId }, options);\n yield { type: 'taskStatus', task };\n // Check if task is terminal\n if (isTerminal(task.status)) {\n if (task.status === 'completed') {\n // Get the final result\n const result = await this.getTaskResult({ taskId }, resultSchema, options);\n yield { type: 'result', result };\n }\n else if (task.status === 'failed') {\n yield {\n type: 'error',\n error: new McpError(ErrorCode.InternalError, `Task ${taskId} failed`)\n };\n }\n else if (task.status === 'cancelled') {\n yield {\n type: 'error',\n error: new McpError(ErrorCode.InternalError, `Task ${taskId} was cancelled`)\n };\n }\n return;\n }\n // When input_required, call tasks/result to deliver queued messages\n // (elicitation, sampling) via SSE and block until terminal\n if (task.status === 'input_required') {\n const result = await this.getTaskResult({ taskId }, resultSchema, options);\n yield { type: 'result', result };\n return;\n }\n // Wait before polling again\n const pollInterval = task.pollInterval ?? this._options?.defaultTaskPollInterval ?? 1000;\n await new Promise(resolve => setTimeout(resolve, pollInterval));\n // Check if cancelled\n options?.signal?.throwIfAborted();\n }\n }\n catch (error) {\n yield {\n type: 'error',\n error: error instanceof McpError ? error : new McpError(ErrorCode.InternalError, String(error))\n };\n }\n }\n /**\n * Sends a request and waits for a response.\n *\n * Do not use this method to emit notifications! Use notification() instead.\n */\n request(request, resultSchema, options) {\n const { relatedRequestId, resumptionToken, onresumptiontoken, task, relatedTask } = options ?? {};\n // Send the request\n return new Promise((resolve, reject) => {\n const earlyReject = (error) => {\n reject(error);\n };\n if (!this._transport) {\n earlyReject(new Error('Not connected'));\n return;\n }\n if (this._options?.enforceStrictCapabilities === true) {\n try {\n this.assertCapabilityForMethod(request.method);\n // If task creation is requested, also check task capabilities\n if (task) {\n this.assertTaskCapability(request.method);\n }\n }\n catch (e) {\n earlyReject(e);\n return;\n }\n }\n options?.signal?.throwIfAborted();\n const messageId = this._requestMessageId++;\n const jsonrpcRequest = {\n ...request,\n jsonrpc: '2.0',\n id: messageId\n };\n if (options?.onprogress) {\n this._progressHandlers.set(messageId, options.onprogress);\n jsonrpcRequest.params = {\n ...request.params,\n _meta: {\n ...(request.params?._meta || {}),\n progressToken: messageId\n }\n };\n }\n // Augment with task creation parameters if provided\n if (task) {\n jsonrpcRequest.params = {\n ...jsonrpcRequest.params,\n task: task\n };\n }\n // Augment with related task metadata if relatedTask is provided\n if (relatedTask) {\n jsonrpcRequest.params = {\n ...jsonrpcRequest.params,\n _meta: {\n ...(jsonrpcRequest.params?._meta || {}),\n [RELATED_TASK_META_KEY]: relatedTask\n }\n };\n }\n const cancel = (reason) => {\n this._responseHandlers.delete(messageId);\n this._progressHandlers.delete(messageId);\n this._cleanupTimeout(messageId);\n this._transport\n ?.send({\n jsonrpc: '2.0',\n method: 'notifications/cancelled',\n params: {\n requestId: messageId,\n reason: String(reason)\n }\n }, { relatedRequestId, resumptionToken, onresumptiontoken })\n .catch(error => this._onerror(new Error(`Failed to send cancellation: ${error}`)));\n // Wrap the reason in an McpError if it isn't already\n const error = reason instanceof McpError ? reason : new McpError(ErrorCode.RequestTimeout, String(reason));\n reject(error);\n };\n this._responseHandlers.set(messageId, response => {\n if (options?.signal?.aborted) {\n return;\n }\n if (response instanceof Error) {\n return reject(response);\n }\n try {\n const parseResult = safeParse(resultSchema, response.result);\n if (!parseResult.success) {\n // Type guard: if success is false, error is guaranteed to exist\n reject(parseResult.error);\n }\n else {\n resolve(parseResult.data);\n }\n }\n catch (error) {\n reject(error);\n }\n });\n options?.signal?.addEventListener('abort', () => {\n cancel(options?.signal?.reason);\n });\n const timeout = options?.timeout ?? DEFAULT_REQUEST_TIMEOUT_MSEC;\n const timeoutHandler = () => cancel(McpError.fromError(ErrorCode.RequestTimeout, 'Request timed out', { timeout }));\n this._setupTimeout(messageId, timeout, options?.maxTotalTimeout, timeoutHandler, options?.resetTimeoutOnProgress ?? false);\n // Queue request if related to a task\n const relatedTaskId = relatedTask?.taskId;\n if (relatedTaskId) {\n // Store the response resolver for this request so responses can be routed back\n const responseResolver = (response) => {\n const handler = this._responseHandlers.get(messageId);\n if (handler) {\n handler(response);\n }\n else {\n // Log error when resolver is missing, but don't fail\n this._onerror(new Error(`Response handler missing for side-channeled request ${messageId}`));\n }\n };\n this._requestResolvers.set(messageId, responseResolver);\n this._enqueueTaskMessage(relatedTaskId, {\n type: 'request',\n message: jsonrpcRequest,\n timestamp: Date.now()\n }).catch(error => {\n this._cleanupTimeout(messageId);\n reject(error);\n });\n // Don't send through transport - queued messages are delivered via tasks/result only\n // This prevents duplicate delivery for bidirectional transports\n }\n else {\n // No related task - send through transport normally\n this._transport.send(jsonrpcRequest, { relatedRequestId, resumptionToken, onresumptiontoken }).catch(error => {\n this._cleanupTimeout(messageId);\n reject(error);\n });\n }\n });\n }\n /**\n * Gets the current status of a task.\n *\n * @experimental Use `client.experimental.tasks.getTask()` to access this method.\n */\n async getTask(params, options) {\n // @ts-expect-error SendRequestT cannot directly contain GetTaskRequest, but we ensure all type instantiations contain it anyways\n return this.request({ method: 'tasks/get', params }, GetTaskResultSchema, options);\n }\n /**\n * Retrieves the result of a completed task.\n *\n * @experimental Use `client.experimental.tasks.getTaskResult()` to access this method.\n */\n async getTaskResult(params, resultSchema, options) {\n // @ts-expect-error SendRequestT cannot directly contain GetTaskPayloadRequest, but we ensure all type instantiations contain it anyways\n return this.request({ method: 'tasks/result', params }, resultSchema, options);\n }\n /**\n * Lists tasks, optionally starting from a pagination cursor.\n *\n * @experimental Use `client.experimental.tasks.listTasks()` to access this method.\n */\n async listTasks(params, options) {\n // @ts-expect-error SendRequestT cannot directly contain ListTasksRequest, but we ensure all type instantiations contain it anyways\n return this.request({ method: 'tasks/list', params }, ListTasksResultSchema, options);\n }\n /**\n * Cancels a specific task.\n *\n * @experimental Use `client.experimental.tasks.cancelTask()` to access this method.\n */\n async cancelTask(params, options) {\n // @ts-expect-error SendRequestT cannot directly contain CancelTaskRequest, but we ensure all type instantiations contain it anyways\n return this.request({ method: 'tasks/cancel', params }, CancelTaskResultSchema, options);\n }\n /**\n * Emits a notification, which is a one-way message that does not expect a response.\n */\n async notification(notification, options) {\n if (!this._transport) {\n throw new Error('Not connected');\n }\n this.assertNotificationCapability(notification.method);\n // Queue notification if related to a task\n const relatedTaskId = options?.relatedTask?.taskId;\n if (relatedTaskId) {\n // Build the JSONRPC notification with metadata\n const jsonrpcNotification = {\n ...notification,\n jsonrpc: '2.0',\n params: {\n ...notification.params,\n _meta: {\n ...(notification.params?._meta || {}),\n [RELATED_TASK_META_KEY]: options.relatedTask\n }\n }\n };\n await this._enqueueTaskMessage(relatedTaskId, {\n type: 'notification',\n message: jsonrpcNotification,\n timestamp: Date.now()\n });\n // Don't send through transport - queued messages are delivered via tasks/result only\n // This prevents duplicate delivery for bidirectional transports\n return;\n }\n const debouncedMethods = this._options?.debouncedNotificationMethods ?? [];\n // A notification can only be debounced if it's in the list AND it's \"simple\"\n // (i.e., has no parameters and no related request ID or related task that could be lost).\n const canDebounce = debouncedMethods.includes(notification.method) && !notification.params && !options?.relatedRequestId && !options?.relatedTask;\n if (canDebounce) {\n // If a notification of this type is already scheduled, do nothing.\n if (this._pendingDebouncedNotifications.has(notification.method)) {\n return;\n }\n // Mark this notification type as pending.\n this._pendingDebouncedNotifications.add(notification.method);\n // Schedule the actual send to happen in the next microtask.\n // This allows all synchronous calls in the current event loop tick to be coalesced.\n Promise.resolve().then(() => {\n // Un-mark the notification so the next one can be scheduled.\n this._pendingDebouncedNotifications.delete(notification.method);\n // SAFETY CHECK: If the connection was closed while this was pending, abort.\n if (!this._transport) {\n return;\n }\n let jsonrpcNotification = {\n ...notification,\n jsonrpc: '2.0'\n };\n // Augment with related task metadata if relatedTask is provided\n if (options?.relatedTask) {\n jsonrpcNotification = {\n ...jsonrpcNotification,\n params: {\n ...jsonrpcNotification.params,\n _meta: {\n ...(jsonrpcNotification.params?._meta || {}),\n [RELATED_TASK_META_KEY]: options.relatedTask\n }\n }\n };\n }\n // Send the notification, but don't await it here to avoid blocking.\n // Handle potential errors with a .catch().\n this._transport?.send(jsonrpcNotification, options).catch(error => this._onerror(error));\n });\n // Return immediately.\n return;\n }\n let jsonrpcNotification = {\n ...notification,\n jsonrpc: '2.0'\n };\n // Augment with related task metadata if relatedTask is provided\n if (options?.relatedTask) {\n jsonrpcNotification = {\n ...jsonrpcNotification,\n params: {\n ...jsonrpcNotification.params,\n _meta: {\n ...(jsonrpcNotification.params?._meta || {}),\n [RELATED_TASK_META_KEY]: options.relatedTask\n }\n }\n };\n }\n await this._transport.send(jsonrpcNotification, options);\n }\n /**\n * Registers a handler to invoke when this protocol object receives a request with the given method.\n *\n * Note that this will replace any previous request handler for the same method.\n */\n setRequestHandler(requestSchema, handler) {\n const method = getMethodLiteral(requestSchema);\n this.assertRequestHandlerCapability(method);\n this._requestHandlers.set(method, (request, extra) => {\n const parsed = parseWithCompat(requestSchema, request);\n return Promise.resolve(handler(parsed, extra));\n });\n }\n /**\n * Removes the request handler for the given method.\n */\n removeRequestHandler(method) {\n this._requestHandlers.delete(method);\n }\n /**\n * Asserts that a request handler has not already been set for the given method, in preparation for a new one being automatically installed.\n */\n assertCanSetRequestHandler(method) {\n if (this._requestHandlers.has(method)) {\n throw new Error(`A request handler for ${method} already exists, which would be overridden`);\n }\n }\n /**\n * Registers a handler to invoke when this protocol object receives a notification with the given method.\n *\n * Note that this will replace any previous notification handler for the same method.\n */\n setNotificationHandler(notificationSchema, handler) {\n const method = getMethodLiteral(notificationSchema);\n this._notificationHandlers.set(method, notification => {\n const parsed = parseWithCompat(notificationSchema, notification);\n return Promise.resolve(handler(parsed));\n });\n }\n /**\n * Removes the notification handler for the given method.\n */\n removeNotificationHandler(method) {\n this._notificationHandlers.delete(method);\n }\n /**\n * Cleans up the progress handler associated with a task.\n * This should be called when a task reaches a terminal status.\n */\n _cleanupTaskProgressHandler(taskId) {\n const progressToken = this._taskProgressTokens.get(taskId);\n if (progressToken !== undefined) {\n this._progressHandlers.delete(progressToken);\n this._taskProgressTokens.delete(taskId);\n }\n }\n /**\n * Enqueues a task-related message for side-channel delivery via tasks/result.\n * @param taskId The task ID to associate the message with\n * @param message The message to enqueue\n * @param sessionId Optional session ID for binding the operation to a specific session\n * @throws Error if taskStore is not configured or if enqueue fails (e.g., queue overflow)\n *\n * Note: If enqueue fails, it's the TaskMessageQueue implementation's responsibility to handle\n * the error appropriately (e.g., by failing the task, logging, etc.). The Protocol layer\n * simply propagates the error.\n */\n async _enqueueTaskMessage(taskId, message, sessionId) {\n // Task message queues are only used when taskStore is configured\n if (!this._taskStore || !this._taskMessageQueue) {\n throw new Error('Cannot enqueue task message: taskStore and taskMessageQueue are not configured');\n }\n const maxQueueSize = this._options?.maxTaskQueueSize;\n await this._taskMessageQueue.enqueue(taskId, message, sessionId, maxQueueSize);\n }\n /**\n * Clears the message queue for a task and rejects any pending request resolvers.\n * @param taskId The task ID whose queue should be cleared\n * @param sessionId Optional session ID for binding the operation to a specific session\n */\n async _clearTaskQueue(taskId, sessionId) {\n if (this._taskMessageQueue) {\n // Reject any pending request resolvers\n const messages = await this._taskMessageQueue.dequeueAll(taskId, sessionId);\n for (const message of messages) {\n if (message.type === 'request' && isJSONRPCRequest(message.message)) {\n // Extract request ID from the message\n const requestId = message.message.id;\n const resolver = this._requestResolvers.get(requestId);\n if (resolver) {\n resolver(new McpError(ErrorCode.InternalError, 'Task cancelled or completed'));\n this._requestResolvers.delete(requestId);\n }\n else {\n // Log error when resolver is missing during cleanup for better observability\n this._onerror(new Error(`Resolver missing for request ${requestId} during task ${taskId} cleanup`));\n }\n }\n }\n }\n }\n /**\n * Waits for a task update (new messages or status change) with abort signal support.\n * Uses polling to check for updates at the task's configured poll interval.\n * @param taskId The task ID to wait for\n * @param signal Abort signal to cancel the wait\n * @returns Promise that resolves when an update occurs or rejects if aborted\n */\n async _waitForTaskUpdate(taskId, signal) {\n // Get the task's poll interval, falling back to default\n let interval = this._options?.defaultTaskPollInterval ?? 1000;\n try {\n const task = await this._taskStore?.getTask(taskId);\n if (task?.pollInterval) {\n interval = task.pollInterval;\n }\n }\n catch {\n // Use default interval if task lookup fails\n }\n return new Promise((resolve, reject) => {\n if (signal.aborted) {\n reject(new McpError(ErrorCode.InvalidRequest, 'Request cancelled'));\n return;\n }\n // Wait for the poll interval, then resolve so caller can check for updates\n const timeoutId = setTimeout(resolve, interval);\n // Clean up timeout and reject if aborted\n signal.addEventListener('abort', () => {\n clearTimeout(timeoutId);\n reject(new McpError(ErrorCode.InvalidRequest, 'Request cancelled'));\n }, { once: true });\n });\n }\n requestTaskStore(request, sessionId) {\n const taskStore = this._taskStore;\n if (!taskStore) {\n throw new Error('No task store configured');\n }\n return {\n createTask: async (taskParams) => {\n if (!request) {\n throw new Error('No request provided');\n }\n return await taskStore.createTask(taskParams, request.id, {\n method: request.method,\n params: request.params\n }, sessionId);\n },\n getTask: async (taskId) => {\n const task = await taskStore.getTask(taskId, sessionId);\n if (!task) {\n throw new McpError(ErrorCode.InvalidParams, 'Failed to retrieve task: Task not found');\n }\n return task;\n },\n storeTaskResult: async (taskId, status, result) => {\n await taskStore.storeTaskResult(taskId, status, result, sessionId);\n // Get updated task state and send notification\n const task = await taskStore.getTask(taskId, sessionId);\n if (task) {\n const notification = TaskStatusNotificationSchema.parse({\n method: 'notifications/tasks/status',\n params: task\n });\n await this.notification(notification);\n if (isTerminal(task.status)) {\n this._cleanupTaskProgressHandler(taskId);\n // Don't clear queue here - it will be cleared after delivery via tasks/result\n }\n }\n },\n getTaskResult: taskId => {\n return taskStore.getTaskResult(taskId, sessionId);\n },\n updateTaskStatus: async (taskId, status, statusMessage) => {\n // Check if task exists\n const task = await taskStore.getTask(taskId, sessionId);\n if (!task) {\n throw new McpError(ErrorCode.InvalidParams, `Task \"${taskId}\" not found - it may have been cleaned up`);\n }\n // Don't allow transitions from terminal states\n if (isTerminal(task.status)) {\n throw new McpError(ErrorCode.InvalidParams, `Cannot update task \"${taskId}\" from terminal status \"${task.status}\" to \"${status}\". Terminal states (completed, failed, cancelled) cannot transition to other states.`);\n }\n await taskStore.updateTaskStatus(taskId, status, statusMessage, sessionId);\n // Get updated task state and send notification\n const updatedTask = await taskStore.getTask(taskId, sessionId);\n if (updatedTask) {\n const notification = TaskStatusNotificationSchema.parse({\n method: 'notifications/tasks/status',\n params: updatedTask\n });\n await this.notification(notification);\n if (isTerminal(updatedTask.status)) {\n this._cleanupTaskProgressHandler(taskId);\n // Don't clear queue here - it will be cleared after delivery via tasks/result\n }\n }\n },\n listTasks: cursor => {\n return taskStore.listTasks(cursor, sessionId);\n }\n };\n }\n}\nfunction isPlainObject(value) {\n return value !== null && typeof value === 'object' && !Array.isArray(value);\n}\nexport function mergeCapabilities(base, additional) {\n const result = { ...base };\n for (const key in additional) {\n const k = key;\n const addValue = additional[k];\n if (addValue === undefined)\n continue;\n const baseValue = result[k];\n if (isPlainObject(baseValue) && isPlainObject(addValue)) {\n result[k] = { ...baseValue, ...addValue };\n }\n else {\n result[k] = addValue;\n }\n }\n return result;\n}\n//# sourceMappingURL=protocol.js.map","var ZQ=((X)=>typeof require<\"u\"?require:typeof Proxy<\"u\"?new Proxy(X,{get:(Y,Z)=>(typeof require<\"u\"?require:Y)[Z]}):X)(function(X){if(typeof require<\"u\")return require.apply(this,arguments);throw Error('Dynamic require of \"'+X+'\" is not supported')});import{CallToolRequestSchema as iQ,CallToolResultSchema as XQ,CreateMessageRequestSchema as nQ,ListPromptsRequestSchema as cQ,ListPromptsResultSchema as lQ,ListResourcesRequestSchema as rQ,ListResourcesResultSchema as oQ,ListResourceTemplatesRequestSchema as sQ,ListResourceTemplatesResultSchema as tQ,ListToolsResultSchema as aQ,LoggingMessageNotificationSchema as eQ,PingRequestSchema as QX,PromptListChangedNotificationSchema as XX,ReadResourceRequestSchema as YX,ReadResourceResultSchema as ZX,ResourceListChangedNotificationSchema as $X,ToolListChangedNotificationSchema as JX}from\"@modelcontextprotocol/sdk/types.js\";import{Protocol as $Q}from\"@modelcontextprotocol/sdk/shared/protocol.js\";class _ extends $Q{_registeredMethods=new Set;_eventSlots=new Map;onEventDispatch(X,Y){}_ensureEventSlot(X){let Y=this._eventSlots.get(X);if(!Y){let Z=this.eventSchemas[X];if(!Z)throw Error(`Unknown event: ${String(X)}`);Y={listeners:[]},this._eventSlots.set(X,Y);let $=Z.shape.method.value;this._registeredMethods.add($);let J=Y;super.setNotificationHandler(Z,(K)=>{let D=K.params;this.onEventDispatch(X,D),J.onHandler?.(D);for(let G of[...J.listeners])G(D)})}return Y}setEventHandler(X,Y){let Z=this._ensureEventSlot(X);if(Z.onHandler&&Y)console.warn(`[MCP Apps] on${String(X)} handler replaced. Use addEventListener(\"${String(X)}\", …) to add multiple listeners without replacing.`);Z.onHandler=Y}getEventHandler(X){return this._eventSlots.get(X)?.onHandler}addEventListener(X,Y){this._ensureEventSlot(X).listeners.push(Y)}removeEventListener(X,Y){let Z=this._eventSlots.get(X);if(!Z)return;let $=Z.listeners.indexOf(Y);if($!==-1)Z.listeners.splice($,1)}setRequestHandler=(X,Y)=>{this._assertMethodNotRegistered(X,\"setRequestHandler\"),super.setRequestHandler(X,Y)};setNotificationHandler=(X,Y)=>{this._assertMethodNotRegistered(X,\"setNotificationHandler\"),super.setNotificationHandler(X,Y)};warnIfRequestHandlerReplaced(X,Y,Z){if(Y&&Z)console.warn(`[MCP Apps] ${X} handler replaced. Previous handler will no longer be called.`)}replaceRequestHandler=(X,Y)=>{let Z=X.shape.method.value;this._registeredMethods.add(Z),super.setRequestHandler(X,Y)};_assertMethodNotRegistered(X,Y){let Z=X.shape.method.value;if(this._registeredMethods.has(Z))throw Error(`Handler for \"${Z}\" already registered (via ${Y}). Use addEventListener() to attach multiple listeners, or the on* setter for replace semantics.`);this._registeredMethods.add(Z)}}var j=\"2026-01-26\",JQ=\"ui/open-link\",KQ=\"ui/download-file\",DQ=\"ui/message\",GQ=\"ui/notifications/sandbox-proxy-ready\",NQ=\"ui/notifications/sandbox-resource-ready\",WQ=\"ui/notifications/size-changed\",jQ=\"ui/notifications/tool-input\",V=\"ui/notifications/tool-input-partial\",BQ=\"ui/notifications/tool-result\",_Q=\"ui/notifications/tool-cancelled\",EQ=\"ui/notifications/host-context-changed\",OQ=\"ui/notifications/request-teardown\",zQ=\"ui/resource-teardown\",IQ=\"ui/initialize\",VQ=\"ui/notifications/initialized\",FQ=\"ui/request-display-mode\";import{z as Q}from\"zod/v4\";import{ContentBlockSchema as c,CallToolResultSchema as LQ,EmbeddedResourceSchema as PQ,ImplementationSchema as l,RequestIdSchema as AQ,ResourceLinkSchema as UQ,ToolSchema as wQ}from\"@modelcontextprotocol/sdk/types.js\";var r=Q.union([Q.literal(\"light\"),Q.literal(\"dark\")]).describe(\"Color theme preference for the host environment.\"),B=Q.union([Q.literal(\"inline\"),Q.literal(\"fullscreen\"),Q.literal(\"pip\")]).describe(\"Display mode for UI presentation.\"),HQ=Q.union([Q.literal(\"--color-background-primary\"),Q.literal(\"--color-background-secondary\"),Q.literal(\"--color-background-tertiary\"),Q.literal(\"--color-background-inverse\"),Q.literal(\"--color-background-ghost\"),Q.literal(\"--color-background-info\"),Q.literal(\"--color-background-danger\"),Q.literal(\"--color-background-success\"),Q.literal(\"--color-background-warning\"),Q.literal(\"--color-background-disabled\"),Q.literal(\"--color-text-primary\"),Q.literal(\"--color-text-secondary\"),Q.literal(\"--color-text-tertiary\"),Q.literal(\"--color-text-inverse\"),Q.literal(\"--color-text-ghost\"),Q.literal(\"--color-text-info\"),Q.literal(\"--color-text-danger\"),Q.literal(\"--color-text-success\"),Q.literal(\"--color-text-warning\"),Q.literal(\"--color-text-disabled\"),Q.literal(\"--color-border-primary\"),Q.literal(\"--color-border-secondary\"),Q.literal(\"--color-border-tertiary\"),Q.literal(\"--color-border-inverse\"),Q.literal(\"--color-border-ghost\"),Q.literal(\"--color-border-info\"),Q.literal(\"--color-border-danger\"),Q.literal(\"--color-border-success\"),Q.literal(\"--color-border-warning\"),Q.literal(\"--color-border-disabled\"),Q.literal(\"--color-ring-primary\"),Q.literal(\"--color-ring-secondary\"),Q.literal(\"--color-ring-inverse\"),Q.literal(\"--color-ring-info\"),Q.literal(\"--color-ring-danger\"),Q.literal(\"--color-ring-success\"),Q.literal(\"--color-ring-warning\"),Q.literal(\"--font-sans\"),Q.literal(\"--font-mono\"),Q.literal(\"--font-weight-normal\"),Q.literal(\"--font-weight-medium\"),Q.literal(\"--font-weight-semibold\"),Q.literal(\"--font-weight-bold\"),Q.literal(\"--font-text-xs-size\"),Q.literal(\"--font-text-sm-size\"),Q.literal(\"--font-text-md-size\"),Q.literal(\"--font-text-lg-size\"),Q.literal(\"--font-heading-xs-size\"),Q.literal(\"--font-heading-sm-size\"),Q.literal(\"--font-heading-md-size\"),Q.literal(\"--font-heading-lg-size\"),Q.literal(\"--font-heading-xl-size\"),Q.literal(\"--font-heading-2xl-size\"),Q.literal(\"--font-heading-3xl-size\"),Q.literal(\"--font-text-xs-line-height\"),Q.literal(\"--font-text-sm-line-height\"),Q.literal(\"--font-text-md-line-height\"),Q.literal(\"--font-text-lg-line-height\"),Q.literal(\"--font-heading-xs-line-height\"),Q.literal(\"--font-heading-sm-line-height\"),Q.literal(\"--font-heading-md-line-height\"),Q.literal(\"--font-heading-lg-line-height\"),Q.literal(\"--font-heading-xl-line-height\"),Q.literal(\"--font-heading-2xl-line-height\"),Q.literal(\"--font-heading-3xl-line-height\"),Q.literal(\"--border-radius-xs\"),Q.literal(\"--border-radius-sm\"),Q.literal(\"--border-radius-md\"),Q.literal(\"--border-radius-lg\"),Q.literal(\"--border-radius-xl\"),Q.literal(\"--border-radius-full\"),Q.literal(\"--border-width-regular\"),Q.literal(\"--shadow-hairline\"),Q.literal(\"--shadow-sm\"),Q.literal(\"--shadow-md\"),Q.literal(\"--shadow-lg\")]).describe(\"CSS variable keys available to MCP apps for theming.\"),RQ=Q.record(HQ.describe(`Style variables for theming MCP apps.\n\nIndividual style keys are optional - hosts may provide any subset of these values.\nValues are strings containing CSS values (colors, sizes, font stacks, etc.).\n\nNote: This type uses \\`Record<K, string | undefined>\\` rather than \\`Partial<Record<K, string>>\\`\nfor compatibility with Zod schema generation. Both are functionally equivalent for validation.`),Q.union([Q.string(),Q.undefined()]).describe(`Style variables for theming MCP apps.\n\nIndividual style keys are optional - hosts may provide any subset of these values.\nValues are strings containing CSS values (colors, sizes, font stacks, etc.).\n\nNote: This type uses \\`Record<K, string | undefined>\\` rather than \\`Partial<Record<K, string>>\\`\nfor compatibility with Zod schema generation. Both are functionally equivalent for validation.`)).describe(`Style variables for theming MCP apps.\n\nIndividual style keys are optional - hosts may provide any subset of these values.\nValues are strings containing CSS values (colors, sizes, font stacks, etc.).\n\nNote: This type uses \\`Record<K, string | undefined>\\` rather than \\`Partial<Record<K, string>>\\`\nfor compatibility with Zod schema generation. Both are functionally equivalent for validation.`),L=Q.object({method:Q.literal(\"ui/open-link\"),params:Q.object({url:Q.string().describe(\"URL to open in the host's browser\")})}),P=Q.object({isError:Q.boolean().optional().describe(\"True if the host failed to open the URL (e.g., due to security policy).\")}).passthrough(),A=Q.object({isError:Q.boolean().optional().describe(\"True if the download failed (e.g., user cancelled or host denied).\")}).passthrough(),U=Q.object({isError:Q.boolean().optional().describe(\"True if the host rejected or failed to deliver the message.\")}).passthrough(),w=Q.object({method:Q.literal(\"ui/notifications/sandbox-proxy-ready\"),params:Q.object({})}),O=Q.object({connectDomains:Q.array(Q.string()).optional().describe(`Origins for network requests (fetch/XHR/WebSocket).\n\n- Maps to CSP \\`connect-src\\` directive\n- Empty or omitted → no network connections (secure default)`),resourceDomains:Q.array(Q.string()).optional().describe(\"Origins for static resources (images, scripts, stylesheets, fonts, media).\\n\\n- Maps to CSP `img-src`, `script-src`, `style-src`, `font-src`, `media-src` directives\\n- Wildcard subdomains supported: `https://*.example.com`\\n- Empty or omitted → no network resources (secure default)\"),frameDomains:Q.array(Q.string()).optional().describe(\"Origins for nested iframes.\\n\\n- Maps to CSP `frame-src` directive\\n- Empty or omitted → no nested iframes allowed (`frame-src 'none'`)\"),baseUriDomains:Q.array(Q.string()).optional().describe(\"Allowed base URIs for the document.\\n\\n- Maps to CSP `base-uri` directive\\n- Empty or omitted → only same origin allowed (`base-uri 'self'`)\")}),z=Q.object({camera:Q.object({}).optional().describe(\"Request camera access.\\n\\nMaps to Permission Policy `camera` feature.\"),microphone:Q.object({}).optional().describe(\"Request microphone access.\\n\\nMaps to Permission Policy `microphone` feature.\"),geolocation:Q.object({}).optional().describe(\"Request geolocation access.\\n\\nMaps to Permission Policy `geolocation` feature.\"),clipboardWrite:Q.object({}).optional().describe(\"Request clipboard write access.\\n\\nMaps to Permission Policy `clipboard-write` feature.\")}),H=Q.object({method:Q.literal(\"ui/notifications/size-changed\"),params:Q.object({width:Q.number().optional().describe(\"New width in pixels.\"),height:Q.number().optional().describe(\"New height in pixels.\")})}),R=Q.object({method:Q.literal(\"ui/notifications/tool-input\"),params:Q.object({arguments:Q.record(Q.string(),Q.unknown().describe(\"Complete tool call arguments as key-value pairs.\")).optional().describe(\"Complete tool call arguments as key-value pairs.\")})}),T=Q.object({method:Q.literal(\"ui/notifications/tool-input-partial\"),params:Q.object({arguments:Q.record(Q.string(),Q.unknown().describe(\"Partial tool call arguments (incomplete, may change).\")).optional().describe(\"Partial tool call arguments (incomplete, may change).\")})}),M=Q.object({method:Q.literal(\"ui/notifications/tool-cancelled\"),params:Q.object({reason:Q.string().optional().describe('Optional reason for the cancellation (e.g., \"user action\", \"timeout\").')})}),o=Q.object({fonts:Q.string().optional()}),s=Q.object({variables:RQ.optional().describe(\"CSS variables for theming the app.\"),css:o.optional().describe(\"CSS blocks that apps can inject.\")}),C=Q.object({method:Q.literal(\"ui/resource-teardown\"),params:Q.object({})}),S=Q.record(Q.string(),Q.unknown()),F=Q.object({text:Q.object({}).optional().describe(\"Host supports text content blocks.\"),image:Q.object({}).optional().describe(\"Host supports image content blocks.\"),audio:Q.object({}).optional().describe(\"Host supports audio content blocks.\"),resource:Q.object({}).optional().describe(\"Host supports resource content blocks.\"),resourceLink:Q.object({}).optional().describe(\"Host supports resource link content blocks.\"),structuredContent:Q.object({}).optional().describe(\"Host supports structured content.\")}),q=Q.object({method:Q.literal(\"ui/notifications/request-teardown\"),params:Q.object({}).optional()}),t=Q.object({experimental:Q.object({}).optional().describe(\"Experimental features (structure TBD).\"),openLinks:Q.object({}).optional().describe(\"Host supports opening external URLs.\"),downloadFile:Q.object({}).optional().describe(\"Host supports file downloads via ui/download-file.\"),serverTools:Q.object({listChanged:Q.boolean().optional().describe(\"Host supports tools/list_changed notifications.\")}).optional().describe(\"Host can proxy tool calls to the MCP server.\"),serverResources:Q.object({listChanged:Q.boolean().optional().describe(\"Host supports resources/list_changed notifications.\")}).optional().describe(\"Host can proxy resource reads to the MCP server.\"),logging:Q.object({}).optional().describe(\"Host accepts log messages.\"),sandbox:Q.object({permissions:z.optional().describe(\"Permissions granted by the host (camera, microphone, geolocation).\"),csp:O.optional().describe(\"CSP domains approved by the host.\")}).optional().describe(\"Sandbox configuration applied by the host.\"),updateModelContext:F.optional().describe(\"Host accepts context updates (ui/update-model-context) to be included in the model's context for future turns.\"),message:F.optional().describe(\"Host supports receiving content messages (ui/message) from the view.\"),sampling:Q.object({tools:Q.object({}).optional().describe(\"Host supports tool use via `tools` and `toolChoice` parameters.\")}).optional().describe(\"Host supports LLM sampling (sampling/createMessage) from the view.\\nMirrors the MCP `ClientCapabilities.sampling` shape so hosts can pass it through.\")}),a=Q.object({experimental:Q.object({}).optional().describe(\"Experimental features (structure TBD).\"),tools:Q.object({listChanged:Q.boolean().optional().describe(\"App supports tools/list_changed notifications.\")}).optional().describe(\"App exposes MCP-style tools that the host can call.\"),availableDisplayModes:Q.array(B).optional().describe(\"Display modes the app supports.\")}),y=Q.object({method:Q.literal(\"ui/notifications/initialized\"),params:Q.object({}).optional()}),TQ=Q.object({csp:O.optional().describe(\"Content Security Policy configuration for UI resources.\"),permissions:z.optional().describe(\"Sandbox permissions requested by the UI resource.\"),domain:Q.string().optional().describe(`Dedicated origin for view sandbox.\n\nUseful when views need stable, dedicated origins for OAuth callbacks, CORS policies, or API key allowlists.\n\n**Host-dependent:** The format and validation rules for this field are determined by each host. Servers MUST consult host-specific documentation for the expected domain format. Common patterns include:\n- Hash-based subdomains (e.g., \\`{hash}.claudemcpcontent.com\\`)\n- URL-derived subdomains (e.g., \\`www-example-com.oaiusercontent.com\\`)\n\nIf omitted, host uses default sandbox origin (typically per-conversation).`),prefersBorder:Q.boolean().optional().describe(`Visual boundary preference - true if view prefers a visible border.\n\nBoolean requesting whether a visible border and background is provided by the host. Specifying an explicit value for this is recommended because hosts' defaults may vary.\n\n- \\`true\\`: request visible border + background\n- \\`false\\`: request no visible border + background\n- omitted: host decides border`)}),I=Q.object({method:Q.literal(\"ui/request-display-mode\"),params:Q.object({mode:B.describe(\"The display mode being requested.\")})}),g=Q.object({mode:B.describe(\"The display mode that was actually set. May differ from requested if not supported.\")}).passthrough(),e=Q.union([Q.literal(\"model\"),Q.literal(\"app\")]).describe(\"Tool visibility scope - who can access the tool.\"),MQ=Q.object({resourceUri:Q.string().optional(),visibility:Q.array(e).optional().describe(`Who can access this tool. Default: [\"model\", \"app\"]\n- \"model\": Tool visible to and callable by the agent\n- \"app\": Tool callable by the app from this server only`),csp:Q.never().optional(),permissions:Q.never().optional()}),OX=Q.object({mimeTypes:Q.array(Q.string()).optional().describe('Array of supported MIME types for UI resources.\\nMust include `\"text/html;profile=mcp-app\"` for MCP Apps support.')}),f=Q.object({method:Q.literal(\"ui/download-file\"),params:Q.object({contents:Q.array(Q.union([PQ,UQ])).describe(\"Resource contents to download — embedded (inline data) or linked (host fetches). Uses standard MCP resource types.\")})}),k=Q.object({method:Q.literal(\"ui/message\"),params:Q.object({role:Q.literal(\"user\").describe('Message role, currently only \"user\" is supported.'),content:Q.array(c).describe(\"Message content blocks (text, image, etc.).\")})}),CQ=Q.object({method:Q.literal(\"ui/notifications/sandbox-resource-ready\"),params:Q.object({html:Q.string().describe(\"HTML content to load into the inner iframe.\"),sandbox:Q.string().optional().describe(\"Optional override for the inner iframe's sandbox attribute.\"),csp:O.optional().describe(\"CSP configuration from resource metadata.\"),permissions:z.optional().describe(\"Sandbox permissions from resource metadata.\")})}),v=Q.object({method:Q.literal(\"ui/notifications/tool-result\"),params:LQ.describe(\"Standard MCP tool execution result.\")}),x=Q.object({toolInfo:Q.object({id:AQ.optional().describe(\"JSON-RPC id of the tools/call request.\"),tool:wQ.describe(\"Tool definition including name, inputSchema, etc.\")}).optional().describe(\"Metadata of the tool call that instantiated this App.\"),theme:r.optional().describe(\"Current color theme preference.\"),styles:s.optional().describe(\"Style configuration for theming the app.\"),displayMode:B.optional().describe(\"How the UI is currently displayed.\"),availableDisplayModes:Q.array(B).optional().describe(\"Display modes the host supports.\"),containerDimensions:Q.union([Q.object({height:Q.number().describe(\"Fixed container height in pixels.\")}),Q.object({maxHeight:Q.union([Q.number(),Q.undefined()]).optional().describe(\"Maximum container height in pixels.\")})]).and(Q.union([Q.object({width:Q.number().describe(\"Fixed container width in pixels.\")}),Q.object({maxWidth:Q.union([Q.number(),Q.undefined()]).optional().describe(\"Maximum container width in pixels.\")})])).optional().describe(`Container dimensions. Represents the dimensions of the iframe or other\ncontainer holding the app. Specify either width or maxWidth, and either height or maxHeight.`),locale:Q.string().optional().describe(\"User's language and region preference in BCP 47 format.\"),timeZone:Q.string().optional().describe(\"User's timezone in IANA format.\"),userAgent:Q.string().optional().describe(\"Host application identifier.\"),platform:Q.union([Q.literal(\"web\"),Q.literal(\"desktop\"),Q.literal(\"mobile\")]).optional().describe(\"Platform type for responsive design decisions.\"),deviceCapabilities:Q.object({touch:Q.boolean().optional().describe(\"Whether the device supports touch input.\"),hover:Q.boolean().optional().describe(\"Whether the device supports hover interactions.\")}).optional().describe(\"Device input capabilities.\"),safeAreaInsets:Q.object({top:Q.number().describe(\"Top safe area inset in pixels.\"),right:Q.number().describe(\"Right safe area inset in pixels.\"),bottom:Q.number().describe(\"Bottom safe area inset in pixels.\"),left:Q.number().describe(\"Left safe area inset in pixels.\")}).optional().describe(\"Mobile safe area boundaries in pixels.\")}).passthrough(),b=Q.object({method:Q.literal(\"ui/notifications/host-context-changed\"),params:x.describe(\"Partial context update containing only changed fields.\")}),d=Q.object({method:Q.literal(\"ui/update-model-context\"),params:Q.object({content:Q.array(c).optional().describe(\"Context content blocks (text, image, etc.).\"),structuredContent:Q.record(Q.string(),Q.unknown().describe(\"Structured content for machine-readable context data.\")).optional().describe(\"Structured content for machine-readable context data.\")})}),u=Q.object({method:Q.literal(\"ui/initialize\"),params:Q.object({appInfo:l.describe(\"App identification (name and version).\"),appCapabilities:a.describe(\"Features and capabilities this app provides.\"),protocolVersion:Q.string().describe(\"Protocol version this app supports.\")})}),h=Q.object({protocolVersion:Q.string().describe('Negotiated protocol version string (e.g., \"2025-11-21\").'),hostInfo:l.describe(\"Host application identification and version.\"),hostCapabilities:t.describe(\"Features and capabilities provided by the host.\"),hostContext:x.describe(\"Rich context about the host environment.\")}).passthrough();import{mergeCapabilities as yQ}from\"@modelcontextprotocol/sdk/shared/protocol.js\";import{CallToolRequestSchema as gQ,CallToolResultSchema as fQ,CreateMessageResultSchema as kQ,CreateMessageResultWithToolsSchema as vQ,EmptyResultSchema as xQ,ListResourcesResultSchema as bQ,ListToolsRequestSchema as dQ,PingRequestSchema as uQ,ReadResourceResultSchema as hQ}from\"@modelcontextprotocol/sdk/types.js\";import{JSONRPCMessageSchema as SQ}from\"@modelcontextprotocol/sdk/types.js\";class E{eventTarget;eventSource;messageListener;constructor(X=window.parent,Y){this.eventTarget=X;this.eventSource=Y;this.messageListener=(Z)=>{if(Y&&Z.source!==this.eventSource){console.debug(\"Ignoring message from unknown source\",Z);return}let $=SQ.safeParse(Z.data);if($.success)console.debug(\"Parsed message\",$.data),this.onmessage?.($.data);else if(Z.data?.jsonrpc!==\"2.0\")console.debug(\"Ignoring non-JSON-RPC message\",$.error.message,Z);else console.error(\"Failed to parse message\",$.error.message,Z),this.onerror?.(Error(\"Invalid JSON-RPC message received: \"+$.error.message))}}async start(){window.addEventListener(\"message\",this.messageListener)}async send(X,Y){if(X.method!==V)console.debug(\"Sending message\",X);this.eventTarget.postMessage(X,\"*\")}async close(){window.removeEventListener(\"message\",this.messageListener),this.onclose?.()}onclose;onerror;onmessage;sessionId;setProtocolVersion}var qQ={target:\"draft-2020-12\"};async function m(X,Y){let Z=X[\"~standard\"];if(Z.jsonSchema)return Z.jsonSchema[Y](qQ);if(Z.vendor===\"zod\"){let{z:$}=await import(\"zod/v4\");return $.toJSONSchema(X,{io:Y})}throw Error(`Schema (vendor: ${Z.vendor}) does not implement Standard JSON Schema (~standard.jsonSchema). Use a library that does (zod v4, ArkType, Valibot) or wrap your schema accordingly.`)}async function p(X,Y,Z=\"\"){let $=await X[\"~standard\"].validate(Y);if($.issues){let J=$.issues.map((K)=>{let D=K.path?.map((G)=>typeof G===\"object\"?G.key:G).join(\".\");return D?`${D}: ${K.message}`:K.message}).join(\"; \");throw Error(Z+J)}return $.value}import{z as mQ}from\"zod/v4\";var i=\"ui/resourceUri\",pQ=\"text/html;profile=mcp-app\";class QQ extends _{_appInfo;_capabilities;options;_hostCapabilities;_hostInfo;_hostContext;_registeredTools={};_initializedSent=!1;_assertInitialized(X){if(this._initializedSent)return;let Y=`[ext-apps] App.${X}() called before connect() completed the ui/initialize handshake. Await app.connect() before calling this method, or move data loading to an ontoolresult handler.`;if(this.options?.strict)throw Error(Y);console.warn(`${Y}. This will throw in a future release.`)}eventSchemas={toolinput:R,toolinputpartial:T,toolresult:v,toolcancelled:M,hostcontextchanged:b};static ONE_SHOT_EVENTS=new Set([\"toolinput\",\"toolinputpartial\",\"toolresult\",\"toolcancelled\"]);_everHadListener=new Set;_assertHandlerTiming(X){if(!QQ.ONE_SHOT_EVENTS.has(X)||this._everHadListener.has(X))return;if(this._everHadListener.add(X),!this._initializedSent)return;let Y=`[ext-apps] \"${String(X)}\" handler registered after connect() completed the ui/initialize handshake. The host may have already sent this notification. Register handlers before calling app.connect().`;if(this.options?.strict)throw Error(Y);console.warn(Y)}setEventHandler(X,Y){if(Y)this._assertHandlerTiming(X);super.setEventHandler(X,Y)}addEventListener(X,Y){this._assertHandlerTiming(X),super.addEventListener(X,Y)}onEventDispatch(X,Y){if(X===\"hostcontextchanged\")this._hostContext={...this._hostContext,...Y}}constructor(X,Y={},Z={autoResize:!0}){super(Z);this._appInfo=X;this._capabilities=Y;this.options=Z;if(!Z.allowUnsafeEval)mQ.config({jitless:!0});this.setRequestHandler(uQ,($)=>{return console.log(\"Received ping:\",$.params),{}}),this.setEventHandler(\"hostcontextchanged\",void 0)}registerCapabilities(X){if(this.transport)throw Error(\"Cannot register capabilities after transport is established\");this._capabilities=yQ(this._capabilities,X)}registerTool(X,Y,Z){if(this._registeredTools[X])throw Error(`Tool ${X} is already registered`);let $=this,J=()=>{if($._initializedSent&&$._capabilities.tools?.listChanged)$.sendToolListChanged()},K=Y.inputSchema!==void 0,D={title:Y.title,description:Y.description,inputSchema:Y.inputSchema,outputSchema:Y.outputSchema,annotations:Y.annotations,_meta:Y._meta,enabled:!0,enable(){this.enabled=!0,J()},disable(){this.enabled=!1,J()},update(G){Object.assign(this,G),J()},remove(){if($._registeredTools[X]!==D)return;delete $._registeredTools[X],J()},handler:async(G,N)=>{if(!D.enabled)throw Error(`Tool ${X} is disabled`);let W;if(K){let n=D.inputSchema,YQ=n?await p(n,G??{},`Invalid input for tool ${X}: `):G??{};W=await Z(YQ,N)}else W=await Z(N);if(D.outputSchema&&!W.isError)W.structuredContent=await p(D.outputSchema,W.structuredContent,`Invalid output for tool ${X}: `);return W}};if(this._registeredTools[X]=D,!this._capabilities.tools&&!this.transport)this.registerCapabilities({tools:{listChanged:!0}});return this.ensureToolHandlersInitialized(),J(),D}_toolHandlersInitialized=!1;ensureToolHandlersInitialized(){if(this._toolHandlersInitialized)return;this._toolHandlersInitialized=!0,this.oncalltool=async(X,Y)=>{let Z=this._registeredTools[X.name];if(!Z)throw Error(`Tool ${X.name} not found`);return Z.handler(X.arguments,Y)},this.onlisttools=async(X,Y)=>{return{tools:await Promise.all(Object.entries(this._registeredTools).filter(([$,J])=>J.enabled).map(async([$,J])=>{let K={name:$,title:J.title,description:J.description,inputSchema:J.inputSchema?await m(J.inputSchema,\"input\"):{type:\"object\",properties:{}}};if(J.outputSchema)K.outputSchema=await m(J.outputSchema,\"output\");if(J.annotations)K.annotations=J.annotations;if(J._meta)K._meta=J._meta;return K}))}}}async sendToolListChanged(X={}){this._assertInitialized(\"sendToolListChanged\"),await this.notification({method:\"notifications/tools/list_changed\",params:X})}getHostCapabilities(){return this._hostCapabilities}getHostVersion(){return this._hostInfo}getHostContext(){return this._hostContext}get ontoolinput(){return this.getEventHandler(\"toolinput\")}set ontoolinput(X){this.setEventHandler(\"toolinput\",X)}get ontoolinputpartial(){return this.getEventHandler(\"toolinputpartial\")}set ontoolinputpartial(X){this.setEventHandler(\"toolinputpartial\",X)}get ontoolresult(){return this.getEventHandler(\"toolresult\")}set ontoolresult(X){this.setEventHandler(\"toolresult\",X)}get ontoolcancelled(){return this.getEventHandler(\"toolcancelled\")}set ontoolcancelled(X){this.setEventHandler(\"toolcancelled\",X)}get onhostcontextchanged(){return this.getEventHandler(\"hostcontextchanged\")}set onhostcontextchanged(X){this.setEventHandler(\"hostcontextchanged\",X)}_onteardown;get onteardown(){return this._onteardown}set onteardown(X){this.warnIfRequestHandlerReplaced(\"onteardown\",this._onteardown,X),this._onteardown=X,this.replaceRequestHandler(C,(Y,Z)=>{if(!this._onteardown)throw Error(\"No onteardown handler set\");return this._onteardown(Y.params,Z)})}_oncalltool;get oncalltool(){return this._oncalltool}set oncalltool(X){this.warnIfRequestHandlerReplaced(\"oncalltool\",this._oncalltool,X),this._oncalltool=X,this.replaceRequestHandler(gQ,(Y,Z)=>{if(!this._oncalltool)throw Error(\"No oncalltool handler set\");return this._oncalltool(Y.params,Z)})}_onlisttools;get onlisttools(){return this._onlisttools}set onlisttools(X){this.warnIfRequestHandlerReplaced(\"onlisttools\",this._onlisttools,X),this._onlisttools=X,this.replaceRequestHandler(dQ,(Y,Z)=>{if(!this._onlisttools)throw Error(\"No onlisttools handler set\");return this._onlisttools(Y.params,Z)})}assertCapabilityForMethod(X){switch(X){case\"sampling/createMessage\":if(!this._hostCapabilities?.sampling)throw Error(`Host does not support sampling (required for ${X})`);break}}assertRequestHandlerCapability(X){switch(X){case\"tools/call\":case\"tools/list\":if(!this._capabilities.tools)throw Error(`Client does not support tool capability (required for ${X})`);return;case\"ping\":case\"ui/resource-teardown\":return;default:throw Error(`No handler for method ${X} registered`)}}assertNotificationCapability(X){}assertTaskCapability(X){throw Error(\"Tasks are not supported in MCP Apps\")}assertTaskHandlerCapability(X){throw Error(\"Task handlers are not supported in MCP Apps\")}async callServerTool(X,Y){if(this._assertInitialized(\"callServerTool\"),typeof X===\"string\")throw Error(`callServerTool() expects an object as its first argument, but received a string (\"${X}\"). Did you mean: callServerTool({ name: \"${X}\", arguments: { ... } })?`);return await this.request({method:\"tools/call\",params:X},fQ,{onprogress:()=>{},resetTimeoutOnProgress:!0,...Y})}async readServerResource(X,Y){return this._assertInitialized(\"readServerResource\"),await this.request({method:\"resources/read\",params:X},hQ,Y)}async listServerResources(X,Y){return this._assertInitialized(\"listServerResources\"),await this.request({method:\"resources/list\",params:X},bQ,Y)}async createSamplingMessage(X,Y){this._assertInitialized(\"createSamplingMessage\");let Z=X.tools?vQ:kQ;return await this.request({method:\"sampling/createMessage\",params:X},Z,Y)}sendMessage(X,Y){return this._assertInitialized(\"sendMessage\"),this.request({method:\"ui/message\",params:X},U,Y)}sendLog(X){return this.notification({method:\"notifications/message\",params:X})}updateModelContext(X,Y){return this._assertInitialized(\"updateModelContext\"),this.request({method:\"ui/update-model-context\",params:X},xQ,Y)}openLink(X,Y){return this._assertInitialized(\"openLink\"),this.request({method:\"ui/open-link\",params:X},P,Y)}sendOpenLink=this.openLink;downloadFile(X,Y){return this._assertInitialized(\"downloadFile\"),this.request({method:\"ui/download-file\",params:X},A,Y)}requestTeardown(X={}){return this.notification({method:\"ui/notifications/request-teardown\",params:X})}requestDisplayMode(X,Y){return this._assertInitialized(\"requestDisplayMode\"),this.request({method:\"ui/request-display-mode\",params:X},g,Y)}sendSizeChanged(X){return this.notification({method:\"ui/notifications/size-changed\",params:X})}setupSizeChangedNotifications(){let X=!1,Y=0,Z=0,$=()=>{if(X)return;X=!0,requestAnimationFrame(()=>{X=!1;let K=document.documentElement,D=K.style.height;K.style.height=\"max-content\";let G=Math.ceil(K.getBoundingClientRect().height);K.style.height=D;let N=Math.ceil(window.innerWidth);if(N!==Y||G!==Z)Y=N,Z=G,this.sendSizeChanged({width:N,height:G})})};$();let J=new ResizeObserver($);return J.observe(document.documentElement),J.observe(document.body),()=>J.disconnect()}async connect(X=new E(window.parent,window.parent),Y){if(this.transport)throw Error(\"App is already connected. Call close() before connecting again.\");this._initializedSent=!1,await super.connect(X);try{let Z=await this.request({method:\"ui/initialize\",params:{appCapabilities:this._capabilities,appInfo:this._appInfo,protocolVersion:j}},h,Y);if(Z===void 0)throw Error(`Server sent invalid initialize result: ${Z}`);if(this._hostCapabilities=Z.hostCapabilities,this._hostInfo=Z.hostInfo,this._hostContext=Z.hostContext,await this.notification({method:\"ui/notifications/initialized\"}),this._initializedSent=!0,this.options?.autoResize)this.setupSizeChangedNotifications()}catch(Z){throw this.close(),Z}}}function FZ(X){let Z=X._meta?.ui?.resourceUri;if(Z===void 0)Z=X._meta?.[i];if(typeof Z===\"string\"&&Z.startsWith(\"ui://\"))return Z;else if(Z!==void 0)throw Error(`Invalid UI resource URI: ${JSON.stringify(Z)}`);return}function LZ(X){let Z=X._meta?.ui?.visibility;if(!Z)return!1;if(Z.length===1&&Z[0]===\"model\")return!0;return!1}function PZ(X){let Z=X._meta?.ui?.visibility;if(!Z)return!1;if(Z.length===1&&Z[0]===\"app\")return!0;return!1}function AZ(X){if(!X)return\"\";let Y=[];if(X.camera)Y.push(\"camera\");if(X.microphone)Y.push(\"microphone\");if(X.geolocation)Y.push(\"geolocation\");if(X.clipboardWrite)Y.push(\"clipboard-write\");return Y.join(\"; \")}var KX=[j];class DX extends _{_client;_hostInfo;_capabilities;_appCapabilities;_hostContext={};_appInfo;_initializedReceived=!1;_baseReplaceRequestHandler=this.replaceRequestHandler;replaceRequestHandler=(X,Y)=>{this._baseReplaceRequestHandler(X,(Z,$)=>{if(!this._initializedReceived)console.warn(`[ext-apps] AppBridge received '${Z.method}' before ui/notifications/initialized. The View is calling host methods before completing the handshake; it should await app.connect() first.`);return Y(Z,$)})};eventSchemas={sizechange:H,sandboxready:w,initialized:y,requestteardown:q,loggingmessage:eQ};constructor(X,Y,Z,$){super($);this._client=X;this._hostInfo=Y;this._capabilities=Z;this.addEventListener(\"initialized\",()=>{this._initializedReceived=!0}),this._hostContext=$?.hostContext||{},this.setRequestHandler(u,(J)=>this._oninitialize(J)),this.setRequestHandler(QX,(J,K)=>{return this.onping?.(J.params,K),{}}),this.replaceRequestHandler(I,(J)=>{return{mode:this._hostContext.displayMode??\"inline\"}})}getAppCapabilities(){return this._appCapabilities}getAppVersion(){return this._appInfo}onping;get onsizechange(){return this.getEventHandler(\"sizechange\")}set onsizechange(X){this.setEventHandler(\"sizechange\",X)}get onsandboxready(){return this.getEventHandler(\"sandboxready\")}set onsandboxready(X){this.setEventHandler(\"sandboxready\",X)}get oninitialized(){return this.getEventHandler(\"initialized\")}set oninitialized(X){this.setEventHandler(\"initialized\",X)}_onmessage;get onmessage(){return this._onmessage}set onmessage(X){this.warnIfRequestHandlerReplaced(\"onmessage\",this._onmessage,X),this._onmessage=X,this.replaceRequestHandler(k,async(Y,Z)=>{if(!this._onmessage)throw Error(\"No onmessage handler set\");return this._onmessage(Y.params,Z)})}_onopenlink;get onopenlink(){return this._onopenlink}set onopenlink(X){this.warnIfRequestHandlerReplaced(\"onopenlink\",this._onopenlink,X),this._onopenlink=X,this.replaceRequestHandler(L,async(Y,Z)=>{if(!this._onopenlink)throw Error(\"No onopenlink handler set\");return this._onopenlink(Y.params,Z)})}_ondownloadfile;get ondownloadfile(){return this._ondownloadfile}set ondownloadfile(X){this.warnIfRequestHandlerReplaced(\"ondownloadfile\",this._ondownloadfile,X),this._ondownloadfile=X,this.replaceRequestHandler(f,async(Y,Z)=>{if(!this._ondownloadfile)throw Error(\"No ondownloadfile handler set\");return this._ondownloadfile(Y.params,Z)})}get onrequestteardown(){return this.getEventHandler(\"requestteardown\")}set onrequestteardown(X){this.setEventHandler(\"requestteardown\",X)}_onrequestdisplaymode;get onrequestdisplaymode(){return this._onrequestdisplaymode}set onrequestdisplaymode(X){this.warnIfRequestHandlerReplaced(\"onrequestdisplaymode\",this._onrequestdisplaymode,X),this._onrequestdisplaymode=X,this.replaceRequestHandler(I,async(Y,Z)=>{if(!this._onrequestdisplaymode)throw Error(\"No onrequestdisplaymode handler set\");return this._onrequestdisplaymode(Y.params,Z)})}get onloggingmessage(){return this.getEventHandler(\"loggingmessage\")}set onloggingmessage(X){this.setEventHandler(\"loggingmessage\",X)}_onupdatemodelcontext;get onupdatemodelcontext(){return this._onupdatemodelcontext}set onupdatemodelcontext(X){this.warnIfRequestHandlerReplaced(\"onupdatemodelcontext\",this._onupdatemodelcontext,X),this._onupdatemodelcontext=X,this.replaceRequestHandler(d,async(Y,Z)=>{if(!this._onupdatemodelcontext)throw Error(\"No onupdatemodelcontext handler set\");return this._onupdatemodelcontext(Y.params,Z)})}_oncalltool;get oncalltool(){return this._oncalltool}set oncalltool(X){this.warnIfRequestHandlerReplaced(\"oncalltool\",this._oncalltool,X),this._oncalltool=X,this.replaceRequestHandler(iQ,async(Y,Z)=>{if(!this._oncalltool)throw Error(\"No oncalltool handler set\");return this._oncalltool(Y.params,Z)})}set oncreatesamplingmessage(X){this.setRequestHandler(nQ,async(Y,Z)=>{return X(Y.params,Z)})}sendToolListChanged(X={}){return this.notification({method:\"notifications/tools/list_changed\",params:X})}_onlistresources;get onlistresources(){return this._onlistresources}set onlistresources(X){this.warnIfRequestHandlerReplaced(\"onlistresources\",this._onlistresources,X),this._onlistresources=X,this.replaceRequestHandler(rQ,async(Y,Z)=>{if(!this._onlistresources)throw Error(\"No onlistresources handler set\");return this._onlistresources(Y.params,Z)})}_onlistresourcetemplates;get onlistresourcetemplates(){return this._onlistresourcetemplates}set onlistresourcetemplates(X){this.warnIfRequestHandlerReplaced(\"onlistresourcetemplates\",this._onlistresourcetemplates,X),this._onlistresourcetemplates=X,this.replaceRequestHandler(sQ,async(Y,Z)=>{if(!this._onlistresourcetemplates)throw Error(\"No onlistresourcetemplates handler set\");return this._onlistresourcetemplates(Y.params,Z)})}_onreadresource;get onreadresource(){return this._onreadresource}set onreadresource(X){this.warnIfRequestHandlerReplaced(\"onreadresource\",this._onreadresource,X),this._onreadresource=X,this.replaceRequestHandler(YX,async(Y,Z)=>{if(!this._onreadresource)throw Error(\"No onreadresource handler set\");return this._onreadresource(Y.params,Z)})}sendResourceListChanged(X={}){return this.notification({method:\"notifications/resources/list_changed\",params:X})}_onlistprompts;get onlistprompts(){return this._onlistprompts}set onlistprompts(X){this.warnIfRequestHandlerReplaced(\"onlistprompts\",this._onlistprompts,X),this._onlistprompts=X,this.replaceRequestHandler(cQ,async(Y,Z)=>{if(!this._onlistprompts)throw Error(\"No onlistprompts handler set\");return this._onlistprompts(Y.params,Z)})}sendPromptListChanged(X={}){return this.notification({method:\"notifications/prompts/list_changed\",params:X})}assertCapabilityForMethod(X){}assertRequestHandlerCapability(X){}assertNotificationCapability(X){}assertTaskCapability(X){throw Error(\"Tasks are not supported in MCP Apps\")}assertTaskHandlerCapability(X){throw Error(\"Task handlers are not supported in MCP Apps\")}getCapabilities(){return this._capabilities}async _oninitialize(X){let Y=X.params.protocolVersion;if(this._appInfo!==void 0)console.warn(\"[ext-apps] AppBridge received a second ui/initialize. The View may be double-mounting (e.g. React StrictMode in dev) without closing the previous App instance. Responding normally; the latest appInfo/appCapabilities replace the previous values.\");return this._appCapabilities=X.params.appCapabilities,this._appInfo=X.params.appInfo,{protocolVersion:KX.includes(Y)?Y:j,hostCapabilities:this.getCapabilities(),hostInfo:this._hostInfo,hostContext:this._hostContext}}setHostContext(X){let Y={},Z=!1;for(let $ of Object.keys(X)){let J=this._hostContext[$],K=X[$];if(GX(J,K))continue;Y[$]=K,Z=!0}if(Z)this._hostContext=X,this.sendHostContextChange(Y)}sendHostContextChange(X){return this.notification({method:\"ui/notifications/host-context-changed\",params:X})}sendToolInput(X){return this.notification({method:\"ui/notifications/tool-input\",params:X})}sendToolInputPartial(X){return this.notification({method:\"ui/notifications/tool-input-partial\",params:X})}sendToolResult(X){return this.notification({method:\"ui/notifications/tool-result\",params:X})}sendToolCancelled(X){return this.notification({method:\"ui/notifications/tool-cancelled\",params:X})}sendSandboxResourceReady(X){return this.notification({method:\"ui/notifications/sandbox-resource-ready\",params:X})}teardownResource(X,Y){return this.request({method:\"ui/resource-teardown\",params:X},S,Y)}sendResourceTeardown=this.teardownResource;callTool(X,Y){return this.request({method:\"tools/call\",params:X},XQ,Y)}listTools(X,Y){return this.request({method:\"tools/list\",params:X},aQ,Y)}async connect(X){if(this.transport)throw Error(\"AppBridge is already connected. Call close() before connecting again.\");if(this._initializedReceived=!1,this._client){let Y=this._client.getServerCapabilities();if(!Y)throw Error(\"Client server capabilities not available\");if(Y.tools){if(this.oncalltool=async(Z,$)=>{return this._client.request({method:\"tools/call\",params:Z},XQ,{signal:$.signal})},Y.tools.listChanged)this._client.setNotificationHandler(JX,(Z)=>this.sendToolListChanged(Z.params))}if(Y.resources){if(this.onlistresources=async(Z,$)=>{return this._client.request({method:\"resources/list\",params:Z},oQ,{signal:$.signal})},this.onlistresourcetemplates=async(Z,$)=>{return this._client.request({method:\"resources/templates/list\",params:Z},tQ,{signal:$.signal})},this.onreadresource=async(Z,$)=>{return this._client.request({method:\"resources/read\",params:Z},ZX,{signal:$.signal})},Y.resources.listChanged)this._client.setNotificationHandler($X,(Z)=>this.sendResourceListChanged(Z.params))}if(Y.prompts){if(this.onlistprompts=async(Z,$)=>{return this._client.request({method:\"prompts/list\",params:Z},lQ,{signal:$.signal})},Y.prompts.listChanged)this._client.setNotificationHandler(XX,(Z)=>this.sendPromptListChanged(Z.params))}}return super.connect(X)}}function GX(X,Y){return JSON.stringify(X)===JSON.stringify(Y)}export{LZ as isToolVisibilityModelOnly,PZ as isToolVisibilityAppOnly,FZ as getToolUiResourceUri,AZ as buildAllowAttribute,BQ as TOOL_RESULT_METHOD,V as TOOL_INPUT_PARTIAL_METHOD,jQ as TOOL_INPUT_METHOD,_Q as TOOL_CANCELLED_METHOD,KX as SUPPORTED_PROTOCOL_VERSIONS,WQ as SIZE_CHANGED_METHOD,NQ as SANDBOX_RESOURCE_READY_METHOD,GQ as SANDBOX_PROXY_READY_METHOD,i as RESOURCE_URI_META_KEY,zQ as RESOURCE_TEARDOWN_METHOD,pQ as RESOURCE_MIME_TYPE,OQ as REQUEST_TEARDOWN_METHOD,FQ as REQUEST_DISPLAY_MODE_METHOD,E as PostMessageTransport,JQ as OPEN_LINK_METHOD,d as McpUiUpdateModelContextRequestSchema,e as McpUiToolVisibilitySchema,v as McpUiToolResultNotificationSchema,MQ as McpUiToolMetaSchema,T as McpUiToolInputPartialNotificationSchema,R as McpUiToolInputNotificationSchema,M as McpUiToolCancelledNotificationSchema,r as McpUiThemeSchema,F as McpUiSupportedContentBlockModalitiesSchema,H as McpUiSizeChangedNotificationSchema,CQ as McpUiSandboxResourceReadyNotificationSchema,w as McpUiSandboxProxyReadyNotificationSchema,S as McpUiResourceTeardownResultSchema,C as McpUiResourceTeardownRequestSchema,z as McpUiResourcePermissionsSchema,TQ as McpUiResourceMetaSchema,O as McpUiResourceCspSchema,q as McpUiRequestTeardownNotificationSchema,g as McpUiRequestDisplayModeResultSchema,I as McpUiRequestDisplayModeRequestSchema,P as McpUiOpenLinkResultSchema,L as McpUiOpenLinkRequestSchema,U as McpUiMessageResultSchema,k as McpUiMessageRequestSchema,y as McpUiInitializedNotificationSchema,h as McpUiInitializeResultSchema,u as McpUiInitializeRequestSchema,s as McpUiHostStylesSchema,o as McpUiHostCssSchema,x as McpUiHostContextSchema,b as McpUiHostContextChangedNotificationSchema,t as McpUiHostCapabilitiesSchema,A as McpUiDownloadFileResultSchema,f as McpUiDownloadFileRequestSchema,B as McpUiDisplayModeSchema,a as McpUiAppCapabilitiesSchema,DQ as MESSAGE_METHOD,j as LATEST_PROTOCOL_VERSION,IQ as INITIALIZE_METHOD,VQ as INITIALIZED_METHOD,EQ as HOST_CONTEXT_CHANGED_METHOD,KQ as DOWNLOAD_FILE_METHOD,DX as AppBridge};\n","import { useEffect, useRef, useState, type JSX } from \"react\";\nimport {\n AppBridge,\n PostMessageTransport,\n buildAllowAttribute,\n type McpUiResourceCsp,\n type McpUiResourcePermissions,\n} from \"@modelcontextprotocol/ext-apps/app-bridge\";\nimport type { McpUiStyles } from \"@modelcontextprotocol/ext-apps\";\nimport type { CallToolResult } from \"@modelcontextprotocol/sdk/types.js\";\nimport { grackleHostStyleVariables } from \"../../utils/grackleHostStyleVariables.js\";\n\n/** Notification method the outer sandbox proxy posts once it is ready. */\nconst SANDBOX_PROXY_READY: string = \"ui/notifications/sandbox-proxy-ready\";\n\n/** Default host identity reported to widgets during the MCP Apps handshake. */\nconst DEFAULT_HOST_INFO: Readonly<{ name: string; version: string }> = {\n name: \"Grackle\",\n version: \"0.0.0\",\n};\n\n/** URL schemes the default link handler is permitted to open. */\nconst SAFE_LINK_PROTOCOLS: ReadonlySet<string> = new Set([\"http:\", \"https:\"]);\n\n/** True if `url` parses as an `http(s)` URL safe to open in a new browsing context. */\nfunction isSafeHttpUrl(url: string): boolean {\n try {\n return SAFE_LINK_PROTOCOLS.has(new URL(url).protocol);\n } catch {\n return false;\n }\n}\n\n/** A tool call the widget asked the host to run on its behalf. */\nexport interface McpAppWidgetCallToolParams {\n name: string;\n arguments?: Record<string, unknown>;\n}\n\n/**\n * Props for {@link McpAppWidget}. Presentational only — all data and side\n * effects arrive as props (no `useGrackle()`).\n */\nexport interface McpAppWidgetProps {\n /** Widget HTML (`text/html;profile=mcp-app` contents) rendered in the sandbox. */\n widgetHtml: string;\n /** URL of the sandbox proxy, served from a DIFFERENT origin than the host. */\n sandboxProxyUrl: string;\n /** Tool input delivered to the widget via `ui/notifications/tool-input`. */\n toolInput?: Record<string, unknown>;\n /** Tool result delivered to the widget via `ui/notifications/tool-result`. */\n toolResult?: CallToolResult;\n /** Content-Security-Policy domains for the widget (from the resource `_meta.ui`). */\n csp?: McpUiResourceCsp;\n /** Permissions to grant the widget iframe (from the resource `_meta.ui`). */\n permissions?: McpUiResourcePermissions;\n /** Style variables for `hostContext.styles`; defaults to Grackle's live theme. */\n hostStyleVariables?: McpUiStyles;\n /** Color theme reported to the widget; defaults to the document's `data-theme`. */\n theme?: \"light\" | \"dark\";\n /** Host identity reported to the widget; defaults to {@link DEFAULT_HOST_INFO}. */\n hostInfo?: { name: string; version: string };\n /** Handle a tool call the widget requests (no MCP client is wired in T1). */\n onCallTool?: (params: McpAppWidgetCallToolParams) => Promise<CallToolResult>;\n /** Handle a link the widget asks the host to open. */\n onOpenLink?: (url: string) => void;\n /** Handle a message the widget asks the host to surface. */\n onSendMessage?: (message: unknown) => void;\n /** Handle a model-context update pushed by the widget. */\n onUpdateModelContext?: (context: unknown) => void;\n /** Notified when the widget requests a new size. */\n onSizeChange?: (size: { width?: number; height?: number }) => void;\n}\n\n/** Resolve the active theme, preferring the prop, then the document, then light. */\nfunction resolveTheme(theme: McpAppWidgetProps[\"theme\"]): \"light\" | \"dark\" {\n if (theme) {\n return theme;\n }\n if (typeof document !== \"undefined\") {\n const attr: string | null = document.documentElement.getAttribute(\"data-theme\");\n if (attr === \"dark\") {\n return \"dark\";\n }\n }\n return \"light\";\n}\n\n/**\n * Point the iframe at the sandbox proxy and resolve once the proxy reports\n * ready. Returns `false` if the iframe was already loaded (guards against an\n * accidental double-invoke) or if `signal` aborts before the proxy responds.\n *\n * The ready listener is bound to `signal` so it is removed on effect cleanup,\n * and only messages from the proxy window AND its expected origin are accepted.\n */\nfunction loadSandboxProxy(\n iframe: HTMLIFrameElement,\n sandboxProxyUrl: string,\n proxyOrigin: string,\n csp: McpUiResourceCsp | undefined,\n permissions: McpUiResourcePermissions | undefined,\n signal: AbortSignal,\n): Promise<boolean> {\n if (iframe.src) {\n return Promise.resolve(false);\n }\n iframe.setAttribute(\"sandbox\", \"allow-scripts allow-same-origin allow-forms\");\n const allow: string = buildAllowAttribute(permissions);\n if (allow) {\n iframe.setAttribute(\"allow\", allow);\n }\n const ready: Promise<boolean> = new Promise<boolean>((resolve) => {\n const listener = (event: MessageEvent): void => {\n const data: { method?: string } | undefined = event.data as { method?: string } | undefined;\n if (\n event.source === iframe.contentWindow &&\n event.origin === proxyOrigin &&\n data?.method === SANDBOX_PROXY_READY\n ) {\n resolve(true);\n }\n };\n // `{ signal }` removes the listener automatically on effect cleanup, so it\n // never outlives the component even if the proxy never responds.\n window.addEventListener(\"message\", listener, { signal });\n signal.addEventListener(\"abort\", () => resolve(false), { once: true });\n });\n const url: URL = new URL(sandboxProxyUrl, window.location.href);\n if (csp) {\n url.searchParams.set(\"csp\", JSON.stringify(csp));\n }\n iframe.src = url.href;\n return ready;\n}\n\n/** Swallow a settled promise's rejection (the host outlives transient widget errors). */\nfunction ignoreRejection(promise: Promise<unknown> | void): void {\n Promise.resolve(promise).catch(() => undefined);\n}\n\n/**\n * Renders an MCP Apps widget (untrusted HTML) inside a double-iframe sandbox and\n * drives it over the `ext-apps` `AppBridge` postMessage protocol.\n *\n * The Grackle chat pane is not an MCP client, so this constructs the bridge with\n * `null` (no client) and serves tool input/result from props. Wiring the bridge\n * to a live MCP server is a later ticket (#1238).\n */\nexport function McpAppWidget(props: McpAppWidgetProps): JSX.Element {\n const {\n widgetHtml,\n sandboxProxyUrl,\n csp,\n permissions,\n hostStyleVariables,\n theme,\n hostInfo,\n toolInput,\n toolResult,\n onCallTool,\n onOpenLink,\n onSendMessage,\n onUpdateModelContext,\n onSizeChange,\n } = props;\n\n // Fail fast on the isolation-breaking misconfiguration: the sandbox proxy MUST\n // be a different origin than the host, otherwise `window.top` is reachable and\n // the double-iframe guarantee is void.\n if (\n typeof window !== \"undefined\" &&\n new URL(sandboxProxyUrl, window.location.href).origin === window.location.origin\n ) {\n throw new Error(\n \"McpAppWidget: sandboxProxyUrl must be served from a DIFFERENT origin than the host.\",\n );\n }\n\n const iframeRef = useRef<HTMLIFrameElement>(null);\n const bridgeRef = useRef<AppBridge | undefined>(undefined);\n // Flips true once the ui/initialize handshake completes; the tool-input/result\n // effects below key on it so late-arriving props still reach the widget.\n const [initialized, setInitialized] = useState<boolean>(false);\n\n // Keep the latest callbacks in a ref so the setup effect can be keyed only on\n // the widget identity (re-running it would reload the iframe).\n const handlers = useRef({\n onCallTool,\n onOpenLink,\n onSendMessage,\n onUpdateModelContext,\n onSizeChange,\n });\n handlers.current = { onCallTool, onOpenLink, onSendMessage, onUpdateModelContext, onSizeChange };\n\n // csp/permissions are part of the widget identity (they affect the proxy URL\n // and sendSandboxResourceReady), so the iframe must reload when they change.\n const cspKey: string = JSON.stringify(csp ?? null);\n const permissionsKey: string = JSON.stringify(permissions ?? null);\n\n useEffect(() => {\n const iframe: HTMLIFrameElement | null = iframeRef.current;\n if (!iframe) {\n return undefined;\n }\n\n // Origin of the proxy, used to validate inbound proxy messages. The\n // different-origin invariant is enforced at render time (see above).\n const proxyOrigin: string = new URL(sandboxProxyUrl, window.location.href).origin;\n const abortController: AbortController = new AbortController();\n const { signal } = abortController;\n // Read abort state through a function so TS flow-analysis can't narrow it to\n // a constant across the awaits below (cleanup flips it asynchronously).\n const isAborted = (): boolean => signal.aborted;\n let resizeObserver: ResizeObserver | undefined;\n\n const run = async (): Promise<void> => {\n const firstTime: boolean = await loadSandboxProxy(\n iframe,\n sandboxProxyUrl,\n proxyOrigin,\n csp,\n permissions,\n signal,\n );\n if (!firstTime || isAborted()) {\n return;\n }\n\n const bridge = new AppBridge(\n null,\n hostInfo ?? DEFAULT_HOST_INFO,\n { openLinks: {}, updateModelContext: { text: {} } },\n {\n hostContext: {\n theme: resolveTheme(theme),\n platform: \"web\",\n styles: { variables: hostStyleVariables ?? grackleHostStyleVariables() },\n containerDimensions: { maxHeight: 6000 },\n displayMode: \"inline\",\n availableDisplayModes: [\"inline\"],\n },\n },\n );\n bridgeRef.current = bridge;\n\n bridge.oncalltool = async (params): Promise<CallToolResult> => {\n const handler = handlers.current.onCallTool;\n if (handler) {\n return handler({ name: params.name, arguments: params.arguments });\n }\n return {\n isError: true,\n content: [{ type: \"text\", text: \"No MCP client is connected to this host.\" }],\n };\n };\n bridge.onopenlink = async ({ url }): Promise<Record<string, never>> => {\n const handler = handlers.current.onOpenLink;\n if (handler) {\n handler(url);\n } else if (isSafeHttpUrl(url)) {\n // Only http(s) — never javascript:/data: from an untrusted widget.\n window.open(url, \"_blank\", \"noopener,noreferrer\");\n }\n return {};\n };\n bridge.onmessage = async (params): Promise<Record<string, never>> => {\n handlers.current.onSendMessage?.(params);\n return {};\n };\n bridge.onupdatemodelcontext = async (params): Promise<Record<string, never>> => {\n handlers.current.onUpdateModelContext?.(params);\n return {};\n };\n bridge.onsizechange = ({ width, height }): void => {\n if (width !== undefined) {\n iframe.style.minWidth = `min(${width}px, 100%)`;\n }\n if (height !== undefined) {\n iframe.style.height = `${height}px`;\n }\n handlers.current.onSizeChange?.({ width, height });\n };\n bridge.onrequestdisplaymode = async (): Promise<{ mode: \"inline\" }> => ({ mode: \"inline\" });\n\n const handshakeComplete: Promise<void> = new Promise<void>((resolve) => {\n bridge.oninitialized = (): void => resolve();\n });\n\n await bridge.connect(\n new PostMessageTransport(iframe.contentWindow as Window, iframe.contentWindow as Window),\n );\n if (isAborted()) {\n return;\n }\n await bridge.sendSandboxResourceReady({ html: widgetHtml, csp, permissions });\n await handshakeComplete;\n if (isAborted()) {\n return;\n }\n // Tool input/result are delivered (and kept in sync) by the effects below\n // now that the handshake is complete.\n setInitialized(true);\n\n resizeObserver = new ResizeObserver(([entry]) => {\n const width: number = Math.round(entry.contentRect.width);\n if (width > 0) {\n ignoreRejection(\n bridge.sendHostContextChange({ containerDimensions: { width, maxHeight: 6000 } }),\n );\n }\n });\n resizeObserver.observe(iframe);\n };\n\n run().catch(() => undefined);\n\n return (): void => {\n abortController.abort();\n setInitialized(false);\n resizeObserver?.disconnect();\n const bridge: AppBridge | undefined = bridgeRef.current;\n bridgeRef.current = undefined;\n if (bridge) {\n ignoreRejection(bridge.teardownResource({}));\n }\n iframe.removeAttribute(\"src\");\n };\n // Setup is keyed on the widget identity (html + proxy URL + csp/permissions).\n // Tool input/result and theme updates flow via the dedicated effects below.\n }, [widgetHtml, sandboxProxyUrl, cspKey, permissionsKey]);\n\n // Deliver tool input after the handshake, and whenever it changes afterwards.\n useEffect(() => {\n if (!initialized) {\n return;\n }\n ignoreRejection(bridgeRef.current?.sendToolInput({ arguments: toolInput ?? {} }));\n }, [initialized, toolInput]);\n\n // Deliver the tool result once it is available, and whenever it changes. The\n // host commonly renders the widget before the result exists.\n useEffect(() => {\n if (!initialized || !toolResult) {\n return;\n }\n ignoreRejection(bridgeRef.current?.sendToolResult(toolResult));\n }, [initialized, toolResult]);\n\n // Propagate theme + style-variable changes to a live widget. When\n // hostStyleVariables is omitted, the Grackle token values themselves change\n // with the theme, so the resolved variables are re-sent too.\n useEffect(() => {\n ignoreRejection(\n bridgeRef.current?.sendHostContextChange({\n theme: resolveTheme(theme),\n styles: { variables: hostStyleVariables ?? grackleHostStyleVariables() },\n }),\n );\n }, [theme, hostStyleVariables]);\n\n return (\n <iframe\n ref={iframeRef}\n data-testid=\"mcp-app-widget\"\n title=\"MCP App widget\"\n style={{ width: \"100%\", border: \"none\", display: \"block\" }}\n />\n );\n}\n"],"names":["DEFAULT_MCP_STYLES","GRACKLE_TOKEN_BY_MCP_NAME","grackleHostStyleVariables","out","computed","writable","mcpName","grackleToken","value","RELATED_TASK_META_KEY","JSONRPC_VERSION","AssertObjectSchema","z.custom","v","ProgressTokenSchema","z.union","z.string","z.number","CursorSchema","z.looseObject","TaskMetadataSchema","z.object","RelatedTaskMetadataSchema","RequestMetaSchema","BaseRequestParamsSchema","TaskAugmentedRequestParamsSchema","isTaskAugmentedRequestParams","RequestSchema","NotificationsParamsSchema","NotificationSchema","ResultSchema","RequestIdSchema","JSONRPCRequestSchema","z\n .object","z.literal","isJSONRPCRequest","JSONRPCNotificationSchema","isJSONRPCNotification","JSONRPCResultResponseSchema","isJSONRPCResultResponse","ErrorCode","JSONRPCErrorResponseSchema","z.unknown","isJSONRPCErrorResponse","JSONRPCMessageSchema","EmptyResultSchema","CancelledNotificationParamsSchema","CancelledNotificationSchema","IconSchema","z.array","z.enum","IconsSchema","BaseMetadataSchema","ImplementationSchema","FormElicitationCapabilitySchema","z.intersection","z.boolean","z.record","ElicitationCapabilitySchema","z.preprocess","ClientTasksCapabilitySchema","z\n .looseObject","z\n .looseObject","ServerTasksCapabilitySchema","ClientCapabilitiesSchema","z\n .object","InitializeRequestParamsSchema","InitializeRequestSchema","ServerCapabilitiesSchema","InitializeResultSchema","InitializedNotificationSchema","PingRequestSchema","ProgressSchema","z.optional","ProgressNotificationParamsSchema","ProgressNotificationSchema","PaginatedRequestParamsSchema","PaginatedRequestSchema","PaginatedResultSchema","TaskStatusSchema","TaskSchema","z.null","CreateTaskResultSchema","TaskStatusNotificationParamsSchema","TaskStatusNotificationSchema","GetTaskRequestSchema","GetTaskResultSchema","GetTaskPayloadRequestSchema","ListTasksRequestSchema","ListTasksResultSchema","CancelTaskRequestSchema","CancelTaskResultSchema","ResourceContentsSchema","TextResourceContentsSchema","Base64Schema","val","BlobResourceContentsSchema","RoleSchema","AnnotationsSchema","z.iso.datetime","ResourceSchema","ResourceTemplateSchema","ListResourcesRequestSchema","ListResourcesResultSchema","ListResourceTemplatesRequestSchema","ListResourceTemplatesResultSchema","ResourceRequestParamsSchema","ReadResourceRequestParamsSchema","ReadResourceRequestSchema","ReadResourceResultSchema","ResourceListChangedNotificationSchema","SubscribeRequestParamsSchema","SubscribeRequestSchema","UnsubscribeRequestParamsSchema","UnsubscribeRequestSchema","ResourceUpdatedNotificationParamsSchema","ResourceUpdatedNotificationSchema","PromptArgumentSchema","PromptSchema","ListPromptsRequestSchema","ListPromptsResultSchema","GetPromptRequestParamsSchema","GetPromptRequestSchema","TextContentSchema","ImageContentSchema","AudioContentSchema","ToolUseContentSchema","EmbeddedResourceSchema","ResourceLinkSchema","ContentBlockSchema","PromptMessageSchema","GetPromptResultSchema","PromptListChangedNotificationSchema","ToolAnnotationsSchema","ToolExecutionSchema","ToolSchema","ListToolsRequestSchema","ListToolsResultSchema","CallToolResultSchema","CallToolRequestParamsSchema","CallToolRequestSchema","ToolListChangedNotificationSchema","LoggingLevelSchema","SetLevelRequestParamsSchema","SetLevelRequestSchema","LoggingMessageNotificationParamsSchema","LoggingMessageNotificationSchema","ModelHintSchema","ModelPreferencesSchema","ToolChoiceSchema","ToolResultContentSchema","SamplingContentSchema","z.discriminatedUnion","SamplingMessageContentBlockSchema","SamplingMessageSchema","CreateMessageRequestParamsSchema","CreateMessageRequestSchema","CreateMessageResultSchema","CreateMessageResultWithToolsSchema","BooleanSchemaSchema","StringSchemaSchema","NumberSchemaSchema","UntitledSingleSelectEnumSchemaSchema","TitledSingleSelectEnumSchemaSchema","LegacyTitledEnumSchemaSchema","SingleSelectEnumSchemaSchema","UntitledMultiSelectEnumSchemaSchema","TitledMultiSelectEnumSchemaSchema","MultiSelectEnumSchemaSchema","EnumSchemaSchema","PrimitiveSchemaDefinitionSchema","ElicitRequestFormParamsSchema","ElicitRequestURLParamsSchema","ElicitRequestParamsSchema","ElicitRequestSchema","ElicitationCompleteNotificationParamsSchema","ElicitationCompleteNotificationSchema","ElicitResultSchema","ResourceTemplateReferenceSchema","PromptReferenceSchema","CompleteRequestParamsSchema","CompleteRequestSchema","CompleteResultSchema","RootSchema","ListRootsRequestSchema","ListRootsResultSchema","RootsListChangedNotificationSchema","McpError","code","message","data","errorData","UrlElicitationRequiredError","elicitations","_a","isZ4Schema","s","safeParse","schema","z4mini.safeParse","getObjectShape","rawShape","_b","getLiteralValue","def","directValue","isTerminal","status","getMethodLiteral","shape","methodSchema","parseWithCompat","result","DEFAULT_REQUEST_TIMEOUT_MSEC","Protocol","_options","notification","_request","request","extra","task","handleTaskResult","taskId","queuedMessage","requestId","resolver","errorMessage","error","messageType","tasks","nextCursor","cancelledTask","controller","messageId","timeout","maxTotalTimeout","onTimeout","resetTimeoutOnProgress","info","totalElapsed","transport","_onclose","_onerror","_onmessage","_c","responseHandlers","handler","capturedTransport","relatedTaskId","errorResponse","abortController","taskCreationParams","taskStore","fullExtra","_d","notificationOptions","r","resultSchema","options","requestOptions","effectiveTaskId","response","progressToken","params","responseHandler","timeoutInfo","isTaskResponse","createResult","pollInterval","resolve","relatedRequestId","resumptionToken","onresumptiontoken","relatedTask","reject","earlyReject","e","jsonrpcRequest","cancel","reason","parseResult","_e","timeoutHandler","responseResolver","jsonrpcNotification","requestSchema","method","parsed","notificationSchema","sessionId","maxQueueSize","messages","signal","interval","timeoutId","taskParams","statusMessage","updatedTask","cursor","X","Y","Z","_","$Q","__publicField","$","J","K","D","G","j","V","Q.union","Q.literal","B","HQ","RQ","Q.record","Q.string","Q.undefined","L","Q.object","Q.boolean","w","O","Q.array","z","H","Q.number","Q.unknown","o","S","F","q","t","a","y","I","Q.never","f","PQ","UQ","k","c","LQ","x","AQ","wQ","d","u","l","E","SQ","AZ","KX","DX","eQ","QX","iQ","nQ","rQ","sQ","YX","cQ","GX","XQ","aQ","JX","oQ","tQ","ZX","$X","lQ","XX","SANDBOX_PROXY_READY","DEFAULT_HOST_INFO","SAFE_LINK_PROTOCOLS","isSafeHttpUrl","url","resolveTheme","theme","loadSandboxProxy","iframe","sandboxProxyUrl","proxyOrigin","csp","permissions","allow","buildAllowAttribute","ready","listener","event","ignoreRejection","promise","McpAppWidget","props","widgetHtml","hostStyleVariables","hostInfo","toolInput","toolResult","onCallTool","onOpenLink","onSendMessage","onUpdateModelContext","onSizeChange","iframeRef","useRef","bridgeRef","initialized","setInitialized","useState","handlers","cspKey","permissionsKey","useEffect","isAborted","resizeObserver","bridge","AppBridge","width","height","handshakeComplete","PostMessageTransport","entry","jsx"],"mappings":"sZAgBA,MAAMA,GAAkC,CACtC,6BAA8B,+BAC9B,+BAAgC,+BAChC,8BAA+B,+BAC/B,6BAA8B,+BAC9B,2BAA4B,oDAC5B,0BAA2B,+BAC3B,4BAA6B,+BAC7B,6BAA8B,+BAC9B,6BAA8B,+BAC9B,8BAA+B,wDAC/B,uBAAwB,+BACxB,yBAA0B,+BAC1B,wBAAyB,+BACzB,uBAAwB,+BACxB,qBAAsB,2DACtB,oBAAqB,+BACrB,sBAAuB,+BACvB,uBAAwB,+BACxB,uBAAwB,+BACxB,wBAAyB,wDACzB,yBAA0B,+BAC1B,2BAA4B,+BAC5B,0BAA2B,+BAC3B,yBAA0B,qDAC1B,uBAAwB,oDACxB,sBAAuB,+BACvB,wBAAyB,+BACzB,yBAA0B,+BAC1B,yBAA0B,+BAC1B,0BAA2B,wDAC3B,uBAAwB,+BACxB,yBAA0B,+BAC1B,uBAAwB,+BACxB,oBAAqB,+BACrB,sBAAuB,+BACvB,uBAAwB,+BACxB,uBAAwB,+BACxB,cAAe,+EACf,cAAe,8DACf,uBAAwB,MACxB,uBAAwB,MACxB,yBAA0B,MAC1B,qBAAsB,MACtB,sBAAuB,UACvB,sBAAuB,WACvB,sBAAuB,OACvB,sBAAuB,WACvB,yBAA0B,UAC1B,yBAA0B,WAC1B,yBAA0B,OAC1B,yBAA0B,UAC1B,yBAA0B,SAC1B,0BAA2B,WAC3B,0BAA2B,UAC3B,6BAA8B,MAC9B,6BAA8B,MAC9B,6BAA8B,MAC9B,6BAA8B,MAC9B,gCAAiC,MACjC,gCAAiC,MACjC,gCAAiC,MACjC,gCAAiC,MACjC,gCAAiC,OACjC,iCAAkC,MAClC,iCAAkC,MAClC,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