@executor-js/plugin-mcp 1.5.21 → 1.5.23

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.
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/sdk/manifest.ts","../src/sdk/plugin.ts","../src/sdk/connection.ts","../src/sdk/discover.ts","../src/sdk/invoke.ts","../src/sdk/probe-shape.ts"],"sourcesContent":["import { Option, Schema } from \"effect\";\n\nimport { McpToolAnnotations } from \"./types\";\n\n// ---------------------------------------------------------------------------\n// Output types\n// ---------------------------------------------------------------------------\n\nexport interface McpToolManifestEntry {\n readonly toolId: string;\n readonly toolName: string;\n readonly description: string | null;\n readonly inputSchema?: unknown;\n readonly outputSchema?: unknown;\n readonly annotations?: McpToolAnnotations;\n}\n\nexport interface McpServerMetadata {\n readonly name: string | null;\n readonly version: string | null;\n /** The server's `instructions` from initialize, when it sent any. */\n readonly instructions: string | null;\n}\n\nexport interface McpToolManifest {\n readonly server: McpServerMetadata | null;\n readonly tools: readonly McpToolManifestEntry[];\n}\n\n// ---------------------------------------------------------------------------\n// Schemas\n// ---------------------------------------------------------------------------\n\nconst ListedTool = Schema.Struct({\n name: Schema.String,\n description: Schema.optional(Schema.NullOr(Schema.String)),\n inputSchema: Schema.optional(Schema.Unknown),\n parameters: Schema.optional(Schema.Unknown),\n outputSchema: Schema.optional(Schema.Unknown),\n annotations: Schema.optional(McpToolAnnotations),\n});\n\nconst ListToolsResult = Schema.Struct({\n tools: Schema.Array(ListedTool),\n});\n\nconst ServerInfo = Schema.Struct({\n name: Schema.optional(Schema.String),\n version: Schema.optional(Schema.String),\n});\n\nconst decodeListToolsResult = Schema.decodeUnknownOption(ListToolsResult);\nconst decodeServerInfo = Schema.decodeUnknownOption(ServerInfo);\n\nexport const isListToolsResult = (value: unknown): boolean =>\n Option.isSome(decodeListToolsResult(value));\n\n// ---------------------------------------------------------------------------\n// Tool ID sanitization\n// ---------------------------------------------------------------------------\n\nconst sanitize = (value: string): string => {\n const s = value\n .trim()\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, \"_\")\n .replace(/^_+|_+$/g, \"\");\n return s || \"tool\";\n};\n\nconst uniqueId = (value: string, seen: Map<string, number>): string => {\n const base = sanitize(value);\n const n = (seen.get(base) ?? 0) + 1;\n seen.set(base, n);\n return n === 1 ? base : `${base}_${n}`;\n};\n\n// ---------------------------------------------------------------------------\n// Public API\n// ---------------------------------------------------------------------------\n\nexport const joinToolPath = (namespace: string | undefined, toolId: string): string =>\n namespace?.trim() ? `${namespace}.${toolId}` : toolId;\n\nexport const extractManifestFromListToolsResult = (\n listToolsResult: unknown,\n metadata?: { serverInfo?: unknown; instructions?: string | undefined },\n): McpToolManifest => {\n const seen = new Map<string, number>();\n\n const listed = decodeListToolsResult(listToolsResult).pipe(\n Option.map((result) => result.tools),\n Option.getOrElse(() => []),\n );\n\n const server = decodeServerInfo(metadata?.serverInfo).pipe(\n Option.map(\n (info): McpServerMetadata => ({\n name: info.name ?? null,\n version: info.version ?? null,\n instructions: metadata?.instructions ?? null,\n }),\n ),\n Option.getOrNull,\n );\n\n const tools = listed.flatMap((tool): McpToolManifestEntry[] => {\n const toolName = tool.name.trim();\n if (!toolName) return [];\n\n return [\n {\n toolId: uniqueId(toolName, seen),\n toolName,\n description: tool.description ?? null,\n inputSchema: tool.inputSchema ?? tool.parameters,\n outputSchema: tool.outputSchema,\n annotations: tool.annotations,\n },\n ];\n });\n\n return { server, tools };\n};\n\n// ---------------------------------------------------------------------------\n// Namespace derivation\n// ---------------------------------------------------------------------------\n\nconst slugify = (value: string): string =>\n value\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, \"_\")\n .replace(/^_+|_+$/g, \"\");\n\nconst hostnameOf = (url: string): string | null => {\n if (!URL.canParse(url)) return null;\n return new URL(url).hostname;\n};\n\nconst basenameOf = (path: string): string => path.trim().split(/[\\\\/]/).pop() ?? path.trim();\n\nexport const deriveMcpNamespace = (input: {\n name?: string | null;\n endpoint?: string | null;\n command?: string | null;\n}): string => {\n if (input.name?.trim()) return slugify(input.name) || \"mcp\";\n\n const fromEndpoint = input.endpoint?.trim() ? hostnameOf(input.endpoint) : null;\n if (fromEndpoint) return slugify(fromEndpoint) || \"mcp\";\n\n if (input.command?.trim()) return slugify(basenameOf(input.command)) || \"mcp\";\n\n return \"mcp\";\n};\n","import { Effect, Layer, Option, Result, Schema } from \"effect\";\nimport type { HttpClient } from \"effect/unstable/http\";\n\nimport type { OAuthClientProvider } from \"@modelcontextprotocol/sdk/client/auth.js\";\nimport { CallToolResultSchema } from \"@modelcontextprotocol/sdk/types.js\";\nimport * as z from \"zod/v4\";\n\nimport {\n authToolFailure,\n AuthTemplateSlug,\n ConnectionName,\n definePlugin,\n IntegrationAlreadyExistsError,\n IntegrationSlug,\n mergeAuthTemplates,\n OAuthClientSlug,\n tool,\n ToolResult,\n type AuthMethodDescriptor,\n type Integration,\n type IntegrationConfig,\n type IntegrationRecord,\n type OAuthClientSummary,\n type Owner,\n type PluginCtx,\n type StaticToolSchema,\n type StorageFailure,\n type ToolAnnotations,\n type ToolDef,\n ToolName,\n} from \"@executor-js/sdk\";\n\nimport {\n TOKEN_VARIABLE,\n describeApiKeyAuthMethod,\n describeNoneAuthMethod,\n renderAuthPlacements,\n requiredPlacementVariables,\n} from \"@executor-js/sdk/http-auth\";\n\nimport { createMcpConnector, type ConnectorInput, type McpConnector } from \"./connection\";\nimport { discoverTools } from \"./discover\";\nimport {\n McpConnectionError,\n McpOAuthReauthorizationRequired,\n McpToolDiscoveryError,\n} from \"./errors\";\nimport { invokeMcpTool } from \"./invoke\";\nimport { deriveMcpNamespace, type McpToolManifestEntry } from \"./manifest\";\nimport { mcpPresets } from \"./presets\";\nimport { probeMcpEndpointShape, type McpShapeProbeResult } from \"./probe-shape\";\nimport {\n McpAuthMethodInput,\n McpAuthShorthand,\n McpRemoteTransport,\n type McpAuthMethod,\n type McpToolAnnotations,\n expandMcpAuthMethodInputs,\n mcpAuthMethodFromShorthand,\n normalizeMcpAuthMethods,\n parseMcpIntegrationConfig,\n type McpIntegrationConfig as McpIntegrationConfigType,\n type McpStdioEnvMethod,\n type McpStdioIntegrationConfig,\n} from \"./types\";\n\nconst MCP_PLUGIN_ID = \"mcp\" as const;\n\nconst legacyOAuthClientSlugCandidate = (value: string): string | null => {\n const slug = value\n .trim()\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, \"-\")\n .replace(/^-+|-+$/g, \"\");\n return slug.length > 0 ? slug : null;\n};\n\nconst legacyOAuthClientSlugCandidates = (\n slug: string,\n integration: (Integration & { readonly config: IntegrationConfig }) | null,\n): ReadonlySet<string> => {\n const candidates = new Set<string>();\n const fromSlug = legacyOAuthClientSlugCandidate(slug);\n if (fromSlug) candidates.add(fromSlug);\n const fromDescription =\n integration == null ? null : legacyOAuthClientSlugCandidate(integration.description);\n if (fromDescription) candidates.add(fromDescription);\n return candidates;\n};\n\nconst oauthClientKey = (owner: Owner, slug: OAuthClientSlug): string => `${owner}:${String(slug)}`;\n\nconst legacyMcpClientMatches = (\n client: OAuthClientSummary,\n candidates: ReadonlySet<string>,\n config: McpIntegrationConfigType | null,\n): boolean => {\n if (!candidates.has(String(client.slug))) return false;\n if (\n !config ||\n config.transport !== \"remote\" ||\n !config.authenticationTemplate.some((method: McpAuthMethod) => method.kind === \"oauth2\")\n ) {\n return false;\n }\n return client.grant === \"authorization_code\" && (client.resource ?? null) === config.endpoint;\n};\n\n// ---------------------------------------------------------------------------\n// Tool annotations carry an `mcp` envelope alongside the executor's policy\n// hints. The executor persists `ToolDef.annotations` verbatim into the tool\n// row's JSON column, so the real MCP tool name + upstream annotations survive\n// to `invokeTool` / `resolveAnnotations` with no plugin-side store (resolveTools\n// has no ctx to write one anyway). The envelope is opaque to core.\n// ---------------------------------------------------------------------------\n\ninterface McpToolStamp {\n readonly toolName: string;\n readonly upstream?: McpToolAnnotations;\n}\n\ntype StampedAnnotations = ToolAnnotations & { readonly mcp: McpToolStamp };\n\nconst McpStampSchema = Schema.Struct({\n toolName: Schema.String,\n upstream: Schema.optional(\n Schema.Struct({\n title: Schema.optional(Schema.String),\n readOnlyHint: Schema.optional(Schema.Boolean),\n destructiveHint: Schema.optional(Schema.Boolean),\n idempotentHint: Schema.optional(Schema.Boolean),\n openWorldHint: Schema.optional(Schema.Boolean),\n }),\n ),\n});\nconst AnnotationsWithStamp = Schema.Struct({ mcp: McpStampSchema });\nconst decodeStamp = Schema.decodeUnknownOption(AnnotationsWithStamp);\n\nconst readStamp = (annotations: unknown): McpToolStamp | null =>\n Option.match(decodeStamp(annotations), {\n onNone: () => null,\n onSome: (decoded) => decoded.mcp,\n });\n\n// ---------------------------------------------------------------------------\n// Extension input shapes — `addServer` registers an MCP integration. A\n// connection (the credential) is then created against it via\n// `executor.connections.create` / `oauth.start`.\n// ---------------------------------------------------------------------------\n\nconst McpRemoteServerInputSchema = Schema.Struct({\n transport: Schema.optional(Schema.Literal(\"remote\")),\n name: Schema.String,\n /** Agent-visible catalog description. Defaults to the display name. */\n description: Schema.optional(Schema.String),\n endpoint: Schema.String,\n remoteTransport: Schema.optional(McpRemoteTransport),\n headers: Schema.optional(Schema.Record(Schema.String, Schema.String)),\n queryParams: Schema.optional(Schema.Record(Schema.String, Schema.String)),\n slug: Schema.optional(Schema.String),\n /** Declared auth methods a connection can be applied through. */\n authenticationTemplate: Schema.optional(Schema.Array(McpAuthMethodInput)),\n /** Single-method shorthand (legacy callers). Ignored when\n * `authenticationTemplate` is present. Defaults to none. */\n auth: Schema.optional(McpAuthShorthand),\n});\n\nconst McpStdioServerInputSchema = Schema.Struct({\n transport: Schema.Literal(\"stdio\"),\n name: Schema.String,\n description: Schema.optional(Schema.String),\n command: Schema.String,\n args: Schema.optional(Schema.Array(Schema.String)),\n /** DECLARE the secret env vars this server needs, by NAME. Their values are\n * supplied as the connection's secret credentials, not here — so the UI\n * defines what env vars exist and the connect step provides the secrets. */\n envVars: Schema.optional(Schema.Array(Schema.String)),\n /** Provide secret env values directly (programmatic / agent one-shot): the\n * add then auto-creates the connection holding them. The UI uses `envVars`\n * instead and leaves the values to the connect step. */\n env: Schema.optional(Schema.Record(Schema.String, Schema.String)),\n cwd: Schema.optional(Schema.String),\n slug: Schema.optional(Schema.String),\n});\n\nconst McpAddServerInputSchema = Schema.Union([\n McpRemoteServerInputSchema,\n McpStdioServerInputSchema,\n]);\n\nconst McpAddServerOutputSchema = Schema.Struct({\n slug: Schema.String,\n});\n\n/** Input for the custom-method-create flow. `merge` (default) appends onto the\n * integration's existing `authenticationTemplate`; `replace` swaps the whole\n * declared set. Mirrors the OpenAPI/GraphQL `configureAuth` inputs. */\nexport const McpConfigureAuthInputSchema = Schema.Struct({\n authenticationTemplate: Schema.Array(McpAuthMethodInput),\n mode: Schema.optional(Schema.Literals([\"merge\", \"replace\"])),\n});\nexport type McpConfigureAuthInput = typeof McpConfigureAuthInputSchema.Type;\n\nconst McpProbeEndpointInputSchema = Schema.Struct({\n endpoint: Schema.String,\n headers: Schema.optional(Schema.Record(Schema.String, Schema.String)),\n queryParams: Schema.optional(Schema.Record(Schema.String, Schema.String)),\n});\n\nconst McpProbeEndpointOutputSchema = Schema.Struct({\n connected: Schema.Boolean,\n requiresAuthentication: Schema.Boolean,\n requiresOAuth: Schema.Boolean,\n supportsDynamicRegistration: Schema.Boolean,\n name: Schema.String,\n slug: Schema.String,\n toolCount: Schema.NullOr(Schema.Number),\n serverName: Schema.NullOr(Schema.String),\n /** The server's `instructions` from initialize — prefill for the add form's\n * description. Only available when the probe connected unauthenticated. */\n instructions: Schema.NullOr(Schema.String),\n});\n\n// ---------------------------------------------------------------------------\n// Extension input/output shapes — `addServer` registers an MCP integration. A\n// connection (the credential) is then created against it via\n// `executor.connections.create` / `oauth.start`. Types are inferred from the\n// schemas above so the wire shape and the TS surface can't drift.\n// ---------------------------------------------------------------------------\n\nexport type McpRemoteServerInput = typeof McpRemoteServerInputSchema.Type;\nexport type McpStdioServerInput = typeof McpStdioServerInputSchema.Type;\nexport type McpServerInput = typeof McpAddServerInputSchema.Type;\nexport type McpProbeResult = typeof McpProbeEndpointOutputSchema.Type;\nexport type McpProbeEndpointInput = typeof McpProbeEndpointInputSchema.Type;\n\nconst McpGetServerInputSchema = Schema.Struct({\n slug: Schema.String,\n});\n\nconst McpGetServerOutputSchema = Schema.Struct({\n integration: Schema.NullOr(Schema.Unknown),\n});\n\nconst schemaToStaticToolSchema = <A, I>(schema: Schema.Decoder<A, I>): StaticToolSchema<A, I> =>\n Schema.toStandardSchemaV1(Schema.toStandardJSONSchemaV1(schema) as never) as StaticToolSchema<\n A,\n I\n >;\n\nconst McpAddServerInputStandardSchema = schemaToStaticToolSchema(McpAddServerInputSchema);\nconst McpAddServerOutputStandardSchema = schemaToStaticToolSchema(McpAddServerOutputSchema);\nconst McpProbeEndpointInputStandardSchema = schemaToStaticToolSchema(McpProbeEndpointInputSchema);\nconst McpProbeEndpointOutputStandardSchema = schemaToStaticToolSchema(McpProbeEndpointOutputSchema);\nconst McpGetServerInputStandardSchema = schemaToStaticToolSchema(McpGetServerInputSchema);\nconst McpGetServerOutputStandardSchema = schemaToStaticToolSchema(McpGetServerOutputSchema);\n\nconst mcpToolFailure = (code: string, message: string, details?: unknown) =>\n ToolResult.fail({\n code,\n message,\n ...(details === undefined ? {} : { details }),\n });\n\nconst mcpInvocationAuthFailure = (input: {\n readonly status: 401 | 403;\n readonly integration: string;\n readonly connection: string;\n}) =>\n authToolFailure({\n code: \"connection_rejected\",\n message:\n input.status === 403\n ? `MCP server rejected connection \"${input.connection}\" with HTTP 403. The credential may lack access or required scope; re-authenticate or update the connection before retrying this tool.`\n : `MCP server rejected connection \"${input.connection}\" with HTTP 401. Re-authenticate or update the connection before retrying this tool.`,\n source: { id: input.integration },\n credential: { kind: \"upstream\", label: input.connection },\n status: input.status,\n upstream: { status: input.status },\n });\n\nconst mcpInvocationOAuthReauthFailure = (input: {\n readonly integration: string;\n readonly connection: string;\n}) =>\n authToolFailure({\n code: \"oauth_reauth_required\",\n message: `OAuth connection \"${input.connection}\" requires reauthorization before retrying this MCP tool.`,\n source: { id: input.integration },\n credential: { kind: \"oauth\", label: input.connection },\n });\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\nconst slugFrom = (slug: string): IntegrationSlug => IntegrationSlug.make(slug);\n\nconst normalizeSlug = (input: McpServerInput): string =>\n input.slug ??\n deriveMcpNamespace({\n name: input.name,\n endpoint: input.transport === \"stdio\" ? undefined : input.endpoint,\n command: input.transport === \"stdio\" ? input.command : undefined,\n });\n\n/** Slug for a stdio server's secret-env auth method (one per integration). */\nconst STDIO_ENV_TEMPLATE = \"env\";\n\n/** The secret env var NAMES a stdio add declares: the explicit `envVars`\n * declaration plus the keys of any one-shot `env` values, de-duplicated and\n * order-preserving. */\nconst stdioEnvVarNames = (input: McpStdioServerInput): readonly string[] => {\n const names = new Set<string>(input.envVars ?? []);\n for (const key of Object.keys(input.env ?? {})) names.add(key);\n return [...names];\n};\n\nconst toIntegrationConfig = (input: McpServerInput): McpIntegrationConfigType => {\n if (input.transport === \"stdio\") {\n // The config only DECLARES the secret env vars by NAME (a `stdio_env`\n // method); their values are credentials and live on the connection, never\n // in this blob. Names come from the explicit `envVars` declaration and/or\n // the keys of any one-shot `env` values.\n const vars = stdioEnvVarNames(input);\n return {\n transport: \"stdio\",\n command: input.command,\n args: input.args ? [...input.args] : undefined,\n cwd: input.cwd,\n authenticationTemplate:\n vars.length > 0\n ? [{ slug: STDIO_ENV_TEMPLATE, kind: \"stdio_env\", vars }]\n : [{ slug: \"none\", kind: \"none\" }],\n };\n }\n return {\n transport: \"remote\",\n endpoint: input.endpoint,\n remoteTransport: input.remoteTransport ?? \"auto\",\n queryParams: input.queryParams,\n headers: input.headers,\n authenticationTemplate: input.authenticationTemplate\n ? normalizeMcpAuthMethods(input.authenticationTemplate)\n : [mcpAuthMethodFromShorthand(input.auth ?? { kind: \"none\" })],\n };\n};\n\ntype JsonSchemaObject = Record<string, unknown> & {\n readonly properties?: Record<string, unknown>;\n};\n\nconst McpCallToolResultJsonSchema = z.toJSONSchema(CallToolResultSchema) as JsonSchemaObject;\n\nconst mcpCallToolResultOutputSchema = (structuredContentSchema?: unknown): JsonSchemaObject => {\n const defaultStructuredContentSchema =\n McpCallToolResultJsonSchema.properties?.structuredContent ?? {};\n\n return {\n ...McpCallToolResultJsonSchema,\n properties: {\n ...McpCallToolResultJsonSchema.properties,\n structuredContent:\n structuredContentSchema === undefined\n ? defaultStructuredContentSchema\n : structuredContentSchema,\n isError: { const: false },\n },\n required:\n structuredContentSchema === undefined ? [\"content\"] : [\"content\", \"structuredContent\"],\n };\n};\n\n/** Build the executor-facing ToolDef for one discovered MCP tool, stamping the\n * real MCP tool name + upstream annotations into the persisted annotations so\n * they survive to invokeTool with no plugin-side store. */\nconst toToolDef = (entry: McpToolManifestEntry): ToolDef => {\n const destructive = entry.annotations?.destructiveHint === true;\n const stamp: McpToolStamp = {\n toolName: entry.toolName,\n ...(entry.annotations ? { upstream: entry.annotations } : {}),\n };\n const annotations: StampedAnnotations = {\n requiresApproval: destructive,\n ...(destructive ? { approvalDescription: entry.annotations?.title ?? entry.toolName } : {}),\n mcp: stamp,\n };\n return {\n name: ToolName.make(entry.toolId),\n description: entry.description ?? `MCP tool: ${entry.toolName}`,\n inputSchema: entry.inputSchema,\n outputSchema: mcpCallToolResultOutputSchema(entry.outputSchema),\n annotations: annotations as ToolAnnotations,\n };\n};\n\nconst McpTextContent = Schema.Struct({ type: Schema.Literal(\"text\"), text: Schema.String });\nconst McpToolCallEnvelope = Schema.Struct({\n isError: Schema.optional(Schema.Boolean),\n content: Schema.optional(Schema.Array(Schema.Unknown)),\n});\n\nconst decodeMcpTextContent = Schema.decodeUnknownOption(McpTextContent);\nconst decodeMcpToolCallEnvelope = Schema.decodeUnknownOption(McpToolCallEnvelope);\n\nconst extractMcpErrorMessage = (content: unknown): string => {\n if (Array.isArray(content)) {\n for (const item of content) {\n const decoded = Option.getOrUndefined(decodeMcpTextContent(item));\n if (decoded !== undefined && decoded.text.length > 0) return decoded.text;\n }\n }\n return \"MCP tool returned an error\";\n};\n\n/** Match `token` as a separator-bounded run inside a URL hostname or path,\n * used as a low-confidence detection hint when wire-shape detection fails. */\nconst urlMatchesToken = (url: URL, token: string): boolean => {\n const re = new RegExp(`(?:^|[^a-z0-9])${token}(?:$|[^a-z0-9])`, \"i\");\n return re.test(url.hostname) || re.test(url.pathname);\n};\n\n/** Translate a hard-stop probe outcome into a message a user can act on.\n * Auth-required shapes are routed to the auth editor upstream, so they never\n * reach here; the only outcomes are an unreachable endpoint or a non-MCP one.\n * Exported for tests. */\nexport const userFacingProbeMessage = (\n shape: Extract<McpShapeProbeResult, { readonly kind: \"unreachable\" | \"not-mcp\" }>,\n): string =>\n shape.kind === \"unreachable\"\n ? \"Couldn't reach this URL. Check the address, your network, and that the server is running.\"\n : \"This URL doesn't appear to host an MCP server. Double-check the address, including the path.\";\n\n// ---------------------------------------------------------------------------\n// MCP-SDK OAuth provider adapter — wraps a pre-resolved access token so the\n// transport sends it as a Bearer header. Refresh is core's responsibility\n// (the connection row carries the OAuth grant); this adapter never initiates\n// a new flow and fails loudly if the SDK tries to.\n// ---------------------------------------------------------------------------\n\nconst makeOAuthProvider = (accessToken: string): OAuthClientProvider => ({\n get redirectUrl() {\n return \"http://localhost/oauth/callback\";\n },\n get clientMetadata() {\n return {\n redirect_uris: [\"http://localhost/oauth/callback\"],\n grant_types: [\"authorization_code\", \"refresh_token\"] as string[],\n response_types: [\"code\"] as string[],\n token_endpoint_auth_method: \"none\" as const,\n client_name: \"Executor\",\n };\n },\n clientInformation: () => undefined,\n saveClientInformation: () => undefined,\n tokens: () => ({ access_token: accessToken, token_type: \"Bearer\" }),\n saveTokens: () => undefined,\n redirectToAuthorization: async () => {\n // oxlint-disable-next-line executor/no-try-catch-or-throw -- boundary: MCP SDK OAuthClientProvider callback can only signal reauthorization by throwing\n throw new McpOAuthReauthorizationRequired({\n message: \"MCP OAuth re-authorization required\",\n });\n },\n saveCodeVerifier: () => undefined,\n codeVerifier: () => {\n // oxlint-disable-next-line executor/no-try-catch-or-throw, executor/no-error-constructor -- boundary: MCP SDK OAuthClientProvider callback requires a thrown verifier failure\n throw new Error(\"No active PKCE verifier\");\n },\n saveDiscoveryState: () => undefined,\n discoveryState: () => undefined,\n});\n\n// ---------------------------------------------------------------------------\n// Connector input — render the integration config + the connection's resolved\n// value through the auth method the connection references (by template slug)\n// into a live `ConnectorInput`.\n// ---------------------------------------------------------------------------\n\n/** The auth method a connection binds: its `template` slug when it matches a\n * declared method. Otherwise fall back to the sole declared method — single-\n * method integrations historically accepted any template slug (rendering was\n * config-driven), so existing connections keep working. Ambiguity across\n * several methods renders no auth rather than guessing. */\nconst selectAuthMethod = (\n config: McpIntegrationConfigType,\n templateSlug: string | null,\n): McpAuthMethod | undefined => {\n const methods = config.authenticationTemplate ?? [];\n if (templateSlug !== null) {\n const match = methods.find((method: McpAuthMethod) => method.slug === templateSlug);\n if (match) return match;\n }\n return methods.length === 1 ? methods[0] : undefined;\n};\n\nconst buildConnectorInput = (\n config: McpIntegrationConfigType,\n values: Record<string, string | null>,\n templateSlug: string | null,\n allowStdio: boolean,\n httpClientLayer?: Layer.Layer<HttpClient.HttpClient>,\n): Effect.Effect<ConnectorInput, McpConnectionError> => {\n if (config.transport === \"stdio\") {\n if (!allowStdio) {\n return Effect.fail(\n new McpConnectionError({\n transport: \"stdio\",\n message:\n \"MCP stdio transport is disabled. Enable it by passing `dangerouslyAllowStdioMCP: true` to mcpPlugin() — only safe for trusted local contexts.\",\n }),\n );\n }\n // Secret env lives on the connection: render the bound `stdio_env`\n // method's vars from the connection's resolved values, layered over any\n // static (non-credential / legacy-inline) env in the config. A var that\n // resolved to nothing is skipped rather than injected as empty.\n const method = selectAuthMethod(config, templateSlug);\n const env: Record<string, string> = { ...(config.env ?? {}) };\n if (method?.kind === \"stdio_env\") {\n for (const variable of method.vars) {\n const value = values[variable];\n if (value != null) env[variable] = value;\n }\n }\n return Effect.succeed({\n transport: \"stdio\" as const,\n command: config.command,\n args: config.args,\n env: Object.keys(env).length > 0 ? env : undefined,\n cwd: config.cwd,\n } satisfies McpStdioIntegrationConfig);\n }\n\n // Credential placements render OVER the integration's static headers /\n // query params — a same-named static entry is overwritten.\n const headers: Record<string, string> = { ...(config.headers ?? {}) };\n const queryParams: Record<string, string> = { ...(config.queryParams ?? {}) };\n let authProvider: OAuthClientProvider | undefined;\n\n const auth = selectAuthMethod(config, templateSlug);\n if (auth?.kind === \"apikey\") {\n const rendered = renderAuthPlacements(auth.placements, values);\n Object.assign(headers, rendered.headers);\n Object.assign(queryParams, rendered.queryParams);\n } else if (auth?.kind === \"oauth2\") {\n const token = values[TOKEN_VARIABLE];\n if (token != null) authProvider = makeOAuthProvider(token);\n }\n\n return Effect.succeed({\n transport: \"remote\" as const,\n endpoint: config.endpoint,\n remoteTransport: config.remoteTransport ?? \"auto\",\n queryParams: Object.keys(queryParams).length > 0 ? queryParams : undefined,\n headers: Object.keys(headers).length > 0 ? headers : undefined,\n authProvider,\n httpClientLayer,\n });\n};\n\n// ---------------------------------------------------------------------------\n// Declared auth methods — project the stored MCP config into the catalog's\n// plugin-agnostic `AuthMethodDescriptor[]`, one per declared method. Pure and\n// tolerant of a malformed or foreign config blob (returns `[]`). Exported for\n// tests.\n//\n// none → a no-auth method carrying no credential inputs\n// stdio → [] (no remote connection to configure)\n// apikey → carried placements (headers / query params) verbatim\n// oauth2 → an oauth method carrying the MCP endpoint to probe\n// (`discoveryUrl`). Endpoints/scopes are discovered\n// live at connect time, so they are NOT pre-resolved\n// here. We mark\n// `supportsDynamicRegistration: true` because MCP\n// OAuth servers are expected to support RFC 7591 DCR;\n// the connect flow probes to confirm and falls back.\n// ---------------------------------------------------------------------------\n\n/** A stdio server's secret env method, projected so the console can render one\n * credential input per env var (carrier `env`) and re-create the connection. */\nconst describeStdioEnvAuthMethod = (method: McpStdioEnvMethod): AuthMethodDescriptor => ({\n id: method.slug,\n label: \"Environment variables\",\n kind: \"apikey\",\n template: method.slug,\n placements: method.vars.map((name) => ({ carrier: \"env\", name, prefix: \"\", variable: name })),\n});\n\nexport const describeMcpAuthMethods = (\n record: IntegrationRecord,\n): readonly AuthMethodDescriptor[] => {\n const config = parseMcpIntegrationConfig(record.config);\n if (!config) return [];\n\n // Stdio servers declare a single `stdio_env` method (or `none`); remote\n // servers declare header/query/oauth methods. Both project from the same\n // optional `authenticationTemplate`.\n const methods = config.authenticationTemplate ?? [];\n return methods.map((method: McpAuthMethod): AuthMethodDescriptor => {\n if (method.kind === \"stdio_env\") return describeStdioEnvAuthMethod(method);\n if (method.kind === \"apikey\") return describeApiKeyAuthMethod(method);\n if (method.kind === \"oauth2\") {\n return {\n id: method.slug,\n label: \"OAuth\",\n kind: \"oauth\",\n template: method.slug,\n // Only remote configs carry an endpoint; stdio never reaches here with\n // oauth2.\n oauth: {\n discoveryUrl: config.transport === \"remote\" ? config.endpoint : undefined,\n supportsDynamicRegistration: true,\n },\n };\n }\n return describeNoneAuthMethod(method.slug);\n });\n};\n\nexport const describeMcpIntegrationDisplay = (\n record: IntegrationRecord,\n): { readonly url?: string } => {\n const config = parseMcpIntegrationConfig(record.config);\n if (!config || config.transport === \"stdio\") return {};\n return { url: config.endpoint };\n};\n\n// ---------------------------------------------------------------------------\n// Plugin factory\n// ---------------------------------------------------------------------------\n\nexport interface McpPluginOptions {\n /**\n * Allow configuring stdio-transport MCP servers. Off by default.\n *\n * Stdio servers spawn a local subprocess that inherits the parent\n * `process.env`. Only enable for trusted single-user contexts.\n */\n readonly dangerouslyAllowStdioMCP?: boolean;\n readonly httpClientLayer?: Layer.Layer<HttpClient.HttpClient>;\n}\n\nexport const mcpPlugin = definePlugin((options?: McpPluginOptions) => {\n const allowStdio = options?.dangerouslyAllowStdioMCP ?? false;\n\n const presetEntries = (\n allowStdio\n ? mcpPresets\n : mcpPresets.filter((preset) => !(\"transport\" in preset && preset.transport === \"stdio\"))\n ).map((preset) => ({\n id: preset.id,\n name: preset.name,\n summary: preset.summary,\n ...(\"url\" in preset && preset.url ? { url: preset.url } : {}),\n ...(\"endpoint\" in preset && preset.endpoint ? { endpoint: preset.endpoint } : {}),\n ...(preset.icon ? { icon: preset.icon } : {}),\n ...(preset.featured ? { featured: preset.featured } : {}),\n transport: (\"transport\" in preset && preset.transport === \"stdio\" ? \"stdio\" : \"remote\") as\n | \"stdio\"\n | \"remote\",\n ...(\"command\" in preset ? { command: preset.command } : {}),\n ...(\"args\" in preset && preset.args ? { args: [...preset.args] } : {}),\n ...(\"env\" in preset && preset.env ? { env: preset.env } : {}),\n }));\n\n return {\n id: MCP_PLUGIN_ID,\n packageName: \"@executor-js/plugin-mcp\",\n integrationPresets: presetEntries,\n // Surfaced to the client bundle via the Vite plugin. The MCP `./client`\n // factory reads `allowStdio` and gates the stdio tab + presets.\n clientConfig: { allowStdio },\n storage: () => ({}),\n\n extension: (ctx: PluginCtx) => {\n const httpClientLayer = options?.httpClientLayer ?? ctx.httpClientLayer;\n\n const probeEndpoint = (input: string | McpProbeEndpointInput) =>\n Effect.gen(function* () {\n const endpoint = typeof input === \"string\" ? input : input.endpoint;\n const trimmed = endpoint.trim();\n if (!trimmed) {\n return yield* new McpConnectionError({\n transport: \"remote\",\n message: \"Endpoint URL is required\",\n });\n }\n\n const name = yield* Effect.try({\n try: () => new URL(trimmed).hostname,\n catch: () => \"mcp\",\n }).pipe(Effect.orElseSucceed(() => \"mcp\"));\n const slug = deriveMcpNamespace({ endpoint: trimmed });\n\n const probeHeaders = typeof input === \"string\" ? undefined : input.headers;\n const probeQueryParams = typeof input === \"string\" ? undefined : input.queryParams;\n\n const connector = createMcpConnector({\n transport: \"remote\",\n endpoint: trimmed,\n headers: probeHeaders,\n queryParams: probeQueryParams,\n httpClientLayer,\n });\n\n const result = yield* discoverTools(connector).pipe(\n Effect.map((m) => ({ ok: true as const, manifest: m })),\n Effect.catch(() => Effect.succeed({ ok: false as const, manifest: null })),\n Effect.withSpan(\"mcp.plugin.discover_tools\"),\n );\n\n if (result.ok && result.manifest) {\n return {\n connected: true,\n requiresAuthentication: false,\n requiresOAuth: false,\n supportsDynamicRegistration: false,\n name: result.manifest.server?.name ?? name,\n slug,\n toolCount: result.manifest.tools.length,\n serverName: result.manifest.server?.name ?? null,\n instructions: result.manifest.server?.instructions ?? null,\n } satisfies McpProbeResult;\n }\n\n // Confirm the endpoint actually speaks MCP before classifying it as\n // OAuth-protected (an OAuth-protected non-MCP service would\n // otherwise be misclassified).\n const shape = yield* probeMcpEndpointShape(trimmed, {\n httpClientLayer,\n headers: probeHeaders,\n queryParams: probeQueryParams,\n });\n\n // A `not-mcp`/auth-required shape only proves the endpoint returned\n // 401, but the add-flow recovery is the same as a spec-compliant MCP\n // auth challenge: declare auth and connect an account afterward.\n // Only an unreachable endpoint or a confirmed wrong-shape is a hard\n // stop.\n if (shape.kind === \"unreachable\") {\n return yield* new McpConnectionError({\n transport: \"remote\",\n message: userFacingProbeMessage(shape),\n });\n }\n\n if (shape.kind === \"not-mcp\") {\n if (shape.category === \"wrong-shape\") {\n return yield* new McpConnectionError({\n transport: \"remote\",\n message: userFacingProbeMessage(shape),\n });\n }\n\n return {\n connected: false,\n requiresAuthentication: true,\n requiresOAuth: false,\n supportsDynamicRegistration: false,\n name,\n slug,\n toolCount: null,\n serverName: null,\n instructions: null,\n } satisfies McpProbeResult;\n }\n\n const probeResult = yield* ctx.oauth.probe({ url: trimmed }).pipe(\n Effect.map((oauth) => ({ ok: true as const, oauth })),\n Effect.catch(() => Effect.succeed({ ok: false as const, oauth: null })),\n Effect.withSpan(\"mcp.plugin.probe_oauth\"),\n );\n\n if (probeResult.ok) {\n return {\n connected: false,\n requiresAuthentication: true,\n requiresOAuth: true,\n supportsDynamicRegistration: probeResult.oauth.registrationEndpoint != null,\n name,\n slug,\n toolCount: null,\n serverName: null,\n instructions: null,\n } satisfies McpProbeResult;\n }\n\n if (shape.requiresAuth) {\n return {\n connected: false,\n requiresAuthentication: true,\n requiresOAuth: false,\n supportsDynamicRegistration: false,\n name,\n slug,\n toolCount: null,\n serverName: null,\n instructions: null,\n } satisfies McpProbeResult;\n }\n\n return yield* new McpConnectionError({\n transport: \"remote\",\n message:\n \"This endpoint looks like MCP, but Executor couldn't discover tools from it. Check the URL and try again.\",\n });\n }).pipe(\n Effect.withSpan(\"mcp.plugin.probe_endpoint\", {\n attributes: { \"mcp.endpoint\": typeof input === \"string\" ? input : input.endpoint },\n }),\n );\n\n const addServer = (input: McpServerInput) =>\n Effect.gen(function* () {\n const slug = normalizeSlug(input);\n const config = toIntegrationConfig(input);\n\n // Block re-adding an existing slug. The core `integrations.register`\n // primitive upserts (so boot re-registration is idempotent), but an\n // explicit add must NOT silently clobber an existing integration's\n // tools, connections, and policies. To add more auth, update the\n // existing integration instead.\n const existing = yield* ctx.core.integrations.get(slugFrom(slug));\n if (existing) {\n return yield* new IntegrationAlreadyExistsError({ slug: slugFrom(slug) });\n }\n\n yield* ctx.core.integrations\n .register({\n slug: slugFrom(slug),\n name: input.name,\n description: input.description?.trim() || input.name,\n config,\n canRemove: true,\n canRefresh: true,\n })\n .pipe(\n Effect.withSpan(\"mcp.plugin.register_integration\", {\n attributes: { \"mcp.integration.slug\": slug },\n }),\n );\n\n // Auto-create the stdio server's default connection so its tools are\n // discovered immediately (without it the integration lands with zero\n // connections and therefore zero tools — the fresh-install \"no tools\n // detected\" report). Two cases connect on add:\n // • one-shot `env` VALUES were supplied (agent path) → bind them as\n // the connection's secrets.\n // • the server needs NO secret env at all → a no-auth connection.\n // When the server only DECLARES env var names (the UI path), the\n // secrets are still missing, so we leave the connection to the connect\n // step where the user enters one masked value per declared var.\n if (input.transport === \"stdio\") {\n const hasValues = input.env != null && Object.keys(input.env).length > 0;\n const declaresSecrets = stdioEnvVarNames(input).length > 0;\n if (hasValues || !declaresSecrets) {\n yield* ctx.connections\n .create({\n owner: \"org\",\n name: ConnectionName.make(\"default\"),\n integration: slugFrom(slug),\n template: AuthTemplateSlug.make(hasValues ? STDIO_ENV_TEMPLATE : \"none\"),\n values: hasValues ? { ...input.env } : {},\n })\n .pipe(\n // These can't arise right after a successful register with\n // valid inputs, but the channel must stay within\n // McpExtensionFailure; surface them as a connection error\n // rather than swallow a real failure.\n Effect.catchTags({\n IntegrationNotFoundError: (cause) =>\n Effect.fail(\n new McpConnectionError({ transport: \"stdio\", message: cause.message }),\n ),\n CredentialProviderNotRegisteredError: (cause) =>\n Effect.fail(\n new McpConnectionError({ transport: \"stdio\", message: cause.message }),\n ),\n InvalidConnectionInputError: (cause) =>\n Effect.fail(\n new McpConnectionError({ transport: \"stdio\", message: cause.message }),\n ),\n }),\n Effect.withSpan(\"mcp.plugin.bootstrap_stdio_connection\", {\n attributes: { \"mcp.integration.slug\": slug },\n }),\n );\n }\n }\n return { slug };\n }).pipe(\n Effect.withSpan(\"mcp.plugin.add_server\", {\n attributes: {\n \"mcp.server.transport\": input.transport ?? \"remote\",\n \"mcp.server.name\": input.name,\n },\n }),\n );\n\n // Heal stdio integrations that pre-date the auto-connect model: before it,\n // adding a stdio server registered only the integration, so it landed with\n // zero connections and therefore zero tools (the \"no tools detected\"\n // report). For each such integration with no connection, create the\n // default one — and move any legacy inline `env` (then stored plaintext in\n // the config blob) into the connection's secret store, rewriting the\n // config to the canonical shape that only declares the var NAMES.\n //\n // Idempotent and order-safe: once a connection exists the integration is\n // skipped; the secret is persisted (connection.create) BEFORE the config\n // is stripped, so a failure between the two leaves the env recoverable\n // (the connection has it, and the still-inline config env also works). A\n // single bad integration is logged and skipped, never failing the caller.\n const reconcileStdioConnections = () =>\n Effect.gen(function* () {\n const integrations = yield* ctx.core.integrations.list();\n for (const integration of integrations) {\n if (integration.kind !== MCP_PLUGIN_ID) continue;\n yield* Effect.gen(function* () {\n const record = yield* ctx.core.integrations.get(integration.slug);\n const config = record ? parseMcpIntegrationConfig(record.config) : null;\n if (!config || config.transport !== \"stdio\") return;\n\n // Only heal LEGACY pre-revamp stdio rows (no declared methods).\n // A new-shape row declares its auth method and owns its connection\n // lifecycle: a zero-connection one is INTENTIONAL — it declared\n // secret env vars (the UI \"declare then connect\" path) and is\n // awaiting its secrets. Auto-creating a no-auth connection here\n // would run a secret-needing server without its secret and clobber\n // that flow.\n if (config.authenticationTemplate !== undefined) return;\n\n const connections = yield* ctx.connections.list({\n integration: integration.slug,\n });\n if (connections.length > 0) return; // already connectable — nothing to heal.\n\n const inlineEnv = config.env ?? {};\n const envVars = Object.keys(inlineEnv);\n const hasEnv = envVars.length > 0;\n\n yield* ctx.connections.create({\n owner: \"org\",\n name: ConnectionName.make(\"default\"),\n integration: integration.slug,\n template: AuthTemplateSlug.make(hasEnv ? STDIO_ENV_TEMPLATE : \"none\"),\n values: hasEnv ? { ...inlineEnv } : {},\n });\n\n // The secret is now on the connection: canonicalize this legacy\n // config (declare the var names as a stdio_env method, dropping the\n // inline plaintext values; or `none` for a no-secret server).\n const nextConfig: McpIntegrationConfigType = {\n transport: \"stdio\",\n command: config.command,\n args: config.args,\n cwd: config.cwd,\n authenticationTemplate: hasEnv\n ? [{ slug: STDIO_ENV_TEMPLATE, kind: \"stdio_env\", vars: envVars }]\n : [{ slug: \"none\", kind: \"none\" }],\n };\n yield* ctx.core.integrations.update(integration.slug, { config: nextConfig });\n }).pipe(\n Effect.catch((cause) =>\n Effect.logWarning(\n `mcp: failed healing stdio connection for \"${integration.slug}\"`,\n cause,\n ),\n ),\n Effect.withSpan(\"mcp.plugin.reconcile_stdio_connection\", {\n attributes: { \"mcp.integration.slug\": String(integration.slug) },\n }),\n );\n }\n }).pipe(Effect.withSpan(\"mcp.plugin.reconcile_stdio_connections\"));\n\n const removeServer = (slug: string) =>\n Effect.gen(function* () {\n const integration = slugFrom(slug);\n const record = yield* ctx.core.integrations.get(integration);\n const config = record ? parseMcpIntegrationConfig(record.config) : null;\n const legacyCandidates = legacyOAuthClientSlugCandidates(slug, record);\n const connections = yield* ctx.connections.list({ integration });\n const allConnections = yield* ctx.connections.list();\n const oauthClientSummaries = yield* ctx.oauth.listClients();\n const usedElsewhere = new Set(\n allConnections\n .filter((connection) => String(connection.integration) !== String(integration))\n .flatMap((connection) =>\n connection.oauthClient == null\n ? []\n : [\n oauthClientKey(\n connection.oauthClientOwner ?? connection.owner,\n connection.oauthClient,\n ),\n ],\n ),\n );\n const oauthClientsByKey = new Map(\n oauthClientSummaries.map((client) => [\n oauthClientKey(client.owner, client.slug),\n client,\n ]),\n );\n const clientsToRemove = new Map<\n string,\n { readonly owner: Owner; readonly slug: OAuthClientSlug }\n >();\n\n for (const connection of connections) {\n if (connection.oauthClient == null) continue;\n const owner = connection.oauthClientOwner ?? connection.owner;\n const key = oauthClientKey(owner, connection.oauthClient);\n const client = oauthClientsByKey.get(key);\n if (client?.origin.kind !== \"dynamic_client_registration\") continue;\n clientsToRemove.set(key, {\n owner,\n slug: connection.oauthClient,\n });\n }\n for (const client of oauthClientSummaries) {\n const key = oauthClientKey(client.owner, client.slug);\n if (usedElsewhere.has(key)) continue;\n if (\n client.origin.kind === \"dynamic_client_registration\" &&\n (client.origin.integration == null || String(client.origin.integration) === slug)\n ) {\n clientsToRemove.set(key, { owner: client.owner, slug: client.slug });\n continue;\n }\n if (legacyMcpClientMatches(client, legacyCandidates, config)) {\n clientsToRemove.set(key, { owner: client.owner, slug: client.slug });\n }\n }\n\n yield* ctx.core.integrations\n .remove(integration)\n .pipe(Effect.catchTag(\"IntegrationRemovalNotAllowedError\", () => Effect.void));\n\n yield* Effect.forEach(\n clientsToRemove.values(),\n (client) => ctx.oauth.removeClient(client.owner, client.slug),\n { discard: true },\n );\n }).pipe(\n Effect.withSpan(\"mcp.plugin.remove_server\", {\n attributes: { \"mcp.integration.slug\": slug },\n }),\n );\n\n const getServer = (slug: string) =>\n ctx.core.integrations.get(slugFrom(slug)).pipe(\n Effect.withSpan(\"mcp.plugin.get_server\", {\n attributes: { \"mcp.integration.slug\": slug },\n }),\n );\n\n const configureServer = (slug: string, config: McpIntegrationConfigType) =>\n ctx.core.integrations.update(slugFrom(slug), { config }).pipe(\n Effect.withSpan(\"mcp.plugin.configure_server\", {\n attributes: { \"mcp.integration.slug\": slug },\n }),\n );\n\n /** Merge-append auth methods onto the integration's existing\n * `authenticationTemplate` (custom-method-create flow), mirroring the\n * OpenAPI/GraphQL `configureAuth`. Returns the merged array. A no-op\n * (returns `[]`) for an unknown slug, a stdio server, or an\n * undecodable config. */\n const configureAuth = (slug: string, input: McpConfigureAuthInput) =>\n Effect.gen(function* () {\n const record = yield* ctx.core.integrations.get(slugFrom(slug));\n const current = record ? parseMcpIntegrationConfig(record.config) : null;\n if (!current || current.transport === \"stdio\") {\n return [] as readonly McpAuthMethod[];\n }\n\n // Replace mode declares the full set — backfill kind-based slugs.\n // Merge mode appends: `mergeAuthTemplates` replaces on slug match and\n // assigns fresh `custom_<id>` slugs to slug-less entries, so a custom\n // method never silently displaces a declared one.\n const merged =\n input.mode === \"replace\"\n ? normalizeMcpAuthMethods(input.authenticationTemplate)\n : mergeAuthTemplates(\n current.authenticationTemplate,\n expandMcpAuthMethodInputs(\n input.authenticationTemplate,\n ) as readonly McpAuthMethod[],\n );\n\n yield* ctx.core.integrations.update(slugFrom(slug), {\n config: { ...current, authenticationTemplate: merged },\n });\n\n return merged;\n }).pipe(\n Effect.withSpan(\"mcp.plugin.configure_auth\", {\n attributes: { \"mcp.integration.slug\": slug },\n }),\n );\n\n return {\n probeEndpoint,\n addServer,\n removeServer,\n reconcileStdioConnections,\n getServer,\n configureServer,\n configureAuth,\n };\n },\n\n // -----------------------------------------------------------------------\n // Per-connection tool production. Dial the server using the connection's\n // resolved value (rendered through the integration's auth template) and\n // list its tools. The real MCP tool name + upstream annotations are\n // stamped into each ToolDef's annotations so invokeTool can recover them.\n // Discovery failures (auth not ready, server down) yield an empty tool set\n // rather than failing — the connection still lands and can be refreshed.\n // -----------------------------------------------------------------------\n resolveTools: ({ config, connection, template, getValues, httpClientLayer }) =>\n Effect.gen(function* () {\n const parsed = parseMcpIntegrationConfig(config);\n if (!parsed) return { tools: [] as readonly ToolDef[] };\n\n // Discovery tolerates unresolved credentials (an open server lists\n // tools unauthenticated; a bad value just yields zero tools).\n const values = yield* getValues().pipe(\n Effect.orElseSucceed(() => ({}) as Record<string, string | null>),\n );\n\n const built = yield* buildConnectorInput(\n parsed,\n values,\n template === null ? null : String(template),\n allowStdio,\n httpClientLayer,\n ).pipe(\n Effect.map((ci) => createMcpConnector(ci)),\n Effect.result,\n );\n\n const manifest = Result.isSuccess(built)\n ? yield* discoverTools(built.success).pipe(\n Effect.map((m) => ({ ok: true as const, manifest: m })),\n Effect.catch(() => Effect.succeed({ ok: false as const, manifest: null })),\n Effect.withSpan(\"mcp.plugin.discover_tools\", {\n attributes: { \"mcp.connection.name\": String(connection.name) },\n }),\n )\n : { ok: false as const, manifest: null };\n\n const entries = manifest.ok && manifest.manifest ? manifest.manifest.tools : [];\n return { tools: entries.map(toToolDef) };\n }).pipe(\n Effect.withSpan(\"mcp.plugin.resolve_tools\", {\n attributes: { \"mcp.connection.name\": String(connection.name) },\n }),\n ) as Effect.Effect<{ readonly tools: readonly ToolDef[] }, StorageFailure>,\n\n invokeTool: ({ ctx, toolRow, credential, args, elicit }) =>\n Effect.gen(function* () {\n const parsed = parseMcpIntegrationConfig(credential.config);\n if (!parsed) {\n return yield* new McpConnectionError({\n transport: \"auto\",\n message: `MCP integration \"${toolRow.integration}\" has no usable config`,\n });\n }\n\n const stamp = readStamp(toolRow.annotations);\n if (!stamp) {\n return yield* new McpToolDiscoveryError({\n stage: \"list_tools\",\n message: `Tool \"${toolRow.name}\" is missing its MCP binding — refresh the connection`,\n });\n }\n\n const transport: string =\n parsed.transport === \"stdio\" ? \"stdio\" : (parsed.remoteTransport ?? \"auto\");\n\n // An apikey method with unresolved inputs fails the invocation\n // explicitly instead of dialing unauthenticated.\n if (parsed.transport === \"remote\") {\n const method = selectAuthMethod(parsed, String(credential.template));\n if (method?.kind === \"apikey\") {\n const missing = requiredPlacementVariables(method.placements).filter(\n (variable) => credential.values[variable] == null,\n );\n if (missing.length > 0) {\n return authToolFailure({\n code: \"connection_value_missing\",\n message: `Connection has no resolvable credential value for input(s): ${missing.join(\", \")}. Re-create the connection with the required value(s).`,\n source: { id: String(credential.integration) },\n credential: { kind: \"upstream\", label: String(credential.connection) },\n });\n }\n }\n }\n\n const connector: McpConnector = yield* buildConnectorInput(\n parsed,\n credential.values,\n String(credential.template),\n allowStdio,\n options?.httpClientLayer ?? ctx.httpClientLayer,\n ).pipe(Effect.map((ci) => createMcpConnector(ci)));\n\n const raw = yield* invokeMcpTool({\n toolId: String(toolRow.name),\n toolName: stamp.toolName,\n args,\n transport,\n connector,\n elicit,\n });\n\n const envelope = Option.getOrUndefined(decodeMcpToolCallEnvelope(raw));\n if (envelope?.isError === true) {\n return ToolResult.fail({\n code: \"mcp_tool_error\",\n message: extractMcpErrorMessage(envelope.content),\n details: { content: envelope.content },\n });\n }\n return ToolResult.ok(raw);\n }).pipe(\n Effect.catchTag(\"McpOAuthReauthorizationRequired\", () =>\n Effect.succeed(\n mcpInvocationOAuthReauthFailure({\n integration: String(credential.integration),\n connection: String(credential.connection),\n }),\n ),\n ),\n Effect.catchTag(\"McpConnectionError\", (error) => {\n return Effect.succeed(\n authToolFailure({\n code: \"connection_rejected\",\n message: error.message,\n source: { id: String(credential.integration) },\n credential: { kind: \"upstream\", label: String(credential.connection) },\n }),\n );\n }),\n Effect.catchTag(\"McpInvocationError\", (error) => {\n if (error.status === 401 || error.status === 403) {\n return Effect.succeed(\n mcpInvocationAuthFailure({\n status: error.status,\n integration: String(credential.integration),\n connection: String(credential.connection),\n }),\n );\n }\n return Effect.fail(error);\n }),\n Effect.withSpan(\"mcp.plugin.invoke_tool\", {\n attributes: {\n \"mcp.tool.name\": String(toolRow.name),\n \"mcp.integration.slug\": String(toolRow.integration),\n },\n }),\n ),\n\n detect: ({ ctx, url }: { readonly ctx: PluginCtx; readonly url: string }) =>\n Effect.gen(function* () {\n const httpClientLayer = options?.httpClientLayer ?? ctx.httpClientLayer;\n const trimmed = url.trim();\n if (!trimmed) return null;\n\n const parsed = yield* Effect.try({\n try: () => new URL(trimmed),\n catch: (cause) => cause,\n }).pipe(Effect.option);\n if (Option.isNone(parsed)) return null;\n\n const name = parsed.value.hostname || \"mcp\";\n const slug = deriveMcpNamespace({ endpoint: trimmed });\n\n const connector = createMcpConnector({\n transport: \"remote\",\n endpoint: trimmed,\n httpClientLayer,\n });\n\n const connected = yield* discoverTools(connector).pipe(\n Effect.map(() => true),\n Effect.catch(() => Effect.succeed(false)),\n Effect.withSpan(\"mcp.plugin.discover_tools\"),\n );\n\n if (connected) {\n return {\n kind: MCP_PLUGIN_ID,\n confidence: \"high\" as const,\n endpoint: trimmed,\n name,\n slug,\n };\n }\n\n const shape = yield* probeMcpEndpointShape(trimmed, { httpClientLayer });\n if (shape.kind === \"mcp\") {\n return {\n kind: MCP_PLUGIN_ID,\n confidence: \"high\" as const,\n endpoint: trimmed,\n name,\n slug,\n };\n }\n\n // Low-confidence URL-token fallback when wire-shape detection can't\n // confirm MCP but the URL itself is a strong hint.\n if (urlMatchesToken(parsed.value, \"mcp\")) {\n return {\n kind: MCP_PLUGIN_ID,\n confidence: \"low\" as const,\n endpoint: trimmed,\n name,\n slug,\n };\n }\n\n return null;\n }).pipe(\n Effect.catch(() => Effect.succeed(null)),\n Effect.withSpan(\"mcp.plugin.detect\", {\n attributes: { \"mcp.endpoint\": url },\n }),\n ),\n\n // Honour upstream destructiveHint from MCP ToolAnnotations using the stamp\n // persisted in each tool row's annotations.\n resolveAnnotations: ({ toolRows }) =>\n Effect.sync(() => {\n const out: Record<string, ToolAnnotations> = {};\n for (const row of toolRows) {\n const stamp = readStamp(row.annotations);\n const ann = stamp?.upstream;\n if (ann?.destructiveHint === true) {\n out[String(row.name)] = {\n requiresApproval: true,\n approvalDescription: ann.title ?? stamp?.toolName ?? String(row.name),\n };\n } else {\n out[String(row.name)] = { requiresApproval: false };\n }\n }\n return out;\n }),\n\n describeAuthMethods: describeMcpAuthMethods,\n describeIntegrationDisplay: describeMcpIntegrationDisplay,\n\n integrationConfigure: {\n type: \"mcp\",\n configure: ({ ctx, integration, config }) =>\n Effect.gen(function* () {\n const next = parseMcpIntegrationConfig(config);\n if (!next) return;\n yield* ctx.core.integrations.update(integration, { config: next });\n }),\n },\n\n staticSources: (self) => [\n {\n id: \"mcp\",\n kind: \"executor\",\n name: \"MCP\",\n tools: [\n tool({\n name: \"probeEndpoint\",\n description:\n \"Probe a remote MCP endpoint before adding it. If the result requires OAuth, run the core OAuth handoff (`oauth.probe`, `oauth.start`) to mint a connection; otherwise create a connection with `connections.create` carrying the API key or header value.\",\n inputSchema: McpProbeEndpointInputStandardSchema,\n outputSchema: McpProbeEndpointOutputStandardSchema,\n execute: (input) =>\n self.probeEndpoint(input as McpProbeEndpointInput).pipe(\n Effect.map(ToolResult.ok),\n Effect.catchTag(\"McpConnectionError\", ({ message, transport }) =>\n Effect.succeed(mcpToolFailure(\"mcp_connection_failed\", message, { transport })),\n ),\n ),\n }),\n tool({\n name: \"getServer\",\n description:\n \"Inspect a registered MCP integration, including transport, endpoint/command, and auth template. Use this before creating a connection (`connections.create` / `oauth.start`).\",\n inputSchema: McpGetServerInputStandardSchema,\n outputSchema: McpGetServerOutputStandardSchema,\n execute: (input) => {\n const args = input as typeof McpGetServerInputSchema.Type;\n return Effect.map(self.getServer(args.slug), (integration) =>\n ToolResult.ok({ integration }),\n );\n },\n }),\n tool({\n name: \"addServer\",\n description:\n \"Register an MCP server in the catalog as an integration. Returns its `slug`. Then create a connection against it: for header/API-key auth call `connections.create` with the value; for OAuth-protected servers run `oauth.probe` + `oauth.start`. Tools are produced per-connection at connection create / refresh.\",\n annotations: {\n requiresApproval: true,\n approvalDescription: \"Add an MCP server\",\n },\n inputSchema: McpAddServerInputStandardSchema,\n outputSchema: McpAddServerOutputStandardSchema,\n execute: (rawInput) => {\n const input = rawInput as typeof McpAddServerInputSchema.Type;\n return self.addServer(input as McpServerInput).pipe(\n Effect.map(ToolResult.ok),\n Effect.catchTag(\n \"IntegrationAlreadyExistsError\",\n ({ slug }: IntegrationAlreadyExistsError) =>\n Effect.succeed(\n mcpToolFailure(\n \"integration_already_exists\",\n `Integration ${slug} already exists; update it instead of re-adding.`,\n ),\n ),\n ),\n );\n },\n }),\n ],\n },\n ],\n };\n});\n\n// ---------------------------------------------------------------------------\n// McpPluginExtension — shape of `executor.mcp` for consumers (api/, react/).\n// ---------------------------------------------------------------------------\n\nexport type McpExtensionFailure = McpConnectionError | McpToolDiscoveryError | StorageFailure;\n\nexport interface McpPluginExtension {\n readonly probeEndpoint: (\n input: string | McpProbeEndpointInput,\n ) => Effect.Effect<McpProbeResult, McpExtensionFailure>;\n readonly addServer: (\n input: McpServerInput,\n ) => Effect.Effect<\n { readonly slug: string },\n McpExtensionFailure | IntegrationAlreadyExistsError\n >;\n readonly removeServer: (slug: string) => Effect.Effect<void, McpExtensionFailure>;\n /** Ensure every stdio integration has its default connection (migrating any\n * legacy inline env into the secret store). Idempotent; safe to run at boot. */\n readonly reconcileStdioConnections: () => Effect.Effect<void, McpExtensionFailure>;\n readonly getServer: (\n slug: string,\n ) => Effect.Effect<\n (Integration & { readonly config: IntegrationConfig }) | null,\n McpExtensionFailure\n >;\n readonly configureServer: (\n slug: string,\n config: McpIntegrationConfigType,\n ) => Effect.Effect<void, McpExtensionFailure>;\n readonly configureAuth: (\n slug: string,\n input: McpConfigureAuthInput,\n ) => Effect.Effect<readonly McpAuthMethod[], McpExtensionFailure>;\n}\n","import type { OAuthClientProvider } from \"@modelcontextprotocol/sdk/client/auth.js\";\nimport { Client } from \"@modelcontextprotocol/sdk/client/index.js\";\nimport { SSEClientTransport } from \"@modelcontextprotocol/sdk/client/sse.js\";\nimport { StreamableHTTPClientTransport } from \"@modelcontextprotocol/sdk/client/streamableHttp.js\";\nimport type { FetchLike } from \"@modelcontextprotocol/sdk/shared/transport.js\";\nimport { CfWorkerJsonSchemaValidator } from \"@modelcontextprotocol/sdk/validation/cfworker\";\nimport { Effect, Layer, Predicate, Stream } from \"effect\";\nimport { HttpClient, HttpClientRequest } from \"effect/unstable/http\";\n\n// NOTE: `StdioClientTransport` is NOT imported eagerly. The upstream module\n// (`@modelcontextprotocol/sdk/client/stdio.js`) touches `node:child_process`\n// at evaluation time, which crashes workerd (incl. vitest-pool-workers) at\n// SIGSEGV on module instantiation. Cloud callers set\n// `dangerouslyAllowStdioMCP: false` and never reach the stdio branch below;\n// prod bundles that DO use stdio load it via a dynamic import inside the\n// stdio branch of `createMcpConnector`.\n\nimport type { McpRemoteIntegrationConfig, McpStdioIntegrationConfig } from \"./types\";\nimport { McpConnectionError, McpOAuthReauthorizationRequired } from \"./errors\";\n\n// ---------------------------------------------------------------------------\n// Connection type\n// ---------------------------------------------------------------------------\n\nexport type McpConnection = {\n readonly client: Client;\n readonly close: () => Promise<void>;\n};\n\nexport type McpConnector = Effect.Effect<\n McpConnection,\n McpConnectionError | McpOAuthReauthorizationRequired\n>;\n\n// ---------------------------------------------------------------------------\n// Connector input — extends stored source data with resolved auth\n// ---------------------------------------------------------------------------\n\nexport type RemoteConnectorInput = Omit<\n McpRemoteIntegrationConfig,\n \"authenticationTemplate\" | \"remoteTransport\" | \"headers\" | \"queryParams\"\n> & {\n readonly remoteTransport?: McpRemoteIntegrationConfig[\"remoteTransport\"];\n readonly headers?: Record<string, string>;\n readonly queryParams?: Record<string, string>;\n readonly authProvider?: OAuthClientProvider;\n readonly httpClientLayer?: Layer.Layer<HttpClient.HttpClient>;\n};\n\nexport type StdioConnectorInput = McpStdioIntegrationConfig;\n\nexport type ConnectorInput = RemoteConnectorInput | StdioConnectorInput;\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\nconst buildEndpointUrl = (endpoint: string, queryParams: Record<string, string>): URL => {\n const url = new URL(endpoint);\n for (const [key, value] of Object.entries(queryParams)) {\n url.searchParams.set(key, value);\n }\n return url;\n};\n\ntype HttpMethod = Parameters<typeof HttpClientRequest.make>[0];\nconst HTTP_METHODS = new Set<HttpMethod>([\n \"DELETE\",\n \"GET\",\n \"HEAD\",\n \"OPTIONS\",\n \"PATCH\",\n \"POST\",\n \"PUT\",\n]);\n\nconst httpMethodFrom = (method: string | undefined): HttpMethod => {\n const normalized = (method ?? \"GET\").toUpperCase() as HttpMethod;\n return HTTP_METHODS.has(normalized) ? normalized : \"POST\";\n};\n\nconst headersFrom = (headers: HeadersInit | undefined): Headers =>\n headers ? new Headers(headers) : new Headers();\n\nconst recordFromHeaders = (headers: Headers): Record<string, string> =>\n Object.fromEntries(headers.entries());\n\nconst applyBody = async (\n request: HttpClientRequest.HttpClientRequest,\n headers: Headers,\n body: BodyInit | null | undefined,\n): Promise<HttpClientRequest.HttpClientRequest> => {\n if (body == null) return request;\n const contentType = headers.get(\"content-type\") ?? undefined;\n if (typeof body === \"string\") return HttpClientRequest.bodyText(request, body, contentType);\n if (body instanceof URLSearchParams) {\n return HttpClientRequest.bodyText(\n request,\n body.toString(),\n contentType ?? \"application/x-www-form-urlencoded;charset=UTF-8\",\n );\n }\n if (body instanceof Uint8Array)\n return HttpClientRequest.bodyUint8Array(request, body, contentType);\n if (body instanceof ArrayBuffer) {\n return HttpClientRequest.bodyUint8Array(request, new Uint8Array(body), contentType);\n }\n const bytes = new Uint8Array(await new Response(body).arrayBuffer());\n return HttpClientRequest.bodyUint8Array(request, bytes, contentType);\n};\n\nconst abortError = (signal: AbortSignal): unknown => {\n if (signal.reason !== undefined) return signal.reason;\n // oxlint-disable-next-line executor/no-error-constructor -- boundary: Fetch-compatible adapter must reject with an AbortError-shaped value\n const error = new Error(\"The operation was aborted\");\n error.name = \"AbortError\";\n return error;\n};\n\nconst fetchFromHttpClientLayer = (\n httpClientLayer: Layer.Layer<HttpClient.HttpClient>,\n): FetchLike => {\n const execute: FetchLike = async (url, init) => {\n const headers = headersFrom(init?.headers);\n const requestWithoutBody = HttpClientRequest.make(httpMethodFrom(init?.method))(url, {\n headers: recordFromHeaders(headers),\n });\n const request = await applyBody(requestWithoutBody, headers, init?.body);\n const effect = Effect.gen(function* () {\n const client = yield* HttpClient.HttpClient;\n const response = yield* client.execute(request);\n const responseHeaders = new Headers();\n for (const [key, value] of Object.entries(response.headers)) {\n if (value !== undefined) responseHeaders.set(key, value);\n }\n const body =\n response.status === 204 || response.status === 205 || response.status === 304\n ? null\n : Stream.toReadableStream(response.stream);\n return new Response(body, {\n status: response.status,\n headers: responseHeaders,\n });\n }).pipe(Effect.provide(httpClientLayer));\n const promise = Effect.runPromise(effect);\n if (!init?.signal) return promise;\n // oxlint-disable-next-line executor/no-promise-reject -- boundary: Fetch-compatible adapter mirrors abort rejection semantics\n if (init.signal.aborted) return Promise.reject(abortError(init.signal));\n const aborted = new Promise<never>((_, reject) => {\n // oxlint-disable-next-line executor/no-promise-reject -- boundary: Fetch-compatible adapter races the Effect request against AbortSignal\n init.signal?.addEventListener(\"abort\", () => reject(abortError(init.signal!)), {\n once: true,\n });\n });\n return Promise.race([promise, aborted]);\n };\n return execute;\n};\n\n// Use the cfworker JSON Schema validator instead of the SDK's default\n// (Ajv). Ajv compiles schemas via `new Function(...)`, which throws\n// `Code generation from strings disallowed for this context` when the\n// MCP plugin runs inside a Cloudflare Worker (executor.sh). The\n// cfworker validator does not use code generation and works in every\n// runtime we ship to.\nconst createClient = (): Client =>\n new Client(\n { name: \"executor-mcp\", version: \"0.1.0\" },\n {\n capabilities: { elicitation: { form: {}, url: {} } },\n jsonSchemaValidator: new CfWorkerJsonSchemaValidator(),\n },\n );\n\nconst connectionFromClient = (client: Client): McpConnection => ({\n client,\n close: () => client.close(),\n});\n\nconst connectionFailure = (\n transport: string,\n message: string,\n cause: unknown,\n): McpConnectionError | McpOAuthReauthorizationRequired => {\n if (Predicate.isTagged(cause, \"McpOAuthReauthorizationRequired\")) {\n return new McpOAuthReauthorizationRequired({ message: \"MCP OAuth re-authorization required\" });\n }\n return new McpConnectionError({ transport, message });\n};\n\nconst connectClient = (input: {\n transport: string;\n createTransport: () => Parameters<Client[\"connect\"]>[0];\n}): Effect.Effect<McpConnection, McpConnectionError | McpOAuthReauthorizationRequired> =>\n Effect.gen(function* () {\n const client = createClient();\n const transportInstance = input.createTransport();\n\n yield* Effect.tryPromise({\n try: () => client.connect(transportInstance),\n catch: (cause) =>\n connectionFailure(input.transport, `Failed connecting via ${input.transport}`, cause),\n }).pipe(\n Effect.withSpan(\"plugin.mcp.connection.handshake\", {\n attributes: { \"plugin.mcp.transport\": input.transport },\n }),\n );\n\n return connectionFromClient(client);\n });\n\n// ---------------------------------------------------------------------------\n// Public factory\n// ---------------------------------------------------------------------------\n\nexport const createMcpConnector = (input: ConnectorInput): McpConnector => {\n if (input.transport === \"stdio\") {\n const command = input.command.trim();\n if (!command) {\n return Effect.fail(\n new McpConnectionError({\n transport: \"stdio\",\n message: \"MCP stdio transport requires a command\",\n }),\n );\n }\n\n return Effect.gen(function* () {\n // Dynamic import so the underlying module (which evaluates\n // `node:child_process`) is only loaded when stdio is actually used.\n const { createStdioTransport } = yield* Effect.tryPromise({\n try: () => import(\"./stdio-connector\"),\n catch: () =>\n new McpConnectionError({\n transport: \"stdio\",\n message: \"Failed to load stdio transport module\",\n }),\n });\n\n return yield* connectClient({\n transport: \"stdio\",\n createTransport: () =>\n createStdioTransport({\n command,\n args: input.args,\n env: input.env,\n cwd: input.cwd?.trim().length ? input.cwd.trim() : undefined,\n }),\n });\n });\n }\n\n // Remote transport\n const headers = input.headers ?? {};\n const remoteTransport = input.remoteTransport ?? \"auto\";\n const requestInit = Object.keys(headers).length > 0 ? { headers } : undefined;\n const fetch = input.httpClientLayer ? fetchFromHttpClientLayer(input.httpClientLayer) : undefined;\n\n const endpoint = buildEndpointUrl(input.endpoint, input.queryParams ?? {});\n\n const connectStreamableHttp = connectClient({\n transport: \"streamable-http\",\n createTransport: () =>\n new StreamableHTTPClientTransport(endpoint, {\n requestInit,\n authProvider: input.authProvider,\n fetch,\n }),\n });\n\n const connectSse = connectClient({\n transport: \"sse\",\n createTransport: () =>\n new SSEClientTransport(endpoint, {\n requestInit,\n authProvider: input.authProvider,\n fetch,\n }),\n });\n\n if (remoteTransport === \"streamable-http\") return connectStreamableHttp;\n if (remoteTransport === \"sse\") return connectSse;\n\n // auto: try streamable-http first, fall back to SSE for transport failures.\n return connectStreamableHttp.pipe(\n Effect.catch((error) =>\n Predicate.isTagged(error, \"McpOAuthReauthorizationRequired\")\n ? Effect.fail(error)\n : connectSse,\n ),\n );\n};\n","// ---------------------------------------------------------------------------\n// MCP tool discovery — connect to an MCP server and list its tools\n// ---------------------------------------------------------------------------\n\nimport { Effect } from \"effect\";\n\nimport type { McpConnector } from \"./connection\";\nimport { McpToolDiscoveryError } from \"./errors\";\nimport {\n extractManifestFromListToolsResult,\n isListToolsResult,\n type McpToolManifest,\n} from \"./manifest\";\n\n// ---------------------------------------------------------------------------\n// Public API\n// ---------------------------------------------------------------------------\n\n/**\n * Connect to an MCP server and discover all available tools.\n * Returns the parsed manifest containing server metadata and tool entries.\n */\nexport const discoverTools = (\n connector: McpConnector,\n): Effect.Effect<McpToolManifest, McpToolDiscoveryError> =>\n Effect.gen(function* () {\n // Acquire connection\n const connection = yield* connector.pipe(\n Effect.mapError(\n ({ message }) =>\n new McpToolDiscoveryError({\n stage: \"connect\",\n message: `Failed connecting to MCP server: ${message}`,\n }),\n ),\n );\n\n // List tools\n const listResult = yield* Effect.tryPromise({\n try: () => connection.client.listTools(),\n catch: () =>\n new McpToolDiscoveryError({\n stage: \"list_tools\",\n message: \"Failed listing MCP tools\",\n }),\n });\n\n if (!isListToolsResult(listResult)) {\n yield* closeConnection(connection);\n return yield* new McpToolDiscoveryError({\n stage: \"list_tools\",\n message: \"MCP listTools response did not match the expected schema\",\n });\n }\n\n const manifest = extractManifestFromListToolsResult(listResult, {\n serverInfo: connection.client.getServerVersion?.(),\n instructions: connection.client.getInstructions?.(),\n });\n\n // Close the connection after discovery\n yield* closeConnection(connection);\n\n return manifest;\n });\n\nconst closeConnection = (connection: {\n readonly close: () => Promise<void>;\n}): Effect.Effect<void, never> =>\n Effect.ignore(\n Effect.tryPromise({\n try: () => connection.close(),\n catch: () =>\n new McpToolDiscoveryError({\n stage: \"list_tools\",\n message: \"Failed closing MCP connection\",\n }),\n }),\n );\n","// ---------------------------------------------------------------------------\n// MCP tool invocation — shared helper called from plugin.invokeTool.\n//\n// Responsible for:\n// 1. Dialing a fresh MCP client connection for the call (no DB-connection\n// caching — request-scoped per the Hyperdrive rule; each invoke acquires\n// and releases its own connection).\n// 2. Installing a per-invocation `ElicitRequestSchema` handler that bridges\n// MCP's elicit capability into the host's elicit function threaded via\n// `InvokeToolInput.elicit`.\n// 3. Calling `client.callTool({ name, arguments })`.\n// ---------------------------------------------------------------------------\n\nimport { Cause, Effect, Exit, Option, Predicate, Schema } from \"effect\";\n\nimport { StreamableHTTPError } from \"@modelcontextprotocol/sdk/client/streamableHttp.js\";\nimport { ElicitRequestSchema } from \"@modelcontextprotocol/sdk/types.js\";\n\nimport {\n ElicitationId,\n FormElicitation,\n UrlElicitation,\n type Elicit,\n type ElicitationRequest,\n} from \"@executor-js/sdk\";\n\nimport { McpConnectionError, McpInvocationError, McpOAuthReauthorizationRequired } from \"./errors\";\nimport type { McpConnection, McpConnector } from \"./connection\";\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\nconst ArgsRecord = Schema.Record(Schema.String, Schema.Unknown);\nconst decodeArgsRecord = Schema.decodeUnknownOption(ArgsRecord);\n\nconst argsRecord = (value: unknown): Record<string, unknown> =>\n Option.getOrElse(decodeArgsRecord(value), () => ({}));\n\nconst SsePostErrorCause = Schema.Struct({ message: Schema.String });\nconst decodeSsePostErrorCause = Schema.decodeUnknownOption(SsePostErrorCause);\n\n// Matches the SDK's SSEClientTransport POST-failure message (sse.js); re-verify\n// on SDK bumps. A format drift just yields undefined (generic error, no crash).\nconst statusFromSsePostError = (cause: unknown): number | undefined =>\n Option.match(decodeSsePostErrorCause(cause), {\n onNone: () => undefined,\n onSome: ({ message }) => {\n const match = /^Error POSTing to endpoint \\(HTTP ([1-5][0-9]{2})\\):/.exec(message);\n if (!match) return undefined;\n return Number(match[1]);\n },\n });\n\nconst statusFromStreamableHttpError = (cause: unknown): number | undefined => {\n // oxlint-disable-next-line executor/no-instanceof-tagged-error -- boundary: MCP SDK exposes transport HTTP failures as this Error subclass; protocol errors can carry the same numeric code\n if (!(cause instanceof StreamableHTTPError)) return undefined;\n const code = cause.code;\n return code !== undefined && code >= 100 && code <= 599 ? code : undefined;\n};\n\nconst httpStatusFromCause = (cause: unknown): number | undefined =>\n statusFromStreamableHttpError(cause) ?? statusFromSsePostError(cause);\n\n// ---------------------------------------------------------------------------\n// Elicitation bridge — decode incoming MCP ElicitRequest, route through\n// the host's elicit function, marshal the response back to MCP shape.\n// ---------------------------------------------------------------------------\n\nconst McpElicitParams = Schema.Union([\n Schema.Struct({\n mode: Schema.Literal(\"url\"),\n message: Schema.String,\n url: Schema.String,\n elicitationId: Schema.optional(Schema.String),\n id: Schema.optional(Schema.String),\n }),\n Schema.Struct({\n mode: Schema.optional(Schema.Literal(\"form\")),\n message: Schema.String,\n requestedSchema: Schema.Record(Schema.String, Schema.Unknown),\n }),\n]);\ntype McpElicitParams = typeof McpElicitParams.Type;\n\nconst decodeElicitParams = Schema.decodeUnknownSync(McpElicitParams);\n\nconst toElicitationRequest = (params: McpElicitParams): ElicitationRequest =>\n params.mode === \"url\"\n ? UrlElicitation.make({\n message: params.message,\n url: params.url,\n elicitationId: ElicitationId.make(params.elicitationId ?? params.id ?? \"\"),\n })\n : FormElicitation.make({\n message: params.message,\n requestedSchema: params.requestedSchema,\n });\n\nconst installElicitationHandler = (client: McpConnection[\"client\"], elicit: Elicit): void => {\n client.setRequestHandler(ElicitRequestSchema, async (request: { params: unknown }) => {\n const params = decodeElicitParams(request.params);\n const req = toElicitationRequest(params);\n // Use runPromiseExit so we can inspect typed failures — `elicit`\n // fails with `ElicitationDeclinedError` on decline/cancel, which\n // we translate into the equivalent MCP elicit response instead of\n // surfacing as a JSON-RPC error.\n const exit = await Effect.runPromiseExit(elicit(req));\n if (Exit.isSuccess(exit)) {\n const response = exit.value;\n return {\n action: response.action,\n ...(response.action === \"accept\" && response.content ? { content: response.content } : {}),\n };\n }\n const failure = exit.cause.reasons.find(Cause.isFailReason);\n if (failure) {\n const err = failure.error;\n if (Predicate.isTagged(err, \"ElicitationDeclinedError\")) {\n const action =\n Predicate.hasProperty(err, \"action\") && err.action === \"cancel\" ? \"cancel\" : \"decline\";\n return { action };\n }\n }\n // oxlint-disable-next-line executor/no-try-catch-or-throw -- boundary: MCP SDK async request handlers signal unexpected failures by rejecting\n throw Cause.squash(exit.cause);\n });\n};\n\n// ---------------------------------------------------------------------------\n// Single tool call — install handler, callTool, return raw result\n// ---------------------------------------------------------------------------\n\nconst useConnection = (\n connection: McpConnection,\n toolName: string,\n args: Record<string, unknown>,\n elicit: Elicit,\n): Effect.Effect<unknown, McpInvocationError | McpOAuthReauthorizationRequired> =>\n Effect.gen(function* () {\n installElicitationHandler(connection.client, elicit);\n return yield* Effect.tryPromise({\n try: () => connection.client.callTool({ name: toolName, arguments: args }),\n catch: (cause) => {\n if (Predicate.isTagged(cause, \"McpOAuthReauthorizationRequired\")) {\n return new McpOAuthReauthorizationRequired({\n message: \"MCP OAuth re-authorization required\",\n });\n }\n const status = httpStatusFromCause(cause);\n return new McpInvocationError({\n toolName,\n message: `MCP tool call failed for ${toolName}`,\n ...(status === undefined ? {} : { status }),\n });\n },\n }).pipe(\n Effect.withSpan(\"plugin.mcp.client.call_tool\", {\n attributes: { \"mcp.tool.name\": toolName },\n }),\n );\n });\n\n// ---------------------------------------------------------------------------\n// Public API\n// ---------------------------------------------------------------------------\n\nexport interface InvokeMcpToolInput {\n readonly toolId: string;\n /** The real MCP tool name advertised by the server. */\n readonly toolName: string;\n readonly args: unknown;\n readonly transport: string;\n /** Dials a fresh connection. The connection is closed after the call. */\n readonly connector: McpConnector;\n readonly elicit: Elicit;\n}\n\nexport const invokeMcpTool = (\n input: InvokeMcpToolInput,\n): Effect.Effect<\n unknown,\n McpConnectionError | McpInvocationError | McpOAuthReauthorizationRequired\n> =>\n Effect.gen(function* () {\n const args = argsRecord(input.args);\n\n const connection = yield* Effect.acquireRelease(\n input.connector.pipe(\n Effect.withSpan(\"plugin.mcp.connection.acquire\", {\n attributes: { \"plugin.mcp.transport\": input.transport },\n }),\n ),\n (conn) =>\n Effect.ignore(\n Effect.tryPromise({\n try: () => conn.close(),\n catch: () =>\n new McpConnectionError({\n transport: input.transport,\n message: \"Failed to close MCP connection\",\n }),\n }),\n ),\n );\n\n return yield* useConnection(connection, input.toolName, args, input.elicit);\n }).pipe(\n Effect.scoped,\n Effect.withSpan(\"plugin.mcp.invoke\", {\n attributes: {\n \"mcp.tool.name\": input.toolName,\n \"plugin.mcp.tool_id\": input.toolId,\n \"plugin.mcp.transport\": input.transport,\n },\n }),\n );\n","// ---------------------------------------------------------------------------\n// MCP endpoint shape probe — decide whether an unknown HTTP endpoint is\n// actually speaking MCP before we try to classify it as such.\n//\n// Background:\n//\n// `discoverTools` (via the MCP SDK's StreamableHTTP / SSE transport)\n// fails for every non-MCP endpoint too — 200-with-HTML, 400-GraphQL,\n// 404, etc. all surface as the same opaque transport error. We need\n// our own classifier that distinguishes \"real MCP\" from\n// \"OAuth-protected non-MCP service\" without relying on RFC 9728/8414\n// metadata, since (a) plenty of non-MCP APIs publish that metadata,\n// and (b) plenty of real MCP servers authenticate with static API\n// keys and publish no OAuth metadata at all (e.g. cubic.dev).\n//\n// The probe issues an unauth JSON-RPC `initialize` POST and accepts\n// only the wire shapes a real MCP server can return:\n//\n// - 2xx with `Content-Type: text/event-stream` — streamable HTTP\n// transport, body is an SSE stream we don't consume.\n// - 2xx with `Content-Type: application/json` whose body parses as a\n// JSON-RPC 2.0 envelope (`{jsonrpc:\"2.0\", result|error|method,...}`).\n// - 401 with `WWW-Authenticate: Bearer` AND a JSON-RPC error envelope\n// in the body. The body shape is what separates a real MCP server\n// from an unrelated OAuth-protected API: GraphQL/REST/HTML 401s\n// don't shape themselves as JSON-RPC.\n//\n// When POST returns 404/405/406/415 we retry with GET + `Accept:\n// text/event-stream` to support legacy SSE-only servers; that path\n// only accepts 2xx with `text/event-stream` or the same 401+Bearer\n// shape.\n//\n// One `fetch` (occasionally two), no MCP-SDK session state, no OAuth\n// round-trip, no DCR — every non-MCP endpoint exits here.\n// ---------------------------------------------------------------------------\n\nimport { Data, Duration, Effect, Layer, Option, Schema } from \"effect\";\nimport { FetchHttpClient, HttpClient, HttpClientRequest } from \"effect/unstable/http\";\n\n/** MCP initialize request body used as the shape probe. Any real MCP\n * server either answers it (unauth-OK server) or returns the spec-\n * mandated 401 + WWW-Authenticate pair. A non-MCP endpoint hit with\n * this body will respond with whatever it does for unknown JSON\n * payloads — 400, 404, HTML, a GraphQL error envelope, etc. — none of\n * which match the gate below. */\nconst INITIALIZE_BODY = JSON.stringify({\n jsonrpc: \"2.0\",\n id: 1,\n method: \"initialize\",\n params: {\n protocolVersion: \"2025-06-18\",\n capabilities: {},\n clientInfo: { name: \"executor-probe\", version: \"0\" },\n },\n});\n\n/** Header-name lookup is case-insensitive per RFC 7230. `fetch`'s\n * `Response.headers` already lower-cases, but we normalise explicitly\n * to stay robust against test mocks that construct `Headers` loosely. */\nconst readHeader = (headers: Readonly<Record<string, string>>, name: string): string | null => {\n const direct = headers[name];\n if (direct !== undefined) return direct;\n const lower = name.toLowerCase();\n for (const [k, v] of Object.entries(headers)) {\n if (k.toLowerCase() === lower) return v;\n }\n return null;\n};\n\nclass ProbeTransportError extends Data.TaggedError(\"ProbeTransportError\")<{\n readonly reason: string;\n readonly cause: unknown;\n}> {}\n\nconst decodeJsonString = Schema.decodeUnknownOption(Schema.fromJsonString(Schema.Unknown));\n\nconst asObject = (body: string): Record<string, unknown> | null => {\n if (!body) return null;\n const parsed = decodeJsonString(body);\n if (Option.isNone(parsed)) return null;\n const value = parsed.value;\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) return null;\n return value as Record<string, unknown>;\n};\n\n/** Quick check that a body parses as a JSON-RPC 2.0 envelope. The MCP wire\n * protocol is JSON-RPC 2.0, so a real MCP server's response to `initialize`\n * (whether 2xx with the result, or a 401 error envelope) carries this\n * shape. Non-MCP services don't — GraphQL APIs return `{errors:[...]}`,\n * REST APIs return their own envelope, marketing pages return HTML. */\nconst isJsonRpcEnvelope = (body: string): boolean => {\n const obj = asObject(body);\n if (!obj) return false;\n if (obj.jsonrpc !== \"2.0\") return false;\n return \"result\" in obj || \"error\" in obj || \"method\" in obj;\n};\n\n/** Quick check that a body parses as an RFC 6750 OAuth Bearer error\n * envelope (`{error: \"invalid_token\", error_description?: ..., ...}`).\n * Real MCP servers like Atlassian return this shape on unauth requests\n * even when their WWW-Authenticate omits `resource_metadata=`. The\n * GraphQL `{errors: [...]}` envelope, which a non-MCP OAuth-protected\n * GraphQL API would return, is explicitly excluded. */\nconst isOAuthErrorBody = (body: string): boolean => {\n const obj = asObject(body);\n if (!obj) return false;\n if (Array.isArray(obj.errors)) return false;\n return typeof obj.error === \"string\";\n};\n\n/** RFC 9728 protected-resource-metadata document. We only need the two\n * fields that prove the document genuinely describes an OAuth-protected\n * resource: `resource` (the resource identifier) and a non-empty\n * `authorization_servers` list. */\nconst ProtectedResourceMetadata = Schema.Struct({\n resource: Schema.String,\n authorization_servers: Schema.Array(Schema.String),\n});\nconst decodeProtectedResourceMetadata = Schema.decodeUnknownOption(\n Schema.fromJsonString(ProtectedResourceMetadata),\n);\n\n/** RFC 9728 §3.1 path-scoped well-known URL: insert\n * `/.well-known/oauth-protected-resource` before the resource's path\n * component. `https://host/api/mcp` → `https://host/.well-known/oauth-\n * protected-resource/api/mcp`. This is exactly the URL the MCP\n * authorization spec tells clients to construct. */\nconst protectedResourceMetadataUrl = (endpoint: URL): string => {\n const path = endpoint.pathname === \"/\" ? \"\" : endpoint.pathname;\n return `${endpoint.origin}/.well-known/oauth-protected-resource${path}`;\n};\n\n/** The RFC 9728 `resource` value must actually describe this endpoint\n * before we trust the document — an exact URL match, or a same-origin\n * parent whose path is a prefix of the endpoint's. Guards against a\n * shared host serving protected-resource metadata for some unrelated\n * resource. */\nconst resourceMatchesEndpoint = (resource: string, endpoint: URL): boolean => {\n if (!URL.canParse(resource)) return false;\n const parsed = new URL(resource);\n if (parsed.origin !== endpoint.origin) return false;\n const resourcePath = parsed.pathname.replace(/\\/+$/, \"\");\n const endpointPath = endpoint.pathname.replace(/\\/+$/, \"\");\n return endpointPath === resourcePath || endpointPath.startsWith(`${resourcePath}/`);\n};\n\n/** Workaround for MCP servers that omit (or under-specify) the\n * `WWW-Authenticate` challenge on their 401 — e.g. Datadog's\n * `mcp.datadoghq.com` returns a bare `401 {\"errors\":[\"Unauthorized\"]}`\n * with no header at all, so the wire-shape gate above can't tell it\n * apart from an unrelated OAuth-protected API and the user lands on the\n * manual-credentials prompt instead of an OAuth sign-in.\n *\n * The MCP authorization spec still requires such servers to publish\n * RFC 9728 metadata at the path-scoped well-known URL. A document there\n * whose `resource` matches this endpoint is a deliberate, MCP-spec-\n * specific signal a generic OAuth API would not emit — strong enough to\n * classify the endpoint as MCP so the OAuth flow can start. */\nconst probeProtectedResourceMetadata = (\n client: HttpClient.HttpClient,\n endpoint: URL,\n timeoutMs: number,\n): Effect.Effect<boolean> =>\n Effect.gen(function* () {\n const response = yield* client\n .execute(\n HttpClientRequest.get(protectedResourceMetadataUrl(endpoint)).pipe(\n HttpClientRequest.setHeader(\"accept\", \"application/json\"),\n ),\n )\n .pipe(Effect.timeout(Duration.millis(timeoutMs)));\n if (response.status < 200 || response.status >= 300) return false;\n const body = yield* response.text.pipe(\n Effect.timeout(Duration.millis(timeoutMs)),\n Effect.catch(() => Effect.succeed(\"\")),\n );\n const metadata = decodeProtectedResourceMetadata(body);\n if (Option.isNone(metadata)) return false;\n if (metadata.value.authorization_servers.length === 0) return false;\n return resourceMatchesEndpoint(metadata.value.resource, endpoint);\n }).pipe(Effect.catch(() => Effect.succeed(false)));\n\nconst ErrorMessageShape = Schema.Struct({ message: Schema.String });\nconst decodeErrorMessageShape = Schema.decodeUnknownOption(ErrorMessageShape);\n\nconst reasonFromBoundaryCause = (cause: unknown): string => {\n const messageShape = decodeErrorMessageShape(cause);\n if (Option.isSome(messageShape)) return messageShape.value.message;\n if (typeof cause === \"string\") return cause;\n if (typeof cause === \"number\" || typeof cause === \"boolean\" || typeof cause === \"bigint\") {\n return `${cause}`;\n }\n if (typeof cause === \"symbol\") return cause.description ?? \"symbol\";\n if (cause === null) return \"null\";\n if (typeof cause === \"undefined\") return \"undefined\";\n return \"fetch failed\";\n};\n\n/** Why the probe rejected an endpoint as not-MCP.\n *\n * - `auth-required` — server returned 401. We don't know for sure it's\n * an MCP server (no spec-compliant Bearer challenge or the body\n * isn't JSON-RPC), but the right next step for the user is the same\n * either way: provide credentials and retry. This is what\n * misclassifies real MCP servers like cubic.dev (no\n * resource_metadata) or ref.tools (no WWW-Authenticate at all)\n * without the URL-token fallback at the detect layer.\n * - `wrong-shape` — endpoint responded but with a body or status that\n * doesn't match any MCP shape (200 HTML, 400 GraphQL, 404 from a\n * static host, etc.). User action: this URL probably isn't MCP. */\nexport type McpProbeRejectCategory = \"auth-required\" | \"wrong-shape\";\n\nexport type McpShapeProbeResult =\n /** Server answered initialize successfully — either a 2xx with a\n * JSON-RPC payload, or a 401 + WWW-Authenticate: Bearer (RFC 6750\n * challenge) that the MCP auth spec requires. */\n | { readonly kind: \"mcp\"; readonly requiresAuth: boolean }\n /** Endpoint is reachable but the response does not look like MCP. */\n | {\n readonly kind: \"not-mcp\";\n readonly reason: string;\n readonly category: McpProbeRejectCategory;\n }\n /** Transport-level failure (DNS, TLS, timeout, abort, ...). */\n | { readonly kind: \"unreachable\"; readonly reason: string };\n\nexport interface ProbeOptions {\n /** Abort the request after this many ms. Default 8000. */\n readonly timeoutMs?: number;\n readonly httpClientLayer?: Layer.Layer<HttpClient.HttpClient>;\n readonly headers?: Record<string, string>;\n readonly queryParams?: Record<string, string>;\n}\n\n/**\n * Hit `endpoint` with a JSON-RPC `initialize` POST and classify the\n * response according to the MCP authorization spec.\n *\n * Returns `{kind: \"mcp\"}` only when the endpoint either:\n * - answers with 2xx (unauth-OK MCP server), or\n * - responds 401 with a `Bearer` WWW-Authenticate challenge.\n *\n * Anything else (400, 404, 200-with-HTML, 200-with-GraphQL-errors, ...)\n * is classified `not-mcp`. Transport errors surface as `unreachable`.\n */\nexport const probeMcpEndpointShape = (\n endpoint: string,\n options: ProbeOptions = {},\n): Effect.Effect<McpShapeProbeResult> =>\n Effect.gen(function* () {\n const timeoutMs = options.timeoutMs ?? 8_000;\n const outcome = yield* Effect.gen(function* () {\n const client = yield* HttpClient.HttpClient;\n\n const readBody = (response: {\n readonly text: Effect.Effect<string, unknown>;\n }): Effect.Effect<string> =>\n response.text.pipe(\n Effect.timeout(Duration.millis(timeoutMs)),\n Effect.catch(() => Effect.succeed(\"\")),\n );\n\n const classify = (\n response: {\n readonly status: number;\n readonly headers: Readonly<Record<string, string>>;\n readonly text: Effect.Effect<string, unknown>;\n },\n method: \"GET\" | \"POST\",\n ): Effect.Effect<McpShapeProbeResult | null> =>\n Effect.gen(function* () {\n const contentType = readHeader(response.headers, \"content-type\") ?? \"\";\n const isSse = /^\\s*text\\/event-stream\\b/i.test(contentType);\n\n if (response.status === 401) {\n const wwwAuth = readHeader(response.headers, \"www-authenticate\");\n if (!wwwAuth || !/^\\s*bearer\\b/i.test(wwwAuth)) {\n // Spec-non-compliant 401 (no `Bearer` challenge). Before\n // giving up, check whether the server still publishes\n // RFC 9728 protected-resource metadata for this path —\n // some real MCP servers (Datadog) do exactly this.\n if (yield* probeProtectedResourceMetadata(client, url, timeoutMs)) {\n return { kind: \"mcp\", requiresAuth: true } as const;\n }\n return {\n kind: \"not-mcp\",\n category: \"auth-required\",\n reason: \"401 without Bearer WWW-Authenticate — not an MCP auth challenge\",\n } as const;\n }\n // Spec-compliant MCP signal: the auth spec mandates a\n // `resource_metadata=` attribute pointing at the server's\n // RFC 9728 document. Real OAuth-protected MCP servers\n // (sentry.dev, etc.) include it. This attribute is rare on\n // unrelated OAuth services and is the cleanest accept signal\n // we have when the 401 body is RFC 6750 OAuth-shape rather\n // than JSON-RPC.\n if (/(?:^|[\\s,])resource_metadata\\s*=/i.test(wwwAuth)) {\n return { kind: \"mcp\", requiresAuth: true } as const;\n }\n // Looser RFC 6750 §3.1 signal: the Bearer challenge carries\n // `error=` / `error_description=` auth-params. Real MCP\n // servers (Supabase, GitHub Copilot, Vercel, Neon, Tavily,\n // Replicate, ...) include this even when they omit\n // `resource_metadata=`. The body alone isn't enough for\n // those — Supabase, e.g., returns `{\"message\":\"Unauthorized\"}`\n // which is neither JSON-RPC nor RFC 6750. The `error=`\n // auth-param is the tiebreaker.\n if (/(?:^|[\\s,])error\\s*=/i.test(wwwAuth)) {\n return { kind: \"mcp\", requiresAuth: true } as const;\n }\n // SSE responses can't carry a JSON-RPC error envelope; accept the\n // Bearer challenge alone in that case (rare but spec-permissible).\n if (isSse) return { kind: \"mcp\", requiresAuth: true } as const;\n // Fallback for MCP servers whose 401 omits\n // `resource_metadata=`. Two body shapes count:\n // - JSON-RPC error (cubic.dev: API-key auth, JSON-RPC\n // errors end-to-end).\n // - RFC 6750 OAuth Bearer error envelope `{error:\n // \"invalid_token\", ...}` without GraphQL `{errors:[...]}`\n // (Atlassian).\n // Non-MCP OAuth-protected services that issue bare Bearer\n // challenges (Railway-style GraphQL, etc.) return `errors`\n // arrays or other shapes that fail both checks.\n const body = yield* readBody(response);\n if (!isJsonRpcEnvelope(body) && !isOAuthErrorBody(body)) {\n // Bearer challenge with no usable accept signal. Same\n // RFC 9728 fallback as the no-`Bearer` case above.\n if (yield* probeProtectedResourceMetadata(client, url, timeoutMs)) {\n return { kind: \"mcp\", requiresAuth: true } as const;\n }\n return {\n kind: \"not-mcp\",\n category: \"auth-required\",\n reason:\n \"401 + Bearer without resource_metadata, JSON-RPC body, or OAuth error body\",\n } as const;\n }\n return { kind: \"mcp\", requiresAuth: true } as const;\n }\n\n if (response.status >= 200 && response.status < 300) {\n if (method === \"GET\") {\n if (!isSse) {\n return {\n kind: \"not-mcp\",\n category: \"wrong-shape\",\n reason: \"GET response is not an SSE stream\",\n } as const;\n }\n return { kind: \"mcp\", requiresAuth: false } as const;\n }\n // POST 2xx: SSE body is opaque to us; otherwise require a\n // JSON-RPC envelope so we don't accept HTML/REST 200 responses.\n if (isSse) return { kind: \"mcp\", requiresAuth: false } as const;\n const body = yield* readBody(response);\n if (!isJsonRpcEnvelope(body)) {\n return {\n kind: \"not-mcp\",\n category: \"wrong-shape\",\n reason: \"2xx POST body is not a JSON-RPC envelope\",\n } as const;\n }\n return { kind: \"mcp\", requiresAuth: false } as const;\n }\n\n return null;\n });\n\n const url = new URL(endpoint);\n for (const [key, value] of Object.entries(options.queryParams ?? {})) {\n url.searchParams.set(key, value);\n }\n\n let postRequest = HttpClientRequest.post(url.toString()).pipe(\n HttpClientRequest.setHeader(\"content-type\", \"application/json\"),\n HttpClientRequest.setHeader(\"accept\", \"application/json, text/event-stream\"),\n HttpClientRequest.bodyText(INITIALIZE_BODY, \"application/json\"),\n );\n for (const [name, value] of Object.entries(options.headers ?? {})) {\n postRequest = HttpClientRequest.setHeader(postRequest, name, value);\n }\n\n const postResponse = yield* client\n .execute(postRequest)\n .pipe(Effect.timeout(Duration.millis(timeoutMs)));\n\n const postResult = yield* classify(postResponse, \"POST\");\n if (postResult) return postResult;\n\n if ([404, 405, 406, 415].includes(postResponse.status)) {\n let getRequest = HttpClientRequest.get(url.toString()).pipe(\n HttpClientRequest.setHeader(\"accept\", \"text/event-stream\"),\n );\n for (const [name, value] of Object.entries(options.headers ?? {})) {\n getRequest = HttpClientRequest.setHeader(getRequest, name, value);\n }\n const getResponse = yield* client\n .execute(getRequest)\n .pipe(Effect.timeout(Duration.millis(timeoutMs)));\n const getResult = yield* classify(getResponse, \"GET\");\n if (getResult) return getResult;\n }\n\n return {\n kind: \"not-mcp\",\n category: \"wrong-shape\",\n reason: `unexpected status ${postResponse.status} for initialize`,\n } as const;\n }).pipe(\n Effect.provide(options.httpClientLayer ?? FetchHttpClient.layer),\n Effect.mapError(\n (cause) =>\n new ProbeTransportError({\n reason: reasonFromBoundaryCause(cause),\n cause,\n }),\n ),\n Effect.catch((cause) =>\n Effect.succeed<McpShapeProbeResult>({\n kind: \"unreachable\",\n reason: cause.reason,\n }),\n ),\n );\n\n return outcome;\n }).pipe(Effect.withSpan(\"mcp.plugin.probe_shape\"));\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAAA,SAAS,QAAQ,cAAc;AAiC/B,IAAM,aAAa,OAAO,OAAO;AAAA,EAC/B,MAAM,OAAO;AAAA,EACb,aAAa,OAAO,SAAS,OAAO,OAAO,OAAO,MAAM,CAAC;AAAA,EACzD,aAAa,OAAO,SAAS,OAAO,OAAO;AAAA,EAC3C,YAAY,OAAO,SAAS,OAAO,OAAO;AAAA,EAC1C,cAAc,OAAO,SAAS,OAAO,OAAO;AAAA,EAC5C,aAAa,OAAO,SAAS,kBAAkB;AACjD,CAAC;AAED,IAAM,kBAAkB,OAAO,OAAO;AAAA,EACpC,OAAO,OAAO,MAAM,UAAU;AAChC,CAAC;AAED,IAAM,aAAa,OAAO,OAAO;AAAA,EAC/B,MAAM,OAAO,SAAS,OAAO,MAAM;AAAA,EACnC,SAAS,OAAO,SAAS,OAAO,MAAM;AACxC,CAAC;AAED,IAAM,wBAAwB,OAAO,oBAAoB,eAAe;AACxE,IAAM,mBAAmB,OAAO,oBAAoB,UAAU;AAEvD,IAAM,oBAAoB,CAAC,UAChC,OAAO,OAAO,sBAAsB,KAAK,CAAC;AAM5C,IAAM,WAAW,CAAC,UAA0B;AAC1C,QAAM,IAAI,MACP,KAAK,EACL,YAAY,EACZ,QAAQ,eAAe,GAAG,EAC1B,QAAQ,YAAY,EAAE;AACzB,SAAO,KAAK;AACd;AAEA,IAAM,WAAW,CAAC,OAAe,SAAsC;AACrE,QAAM,OAAO,SAAS,KAAK;AAC3B,QAAM,KAAK,KAAK,IAAI,IAA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,aAAa;AAAA,YACb,cAAc;AAAA,YACd,SAAS,CAAC,aAAa;AACrB,oBAAM,QAAQ;AACd,qBAAO,KAAK,UAAU,KAAuB,EAAE;AAAA,gBAC7CA,QAAO,IAAI,WAAW,EAAE;AAAA,gBACxBA,QAAO;AAAA,kBACL;AAAA,kBACA,CAAC,EAAE,KAAK,MACNA,QAAO;AAAA,oBACL;AAAA,sBACE;AAAA,sBACA,eAAe,IAAI;AAAA,oBACrB;AAAA,kBACF;AAAA,gBACJ;AAAA,cACF;AAAA,YACF;AAAA,UACF,CAAC;AAAA,QACH;AAAA,MACF;AAAA,IACF;AAAA,EACF;AACF,CAAC;","names":["tool","Effect","Option","Schema","Effect","Effect","Effect","Option","Predicate","Schema","Schema","Option","Effect","Predicate","Effect","Option","Schema","HttpClient","HttpClientRequest","Schema","Option","Effect"]}
package/dist/client.js CHANGED
@@ -8,9 +8,9 @@ import { defineClientPlugin } from "@executor-js/sdk/client";
8
8
  // src/react/source-plugin.tsx
9
9
  import { lazy } from "react";
10
10
  import { jsx } from "react/jsx-runtime";
11
- var importAdd = () => import("./AddMcpSource-GOIRH5FQ.js");
12
- var importEditSheet = () => import("./EditMcpSource-AS3ZTP6W.js");
13
- var importAccounts = () => import("./McpAccountsPanel-4F5WE7FH.js");
11
+ var importAdd = () => import("./AddMcpSource-I67EKOO6.js");
12
+ var importEditSheet = () => import("./EditMcpSource-GPXZQFL5.js");
13
+ var importAccounts = () => import("./McpAccountsPanel-CNUWTJ4R.js");
14
14
  var LazyAddMcpSource = lazy(importAdd);
15
15
  var LazyEditMcpSheet = lazy(importEditSheet);
16
16
  var LazyMcpAccountsPanel = lazy(importAccounts);
package/dist/core.js CHANGED
@@ -4,7 +4,7 @@ import {
4
4
  joinToolPath,
5
5
  mcpPlugin,
6
6
  userFacingProbeMessage
7
- } from "./chunk-5GLUVX3H.js";
7
+ } from "./chunk-OHITN5WV.js";
8
8
  import "./chunk-CLAWPLDI.js";
9
9
  import {
10
10
  McpAuthMethod,
@@ -21,7 +21,7 @@ import {
21
21
  McpToolDiscoveryError,
22
22
  McpTransport,
23
23
  parseMcpIntegrationConfig
24
- } from "./chunk-4V3H3DDH.js";
24
+ } from "./chunk-OCDAATE3.js";
25
25
 
26
26
  // src/sdk/migrate-config.ts
27
27
  import { Option, Schema } from "effect";
package/dist/index.js CHANGED
@@ -1,8 +1,8 @@
1
1
  import {
2
2
  mcpPlugin
3
- } from "./chunk-5GLUVX3H.js";
3
+ } from "./chunk-OHITN5WV.js";
4
4
  import "./chunk-CLAWPLDI.js";
5
- import "./chunk-4V3H3DDH.js";
5
+ import "./chunk-OCDAATE3.js";
6
6
  export {
7
7
  mcpPlugin
8
8
  };
@@ -23,6 +23,10 @@ export declare const mcpServerAtom: (slug: IntegrationSlug) => import("effect/un
23
23
  } | {
24
24
  readonly slug: string;
25
25
  readonly kind: "oauth2";
26
+ } | {
27
+ readonly slug: string;
28
+ readonly kind: "stdio_env";
29
+ readonly vars: readonly string[];
26
30
  })[];
27
31
  readonly headers?: {
28
32
  readonly [x: string]: string;
@@ -34,11 +38,33 @@ export declare const mcpServerAtom: (slug: IntegrationSlug) => import("effect/un
34
38
  } | {
35
39
  readonly transport: "stdio";
36
40
  readonly command: string;
37
- readonly args?: readonly string[] | undefined;
38
- readonly cwd?: string | undefined;
39
41
  readonly env?: {
40
42
  readonly [x: string]: string;
41
43
  } | undefined;
44
+ readonly args?: readonly string[] | undefined;
45
+ readonly cwd?: string | undefined;
46
+ readonly authenticationTemplate?: readonly ({
47
+ readonly slug: string;
48
+ readonly kind: "apikey";
49
+ readonly placements: readonly {
50
+ readonly name: string;
51
+ readonly carrier: "header" | "query";
52
+ readonly variable?: string | undefined;
53
+ readonly prefix?: string | undefined;
54
+ readonly literal?: string | undefined;
55
+ }[];
56
+ readonly label?: string | undefined;
57
+ } | {
58
+ readonly slug: string;
59
+ readonly kind: "none";
60
+ } | {
61
+ readonly slug: string;
62
+ readonly kind: "oauth2";
63
+ } | {
64
+ readonly slug: string;
65
+ readonly kind: "stdio_env";
66
+ readonly vars: readonly string[];
67
+ })[] | undefined;
42
68
  };
43
69
  readonly canRemove: boolean;
44
70
  readonly canRefresh: boolean;
@@ -121,12 +147,13 @@ export declare const addMcpServer: import("effect/unstable/reactivity/Atom").Ato
121
147
  readonly transport: "stdio";
122
148
  readonly command: string;
123
149
  readonly slug?: string | undefined;
124
- readonly description?: string | undefined;
125
- readonly args?: readonly string[] | undefined;
126
- readonly cwd?: string | undefined;
127
150
  readonly env?: {
128
151
  readonly [x: string]: string;
129
152
  } | undefined;
153
+ readonly description?: string | undefined;
154
+ readonly args?: readonly string[] | undefined;
155
+ readonly cwd?: string | undefined;
156
+ readonly envVars?: readonly string[] | undefined;
130
157
  };
131
158
  readonly responseMode?: "decoded-only" | undefined;
132
159
  readonly reactivityKeys?: readonly unknown[] | import("effect/Record").ReadonlyRecord<string, readonly unknown[]> | undefined;
@@ -167,6 +194,10 @@ export declare const configureMcpServer: import("effect/unstable/reactivity/Atom
167
194
  } | {
168
195
  readonly slug: string;
169
196
  readonly kind: "oauth2";
197
+ } | {
198
+ readonly slug: string;
199
+ readonly kind: "stdio_env";
200
+ readonly vars: readonly string[];
170
201
  })[];
171
202
  readonly headers?: {
172
203
  readonly [x: string]: string;
@@ -178,11 +209,33 @@ export declare const configureMcpServer: import("effect/unstable/reactivity/Atom
178
209
  } | {
179
210
  readonly transport: "stdio";
180
211
  readonly command: string;
181
- readonly args?: readonly string[] | undefined;
182
- readonly cwd?: string | undefined;
183
212
  readonly env?: {
184
213
  readonly [x: string]: string;
185
214
  } | undefined;
215
+ readonly args?: readonly string[] | undefined;
216
+ readonly cwd?: string | undefined;
217
+ readonly authenticationTemplate?: readonly ({
218
+ readonly slug: string;
219
+ readonly kind: "apikey";
220
+ readonly placements: readonly {
221
+ readonly name: string;
222
+ readonly carrier: "header" | "query";
223
+ readonly variable?: string | undefined;
224
+ readonly prefix?: string | undefined;
225
+ readonly literal?: string | undefined;
226
+ }[];
227
+ readonly label?: string | undefined;
228
+ } | {
229
+ readonly slug: string;
230
+ readonly kind: "none";
231
+ } | {
232
+ readonly slug: string;
233
+ readonly kind: "oauth2";
234
+ } | {
235
+ readonly slug: string;
236
+ readonly kind: "stdio_env";
237
+ readonly vars: readonly string[];
238
+ })[] | undefined;
186
239
  };
187
240
  };
188
241
  readonly responseMode?: "decoded-only" | undefined;
@@ -208,6 +261,10 @@ export declare const configureMcpServer: import("effect/unstable/reactivity/Atom
208
261
  } | {
209
262
  readonly slug: string;
210
263
  readonly kind: "oauth2";
264
+ } | {
265
+ readonly slug: string;
266
+ readonly kind: "stdio_env";
267
+ readonly vars: readonly string[];
211
268
  })[];
212
269
  readonly headers?: {
213
270
  readonly [x: string]: string;
@@ -219,11 +276,33 @@ export declare const configureMcpServer: import("effect/unstable/reactivity/Atom
219
276
  } | {
220
277
  readonly transport: "stdio";
221
278
  readonly command: string;
222
- readonly args?: readonly string[] | undefined;
223
- readonly cwd?: string | undefined;
224
279
  readonly env?: {
225
280
  readonly [x: string]: string;
226
281
  } | undefined;
282
+ readonly args?: readonly string[] | undefined;
283
+ readonly cwd?: string | undefined;
284
+ readonly authenticationTemplate?: readonly ({
285
+ readonly slug: string;
286
+ readonly kind: "apikey";
287
+ readonly placements: readonly {
288
+ readonly name: string;
289
+ readonly carrier: "header" | "query";
290
+ readonly variable?: string | undefined;
291
+ readonly prefix?: string | undefined;
292
+ readonly literal?: string | undefined;
293
+ }[];
294
+ readonly label?: string | undefined;
295
+ } | {
296
+ readonly slug: string;
297
+ readonly kind: "none";
298
+ } | {
299
+ readonly slug: string;
300
+ readonly kind: "oauth2";
301
+ } | {
302
+ readonly slug: string;
303
+ readonly kind: "stdio_env";
304
+ readonly vars: readonly string[];
305
+ })[] | undefined;
227
306
  };
228
307
  }, import("@executor-js/sdk").InternalError | import("../sdk").McpConnectionError | import("../sdk").McpToolDiscoveryError>;
229
308
  export declare const configureMcpAuth: import("effect/unstable/reactivity/Atom").AtomResultFn<{
@@ -276,5 +355,9 @@ export declare const configureMcpAuth: import("effect/unstable/reactivity/Atom")
276
355
  } | {
277
356
  readonly slug: string;
278
357
  readonly kind: "oauth2";
358
+ } | {
359
+ readonly slug: string;
360
+ readonly kind: "stdio_env";
361
+ readonly vars: readonly string[];
279
362
  })[];
280
363
  }, import("@executor-js/sdk").InternalError | import("../sdk").McpConnectionError | import("../sdk").McpToolDiscoveryError>;